<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2343
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1364840 by johtaylo@johtaylo-jtincrementor-increment on 2017/01/23 03:00:29<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
# define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
# define AMD_PLATFORM_BUILD_NUMBER 2344
#endif // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
# define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
# define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \
    "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
# define AMD_PLATFORM_INFO "AMD-APP" AMD_PLATFORM_RELEASE_INFO \
    DEBUG_ONLY("." IF(IS_OPTIMIZED,"opt","dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO

#endif // VERSIONS_HPP_
<|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1447247 by johtaylo@johtaylo-jtincrementor-increment on 2017/08/15 03:00:04<commit_after><|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1451630 by johtaylo@johtaylo-jtincrementor-increment on 2017/08/25 03:00:06<commit_after><|endoftext|>


<commit_before><commit_msg>P4 to Git Change 1584378 by chui@ocl-promo-incrementor on 2018/07/24 02:56:41<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include "MainScene.h"
#include "TWScene.h"

Scene* TWScene::createScene()
{
	auto scene = Scene::create();

	auto layer = TWScene::create();

	scene->addChild(layer);

	return scene;
}

bool TWScene::init()
{
	if (!CCLayerColor::initWithColor(Color4B::BLUE))
	{
		return false;
	}

	//1ȸ ͵
	auto mainTitle = Label::createWithTTF("Main Title\n fuck!!!!", "fonts/NanumGothic.ttf", 34);
	mainTitle->setPosition(Point(160, 240));
	mainTitle->setName("MainTitle");

	Size winSize = Director::getInstance()->getVisibleSize();
	float labelWidth = mainTitle->getContentSize().width;
	float labelHeight = mainTitle->getContentSize().height;
	auto action1 = MoveTo::create(10.0 / labelHeight, Point(labelWidth / 2, winSize.height - labelHeight / 2));
	auto action2 = MoveTo::create(10.0 / labelWidth, Point(winSize.width - labelWidth / 2, winSize.height - labelHeight / 2));
	auto action3 = MoveTo::create(10.0 / labelHeight, Point(winSize.width - labelWidth / 2, labelHeight / 2));
	auto action4 = MoveTo::create(10.0 / labelWidth, Point(labelWidth / 2, labelHeight / 2));
	auto sequence_action = Sequence::create(action1, action2, action3, action4, NULL);
	auto forever_repeat_action = RepeatForever::create(sequence_action);

	mainTitle->runAction(forever_repeat_action);
	//mainTitle->stopAction(forever_repeat_action);
	this->addChild(mainTitle);

	auto listener = EventListenerMouse::create();
	listener->onMouseUp = CC_CALLBACK_1(TWScene::onMouseUP, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

	//2ȸ ͵
	Sprite* character = Sprite::create();
	this->addChild(character);
	character->setPosition(Point(winSize.width / 2, winSize.height / 2));
	Vector<SpriteFrame*> animFrames;
	animFrames.reserve(4);
	for (int i = 0; i < 4; i++)
		animFrames.pushBack(SpriteFrame::create("res/lisa.png", Rect(0, 48 * i, 27, 48)));

	// create the animation out of the frame
	Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f);
	Animate* animate = Animate::create(animation);

	// run it and repeat it forever
	RepeatForever *action = RepeatForever::create(animate);

	character->runAction(action);

	this->schedule(schedule_selector(TWScene::ChangeBackground), 1.0);

	Layer* bgLayer = Layer::create();
	this->addChild(bgLayer, 1);

	auto spr_0 = Sprite::create("res/mc.jpg");
	spr_0->setScaleX(winSize.width);
	spr_0->setScaleY(winSize.height);
	spr_0->setAnchorPoint(Point::ZERO);
	spr_0->setPosition(Point::ZERO);
	bgLayer->addChild(spr_0);

	auto action_0 = MoveBy::create(10.0, Point(-2000, 0));
	auto action_1 = Place::create(Point::ZERO);
	auto action_2 = Sequence::create(action_0, action_1, NULL);
	auto action_3 = RepeatForever::create(action_2);
	bgLayer->runAction(action_3);

	return true;
}

void TWScene::ChangeBackground(float deltaTIme)
{
	Color3B color;
	int rand = random() % 5;
	switch (rand){
	case 0:
		color = Color3B::YELLOW;
		break;
	case 1:
		color = Color3B::BLUE;
		break;
	case 2:
		color = Color3B::GREEN;
		break;
	case 3:
		color = Color3B::RED;
		break;
	case 4:
		color = Color3B::MAGENTA;
		break;
	case 5:
		color = Color3B::BLACK;
		break;
	case 6:
		color = Color3B::ORANGE;
		break;
	case 7:
		color = Color3B::GRAY;
		break;
	}
	this->setColor(color);
}

void TWScene::ChangeToMainScene(Ref* pSender)
{
	Director::getInstance()->replaceScene(MainScene::createScene());
}

void TWScene::onMouseUP(cocos2d::Event* event)
{
	auto mainTitle = this->getChildByName("MainTitle");
	if (!mainTitle->isVisible())
		mainTitle->setVisible(true);
	else
		mainTitle->setVisible(false);
}
<commit_msg>Unsolved<commit_after>#include "stdafx.h"
#include "MainScene.h"
#include "TWScene.h"

Scene* TWScene::createScene()
{
	auto scene = Scene::create();

	auto layer = TWScene::create();

	scene->addChild(layer);

	return scene;
}

bool TWScene::init()
{
	if (!CCLayerColor::initWithColor(Color4B::BLUE))
	{
		return false;
	}

	//1ȸ ͵
	auto mainTitle = Label::createWithTTF("Main Title\n fuck!!!!", "fonts/NanumGothic.ttf", 34);
	mainTitle->setPosition(Point(160, 240));
	mainTitle->setName("MainTitle");

	Size winSize = Director::getInstance()->getVisibleSize();
	float labelWidth = mainTitle->getContentSize().width;
	float labelHeight = mainTitle->getContentSize().height;
	auto action1 = MoveTo::create(10.0 / labelHeight, Point(labelWidth / 2, winSize.height - labelHeight / 2));
	auto action2 = MoveTo::create(10.0 / labelWidth, Point(winSize.width - labelWidth / 2, winSize.height - labelHeight / 2));
	auto action3 = MoveTo::create(10.0 / labelHeight, Point(winSize.width - labelWidth / 2, labelHeight / 2));
	auto action4 = MoveTo::create(10.0 / labelWidth, Point(labelWidth / 2, labelHeight / 2));
	auto sequence_action = Sequence::create(action1, action2, action3, action4, NULL);
	auto forever_repeat_action = RepeatForever::create(sequence_action);

	mainTitle->runAction(forever_repeat_action);
	//mainTitle->stopAction(forever_repeat_action);
	this->addChild(mainTitle);

	auto listener = EventListenerMouse::create();
	listener->onMouseUp = CC_CALLBACK_1(TWScene::onMouseUP, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

	//2ȸ ͵
	Sprite* character = Sprite::create();
	this->addChild(character);
	character->setPosition(Point(winSize.width / 2, winSize.height / 2));
	Vector<SpriteFrame*> animFrames;
	animFrames.reserve(4);
	for (int i = 0; i < 4; i++)
		animFrames.pushBack(SpriteFrame::create("res/lisa.png", Rect(0, 48 * i, 27, 48)));

	// create the animation out of the frame
	Animation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f);
	Animate* animate = Animate::create(animation);

	// run it and repeat it forever
	RepeatForever *action = RepeatForever::create(animate);

	character->runAction(action);

	this->schedule(schedule_selector(TWScene::ChangeBackground), 1.0);

	Layer* bgLayer = Layer::create();
	this->addChild(bgLayer, 1);

	auto spr_0 = Sprite::create("res/mc.jpg");
	spr_0->setScaleX(winSize.width / spr_0->getContentSize().width);
	spr_0->setScaleY(winSize.height / spr_0->getContentSize().height);
	spr_0->setAnchorPoint(Point::ZERO);
	spr_0->setPosition(Point::ZERO);
	bgLayer->addChild(spr_0);

	auto spr_1 = Sprite::create("res/mc.jpg");
	spr_1->setScaleX(winSize.width / spr_1->getContentSize().width);
	spr_1->setScaleY(winSize.height / spr_1->getContentSize().height);
	spr_1->setAnchorPoint(Point::ZERO);
	spr_1->setPosition(Point(winSize.width, 0));
	bgLayer->addChild(spr_1);

	auto action_0 = MoveBy::create(10.0, Point(-2000, 0));
	auto action_1 = Place::create(Point::ZERO);
	auto action_2 = Sequence::create(action_0, action_1, NULL);
	auto action_3 = RepeatForever::create(action_2);
	bgLayer->runAction(action_3);

	return true;
}

void TWScene::ChangeBackground(float deltaTIme)
{
	Color3B color;
	int rand = random() % 5;
	switch (rand){
	case 0:
		color = Color3B::YELLOW;
		break;
	case 1:
		color = Color3B::BLUE;
		break;
	case 2:
		color = Color3B::GREEN;
		break;
	case 3:
		color = Color3B::RED;
		break;
	case 4:
		color = Color3B::MAGENTA;
		break;
	case 5:
		color = Color3B::BLACK;
		break;
	case 6:
		color = Color3B::ORANGE;
		break;
	case 7:
		color = Color3B::GRAY;
		break;
	}
	this->setColor(color);
}

void TWScene::ChangeToMainScene(Ref* pSender)
{
	Director::getInstance()->replaceScene(MainScene::createScene());
}

void TWScene::onMouseUP(cocos2d::Event* event)
{
	auto mainTitle = this->getChildByName("MainTitle");
	if (!mainTitle->isVisible())
		mainTitle->setVisible(true);
	else
		mainTitle->setVisible(false);
}
<|endoftext|>


<commit_before>// @(#)root/hist:$Id$
// Author: David Gonzalez Maline   12/11/09

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TFitResultPtr.h"
#include "TFitResult.h"
#include "TError.h"

/**
TFitResultPtr provides an indirection to the TFitResult class and with a semantics
identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult.
In addition it provides an automatic comversion to an integer. In this way it can be
returned from the TH1::Fit method and the change in TH1::Fit be backward compatible.
The class

 */

ClassImp(TFitResultPtr)

TFitResultPtr::TFitResultPtr(TFitResult * p) :
   fStatus(-1),
   fPointer(p)
{
   // constructor from a TFitResult pointer
   if (fPointer != 0) fStatus = fPointer->Status();
}

TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) :
   fStatus(rhs.fStatus), fPointer(0)
{
   // copy constructor - create a new TFitResult if needed
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
}

TFitResultPtr::~TFitResultPtr()
{
   // destructor - delete the contained TFitResult pointer if needed
   if ( fPointer != 0)
      delete fPointer;
}

TFitResult& TFitResultPtr::operator*() const
{
   // impelment the de-reference operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   if  (fPointer == 0) {
      Error("TFitResultPtr","TFitResult is empty - use the fit option S");
      return *(new TFitResult() );
   }
   return *fPointer;
}

TFitResult* TFitResultPtr::operator->() const
{
   // implement the -> operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   if  (fPointer == 0) {
      Error("TFitResultPtr","TFitResult is empty - use the fit option S");
      return new TFitResult();
   }
   return fPointer;
}

TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs)
{
   // assignment operator
   // if needed copy the TFitResult  object and delete previous one if existing
   if ( &rhs == this) return *this; // self assignment
   fStatus = rhs.fStatus;
   if ( fPointer ) delete fPointer;
   fPointer = 0;
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
   return *this;
}

<commit_msg>fix minor typo<commit_after>// @(#)root/hist:$Id$
// Author: David Gonzalez Maline   12/11/09

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TFitResultPtr.h"
#include "TFitResult.h"
#include "TError.h"

/**
TFitResultPtr provides an indirection to the TFitResult class and with a semantics
identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult.
In addition it provides an automatic comversion to an integer. In this way it can be
returned from the TH1::Fit method and the change in TH1::Fit be backward compatible.
The class

 */

ClassImp(TFitResultPtr)

TFitResultPtr::TFitResultPtr(TFitResult * p) :
   fStatus(-1),
   fPointer(p)
{
   // constructor from a TFitResult pointer
   if (fPointer != 0) fStatus = fPointer->Status();
}

TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) :
   fStatus(rhs.fStatus), fPointer(0)
{
   // copy constructor - create a new TFitResult if needed
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
}

TFitResultPtr::~TFitResultPtr()
{
   // destructor - delete the contained TFitResult pointer if needed
   if ( fPointer != 0)
      delete fPointer;
}

TFitResult& TFitResultPtr::operator*() const
{
   // implement the de-reference operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   if  (fPointer == 0) {
      Error("TFitResultPtr","TFitResult is empty - use the fit option S");
      return *(new TFitResult() );
   }
   return *fPointer;
}

TFitResult* TFitResultPtr::operator->() const
{
   // implement the -> operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   if  (fPointer == 0) {
      Error("TFitResultPtr","TFitResult is empty - use the fit option S");
      return new TFitResult();
   }
   return fPointer;
}

TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs)
{
   // assignment operator
   // if needed copy the TFitResult  object and delete previous one if existing
   if ( &rhs == this) return *this; // self assignment
   fStatus = rhs.fStatus;
   if ( fPointer ) delete fPointer;
   fPointer = 0;
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
   return *this;
}

<|endoftext|>


<commit_before>#include <opencv2\opencv.hpp>
#include <opencv2\imgproc.hpp>
#include <opencv2\highgui.hpp>
#include <opencv2\ml.hpp>
#include <vector>
#include <iostream>
#include <random>
#include "AdaBoost.h"
#include "VectorData.h"
#include "MatData.h"
#include "WeakVectorClassifierFactory.h"
#include "WeakHaarClassifierFactory.h"
#include "AdaBoostEdgeDetector.h"

const double PI = 3.14159265;

void test2DPoints()
{
	//Mat img = imread("sky.jpg");
	//Mat gray;
	//cv::cvtColor(img, gray, CV_BGR2GRAY);

	//imshow("Colored Image", img);
	//imshow("Gray Image", gray);

	//waitKey();

	// generate the data
	std::vector<DataPoint*> data;
	int i = 0;
	cv::Mat img = cv::Mat::zeros(1100, 1100, CV_32FC3);
	for (double r = 0.1 * 1000; r <= 0.51 * 1000; r += 0.05 * 1000)
	{
		for (double theta = 0; theta <= 1.81 * PI; theta += (PI / 5),i++)
		{
			std::vector<double> d = std::vector<double>(2, 0);
			d[0] = 0.5f + r * std::cos(theta);
			d[1] = 0.5f + (r - 0.05) * std::sin(theta);

			data.push_back(new VectorData(d));
		}
	}
	// test
	//data.clear();
	//label.clear();
	//for (int i = 0; i < 3; i++)
	//{
	//	data.push_back(std::vector<double>(2, 0));
	//	data[i][0] = i;
	//	data[i][1] = rand() % 10;
	//}
	//for (int i = 3; i < 6; i++)
	//{
	//	data.push_back(std::vector<double>(2, 0));
	//	data[i][0] = i;
	//	data[i][1] = rand() % 20;
	//}
	//
	std::cout << data.size() << std::endl;
	int shift = 510;
	std::vector<int> label(30,1);
	label.resize(data.size(), -1);
	for (int i = 0; i < data.size(); i++)
	{
		cv::circle(img, cv::Point(data[i]->getVectorData()[0] + shift, data[i]->getVectorData()[1] + shift),
			2, cv::Scalar(((label[i] - 1) / -2) * 255, 0, ((label[i] + 1)/2) * 255), -1);
	}
	//freopen("result.csv", "w", stdout);
	WeakClassifierFactory * factory = new WeakVectorClassifierFactory();
	for (int i = 1; i < 30; i+=2)
	{
		AdaBoost adaboost(i, factory);
		std::vector<int> outLabels;
		double accuracy = adaboost.train(data, label, outLabels);
		std::cout << i << ", " << accuracy << std::endl;
		//system("PAUSE");
	}
	cv::imshow("img", img);
	cv::waitKey();
}

void displayIntegralImage(cv::Mat Iimg)
{
	double min, max;
	cv::minMaxLoc(Iimg, &min, &max);
	Iimg -= min;
	Iimg /= (max - min);
	cv::imshow("image", Iimg);
	cv::waitKey();
}
/*
void testMatData()
{
	cv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1);
	m(cv::Rect(0, 0, 200, 200)) = 50;
	m(cv::Rect(0, 200, 200, 200)) = 200;
	m(cv::Rect(200, 0, 200, 200)) = 150;
	m(cv::Rect(200, 200, 200, 200)) = 100;
	cv::Mat Iimg, I2img;
	cv::integral(m, Iimg, I2img, CV_32FC1);
	// display
	//displayIntegralImage(Iimg);
	cv::Mat edges = AdaBoostEdgeDetector::cannyEdgeDetection(m);

	// prepare data vector
	std::vector<DataPoint*> trainData;
	std::vector<int> labels;
	cv::Mat show;
	cv::cvtColor(m, show, CV_GRAY2BGR);
	// make patches 10x10 with step 5
	for (int r = 0; r <= 390; r += 5)
	{
		for (int c = 0; c <= 390; c += 5)
		{
			cv::Rect win = cv::Rect(c, r, 10, 10);
			trainData.push_back(new MatData(Iimg, win));
			//MatData testData(m, win);
			//cv::imshow("window", testData.getMatData());
			//cv::waitKey();
			if (cv::sum(edges(win)).val[0] > 1)
			{
				// edge
				labels.push_back(1);
				cv::rectangle(show, win, cv::Scalar(255, 0, 0));
			}
			else
			{
				// non edge
				labels.push_back(-1);
			}
		}
	}

	cv::imshow("my edges", show);
	cv::waitKey(50);

	// prepare the Haar Classifier Factory
	std::vector<std::vector<std::vector<int> > > shapes;
	int arr[] = { -1,1 };
	std::vector<std::vector<int> > shape1(2,std::vector<int>(1,1));
	shape1[0][0] = -1;
	std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1));
	shape2[0][0] = shape2[1][1] = -1;

	shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2)));
	shapes.push_back(shape1);
	//shapes.push_back(shape2);

	std::vector<cv::Point> locs(1, cv::Point(0, 0));
	std::vector<cv::Size> sizes;
	sizes.push_back(cv::Size(5, 10));
	sizes.push_back(cv::Size(10, 5));
	//sizes.push_back(cv::Size(5, 5));

	for (int i = 1; i < 30; i ++)
	{
		WeakClassifierFactory * factory = new WeakHaarClassifierFactory(shapes, sizes, locs);

		AdaBoost adaboost(i, factory);
		std::vector<int> y;
		double accuracy = adaboost.train(trainData, labels, y);
		std::cout << i << ", " << accuracy << std::endl;
		cv::Mat show1;
		show.copyTo(show1);
		for (int j = 0; j < y.size(); j++)
		{
			if (y[j] == 1)
			{
				if (labels[j] == 1)
				{
					cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 255, 0));
				}
				else
				{
					cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 0, 255));
				}
			}
		}
		cv::imshow("my edges", show1);
		cv::waitKey(0);
		//system("PAUSE");
	}
}
*/
void testAdaBoostEdgeDetection()
{
	cv::Mat testImg = cv::imread("test.png", 0);

	cv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1);
	m(cv::Rect(0, 0, 200, 200)) = 50;
	m(cv::Rect(0, 200, 200, 200)) = 200;
	m(cv::Rect(200, 0, 200, 200)) = 150;
	m(cv::Rect(200, 200, 200, 200)) = 100;
	cv::imwrite("orig.png", m);
	std::vector<cv::Mat> images;
	images.push_back(m);

	std::vector<std::vector<std::vector<int> > > shapes;
	int arr[] = { -1,1 };
	std::vector<std::vector<int> > shape1(2, std::vector<int>(1, 1));
	shape1[0][0] = -1;
	std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1));
	shape2[0][0] = shape2[1][1] = -1;

	shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2)));
	shapes.push_back(shape1);
	//shapes.push_back(shape2);

	for (int t = 1; t < 20; t++)
	{
		AdaBoostEdgeDetector adaBoostEdgeDetector(t, shapes, cv::Size(4,4), 2);
		adaBoostEdgeDetector.train(images, true);
		adaBoostEdgeDetector.test(testImg, true);
	}

}

int main()
{
	//test2DPoints();
	//testMatData();
	testAdaBoostEdgeDetection();
	return 0;
}<commit_msg>final test before class<commit_after>#include <opencv2\opencv.hpp>
#include <opencv2\imgproc.hpp>
#include <opencv2\highgui.hpp>
#include <opencv2\ml.hpp>
#include <vector>
#include <iostream>
#include <random>
#include "AdaBoost.h"
#include "VectorData.h"
#include "MatData.h"
#include "WeakVectorClassifierFactory.h"
#include "WeakHaarClassifierFactory.h"
#include "AdaBoostEdgeDetector.h"

const double PI = 3.14159265;

void test2DPoints()
{
	//Mat img = imread("sky.jpg");
	//Mat gray;
	//cv::cvtColor(img, gray, CV_BGR2GRAY);

	//imshow("Colored Image", img);
	//imshow("Gray Image", gray);

	//waitKey();

	// generate the data
	std::vector<DataPoint*> data;
	int i = 0;
	cv::Mat img = cv::Mat::zeros(1100, 1100, CV_32FC3);
	for (double r = 0.1 * 1000; r <= 0.51 * 1000; r += 0.05 * 1000)
	{
		for (double theta = 0; theta <= 1.81 * PI; theta += (PI / 5),i++)
		{
			std::vector<double> d = std::vector<double>(2, 0);
			d[0] = 0.5f + r * std::cos(theta);
			d[1] = 0.5f + (r - 0.05) * std::sin(theta);

			data.push_back(new VectorData(d));
		}
	}
	// test
	//data.clear();
	//label.clear();
	//for (int i = 0; i < 3; i++)
	//{
	//	data.push_back(std::vector<double>(2, 0));
	//	data[i][0] = i;
	//	data[i][1] = rand() % 10;
	//}
	//for (int i = 3; i < 6; i++)
	//{
	//	data.push_back(std::vector<double>(2, 0));
	//	data[i][0] = i;
	//	data[i][1] = rand() % 20;
	//}
	//
	std::cout << data.size() << std::endl;
	int shift = 510;
	std::vector<int> label(30,1);
	label.resize(data.size(), -1);
	for (int i = 0; i < data.size(); i++)
	{
		cv::circle(img, cv::Point(data[i]->getVectorData()[0] + shift, data[i]->getVectorData()[1] + shift),
			2, cv::Scalar(((label[i] - 1) / -2) * 255, 0, ((label[i] + 1)/2) * 255), -1);
	}
	//freopen("result.csv", "w", stdout);
	WeakClassifierFactory * factory = new WeakVectorClassifierFactory();
	for (int i = 1; i < 30; i+=2)
	{
		AdaBoost adaboost(i, factory);
		std::vector<int> outLabels;
		double accuracy = adaboost.train(data, label, outLabels);
		std::cout << i << ", " << accuracy << std::endl;
		//system("PAUSE");
	}
	cv::imshow("img", img);
	cv::waitKey();
}

void displayIntegralImage(cv::Mat Iimg)
{
	double min, max;
	cv::minMaxLoc(Iimg, &min, &max);
	Iimg -= min;
	Iimg /= (max - min);
	cv::imshow("image", Iimg);
	cv::waitKey();
}
/*
void testMatData()
{
	cv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1);
	m(cv::Rect(0, 0, 200, 200)) = 50;
	m(cv::Rect(0, 200, 200, 200)) = 200;
	m(cv::Rect(200, 0, 200, 200)) = 150;
	m(cv::Rect(200, 200, 200, 200)) = 100;
	cv::Mat Iimg, I2img;
	cv::integral(m, Iimg, I2img, CV_32FC1);
	// display
	//displayIntegralImage(Iimg);
	cv::Mat edges = AdaBoostEdgeDetector::cannyEdgeDetection(m);

	// prepare data vector
	std::vector<DataPoint*> trainData;
	std::vector<int> labels;
	cv::Mat show;
	cv::cvtColor(m, show, CV_GRAY2BGR);
	// make patches 10x10 with step 5
	for (int r = 0; r <= 390; r += 5)
	{
		for (int c = 0; c <= 390; c += 5)
		{
			cv::Rect win = cv::Rect(c, r, 10, 10);
			trainData.push_back(new MatData(Iimg, win));
			//MatData testData(m, win);
			//cv::imshow("window", testData.getMatData());
			//cv::waitKey();
			if (cv::sum(edges(win)).val[0] > 1)
			{
				// edge
				labels.push_back(1);
				cv::rectangle(show, win, cv::Scalar(255, 0, 0));
			}
			else
			{
				// non edge
				labels.push_back(-1);
			}
		}
	}

	cv::imshow("my edges", show);
	cv::waitKey(50);

	// prepare the Haar Classifier Factory
	std::vector<std::vector<std::vector<int> > > shapes;
	int arr[] = { -1,1 };
	std::vector<std::vector<int> > shape1(2,std::vector<int>(1,1));
	shape1[0][0] = -1;
	std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1));
	shape2[0][0] = shape2[1][1] = -1;

	shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2)));
	shapes.push_back(shape1);
	//shapes.push_back(shape2);

	std::vector<cv::Point> locs(1, cv::Point(0, 0));
	std::vector<cv::Size> sizes;
	sizes.push_back(cv::Size(5, 10));
	sizes.push_back(cv::Size(10, 5));
	//sizes.push_back(cv::Size(5, 5));

	for (int i = 1; i < 30; i ++)
	{
		WeakClassifierFactory * factory = new WeakHaarClassifierFactory(shapes, sizes, locs);

		AdaBoost adaboost(i, factory);
		std::vector<int> y;
		double accuracy = adaboost.train(trainData, labels, y);
		std::cout << i << ", " << accuracy << std::endl;
		cv::Mat show1;
		show.copyTo(show1);
		for (int j = 0; j < y.size(); j++)
		{
			if (y[j] == 1)
			{
				if (labels[j] == 1)
				{
					cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 255, 0));
				}
				else
				{
					cv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 0, 255));
				}
			}
		}
		cv::imshow("my edges", show1);
		cv::waitKey(0);
		//system("PAUSE");
	}
}
*/
void testAdaBoostEdgeDetection(int horizontal = 1, int vertical = 1, int t = 6, std::string trainImg = "orig.png",std::string testImage = "test.png")
{
	cv::Mat testImg = cv::imread(testImage, 0);

	cv::Mat m = cv::imread(trainImg, 0);
	std::vector<cv::Mat> images;
	images.push_back(m);

	std::vector<std::vector<std::vector<int> > > shapes;
	int arr[] = { -1,1 };
	std::vector<std::vector<int> > shape1(2, std::vector<int>(1, 1));
	shape1[0][0] = -1;
	std::vector<std::vector<int> > shape2(2, std::vector<int>(2, 1));
	shape2[0][0] = shape2[1][1] = -1;

	if (horizontal)
	{
		shapes.push_back(std::vector<std::vector<int> >(1, std::vector<int>(arr, arr + 2)));
	}
	if (vertical)
	{
		shapes.push_back(shape1);
	}
	//shapes.push_back(shape2);

	//for (int t = 1; t < 20; t++)
	{
		AdaBoostEdgeDetector adaBoostEdgeDetector(t, shapes, cv::Size(4,4), 2);
		adaBoostEdgeDetector.train(images, true);
		adaBoostEdgeDetector.test(testImg, true);
	}

}

int main(int argc, char*argv[])
{
	int horizontal = 1;
	int vertical = 1;
	int t = 6;
	std::string trainImg = "orig.png";
	std::string testImage = "test.png";
	for (int i = 0; i < argc; i++)
	{
		if (std::string(argv[i]) == "-h")
		{
			horizontal = std::stoi(argv[i + 1]);
		}
		else if (std::string(argv[i]) == "-v")
		{
			vertical = std::stoi(argv[i + 1]);
		}
		else if (std::string(argv[i]) == "-t")
		{
			t = std::stoi(argv[i + 1]);
		}
		else if (std::string(argv[i]) == "-i")
		{
			trainImg = argv[i + 1];
		}
		else if (std::string(argv[i]) == "-o")
		{
			testImage = argv[i + 1];
		}
		else
		{
			i--;
		}
		i++;
	}
	//test2DPoints();
	//testMatData();
	testAdaBoostEdgeDetection(horizontal,vertical,t,trainImg,testImage);
	return 0;
}<|endoftext|>


<commit_before>// FROM: http://playground.arduino.cc/Code/EEPROMLoadAndSaveSettings

/* LoadAndSaveSettings
 * footswitch 2012-03-05, original code by Joghurt (2010)
 * Demonstrates how to load and save settings to the EEPROM
 * Tested on Arduino Uno R2 with Arduino 0023
 */
// Contains EEPROM.read() and EEPROM.write()
#include <EEPROM.h>
#include <Arduino.h>
#include "Settings.h"

#define MAD_SETTINGS_LOGGING 1

StoreStruct my_settings = {
  // The default values
  0.2f,
  -0.25f,
  // 220, 1884,
  // 'c',
  // 10000,
  // {4.5, 5.5, 7, 8.5, 10, 12},
  CONFIG_VERSION
};

bool my_settings_loaded = false;

void loadConfig() {
  // To make sure there are settings, and they are YOURS!
  // If nothing is found it will use the default settings.
  if (//EEPROM.read(CONFIG_START + sizeof(settings) - 1) == settings.version_of_program[3] // this is '\0'
      EEPROM.read(CONFIG_START + sizeof(my_settings) - 2) == my_settings.version_of_program[2] &&
      EEPROM.read(CONFIG_START + sizeof(my_settings) - 3) == my_settings.version_of_program[1] &&
      EEPROM.read(CONFIG_START + sizeof(my_settings) - 4) == my_settings.version_of_program[0])
  { // reads settings from EEPROM
    for (unsigned int t=0; t<sizeof(my_settings); t++) {
      *((char*)&my_settings + t) = EEPROM.read(CONFIG_START + t);
    }

    #if MAD_SETTINGS_LOGGING
    // error writing to EEPROM
    Serial.println("[SETTINGS] Loaded!");
    #endif

    my_settings_loaded = true;

  } else {
    // settings aren't valid! will overwrite with default settings
    saveConfig();
  }
}

void saveConfig() {
  for (unsigned int t=0; t<sizeof(my_settings); t++)
  {
    // writes to EEPROM
    EEPROM.write(CONFIG_START + t, *((char*)&my_settings + t));
    // and verifies the data
    if (EEPROM.read(CONFIG_START + t) != *((char*)&my_settings + t))
    {
      #if MAD_SETTINGS_LOGGING
      // error writing to EEPROM
      Serial.println("[SETTINGS] Write Error");
      #endif
    } else {

      #if MAD_SETTINGS_LOGGING
      // error writing to EEPROM
      Serial.println("[SETTINGS] Write Success!");
      #endif
    }
  }
}

// void setup() {
//   loadConfig();
// }

// void loop() {
//   // [...]
//   int i = settings.c - 'a';
//   // [...]

//   // [...]
//   settings.c = 'a';
//   if (some_condition)
//     saveConfig();
//   // [...]
// }
// [Get Code]
<commit_msg>minor<commit_after>// FROM: http://playground.arduino.cc/Code/EEPROMLoadAndSaveSettings

/* LoadAndSaveSettings
 * footswitch 2012-03-05, original code by Joghurt (2010)
 * Demonstrates how to load and save settings to the EEPROM
 * Tested on Arduino Uno R2 with Arduino 0023
 */
// Contains EEPROM.read() and EEPROM.write()
#include <EEPROM.h>
#include <Arduino.h>
#include "Settings.h"

#define MAD_SETTINGS_LOGGING 1

StoreStruct my_settings = {
  // The default values
  0.2f,
  -0.25f,
  // 220, 1884,
  // 'c',
  // 10000,
  // {4.5, 5.5, 7, 8.5, 10, 12},
  CONFIG_VERSION
};

bool my_settings_loaded = false;

void loadConfig() {
  // To make sure there are settings, and they are YOURS!
  // If nothing is found it will use the default settings.
  if (//EEPROM.read(CONFIG_START + sizeof(settings) - 1) == settings.version_of_program[3] // this is '\0'
      EEPROM.read(CONFIG_START + sizeof(my_settings) - 2) == my_settings.version_of_program[2] &&
      EEPROM.read(CONFIG_START + sizeof(my_settings) - 3) == my_settings.version_of_program[1] &&
      EEPROM.read(CONFIG_START + sizeof(my_settings) - 4) == my_settings.version_of_program[0])
  { // reads settings from EEPROM
    for (unsigned int t=0; t<sizeof(my_settings); t++) {
      *((char*)&my_settings + t) = EEPROM.read(CONFIG_START + t);
    }

    #if MAD_SETTINGS_LOGGING
    // error writing to EEPROM
    Serial.print("[SETTINGS] Loaded!  Float Value="); Serial.print(my_settings.accelerometer_angle_positive); Serial.println("!");
    #endif

    my_settings_loaded = true;

  } else {
    // settings aren't valid! will overwrite with default settings
    saveConfig();
  }
}

void saveConfig() {
  for (unsigned int t=0; t<sizeof(my_settings); t++)
  {
    // writes to EEPROM
    EEPROM.write(CONFIG_START + t, *((char*)&my_settings + t));
    // and verifies the data
    if (EEPROM.read(CONFIG_START + t) != *((char*)&my_settings + t))
    {
      #if MAD_SETTINGS_LOGGING
      // error writing to EEPROM
      Serial.println("[SETTINGS] Write Error");
      #endif
    } else {

      #if MAD_SETTINGS_LOGGING
      // error writing to EEPROM
      Serial.println("[SETTINGS] Write Success!");
      #endif
    }
  }
}

// void setup() {
//   loadConfig();
// }

// void loop() {
//   // [...]
//   int i = settings.c - 'a';
//   // [...]

//   // [...]
//   settings.c = 'a';
//   if (some_condition)
//     saveConfig();
//   // [...]
// }
// [Get Code]
<|endoftext|>


<commit_before><commit_msg>Replace fedpeg template init check for pak one<commit_after><|endoftext|>


<commit_before>#pragma once

#include <string>
#include <stdexcept>

#include <clang-c/Index.h>

namespace color_coded
{
  namespace clang
  {
    namespace token
    {
      inline std::string map_type_kind(CXTypeKind const kind)
      {
        switch(kind)
        {
          case CXType_Unexposed:
            return "Variable";

          case CXType_Void:
          case CXType_Bool:
          case CXType_Char_U:
          case CXType_UChar:
          case CXType_Char16:
          case CXType_Char32:
          case CXType_UShort:
          case CXType_UInt:
          case CXType_ULong:
          case CXType_ULongLong:
          case CXType_UInt128:
          case CXType_Char_S:
          case CXType_SChar:
          case CXType_WChar:
          case CXType_Short:
          case CXType_Int:
          case CXType_Long:
          case CXType_LongLong:
          case CXType_Int128:
          case CXType_Float:
          case CXType_Double:
          case CXType_LongDouble:
          case CXType_NullPtr:
          case CXType_Overload:
          case CXType_Dependent:
          case CXType_ObjCId:
          case CXType_ObjCClass:
          case CXType_ObjCSel:
            return "Variable";

          case CXType_Complex:
          case CXType_Pointer:
          case CXType_BlockPointer:
          case CXType_LValueReference:
          case CXType_RValueReference:
          case CXType_Record:
          case CXType_Typedef:
          case CXType_ObjCInterface:
          case CXType_ObjCObjectPointer:
          case CXType_ConstantArray:
          case CXType_Vector:
          case CXType_IncompleteArray:
          case CXType_VariableArray:
          case CXType_DependentSizedArray:
            return "Variable";

          case CXType_MemberPointer:
            return "Member";

          case CXType_Enum:
            return "EnumConstant";

          case CXType_FunctionNoProto:
          case CXType_FunctionProto:
            return "Function";

          case CXType_Auto:
            return "Variable";

          default:
            return "";
            //return "Error1 " + std::to_string(kind);
        }
      }

      inline std::string map_cursor_kind(CXCursorKind const kind,
                                         CXTypeKind const type)
      {
        switch(kind)
        {
          /********* Declarations **********/
          case CXCursor_UnexposedDecl: /* Unknown declaration */
            return "";
          case CXCursor_StructDecl:
            return "StructDecl";
          case CXCursor_UnionDecl:
            return "UnionDecl";
          case CXCursor_ClassDecl:
            return "ClassDecl";
          case CXCursor_EnumDecl:
            return "EnumDecl";
          case CXCursor_FieldDecl:
            return "FieldDecl";
          case CXCursor_EnumConstantDecl:
            return "EnumConstantDecl";
          case CXCursor_FunctionDecl:
            return "FunctionDecl";
          case CXCursor_VarDecl:
            return "VarDecl";
          case CXCursor_ParmDecl:
            return "ParmDecl";
          case CXCursor_ObjCInterfaceDecl:
            return "ObjCInterfaceDecl";
          case CXCursor_ObjCCategoryDecl:
            return "ObjCCategoryDecl";
          case CXCursor_ObjCProtocolDecl:
            return "ObjCProtocolDecl";
          case CXCursor_ObjCPropertyDecl:
            return "ObjCPropertyDecl";
          case CXCursor_ObjCIvarDecl:
            return "ObjCIvarDecl";
          case CXCursor_ObjCInstanceMethodDecl:
            return "ObjCInstanceMethodDecl";
          case CXCursor_ObjCClassMethodDecl:
            return "ObjCClassMethodDecl";
          case CXCursor_ObjCImplementationDecl:
            return "ObjCImplementationDecl";
          case CXCursor_ObjCCategoryImplDecl:
            return "ObjCCategoryImplDecl";
          case CXCursor_TypedefDecl:
            return "TypedefDecl";
          case CXCursor_CXXMethod:
            return "CXXMethod";
          case CXCursor_Namespace:
            return "Namespace";
          case CXCursor_LinkageSpec:
            return "LinkageSpec";
          case CXCursor_Constructor:
            return "Constructor";
          case CXCursor_Destructor:
            return "Destructor";
          case CXCursor_ConversionFunction:
            return "ConversionFunction";
          case CXCursor_TemplateTypeParameter:
            return "TemplateTypeParameter";
          case CXCursor_NonTypeTemplateParameter:
            return "NonTypeTemplateParameter";
          case CXCursor_TemplateTemplateParameter:
            return "TemplateTemplateParameter";
          case CXCursor_FunctionTemplate:
            return "FunctionTemplate";
          case CXCursor_ClassTemplate:
            return "ClassTemplate";
          case CXCursor_ClassTemplatePartialSpecialization:
            return "ClassTemplatePartialSpecialization";
          case CXCursor_NamespaceAlias:
            return "NamespaceAlias";
          case CXCursor_UsingDirective:
            return "UsingDirective";
          case CXCursor_UsingDeclaration:
            return "UsingDeclaration";
          case CXCursor_TypeAliasDecl:
            return "TypeAliasDecl";
          case CXCursor_ObjCSynthesizeDecl:
            return "ObjCSynthesizeDecl";
          case CXCursor_ObjCDynamicDecl:
            return "ObjCDynamicDecl";
          case CXCursor_CXXAccessSpecifier:
            return "CXXAccessSpecifier";

            /********* References **********/
          case CXCursor_ObjCSuperClassRef:
            return "ObjCSuperClassRef";
          case CXCursor_ObjCProtocolRef:
            return "ObjCProtocolRef";
          case CXCursor_ObjCClassRef:
            return "ObjCClassRef";
          case CXCursor_TypeRef:
            return "TypeRef";
          case CXCursor_CXXBaseSpecifier:
            return "CXXBaseSpecifier";
          case CXCursor_TemplateRef:
            return "TemplateRef";
          case CXCursor_NamespaceRef:
            return "NamespaceRef";
          case CXCursor_MemberRef:
            return "MemberRef";
          case CXCursor_LabelRef:
            return "LabelRef";
          case CXCursor_OverloadedDeclRef:
            return "OverloadedDeclRef";
          case CXCursor_VariableRef:
            return "VariableRef";

            /********* Errors **********/
          case CXCursor_InvalidFile:
            return "";
          case CXCursor_NoDeclFound:
            return "";
          case CXCursor_NotImplemented:
            return "";
          case CXCursor_InvalidCode:
            return "";

            /********* Expressions **********/
          case CXCursor_UnexposedExpr:
            break;
          case CXCursor_DeclRefExpr:
            return map_type_kind(type);
          case CXCursor_MemberRefExpr:
            return "MemberRefExpr";
          case CXCursor_CallExpr:
            return "CallExpr";
          case CXCursor_ObjCMessageExpr:
            return "ObjCMessageExpr";
          case CXCursor_BlockExpr:
            return "BlockExpr";
          case CXCursor_MacroDefinition:
            return "MacroDefinition";
          case CXCursor_MacroInstantiation:
            return "MacroInstantiation";
          case CXCursor_PreprocessingDirective: /* XXX: do not want */
            return "";
          case CXCursor_InclusionDirective: /* XXX: do not want */
            return "";
          case CXCursor_CompoundStmt:
            return "";
          case CXCursor_ParenExpr:
          case CXCursor_LambdaExpr:
          case CXCursor_CXXForRangeStmt:
          case CXCursor_DeclStmt:
            return "";
          default:
            return "";
            //return "Error2 " + std::to_string(kind);
        }
        return "";
        //return "Error3 " + std::to_string(kind);
      }

      inline std::string map_literal_kind(CXCursorKind const kind)
      {
        switch(kind)
        {
          case CXCursor_IntegerLiteral:
            return "Number";
          case CXCursor_FloatingLiteral:
            return "Float";
          case CXCursor_ImaginaryLiteral:
            return "Number";
          case CXCursor_StringLiteral:
            return ""; /* Allow vim to do this. */
          case CXCursor_CharacterLiteral:
            return "Character";
          case CXType_Unexposed:
            return "";
          default:
            return "";
            //return "Error4 " + std::to_string(kind);
        }
      }

      /* Clang token/cursor -> Vim highlight group. */
      inline std::string map_token_kind(CXTokenKind const token_kind,
          CXCursorKind const cursor_kind,
          CXTypeKind const cursor_type)
      {
        switch (token_kind)
        {
          case CXToken_Punctuation:
            return ""; /* Allow vim to do this. */
          case CXToken_Keyword:
            return ""; /* Allow vim to do this. */
          case CXToken_Identifier:
            return map_cursor_kind(cursor_kind, cursor_type);
          case CXToken_Literal:
            return map_literal_kind(cursor_kind);
          case CXToken_Comment:
            return ""; /* Allow vim to do this. */
          default:
            return "";
            //return "Error5 " + std::to_string(token_kind);
        }
      }
    }
  }
}
<commit_msg>Preserve compatibility with clang 3.6<commit_after>#pragma once

#include <string>
#include <stdexcept>

#include <clang-c/Index.h>

namespace color_coded
{
  namespace clang
  {
    namespace token
    {
      inline std::string map_type_kind(CXTypeKind const kind)
      {
        switch(kind)
        {
          case CXType_Unexposed:
            return "Variable";

          case CXType_Void:
          case CXType_Bool:
          case CXType_Char_U:
          case CXType_UChar:
          case CXType_Char16:
          case CXType_Char32:
          case CXType_UShort:
          case CXType_UInt:
          case CXType_ULong:
          case CXType_ULongLong:
          case CXType_UInt128:
          case CXType_Char_S:
          case CXType_SChar:
          case CXType_WChar:
          case CXType_Short:
          case CXType_Int:
          case CXType_Long:
          case CXType_LongLong:
          case CXType_Int128:
          case CXType_Float:
          case CXType_Double:
          case CXType_LongDouble:
          case CXType_NullPtr:
          case CXType_Overload:
          case CXType_Dependent:
          case CXType_ObjCId:
          case CXType_ObjCClass:
          case CXType_ObjCSel:
            return "Variable";

          case CXType_Complex:
          case CXType_Pointer:
          case CXType_BlockPointer:
          case CXType_LValueReference:
          case CXType_RValueReference:
          case CXType_Record:
          case CXType_Typedef:
          case CXType_ObjCInterface:
          case CXType_ObjCObjectPointer:
          case CXType_ConstantArray:
          case CXType_Vector:
          case CXType_IncompleteArray:
          case CXType_VariableArray:
          case CXType_DependentSizedArray:
            return "Variable";

          case CXType_MemberPointer:
            return "Member";

          case CXType_Enum:
            return "EnumConstant";

          case CXType_FunctionNoProto:
          case CXType_FunctionProto:
            return "Function";
#if CINDEX_VERSION_MINOR >= 32
          case CXType_Auto:
            return "Variable";
#endif
          default:
            return "";
            //return "Error1 " + std::to_string(kind);
        }
      }

      inline std::string map_cursor_kind(CXCursorKind const kind,
                                         CXTypeKind const type)
      {
        switch(kind)
        {
          /********* Declarations **********/
          case CXCursor_UnexposedDecl: /* Unknown declaration */
            return "";
          case CXCursor_StructDecl:
            return "StructDecl";
          case CXCursor_UnionDecl:
            return "UnionDecl";
          case CXCursor_ClassDecl:
            return "ClassDecl";
          case CXCursor_EnumDecl:
            return "EnumDecl";
          case CXCursor_FieldDecl:
            return "FieldDecl";
          case CXCursor_EnumConstantDecl:
            return "EnumConstantDecl";
          case CXCursor_FunctionDecl:
            return "FunctionDecl";
          case CXCursor_VarDecl:
            return "VarDecl";
          case CXCursor_ParmDecl:
            return "ParmDecl";
          case CXCursor_ObjCInterfaceDecl:
            return "ObjCInterfaceDecl";
          case CXCursor_ObjCCategoryDecl:
            return "ObjCCategoryDecl";
          case CXCursor_ObjCProtocolDecl:
            return "ObjCProtocolDecl";
          case CXCursor_ObjCPropertyDecl:
            return "ObjCPropertyDecl";
          case CXCursor_ObjCIvarDecl:
            return "ObjCIvarDecl";
          case CXCursor_ObjCInstanceMethodDecl:
            return "ObjCInstanceMethodDecl";
          case CXCursor_ObjCClassMethodDecl:
            return "ObjCClassMethodDecl";
          case CXCursor_ObjCImplementationDecl:
            return "ObjCImplementationDecl";
          case CXCursor_ObjCCategoryImplDecl:
            return "ObjCCategoryImplDecl";
          case CXCursor_TypedefDecl:
            return "TypedefDecl";
          case CXCursor_CXXMethod:
            return "CXXMethod";
          case CXCursor_Namespace:
            return "Namespace";
          case CXCursor_LinkageSpec:
            return "LinkageSpec";
          case CXCursor_Constructor:
            return "Constructor";
          case CXCursor_Destructor:
            return "Destructor";
          case CXCursor_ConversionFunction:
            return "ConversionFunction";
          case CXCursor_TemplateTypeParameter:
            return "TemplateTypeParameter";
          case CXCursor_NonTypeTemplateParameter:
            return "NonTypeTemplateParameter";
          case CXCursor_TemplateTemplateParameter:
            return "TemplateTemplateParameter";
          case CXCursor_FunctionTemplate:
            return "FunctionTemplate";
          case CXCursor_ClassTemplate:
            return "ClassTemplate";
          case CXCursor_ClassTemplatePartialSpecialization:
            return "ClassTemplatePartialSpecialization";
          case CXCursor_NamespaceAlias:
            return "NamespaceAlias";
          case CXCursor_UsingDirective:
            return "UsingDirective";
          case CXCursor_UsingDeclaration:
            return "UsingDeclaration";
          case CXCursor_TypeAliasDecl:
            return "TypeAliasDecl";
          case CXCursor_ObjCSynthesizeDecl:
            return "ObjCSynthesizeDecl";
          case CXCursor_ObjCDynamicDecl:
            return "ObjCDynamicDecl";
          case CXCursor_CXXAccessSpecifier:
            return "CXXAccessSpecifier";

            /********* References **********/
          case CXCursor_ObjCSuperClassRef:
            return "ObjCSuperClassRef";
          case CXCursor_ObjCProtocolRef:
            return "ObjCProtocolRef";
          case CXCursor_ObjCClassRef:
            return "ObjCClassRef";
          case CXCursor_TypeRef:
            return "TypeRef";
          case CXCursor_CXXBaseSpecifier:
            return "CXXBaseSpecifier";
          case CXCursor_TemplateRef:
            return "TemplateRef";
          case CXCursor_NamespaceRef:
            return "NamespaceRef";
          case CXCursor_MemberRef:
            return "MemberRef";
          case CXCursor_LabelRef:
            return "LabelRef";
          case CXCursor_OverloadedDeclRef:
            return "OverloadedDeclRef";
          case CXCursor_VariableRef:
            return "VariableRef";

            /********* Errors **********/
          case CXCursor_InvalidFile:
            return "";
          case CXCursor_NoDeclFound:
            return "";
          case CXCursor_NotImplemented:
            return "";
          case CXCursor_InvalidCode:
            return "";

            /********* Expressions **********/
          case CXCursor_UnexposedExpr:
            break;
          case CXCursor_DeclRefExpr:
            return map_type_kind(type);
          case CXCursor_MemberRefExpr:
            return "MemberRefExpr";
          case CXCursor_CallExpr:
            return "CallExpr";
          case CXCursor_ObjCMessageExpr:
            return "ObjCMessageExpr";
          case CXCursor_BlockExpr:
            return "BlockExpr";
          case CXCursor_MacroDefinition:
            return "MacroDefinition";
          case CXCursor_MacroInstantiation:
            return "MacroInstantiation";
          case CXCursor_PreprocessingDirective: /* XXX: do not want */
            return "";
          case CXCursor_InclusionDirective: /* XXX: do not want */
            return "";
          case CXCursor_CompoundStmt:
            return "";
          case CXCursor_ParenExpr:
          case CXCursor_LambdaExpr:
          case CXCursor_CXXForRangeStmt:
          case CXCursor_DeclStmt:
            return "";
          default:
            return "";
            //return "Error2 " + std::to_string(kind);
        }
        return "";
        //return "Error3 " + std::to_string(kind);
      }

      inline std::string map_literal_kind(CXCursorKind const kind)
      {
        switch(kind)
        {
          case CXCursor_IntegerLiteral:
            return "Number";
          case CXCursor_FloatingLiteral:
            return "Float";
          case CXCursor_ImaginaryLiteral:
            return "Number";
          case CXCursor_StringLiteral:
            return ""; /* Allow vim to do this. */
          case CXCursor_CharacterLiteral:
            return "Character";
          case CXType_Unexposed:
            return "";
          default:
            return "";
            //return "Error4 " + std::to_string(kind);
        }
      }

      /* Clang token/cursor -> Vim highlight group. */
      inline std::string map_token_kind(CXTokenKind const token_kind,
          CXCursorKind const cursor_kind,
          CXTypeKind const cursor_type)
      {
        switch (token_kind)
        {
          case CXToken_Punctuation:
            return ""; /* Allow vim to do this. */
          case CXToken_Keyword:
            return ""; /* Allow vim to do this. */
          case CXToken_Identifier:
            return map_cursor_kind(cursor_kind, cursor_type);
          case CXToken_Literal:
            return map_literal_kind(cursor_kind);
          case CXToken_Comment:
            return ""; /* Allow vim to do this. */
          default:
            return "";
            //return "Error5 " + std::to_string(token_kind);
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 <memory>

#include "SurgSim/Blocks/BasicSceneElement.h"
#include "SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h"
#include "SurgSim/Framework/BehaviorManager.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgManager.h"
#include "SurgSim/Graphics/OsgPointCloudRepresentation.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgViewElement.h"
#include "SurgSim/Graphics/PointCloudRepresentation.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/Fem1DRepresentation.h"
#include "SurgSim/Physics/FemElement1DBeam.h"
#include "SurgSim/Physics/PhysicsManager.h"

using SurgSim::Blocks::BasicSceneElement;
using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior;
using SurgSim::Framework::SceneElement;
using SurgSim::Graphics::OsgPointCloudRepresentation;
using SurgSim::Math::Vector3d;
using SurgSim::Physics::DeformableRepresentationState;
using SurgSim::Physics::Fem1DRepresentation;
using SurgSim::Physics::FemElement1DBeam;
using SurgSim::Physics::PhysicsManager;

///\file Example of how to put together a very simple demo of Fem1D

namespace
{

void loadModelFem1D(std::shared_ptr<Fem1DRepresentation> physicsRepresentation, unsigned int numNodes)
{
	std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>();
	restState->setNumDof(physicsRepresentation->getNumDofPerNode(), numNodes);

	// Sets the initial state (node positions and boundary conditions)
	SurgSim::Math::Vector& x = restState->getPositions();
	for (unsigned int nodeId = 0; nodeId < numNodes; nodeId++)
	{
		SurgSim::Math::getSubVector(x, nodeId, physicsRepresentation->getNumDofPerNode()).segment<3>(0)
			= Vector3d(static_cast<double>(nodeId) / static_cast<double>(numNodes), 0.0, 0.0);
	}

	// Fix the start and end nodes
	restState->addBoundaryCondition(0 + 0);
	restState->addBoundaryCondition(0 + 1);
	restState->addBoundaryCondition(0 + 2);
	restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 0);
	restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 1);
	restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 2);

	physicsRepresentation->setInitialState(restState);

	// Adds all the FemElements
	for (unsigned int beamId = 0; beamId < numNodes - 1; beamId++)
	{
		std::array<unsigned int, 2> beamNodeIds = {{beamId, beamId + 1}};
		std::shared_ptr<FemElement1DBeam> beam = std::make_shared<FemElement1DBeam>(beamNodeIds);
		beam->setRadius(0.10);
		beam->setMassDensity(3000.0);
		beam->setPoissonRatio(0.45);
		beam->setYoungModulus(1e6);
		physicsRepresentation->addFemElement(beam);
	}
}

std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height)
{
	using SurgSim::Graphics::OsgViewElement;

	std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name);
	viewElement->getView()->setPosition(x, y);
	viewElement->getView()->setDimensions(width, height);

	return viewElement;
}

// Generates a 1d fem comprised of adjacent elements along a straight line.  The number of fem elements is determined
// by loadModelFem1D.
std::shared_ptr<SceneElement> createFem1D(const std::string& name,
										  const SurgSim::Math::RigidTransform3d& gfxPose,
										  const SurgSim::Math::Vector4d& color,
										  SurgSim::Math::IntegrationScheme integrationScheme)
{
	std::shared_ptr<Fem1DRepresentation> physicsRepresentation
		= std::make_shared<Fem1DRepresentation>("Physics Representation: " + name);

	// In this example, the physics representations are not transformed, only the graphics will be transformed
	loadModelFem1D(physicsRepresentation, 10);

	physicsRepresentation->setIntegrationScheme(integrationScheme);
	physicsRepresentation->setRayleighDampingMass(5e-2);
	physicsRepresentation->setRayleighDampingStiffness(5e-3);

	std::shared_ptr<BasicSceneElement> femSceneElement = std::make_shared<BasicSceneElement>(name);
	femSceneElement->addComponent(physicsRepresentation);

	std::shared_ptr<SurgSim::Graphics::PointCloudRepresentation<void>> graphicsRepresentation
		= std::make_shared<OsgPointCloudRepresentation<void>>("Graphics Representation: " + name);
	graphicsRepresentation->setInitialPose(gfxPose);
	graphicsRepresentation->setColor(color);
	graphicsRepresentation->setPointSize(3.0f);
	graphicsRepresentation->setVisible(true);

	femSceneElement->addComponent(graphicsRepresentation);

	femSceneElement->addComponent(
		std::make_shared<TransferDeformableStateToVerticesBehavior<void>>("Transfer from Physics to Graphics: " + name,
																		  physicsRepresentation->getFinalState(),
																		  graphicsRepresentation->getVertices()));

	return femSceneElement;
}

} // anonymous namespace

int main(int argc, char* argv[])
{
	using SurgSim::Math::makeRigidTransform;
	using SurgSim::Math::Vector4d;

	std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>();
	std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>();
	std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager
		= std::make_shared<SurgSim::Framework::BehaviorManager>();
	std::shared_ptr<SurgSim::Framework::Runtime> runtime = std::make_shared<SurgSim::Framework::Runtime>();

	runtime->addManager(physicsManager);
	runtime->addManager(graphicsManager);
	runtime->addManager(behaviorManager);

	std::shared_ptr<SurgSim::Graphics::OsgCamera> camera = graphicsManager->getDefaultCamera();
	std::shared_ptr<SurgSim::Framework::Scene> scene = runtime->getScene();

	const SurgSim::Math::Quaterniond quaternionIdentity = SurgSim::Math::Quaterniond::Identity();

	scene->addSceneElement(
		createFem1D("Euler Explicit",                                                  // name
					makeRigidTransform(quaternionIdentity, Vector3d(-3.5, 0.5, -3.0)), // graphics pose (rot., trans.)
					Vector4d(1, 0, 0, 1),                                              // color (r, g, b, a)
					SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER));                 // technique to update object

	scene->addSceneElement(
		createFem1D("Modified Euler Explicit",
					makeRigidTransform(quaternionIdentity, Vector3d(-0.5, 0.5, -3.0)),
					Vector4d(0, 1, 0, 1),
					SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));

	scene->addSceneElement(
		createFem1D("Euler Implicit",
					makeRigidTransform(quaternionIdentity, Vector3d(2.5, 0.5, -3.0)),
					Vector4d(0, 0, 1, 1),
					SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));

	scene->addSceneElement(createView("view1", 0, 0, 1023, 768));

	camera->setInitialPose(SurgSim::Math::makeRigidTransform(quaternionIdentity, Vector3d(0.0, 0.5, 5.0)));

	runtime->execute();

	return 0;
}
<commit_msg>Minor fix fem1d example, reduce visual spacing<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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 <memory>

#include "SurgSim/Blocks/BasicSceneElement.h"
#include "SurgSim/Blocks/TransferDeformableStateToVerticesBehavior.h"
#include "SurgSim/Framework/BehaviorManager.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Scene.h"
#include "SurgSim/Framework/SceneElement.h"
#include "SurgSim/Graphics/OsgCamera.h"
#include "SurgSim/Graphics/OsgManager.h"
#include "SurgSim/Graphics/OsgPointCloudRepresentation.h"
#include "SurgSim/Graphics/OsgView.h"
#include "SurgSim/Graphics/OsgViewElement.h"
#include "SurgSim/Graphics/PointCloudRepresentation.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/Fem1DRepresentation.h"
#include "SurgSim/Physics/FemElement1DBeam.h"
#include "SurgSim/Physics/PhysicsManager.h"

using SurgSim::Blocks::BasicSceneElement;
using SurgSim::Blocks::TransferDeformableStateToVerticesBehavior;
using SurgSim::Framework::SceneElement;
using SurgSim::Graphics::OsgPointCloudRepresentation;
using SurgSim::Math::Vector3d;
using SurgSim::Physics::DeformableRepresentationState;
using SurgSim::Physics::Fem1DRepresentation;
using SurgSim::Physics::FemElement1DBeam;
using SurgSim::Physics::PhysicsManager;

///\file Example of how to put together a very simple demo of Fem1D

namespace
{

void loadModelFem1D(std::shared_ptr<Fem1DRepresentation> physicsRepresentation, unsigned int numNodes)
{
	std::shared_ptr<DeformableRepresentationState> restState = std::make_shared<DeformableRepresentationState>();
	restState->setNumDof(physicsRepresentation->getNumDofPerNode(), numNodes);

	// Sets the initial state (node positions and boundary conditions)
	SurgSim::Math::Vector& x = restState->getPositions();
	for (unsigned int nodeId = 0; nodeId < numNodes; nodeId++)
	{
		SurgSim::Math::getSubVector(x, nodeId, physicsRepresentation->getNumDofPerNode()).segment<3>(0)
			= Vector3d(static_cast<double>(nodeId) / static_cast<double>(numNodes), 0.0, 0.0);
	}

	// Fix the start and end nodes
	restState->addBoundaryCondition(0 + 0);
	restState->addBoundaryCondition(0 + 1);
	restState->addBoundaryCondition(0 + 2);
	restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 0);
	restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 1);
	restState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 2);

	physicsRepresentation->setInitialState(restState);

	// Adds all the FemElements
	for (unsigned int beamId = 0; beamId < numNodes - 1; beamId++)
	{
		std::array<unsigned int, 2> beamNodeIds = {{beamId, beamId + 1}};
		std::shared_ptr<FemElement1DBeam> beam = std::make_shared<FemElement1DBeam>(beamNodeIds);
		beam->setRadius(0.10);
		beam->setMassDensity(3000.0);
		beam->setPoissonRatio(0.45);
		beam->setYoungModulus(1e6);
		physicsRepresentation->addFemElement(beam);
	}
}

std::shared_ptr<SurgSim::Graphics::ViewElement> createView(const std::string& name, int x, int y, int width, int height)
{
	using SurgSim::Graphics::OsgViewElement;

	std::shared_ptr<OsgViewElement> viewElement = std::make_shared<OsgViewElement>(name);
	viewElement->getView()->setPosition(x, y);
	viewElement->getView()->setDimensions(width, height);

	return viewElement;
}

// Generates a 1d fem comprised of adjacent elements along a straight line.  The number of fem elements is determined
// by loadModelFem1D.
std::shared_ptr<SceneElement> createFem1D(const std::string& name,
										  const SurgSim::Math::RigidTransform3d& gfxPose,
										  const SurgSim::Math::Vector4d& color,
										  SurgSim::Math::IntegrationScheme integrationScheme)
{
	std::shared_ptr<Fem1DRepresentation> physicsRepresentation
		= std::make_shared<Fem1DRepresentation>("Physics Representation: " + name);

	// In this example, the physics representations are not transformed, only the graphics will be transformed
	loadModelFem1D(physicsRepresentation, 10);

	physicsRepresentation->setIntegrationScheme(integrationScheme);
	physicsRepresentation->setRayleighDampingMass(5e-2);
	physicsRepresentation->setRayleighDampingStiffness(5e-3);

	std::shared_ptr<BasicSceneElement> femSceneElement = std::make_shared<BasicSceneElement>(name);
	femSceneElement->addComponent(physicsRepresentation);

	std::shared_ptr<SurgSim::Graphics::PointCloudRepresentation<void>> graphicsRepresentation
		= std::make_shared<OsgPointCloudRepresentation<void>>("Graphics Representation: " + name);
	graphicsRepresentation->setInitialPose(gfxPose);
	graphicsRepresentation->setColor(color);
	graphicsRepresentation->setPointSize(3.0f);
	graphicsRepresentation->setVisible(true);

	femSceneElement->addComponent(graphicsRepresentation);

	femSceneElement->addComponent(
		std::make_shared<TransferDeformableStateToVerticesBehavior<void>>("Transfer from Physics to Graphics: " + name,
																		  physicsRepresentation->getFinalState(),
																		  graphicsRepresentation->getVertices()));

	return femSceneElement;
}

} // anonymous namespace

int main(int argc, char* argv[])
{
	using SurgSim::Math::makeRigidTransform;
	using SurgSim::Math::Vector4d;

	std::shared_ptr<SurgSim::Graphics::OsgManager> graphicsManager = std::make_shared<SurgSim::Graphics::OsgManager>();
	std::shared_ptr<PhysicsManager> physicsManager = std::make_shared<PhysicsManager>();
	std::shared_ptr<SurgSim::Framework::BehaviorManager> behaviorManager
		= std::make_shared<SurgSim::Framework::BehaviorManager>();
	std::shared_ptr<SurgSim::Framework::Runtime> runtime = std::make_shared<SurgSim::Framework::Runtime>();

	runtime->addManager(physicsManager);
	runtime->addManager(graphicsManager);
	runtime->addManager(behaviorManager);

	std::shared_ptr<SurgSim::Graphics::OsgCamera> camera = graphicsManager->getDefaultCamera();
	std::shared_ptr<SurgSim::Framework::Scene> scene = runtime->getScene();

	const SurgSim::Math::Quaterniond quaternionIdentity = SurgSim::Math::Quaterniond::Identity();

	scene->addSceneElement(
		createFem1D("Euler Explicit",                                                  // name
					makeRigidTransform(quaternionIdentity, Vector3d(-3.0, 0.5, -3.0)), // graphics pose (rot., trans.)
					Vector4d(1, 0, 0, 1),                                              // color (r, g, b, a)
					SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER));                 // technique to update object

	scene->addSceneElement(
		createFem1D("Modified Euler Explicit",
					makeRigidTransform(quaternionIdentity, Vector3d(-0.5, 0.5, -3.0)),
					Vector4d(0, 1, 0, 1),
					SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));

	scene->addSceneElement(
		createFem1D("Euler Implicit",
					makeRigidTransform(quaternionIdentity, Vector3d(2.0, 0.5, -3.0)),
					Vector4d(0, 0, 1, 1),
					SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));

	scene->addSceneElement(createView("view1", 0, 0, 1023, 768));

	camera->setInitialPose(SurgSim::Math::makeRigidTransform(quaternionIdentity, Vector3d(0.0, 0.5, 5.0)));

	runtime->execute();

	return 0;
}
<|endoftext|>


<commit_before>// Halide tutorial lesson 16: RGB images and memory layouts part 1

// This lesson demonstrates how to feed Halide RGB images in
// interleaved or planar format, and how to write code optimized for
// each case.

// On linux or os x, you can compile and run it like so:

// g++ lesson_16_rgb_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_16_generate
// export LD_LIBRARY_PATH=../bin   # For linux
// export DYLD_LIBRARY_PATH=../bin # For OS X
// ./lesson_16_generate -o . -f brighten_planar      target=host layout=planar
// ./lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved
// ./lesson_16_generate -o . -f brighten_either      target=host layout=either
// ./lesson_16_generate -o . -f brighten_specialized target=host layout=specialized
// g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run
// ./lesson_16_run

// If you have the entire Halide source tree, you can also build it by
// running:
//    make tutorial_lesson_16_rgb_run
// in a shell with the current directory at the top of the halide
// source tree.

#include "Halide.h"
#include <stdio.h>

using namespace Halide;

// We will define a generator that brightens an RGB image.
class Brighten : public Halide::Generator<Brighten> {
public:
    // We declare a three-dimensional input image. The first two
    // dimensions will be x, and y, and the third dimension will be
    // the color channel.
    ImageParam input{UInt(8), 3, "input"};

    // We will compile this generator in several ways to accept
    // several different memory layouts for the input and output. This
    // is a good use of a GeneratorParam (see lesson 15).
    enum class Layout { Planar, Interleaved, Either, Specialized };
    GeneratorParam<Layout> layout{"layout",
            // default value
            Layout::Planar,
            // map from names to values
                {{ "planar",        Layout::Planar },
                 { "interleaved",   Layout::Interleaved },
                 { "either",        Layout::Either },
                 { "specialized",   Layout::Specialized }}};

    // We also declare a scalar parameter to control the amount of
    // brightening.
    Param<uint8_t> offset{"offset"};

    // Declare our Vars
    Var x, y, c;

    Func build() {
        // Define the Func.
        Func brighter("brighter");
        brighter(x, y, c) = input(x, y, c) + offset;

        // Schedule it.
        brighter.vectorize(x, 16);

        // We will compile this pipeline to handle memory layouts in
        // several different ways, depending on the 'layout' generator
        // param.
        if (layout == Layout::Planar) {
            // This pipeline as written will only work with images in
            // which each scanline is densely-packed single color
            // channel. In terms of the strides described in lesson
            // 10, Halide assumes and asserts that the stride in x is
            // one.

            // This constraint permits planar images, where the red,
            // green, and blue channels are laid out in memory like
            // this:

            // RRRRRRRR
            // RRRRRRRR
            // RRRRRRRR
            // RRRRRRRR
            // GGGGGGGG
            // GGGGGGGG
            // GGGGGGGG
            // GGGGGGGG
            // BBBBBBBB
            // BBBBBBBB
            // BBBBBBBB
            // BBBBBBBB

            // It also works with the less-commonly used line-by-line
            // layout, in which scanlines of red, green, and blue
            // alternate.

            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB
            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB
            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB
            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB

        } else if (layout == Layout::Interleaved) {
            // Another common format is 'interleaved', in which the
            // red, green, and blue values for each pixel occur next
            // to each other in memory:

            // RGBRGBRGBRGBRGBRGBRGBRGB
            // RGBRGBRGBRGBRGBRGBRGBRGB
            // RGBRGBRGBRGBRGBRGBRGBRGB
            // RGBRGBRGBRGBRGBRGBRGBRGB

            // In this case the stride in x is three, the stride in y
            // is three times the width of the image, and the stride
            // in c is one. We can tell Halide to assume (and assert)
            // that this is the case for the input and output like so:

            input
                .set_stride(0, 3) // stride in dimension 0 (x) is three
                .set_stride(2, 1); // stride in dimension 2 (c) is one

            brighter.output_buffer()
                .set_stride(0, 3)
                .set_stride(2, 1);

            // For interleaved layout, you may want to use a different
            // schedule. We'll tell Halide to additionally assume and
            // assert that there are three color channels, then
            // exploit this fact to make the loop over 'c' innermost
            // and unrolled.

            input.set_bounds(2, 0, 3); // Dimension 2 (c) starts at 0 and has extent 3.
            brighter.output_buffer().set_bounds(2, 0, 3);

            // Move the loop over color channels innermost and unroll
            // it.
            brighter.reorder(c, x, y).unroll(c);

            // Note that if we were dealing with an image with an
            // alpha channel (RGBA), then the stride in x and the
            // bounds of the channels dimension would both be four
            // instead of three.

        } else if (layout == Layout::Either) {
            // We can also remove all constraints and compile a
            // pipeline that will work with any memory layout. It will
            // probably be slow, because all vector loads become
            // gathers, and all vector stores become scatters.
            input.set_stride(0, Expr()); // Use a default-constructed
                                         // undefined Expr to mean
                                         // there is no constraint.

            brighter.output_buffer().set_stride(0, Expr());

        } else if (layout == Layout::Specialized) {
            // We can accept any memory layout with good performance
            // by telling Halide to inspect the memory layout at
            // runtime, and branch to different code depending on the
            // strides it find. First we relax the default constraint
            // that stride(0) == 1:

            input.set_stride(0, Expr()); // Use an undefined Expr to
                                         // mean there is no
                                         // constraint.

            brighter.output_buffer().set_stride(0, Expr());

            // The we construct boolean Exprs that detect at runtime
            // whether we're planar or interleaved. The conditions
            // should check for all the facts we want to exploit in
            // each case.
            Expr input_is_planar =
                (input.stride(0) == 1);
            Expr input_is_interleaved =
                (input.stride(0) == 3 &&
                 input.stride(2) == 1 &&
                 input.extent(2) == 3);

            Expr output_is_planar =
                (brighter.output_buffer().stride(0) == 1);
            Expr output_is_interleaved =
                (brighter.output_buffer().stride(0) == 3 &&
                 brighter.output_buffer().stride(2) == 1 &&
                 brighter.output_buffer().extent(2) == 3);

            // We can then use Func::specialize to write a schedule
            // that switches at runtime to specialized code based on a
            // boolean Expr. That code will exploit the fact that the
            // Expr is known to be true.
            brighter.specialize(input_is_planar && output_is_planar);

            // We've already vectorized and parallelized brighter, and
            // our two specializations will inherit those scheduling
            // directives. We can also add additional scheduling
            // directives that apply to a single specialization
            // only. We'll tell Halide to make a specialized version
            // of the code for interleaved layouts, and to reorder and
            // unroll that specialized code.
            brighter.specialize(input_is_interleaved && output_is_interleaved)
                .reorder(c, x, y).unroll(c);

            // We could also add specializations for if the input is
            // interleaved and the output is planar, and vice versa,
            // but two specializations is enough to demonstrate the
            // feature. A later tutorial will explore more creative
            // uses of Func::specialize.

            // Adding specializations can improve performance
            // substantially for the cases they apply to, but it also
            // increases the amount of code to compile and ship. If
            // binary sizes are a concern and the input and output
            // memory layouts are known, you probably want to use
            // set_stride and set_extent instead.
        }

        return brighter;
    }
};

// As in lesson 15, we register our generator and then compile this
// file along with tools/GenGen.cpp.
RegisterGenerator<Brighten> my_first_generator{"brighten"};

// After compiling this file, see how to use it in
// lesson_16_rgb_run.cpp
<commit_msg>Fix tutorial convention<commit_after>// Halide tutorial lesson 16: RGB images and memory layouts part 1

// This lesson demonstrates how to feed Halide RGB images in
// interleaved or planar format, and how to write code optimized for
// each case.

// On linux or os x, you can compile and run it like so:

// g++ lesson_16_rgb_generate.cpp ../tools/GenGen.cpp -g -std=c++11 -fno-rtti -I ../include -L ../bin -lHalide -lpthread -ldl -o lesson_16_generate
// export LD_LIBRARY_PATH=../bin   # For linux
// export DYLD_LIBRARY_PATH=../bin # For OS X
// ./lesson_16_generate -o . -f brighten_planar      target=host layout=planar
// ./lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved
// ./lesson_16_generate -o . -f brighten_either      target=host layout=either
// ./lesson_16_generate -o . -f brighten_specialized target=host layout=specialized
// g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run
// ./lesson_16_run

// If you have the entire Halide source tree, you can also build it by
// running:
//    make tutorial_lesson_16_rgb_run
// in a shell with the current directory at the top of the halide
// source tree.

#include "Halide.h"
#include <stdio.h>

using namespace Halide;

// We will define a generator that brightens an RGB image.
class Brighten : public Halide::Generator<Brighten> {
public:
    // We declare a three-dimensional input image. The first two
    // dimensions will be x, and y, and the third dimension will be
    // the color channel.
    ImageParam input{UInt(8), 3, "input"};

    // We will compile this generator in several ways to accept
    // several different memory layouts for the input and output. This
    // is a good use of a GeneratorParam (see lesson 15).
    enum class Layout { Planar, Interleaved, Either, Specialized };
    GeneratorParam<Layout> layout{"layout",
            // default value
            Layout::Planar,
            // map from names to values
                {{ "planar",        Layout::Planar },
                 { "interleaved",   Layout::Interleaved },
                 { "either",        Layout::Either },
                 { "specialized",   Layout::Specialized }}};

    // We also declare a scalar parameter to control the amount of
    // brightening.
    Param<uint8_t> offset{"offset"};

    // Declare our Vars
    Var x, y, c;

    Func build() {
        // Define the Func.
        Func brighter("brighter");
        brighter(x, y, c) = input(x, y, c) + offset;

        // Schedule it.
        brighter.vectorize(x, 16);

        // We will compile this pipeline to handle memory layouts in
        // several different ways, depending on the 'layout' generator
        // param.
        if (layout == Layout::Planar) {
            // This pipeline as written will only work with images in
            // which each scanline is densely-packed single color
            // channel. In terms of the strides described in lesson
            // 10, Halide assumes and asserts that the stride in x is
            // one.

            // This constraint permits planar images, where the red,
            // green, and blue channels are laid out in memory like
            // this:

            // RRRRRRRR
            // RRRRRRRR
            // RRRRRRRR
            // RRRRRRRR
            // GGGGGGGG
            // GGGGGGGG
            // GGGGGGGG
            // GGGGGGGG
            // BBBBBBBB
            // BBBBBBBB
            // BBBBBBBB
            // BBBBBBBB

            // It also works with the less-commonly used line-by-line
            // layout, in which scanlines of red, green, and blue
            // alternate.

            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB
            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB
            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB
            // RRRRRRRR
            // GGGGGGGG
            // BBBBBBBB

        } else if (layout == Layout::Interleaved) {
            // Another common format is 'interleaved', in which the
            // red, green, and blue values for each pixel occur next
            // to each other in memory:

            // RGBRGBRGBRGBRGBRGBRGBRGB
            // RGBRGBRGBRGBRGBRGBRGBRGB
            // RGBRGBRGBRGBRGBRGBRGBRGB
            // RGBRGBRGBRGBRGBRGBRGBRGB

            // In this case the stride in x is three, the stride in y
            // is three times the width of the image, and the stride
            // in c is one. We can tell Halide to assume (and assert)
            // that this is the case for the input and output like so:

            input
                .dim(0).set_stride(3) // stride in dimension 0 (x) is three
                .dim(2).set_stride(1); // stride in dimension 2 (c) is one

            brighter.output_buffer()
                .dim(0).set_stride(3)
                .dim(2).set_stride(1);

            // For interleaved layout, you may want to use a different
            // schedule. We'll tell Halide to additionally assume and
            // assert that there are three color channels, then
            // exploit this fact to make the loop over 'c' innermost
            // and unrolled.

            input.dim(2).set_bounds(0, 3); // Dimension 2 (c) starts at 0 and has extent 3.
            brighter.output_buffer().dim(2).set_bounds(0, 3);

            // Move the loop over color channels innermost and unroll
            // it.
            brighter.reorder(c, x, y).unroll(c);

            // Note that if we were dealing with an image with an
            // alpha channel (RGBA), then the stride in x and the
            // bounds of the channels dimension would both be four
            // instead of three.

        } else if (layout == Layout::Either) {
            // We can also remove all constraints and compile a
            // pipeline that will work with any memory layout. It will
            // probably be slow, because all vector loads become
            // gathers, and all vector stores become scatters.
            input.dim(0).set_stride(Expr()); // Use a default-constructed
                                         // undefined Expr to mean
                                         // there is no constraint.

            brighter.output_buffer().dim(0).set_stride(Expr());

        } else if (layout == Layout::Specialized) {
            // We can accept any memory layout with good performance
            // by telling Halide to inspect the memory layout at
            // runtime, and branch to different code depending on the
            // strides it find. First we relax the default constraint
            // that dim(0).stride() == 1:

            input.dim(0).set_stride(Expr()); // Use an undefined Expr to
                                         // mean there is no
                                         // constraint.

            brighter.output_buffer().dim(0).set_stride(Expr());

            // The we construct boolean Exprs that detect at runtime
            // whether we're planar or interleaved. The conditions
            // should check for all the facts we want to exploit in
            // each case.
            Expr input_is_planar =
                (input.dim(0).stride() == 1);
            Expr input_is_interleaved =
                (input.dim(0).stride() == 3 &&
                 input.dim(2).stride() == 1 &&
                 input.dim(2).extent() == 3);

            Expr output_is_planar =
                (brighter.output_buffer().dim(0).stride() == 1);
            Expr output_is_interleaved =
                (brighter.output_buffer().dim(0).stride() == 3 &&
                 brighter.output_buffer().dim(2).stride() == 1 &&
                 brighter.output_buffer().dim(2).extent() == 3);

            // We can then use Func::specialize to write a schedule
            // that switches at runtime to specialized code based on a
            // boolean Expr. That code will exploit the fact that the
            // Expr is known to be true.
            brighter.specialize(input_is_planar && output_is_planar);

            // We've already vectorized and parallelized brighter, and
            // our two specializations will inherit those scheduling
            // directives. We can also add additional scheduling
            // directives that apply to a single specialization
            // only. We'll tell Halide to make a specialized version
            // of the code for interleaved layouts, and to reorder and
            // unroll that specialized code.
            brighter.specialize(input_is_interleaved && output_is_interleaved)
                .reorder(c, x, y).unroll(c);

            // We could also add specializations for if the input is
            // interleaved and the output is planar, and vice versa,
            // but two specializations is enough to demonstrate the
            // feature. A later tutorial will explore more creative
            // uses of Func::specialize.

            // Adding specializations can improve performance
            // substantially for the cases they apply to, but it also
            // increases the amount of code to compile and ship. If
            // binary sizes are a concern and the input and output
            // memory layouts are known, you probably want to use
            // set_stride and set_extent instead.
        }

        return brighter;
    }
};

// As in lesson 15, we register our generator and then compile this
// file along with tools/GenGen.cpp.
RegisterGenerator<Brighten> my_first_generator{"brighten"};

// After compiling this file, see how to use it in
// lesson_16_rgb_run.cpp
<|endoftext|>