<commit_before>//Copyright (c) 2019 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <gtest/gtest.h>
#include <clipper.hpp>
#include <../src/utils/AABB.h>
#include <../src/utils/AABB3D.h>
#include <../src/utils/polygon.h>

namespace cura
{
    inline AABB3D toBox(const coord_t& x, const coord_t& y, const coord_t& z)
    {
        const Point3 pt(x, y, z);
        return AABB3D(pt, pt);
    }

    TEST(AABB3DTest, TestConstructEmpty)
    {
        AABB3D empty_box;

        EXPECT_FALSE(empty_box.hit(toBox(0, 0, 0))) << "Empty box shouldn't contain anything.";
        EXPECT_FALSE(empty_box.hit(empty_box)) << "Empty boxes shouldn't intersect.";

        empty_box.include(Point3(-10, -5, -2));
        empty_box.include(Point3(5, 10, 2));

        EXPECT_TRUE(empty_box.hit(toBox(0, 0, 0))) << "The previously empty box should now contain this point.";
        EXPECT_FALSE(empty_box.hit(toBox(11, 5, 0))) << "The previously empty box should now still not contain this point.";
    }

    TEST(AABB3DTest, TestConstructPoint)
    {
        AABB3D point_box(Point3(-10, -5, -2), Point3(5, 10, 2));

        EXPECT_TRUE(point_box.hit(toBox(0, 0, 0))) << "Box constructed from points around the origin should contain it.";
        EXPECT_FALSE(point_box.hit(toBox(11, 5, 0))) << "The box shouldn't contain a point outside of it.";
    }

    TEST(AABB3DTest, TestConstructInverse)
    {
        AABB3D inverse_box(Point3(5, 10, 2), Point3(-10, -5, -2));

        EXPECT_FALSE(inverse_box.hit(toBox(0, 0, 0))) << "'Inverse' box shouldn't contain anything.";
        EXPECT_FALSE(inverse_box.hit(inverse_box)) << "'Inverse' boxes shouldn't intersect.";

        inverse_box.include(Point3(-5, -2, -1));
        inverse_box.include(Point3(2, 5, 1));

        EXPECT_TRUE(inverse_box.hit(toBox(0, 0, 0))) << "The previously 'inverse' box should now contain this point.";
        EXPECT_FALSE(inverse_box.hit(toBox(4, 8, -1))) << "The previously 'inverse' box should now still not contain this point.";
    }

    TEST(AABB3DTest, TestHit)
    {
        AABB3D box_a(Point3(-10, -5, -2), Point3(5, 10, 2));
        AABB3D box_b(Point3(4, 9, 0), Point3(12, 12, 12));
        AABB3D box_c(Point3(11, 11, 11), Point3(14, 14, 14));

        EXPECT_TRUE(box_a.hit(box_a)) << "Box should overlap itself.";

        EXPECT_TRUE(box_a.hit(box_b)) << "These boxes should overlap (case AB).";
        EXPECT_TRUE(box_b.hit(box_a)) << "These boxes should overlap (case BA).";
        EXPECT_TRUE(box_b.hit(box_c)) << "These boxes should overlap (case BC).";
        EXPECT_TRUE(box_c.hit(box_b)) << "These boxes should overlap (case CB).";

        EXPECT_FALSE(box_a.hit(box_c)) << "These boxes should not overlap (case AC).";
        EXPECT_FALSE(box_c.hit(box_a)) << "These boxes should not overlap (case CA).";

        AABB3D box_d(Point3(3, 10, 2), Point3(12, 12, 12));
        AABB3D box_e(Point3(5, 10, 2), Point3(12, 12, 12));

        EXPECT_TRUE(box_a.hit(box_d)) << "Overlap-check is inclusive (case AD).";
        EXPECT_TRUE(box_d.hit(box_a)) << "Overlap-check is inclusive (case DA).";
        EXPECT_TRUE(box_a.hit(box_e)) << "Overlap-check is inclusive (case AE).";
        EXPECT_TRUE(box_e.hit(box_a)) << "Overlap-check is inclusive (case EA).";
    }

    TEST(AABB3DTest, TestGetMiddle)
    {
        AABB3D box_a(Point3(-10, -6, -5), Point3(6, 10, 3));
        AABB3D box_b(Point3(4, 10, 2), Point3(12, 12, 12));

        EXPECT_EQ(box_a.getMiddle(), Point3(-2, 2, -1)) << "The middle of the AABB should be this point (case A).";
        EXPECT_EQ(box_b.getMiddle(), Point3(8, 11, 7)) << "The middle of the AABB should be this point (case B).";
    }

    TEST(AABB3DTest, TestInclude)
    {
        AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));

        EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << "The unexpanded (via include/point) box should not contain a point in the (future) expanded area.";

        box.include(Point3(0, 0, 0));

        EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << "The expanded (via include/point) box should contain a point in the expanded area.";
        EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << "The unexpanded (via include/other) box should not contain a point in the (future) expanded area.";

        box.include(AABB3D(Point3(7, 9, -2), Point3(8, 10, 0)));

        EXPECT_TRUE(box.hit(toBox(6, 9, -1))) << "The expanded (via include/other) box should contain a point in the expanded area.";

        box.includeZ(-6);

        EXPECT_TRUE(box.hit(toBox(6, 9, -3))) << "The expanded (via includeZ/scalar) box should contain a point in the expanded area.";
    }

    TEST(AABB3DTest, TestOffset)
    {
        AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));

        EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << "The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.";

        box.offset(Point3(-2, -2, -2));

        EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << "The expanded (via offset-3D) box should contain a point in the expanded area.";
        EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << "The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.";

        box.offset(Point(-2, -2));

        EXPECT_TRUE(box.hit(toBox(-1, -1, 0))) << "The expanded (via offset-2D) box should contain a point in the expanded area.";
    }

    TEST(AABB3DTest, TestExpand)
    {
        AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));

        EXPECT_FALSE(box.hit(toBox(6, 11, 3))) << "Before expanding, the box shouldn't contain this point.";

        box.expandXY(2);

        EXPECT_TRUE(box.hit(toBox(6, 11, 1))) << "After expanding, the box should contain this point.";

        box.expandXY(-2);

        EXPECT_FALSE(box.hit(toBox(6, 11, 1))) << "After shrinking, the box shouldn't contain this point anymore.";
    }

    TEST(AABB3DTest, TestFlatten)
    {
        AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));

        AABB flat = box.flatten();

        EXPECT_TRUE(flat.contains(Point(1, 1))) << "The flattened box should contain this point.";
        EXPECT_FALSE(flat.contains(Point(-11, 3))) << "The flattened box shouldn't contain this point.";
    }
}
<commit_msg>Use include double quotes for local header files<commit_after>//Copyright (c) 2019 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <gtest/gtest.h>
#include <clipper.hpp>

#include "../src/utils/AABB.h"
#include "../src/utils/AABB3D.h"
#include "../src/utils/polygon.h"

namespace cura
{
    inline AABB3D toBox(const coord_t& x, const coord_t& y, const coord_t& z)
    {
        const Point3 pt(x, y, z);
        return AABB3D(pt, pt);
    }

    TEST(AABB3DTest, TestConstructEmpty)
    {
        AABB3D empty_box;

        EXPECT_FALSE(empty_box.hit(toBox(0, 0, 0))) << "Empty box shouldn't contain anything.";
        EXPECT_FALSE(empty_box.hit(empty_box)) << "Empty boxes shouldn't intersect.";

        empty_box.include(Point3(-10, -5, -2));
        empty_box.include(Point3(5, 10, 2));

        EXPECT_TRUE(empty_box.hit(toBox(0, 0, 0))) << "The previously empty box should now contain this point.";
        EXPECT_FALSE(empty_box.hit(toBox(11, 5, 0))) << "The previously empty box should now still not contain this point.";
    }

    TEST(AABB3DTest, TestConstructPoint)
    {
        AABB3D point_box(Point3(-10, -5, -2), Point3(5, 10, 2));

        EXPECT_TRUE(point_box.hit(toBox(0, 0, 0))) << "Box constructed from points around the origin should contain it.";
        EXPECT_FALSE(point_box.hit(toBox(11, 5, 0))) << "The box shouldn't contain a point outside of it.";
    }

    TEST(AABB3DTest, TestConstructInverse)
    {
        AABB3D inverse_box(Point3(5, 10, 2), Point3(-10, -5, -2));

        EXPECT_FALSE(inverse_box.hit(toBox(0, 0, 0))) << "'Inverse' box shouldn't contain anything.";
        EXPECT_FALSE(inverse_box.hit(inverse_box)) << "'Inverse' boxes shouldn't intersect.";

        inverse_box.include(Point3(-5, -2, -1));
        inverse_box.include(Point3(2, 5, 1));

        EXPECT_TRUE(inverse_box.hit(toBox(0, 0, 0))) << "The previously 'inverse' box should now contain this point.";
        EXPECT_FALSE(inverse_box.hit(toBox(4, 8, -1))) << "The previously 'inverse' box should now still not contain this point.";
    }

    TEST(AABB3DTest, TestHit)
    {
        AABB3D box_a(Point3(-10, -5, -2), Point3(5, 10, 2));
        AABB3D box_b(Point3(4, 9, 0), Point3(12, 12, 12));
        AABB3D box_c(Point3(11, 11, 11), Point3(14, 14, 14));

        EXPECT_TRUE(box_a.hit(box_a)) << "Box should overlap itself.";

        EXPECT_TRUE(box_a.hit(box_b)) << "These boxes should overlap (case AB).";
        EXPECT_TRUE(box_b.hit(box_a)) << "These boxes should overlap (case BA).";
        EXPECT_TRUE(box_b.hit(box_c)) << "These boxes should overlap (case BC).";
        EXPECT_TRUE(box_c.hit(box_b)) << "These boxes should overlap (case CB).";

        EXPECT_FALSE(box_a.hit(box_c)) << "These boxes should not overlap (case AC).";
        EXPECT_FALSE(box_c.hit(box_a)) << "These boxes should not overlap (case CA).";

        AABB3D box_d(Point3(3, 10, 2), Point3(12, 12, 12));
        AABB3D box_e(Point3(5, 10, 2), Point3(12, 12, 12));

        EXPECT_TRUE(box_a.hit(box_d)) << "Overlap-check is inclusive (case AD).";
        EXPECT_TRUE(box_d.hit(box_a)) << "Overlap-check is inclusive (case DA).";
        EXPECT_TRUE(box_a.hit(box_e)) << "Overlap-check is inclusive (case AE).";
        EXPECT_TRUE(box_e.hit(box_a)) << "Overlap-check is inclusive (case EA).";
    }

    TEST(AABB3DTest, TestGetMiddle)
    {
        AABB3D box_a(Point3(-10, -6, -5), Point3(6, 10, 3));
        AABB3D box_b(Point3(4, 10, 2), Point3(12, 12, 12));

        EXPECT_EQ(box_a.getMiddle(), Point3(-2, 2, -1)) << "The middle of the AABB should be this point (case A).";
        EXPECT_EQ(box_b.getMiddle(), Point3(8, 11, 7)) << "The middle of the AABB should be this point (case B).";
    }

    TEST(AABB3DTest, TestInclude)
    {
        AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));

        EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << "The unexpanded (via include/point) box should not contain a point in the (future) expanded area.";

        box.include(Point3(0, 0, 0));

        EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << "The expanded (via include/point) box should contain a point in the expanded area.";
        EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << "The unexpanded (via include/other) box should not contain a point in the (future) expanded area.";

        box.include(AABB3D(Point3(7, 9, -2), Point3(8, 10, 0)));

        EXPECT_TRUE(box.hit(toBox(6, 9, -1))) << "The expanded (via include/other) box should contain a point in the expanded area.";

        box.includeZ(-6);

        EXPECT_TRUE(box.hit(toBox(6, 9, -3))) << "The expanded (via includeZ/scalar) box should contain a point in the expanded area.";
    }

    TEST(AABB3DTest, TestOffset)
    {
        AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3));

        EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << "The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.";

        box.offset(Point3(-2, -2, -2));

        EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << "The expanded (via offset-3D) box should contain a point in the expanded area.";
        EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << "The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area.";

        box.offset(Point(-2, -2));

        EXPECT_TRUE(box.hit(toBox(-1, -1, 0))) << "The expanded (via offset-2D) box should contain a point in the expanded area.";
    }

    TEST(AABB3DTest, TestExpand)
    {
        AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));

        EXPECT_FALSE(box.hit(toBox(6, 11, 3))) << "Before expanding, the box shouldn't contain this point.";

        box.expandXY(2);

        EXPECT_TRUE(box.hit(toBox(6, 11, 1))) << "After expanding, the box should contain this point.";

        box.expandXY(-2);

        EXPECT_FALSE(box.hit(toBox(6, 11, 1))) << "After shrinking, the box shouldn't contain this point anymore.";
    }

    TEST(AABB3DTest, TestFlatten)
    {
        AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2));

        AABB flat = box.flatten();

        EXPECT_TRUE(flat.contains(Point(1, 1))) << "The flattened box should contain this point.";
        EXPECT_FALSE(flat.contains(Point(-11, 3))) << "The flattened box shouldn't contain this point.";
    }
}
<|endoftext|>


<commit_before>// Code for basic data manipulation
//
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

#define ERROR        "Error: "
#define MAX_WORD_LEN 100

struct node{				// node data structure for DLL
	char word[MAX_WORD_LEN];
	node * next;
	node * prev;
};

/*node**/int getWords(char * infile)
{
	ifstream file (infile);								// open file into an input file stream
	if(file.is_open()){
		string word;
		while(file >> word){							// stream operator parses on white space (seperating words)
			transform(word.begin(), word.end(), word.begin(), ::tolower);	// make sure all words are lower case
			cout << word << endl;
			//TODO sort the words (as chars), in order, into a dll
		}
		file.close();
	}else{
		cout << ERROR << "cannot open file" << endl;
		return 0;
	}
	return -1;
}

void printDLL_forward(node * head)
{
	node * current = head;
	while(current != NULL ){		// rotate threw list untill end
		cout << current->word << ", ";  // print out the current word
		current = current->next;	// set the next node to be the current
	}
	cout << endl;
}

void printDLL_backward(node * head)
{
	node * current = head;
	while(current->next != NULL){		// find the tail
		current = current->next;
	}

	while(current != NULL){
		cout << current->word << ", ";
		current = current->prev;
	}
	cout << endl;
}

int main(int argc, char * argv[])
{
	// get file input
	if(argc != 2){
		cout << ERROR << "Please include file to open" << endl;
		return -1;
	}

	getWords(argv[1]);
	// get doubly linked list of words
//	node* head;
//
//	cout << "Test 1: Words in order" << endl;
//
//	cout << "Test 2: Words in reverse order" << endl;
//
//	cout << "Test 3: Remove the 2nd item" << endl;
//
//	cout << "Test 4: Words in order" << endl;

	return 0;
}

<commit_msg>implemented DLL to store words: works!<commit_after>// Code for basic data manipulation
//
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

#define ERROR        "Error: "
#define MAX_WORD_LEN 100

struct node{				// node data structure for DLL
	char word[MAX_WORD_LEN];
	node * next;
	node * prev;
};

node * getWords(char * infile)
{
	node * head = NULL;
	node * prev = NULL;

	ifstream file (infile);								// open file into an input file stream
	if(file.is_open()){
		string word;
		while(file >> word){							// stream operator parses on white space (seperating words)
			transform(word.begin(), word.end(), word.begin(), ::tolower);	// make sure all words are lower case

			node * current;				// create a new node pointer
			current = new node;			// allocate memory for the node

			strcpy(current->word, word.c_str());	// copy the lower case word into the node
			if(prev != NULL){
			       	prev->next = current;		// set next, prev pointers
				current->prev = prev;
			}

			if(head == NULL) head = current;	// set head node pointer
			prev = current;				// remember the last node
		}
		file.close();
	}else{
		cout << ERROR << "cannot open file" << endl;
		return NULL;
	}
	return head;
}

void printDLL_forward(node * head)
{
	node * current = head;
	while(current->next != NULL ){		// rotate threw list untill end
		cout << current->word << ", ";  // print out the current word
		current = current->next;	// set the next node to be the current
	}
	cout << current->word << endl;
}

void printDLL_backward(node * head)
{
	node * current = head;
	while(current->next != NULL){		// find the tail
		current = current->next;
	}

	while(current != NULL){
		cout << current->word << ", ";
		current = current->prev;
	}
	cout << endl;
}

int main(int argc, char * argv[])
{
	// get file input
	if(argc != 2){
		cout << ERROR << "Please include file to open" << endl;
		return -1;
	}
	node * head = getWords(argv[1]);

	cout << "Test 1: Words in order" << endl;
	printDLL_forward(head);

//	cout << "Test 2: Words in reverse order" << endl;
//
//	cout << "Test 3: Remove the 2nd item" << endl;
//
//	cout << "Test 4: Words in order" << endl;

	return 0;
}

<|endoftext|>


<commit_before>#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <interrupt/PCINT0.hpp>
#include <common.hpp>
#include <port.hpp>
#include <sensor.hpp>

typedef Pin<Port<A>, 3> GDO0;

static void write_eeprom(int addr, unsigned char value)
{
	EECR = 0;

	EEAR = addr;
	EEDR = value;

	EECR |= _BV(EEMPE);
	EECR |= _BV(EEPE);

	loop_until_bit_is_clear(EECR, EEPE);
}

static unsigned int eeprom_addr = 0;

static void mark_eeprom_eof()
{
	write_eeprom(eeprom_addr, 0xff);
}

static void receive()
{
	while (GDO0::is_set()) {
		radio::select();
		unsigned char rxbytes = radio::status<radio::RXBYTES>();
		unsigned char d[rxbytes];
		radio::read_rxfifo(d, rxbytes);
		if (rxbytes >= 2 && rxbytes <= 32 && rxbytes == d[0] + 3) {
			SensorValue<RSSI>::encode(static_cast<int>(d[rxbytes - 2]) - 148, d + rxbytes - 2);
			d[0] += 2;
			for (int i = 0; i < rxbytes; ++i) {
				write_eeprom(eeprom_addr++, d[i]);
			}
		}
	}
	mark_eeprom_eof();
}

static void receive_loop()
{
	radio::select();
	radio::wcmd<radio::SRX>();
	radio::release();
	PCINT0Interrupt::set(receive);

	while(1) {
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
		PCINT0Interrupt::pending();
	}
}

int main()
{
	mark_eeprom_eof();

	GDO0::mode(INPUT);

	radio::setup();
	radio_reset();
	radio::select();
	radio::set<radio::IOCFG2>(0x7);
	radio::set<radio::IOCFG0>(0x7);
	radio::release();

	GIMSK |= _BV(PCIE0);
	PCMSK0 |= _BV(PCINT3);

	sei();

	receive_loop();
}
<commit_msg>Extra check for packet<commit_after>#include <avr/io.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <interrupt/PCINT0.hpp>
#include <common.hpp>
#include <port.hpp>
#include <sensor.hpp>

typedef Pin<Port<A>, 3> GDO0;

static void write_eeprom(int addr, unsigned char value)
{
	EECR = 0;

	EEAR = addr;
	EEDR = value;

	EECR |= _BV(EEMPE);
	EECR |= _BV(EEPE);

	loop_until_bit_is_clear(EECR, EEPE);
}

static unsigned int eeprom_addr = 0;

static void mark_eeprom_eof()
{
	write_eeprom(eeprom_addr, 0xff);
}

static void receive()
{
	while (GDO0::is_set()) {
		radio::select();
		unsigned char rxbytes = radio::status<radio::RXBYTES>();
		unsigned char d[rxbytes];
		radio::read_rxfifo(d, rxbytes);
		if (rxbytes >= 3 && rxbytes <= 32 && rxbytes == d[0] + 3) {
			SensorValue<RSSI>::encode(static_cast<int>(d[rxbytes - 2]) - 148, d + rxbytes - 2);
			d[0] += 2;
			for (int i = 0; i < rxbytes; ++i) {
				write_eeprom(eeprom_addr++, d[i]);
			}
		}
	}
	mark_eeprom_eof();
}

static void receive_loop()
{
	radio::select();
	radio::wcmd<radio::SRX>();
	radio::release();
	PCINT0Interrupt::set(receive);

	while(1) {
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
		PCINT0Interrupt::pending();
	}
}

int main()
{
	mark_eeprom_eof();

	GDO0::mode(INPUT);

	radio::setup();
	radio_reset();
	radio::select();
	radio::set<radio::IOCFG2>(0x7);
	radio::set<radio::IOCFG0>(0x7);
	radio::release();

	GIMSK |= _BV(PCIE0);
	PCMSK0 |= _BV(PCINT3);

	sei();

	receive_loop();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AsynchronousCall.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2006-01-19 12:51:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_ASYNCHRONOUS_CALL_HXX
#define SD_ASYNCHRONOUS_CALL_HXX

#include <vcl/timer.hxx>
#include <memory>
#include <boost/function.hpp>

namespace sd { namespace tools {

/** Store a function object and execute it asynchronous.

    This features of this class are:
    a) It provides a wrapper around a VCL Timer so that generic function
    objects can be used.
    b) When more than one function objects are posted to be executed later
    then the pending ones are erased and only the last will actually be
    executed.

    Use this class like this:
    aInstanceOfAsynchronousCall.Post(
        ::boost::bind(
            ::std::mem_fun(&DrawViewShell::SwitchPage),
            pDrawViewShell,
            11));
*/
class AsynchronousCall
{
public:
    /** Create a new asynchronous call.  Each object of this class processes
        one (semantical) type of call.
    */
    AsynchronousCall (void);

    ~AsynchronousCall (void);

    /** Post a function object that is to executed asynchronously.  When
        this method is called while the current function object has not bee
        executed then the later is destroyed and only the given function
        object will be executed.
        @param rFunction
            The function object that may be called asynchronously in the
            near future.
        @param nTimeoutInMilliseconds
            The timeout in milliseconds until the function object is
            executed.
    */
    typedef ::boost::function0<void> AsynchronousFunction;
    void Post (
        const AsynchronousFunction& rFunction,
        sal_uInt32 nTimeoutInMilliseconds=10);

private:
    Timer maTimer;
    /** The function object that will be executed when the TimerCallback
        function is called the next time.  This pointer may be NULL.
    */
    ::std::auto_ptr<AsynchronousFunction> mpFunction;
    DECL_LINK(TimerCallback,Timer*);
};

} } // end of namespace ::sd::tools

#endif
<commit_msg>INTEGRATION: CWS components1 (1.2.150); FILE MERGED 2007/02/16 14:05:31 af 1.2.150.2: #i68075# Fixed comments. 2006/12/07 09:24:19 af 1.2.150.1: #i71253# Fixed a typo.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AsynchronousCall.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:14:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_ASYNCHRONOUS_CALL_HXX
#define SD_ASYNCHRONOUS_CALL_HXX

#include <vcl/timer.hxx>
#include <memory>
#include <boost/function.hpp>

namespace sd { namespace tools {

/** Store a function object and execute it asynchronous.

    The features of this class are:
    a) It provides a wrapper around a VCL Timer so that generic function
    objects can be used.
    b) When more than one function objects are posted to be executed later
    then the pending ones are erased and only the last one will actually be
    executed.

    Use this class like this:
    aInstanceOfAsynchronousCall.Post(
        ::boost::bind(
            ::std::mem_fun(&DrawViewShell::SwitchPage),
            pDrawViewShell,
            11));
*/
class AsynchronousCall
{
public:
    /** Create a new asynchronous call.  Each object of this class processes
        one (semantical) type of call.
    */
    AsynchronousCall (void);

    ~AsynchronousCall (void);

    /** Post a function object that is to be executed asynchronously.  When
        this method is called while the current function object has not bee
        executed then the later is destroyed and only the given function
        object will be executed.
        @param rFunction
            The function object that may be called asynchronously in the
            near future.
        @param nTimeoutInMilliseconds
            The timeout in milliseconds until the function object is
            executed.
    */
    typedef ::boost::function0<void> AsynchronousFunction;
    void Post (
        const AsynchronousFunction& rFunction,
        sal_uInt32 nTimeoutInMilliseconds=10);

private:
    Timer maTimer;
    /** The function object that will be executed when the TimerCallback
        function is called the next time.  This pointer may be NULL.
    */
    ::std::auto_ptr<AsynchronousFunction> mpFunction;
    DECL_LINK(TimerCallback,Timer*);
};

} } // end of namespace ::sd::tools

#endif
<|endoftext|>


<commit_before>#include "rosplan_knowledge_base/VALVisitorProblem.h"
#include <iostream>

/* implementation of rosplan_knowledge_base::VALVisitorPredicate */
namespace KCL_rosplan {

	/*----------------*/
	/* return methods */
	/*----------------*/

	std::map <std::string, std::vector<std::string> > VALVisitorProblem::returnInstances() {
		VAL::const_symbol_list *c = problem->objects;
		for (VAL::const_symbol_list::const_iterator symbolListIterator = c->begin();
			symbolListIterator != c->end(); symbolListIterator++) {
			const VAL::const_symbol *object = *symbolListIterator;
			instances[object->type->getName()].push_back(object->pddl_typed_symbol::getName());
		}
		return instances;
	}

	std::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFacts(){
		if(!effects_read) {
			visit_effect_lists(problem->initial_state);
			effects_read = true;
		}
		return facts;
	}

	std::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFunctions(){
		if(!effects_read) {
			visit_effect_lists(problem->initial_state);
			effects_read = true;
		}
		return functions;
	}

	std::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnGoals() {
		problem->the_goal->visit(this);
		return goals;
	}

	rosplan_knowledge_msgs::KnowledgeItem VALVisitorProblem::returnMetric() {
		problem->metric->visit(this);
		return metric;
	}

	/*--------------*/
	/* propositions */
	/*--------------*/

	/**
	 * Visit a proposition to pack into ROS message
	 */
	void VALVisitorProblem::visit_proposition(VAL::proposition *p) {

		last_prop.typed_parameters.clear();
		last_prop.name = p->head->getName();

		std::vector<std::string> predicateLabels;

		// parse domain for predicates
		VAL::pred_decl_list *predicates = domain->predicates;
		for (VAL::pred_decl_list::const_iterator predicateIterator = predicates->begin(); predicateIterator != predicates->end(); predicateIterator++) {

			VAL::pred_decl *tempPredicate = *predicateIterator;

			// compare pedicate name with last proposition name
			if (tempPredicate->getPred()->symbol::getName() == last_prop.name) {

				// iterate the predicate symbols
				for (VAL::var_symbol_list::const_iterator varSymbolIterator = tempPredicate->getArgs()->begin();
						 varSymbolIterator != tempPredicate->getArgs()->end(); varSymbolIterator++) {

					// add labels to predicateLabels
					const VAL::var_symbol *tempVarSymbol = *varSymbolIterator;
					predicateLabels.push_back(tempVarSymbol->pddl_typed_symbol::getName());
				}
			}
		}

		// pack parameters
		int index = 0;
		for (VAL::parameter_symbol_list::const_iterator vi = p->args->begin(); vi != p->args->end(); vi++) {

			const VAL::parameter_symbol* var = *vi;

			diagnostic_msgs::KeyValue param;
			param.key = predicateLabels[index];
			param.value = var->pddl_typed_symbol::getName();
			last_prop.typed_parameters.push_back(param);

			++index;
		}
	}

	/*---------*/
	/* Effects */
	/*---------*/

	void VALVisitorProblem::visit_effect_lists(VAL::effect_lists * e) {

		problem_eff_neg = false;
		e->add_effects.pc_list<VAL::simple_effect*>::visit(this);

		problem_eff_neg = true;
		e->del_effects.pc_list<VAL::simple_effect*>::visit(this);
		problem_eff_neg = false;

		e->forall_effects.pc_list<VAL::forall_effect*>::visit(this);
		e->cond_effects.pc_list<VAL::cond_effect*>::visit(this);
		e->cond_assign_effects.pc_list<VAL::cond_effect*>::visit(this);
		e->assign_effects.pc_list<VAL::assignment*>::visit(this);
		e->timed_effects.pc_list<VAL::timed_effect*>::visit(this);
	}

	void VALVisitorProblem::visit_timed_effect(VAL::timed_effect * e) {
		problem_eff_time = e->ts;
		e->effs->visit(this);
	}

	void VALVisitorProblem::visit_simple_effect(VAL::simple_effect * e) {

		e->prop->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 1;
		item.attribute_name = last_prop.name;
		item.is_negative = problem_eff_neg;

		for(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {
			diagnostic_msgs::KeyValue param;
			param.key = last_prop.typed_parameters[a].key;
			param.value = last_prop.typed_parameters[a].value;
			item.values.push_back(param);
		}

		facts.push_back(item);
	}

	void VALVisitorProblem::visit_assignment(VAL::assignment *e) {

		e->getFTerm()->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 1;
		item.attribute_name = last_func_term.name;
		item.is_negative = false;

		for(unsigned int a = 0; a < last_func_term.typed_parameters.size(); a++) {
			diagnostic_msgs::KeyValue param;
			param.key = last_func_term.typed_parameters[a].key;
			param.value = last_func_term.typed_parameters[a].value;
			item.values.push_back(param);
		}

		expression.str("");
		e->getExpr()->visit(this);
		item.function_value = std::atof(expression.str().c_str());

		functions.push_back(item);
	}

	void VALVisitorProblem::visit_forall_effect(VAL::forall_effect * e) {
		ROS_ERROR("Not yet implemented forall effects in intial state parser.");
	}

	void VALVisitorProblem::visit_cond_effect(VAL::cond_effect * e) {
		ROS_ERROR("Not yet implemented conditional effects in intial state parser.");
	}

	/*-------*/
	/* Goals */
	/*-------*/

	void VALVisitorProblem::visit_conj_goal(VAL::conj_goal * g){
		g->getGoals()->visit(this);
	}

	void VALVisitorProblem::visit_timed_goal(VAL::timed_goal *c){
		problem_cond_time = c->getTime();
		c->getGoal()->visit(this);
	}

	void VALVisitorProblem::visit_neg_goal(VAL::neg_goal *c) {
		problem_cond_neg = !problem_cond_neg;
		c->getGoal()->visit(this);
		problem_cond_neg = !problem_cond_neg;
	}

	void VALVisitorProblem::visit_simple_goal(VAL::simple_goal* g) {

		g->getProp()->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 1;
		item.attribute_name = last_prop.name;
		item.is_negative = problem_cond_neg;

		for(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {
			diagnostic_msgs::KeyValue param;
			param.key = last_prop.typed_parameters[a].key;
			param.value = last_prop.typed_parameters[a].value;
			item.values.push_back(param);
		}

		goals.push_back(item);
	}

	void VALVisitorProblem::visit_qfied_goal(VAL::qfied_goal *) {}
	void VALVisitorProblem::visit_disj_goal(VAL::disj_goal *) {}
	void VALVisitorProblem::visit_imply_goal(VAL::imply_goal *) {}
	void VALVisitorProblem::visit_comparison(VAL::comparison *c) {}

	/*---------*/
	/* metrics */
	/*---------*/

	void VALVisitorProblem::visit_metric_spec(VAL::metric_spec * s){

		expression.str("");
        cout << "metric start\n";
		s->expr->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 2;
		diagnostic_msgs::KeyValue param;

		if (s->opt == 0){
			param.key = "minimize";
		}
		else {
			param.key = "maximize";
		}

		param.value = expression.str();
		item.values.push_back(param);
		metric = item;
        cout << "metric end\n";
	}

	/*-------------*/
	/* expressions */
	/*-------------*/

	void VALVisitorProblem::visit_plus_expression(VAL::plus_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_minus_expression(VAL::minus_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_mul_expression(VAL::mul_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_div_expression(VAL::div_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_uminus_expression(VAL::uminus_expression * s){
		s->getExpr()->visit(this);

	}
	void VALVisitorProblem::visit_int_expression(VAL::int_expression * s){
		expression << s->double_value();
        cout << "expression value int: "+ expression.str()+"\n";
	}
	void VALVisitorProblem::visit_float_expression(VAL::float_expression * s){
		expression << s->double_value();
        cout << "expression value float: "+ expression.str()+"\n";
	}
	void VALVisitorProblem::visit_special_val_expr(VAL::special_val_expr * s){
        string tempExpression;
        switch(s->getKind()) {
            case 0:
                tempExpression = "hasht";
                break;
            case 1:
                tempExpression = "duration-var";
                break;
            case 2:
                tempExpression = "total-time";
        }
		expression << tempExpression;
        cout << "expression value special val: "+ expression.str()+"\n";
	}
	void VALVisitorProblem::visit_violation_term(VAL::violation_term * v){
		expression << v->getName();
        cout << "expression value violation: "+ expression.str()+"\n";
	}
	void VALVisitorProblem::visit_func_term(VAL::func_term * s) {

		last_func_term.typed_parameters.clear();

		// func_term name
		last_func_term.name = s->getFunction()->getName();
        cout << "expression value: "+s->getFunction()->getName()+"\n";
		expression << last_func_term.name;

		std::vector<std::string> parameterLabels;

		// parse domain for parameter labels
		for (VAL::func_decl_list::const_iterator fit = domain->functions->begin(); fit != domain->functions->end(); fit++) {
			if ((*fit)->getFunction()->symbol::getName() == last_func_term.name) {
				VAL::var_symbol_list::const_iterator vit = (*fit)->getArgs()->begin();
				for(; vit != (*fit)->getArgs()->end(); vit++) {
					parameterLabels.push_back((*vit)->pddl_typed_symbol::getName());
				}
			}
		}

		// func_term variables
		int index = 0;
		for (VAL::parameter_symbol_list::const_iterator vi = s->getArgs()->begin(); vi != s->getArgs()->end(); vi++) {

			diagnostic_msgs::KeyValue param;
			param.key = parameterLabels[index];
			param.value = (*vi)->getName();
			last_func_term.typed_parameters.push_back(param);
			index++;

			expression << " " << (*vi)->getName();
		}
	}

	/*----------------------*/
	/* unused visit methods */
	/*----------------------*/

	void VALVisitorProblem::visit_operator_(VAL::operator_ *) {}
	void VALVisitorProblem::visit_derivation_rule(VAL::derivation_rule *o) {}

} // close namespace
<commit_msg>code refactoring<commit_after>#include "rosplan_knowledge_base/VALVisitorProblem.h"
#include <iostream>

/* implementation of rosplan_knowledge_base::VALVisitorPredicate */
namespace KCL_rosplan {

	/*----------------*/
	/* return methods */
	/*----------------*/

	std::map <std::string, std::vector<std::string> > VALVisitorProblem::returnInstances() {
		VAL::const_symbol_list *c = problem->objects;
		for (VAL::const_symbol_list::const_iterator symbolListIterator = c->begin();
			symbolListIterator != c->end(); symbolListIterator++) {
			const VAL::const_symbol *object = *symbolListIterator;
			instances[object->type->getName()].push_back(object->pddl_typed_symbol::getName());
		}
		return instances;
	}

	std::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFacts(){
		if(!effects_read) {
			visit_effect_lists(problem->initial_state);
			effects_read = true;
		}
		return facts;
	}

	std::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnFunctions(){
		if(!effects_read) {
			visit_effect_lists(problem->initial_state);
			effects_read = true;
		}
		return functions;
	}

	std::vector<rosplan_knowledge_msgs::KnowledgeItem> VALVisitorProblem::returnGoals() {
		problem->the_goal->visit(this);
		return goals;
	}

	rosplan_knowledge_msgs::KnowledgeItem VALVisitorProblem::returnMetric() {
		problem->metric->visit(this);
		return metric;
	}

	/*--------------*/
	/* propositions */
	/*--------------*/

	/**
	 * Visit a proposition to pack into ROS message
	 */
	void VALVisitorProblem::visit_proposition(VAL::proposition *p) {

		last_prop.typed_parameters.clear();
		last_prop.name = p->head->getName();

		std::vector<std::string> predicateLabels;

		// parse domain for predicates
		VAL::pred_decl_list *predicates = domain->predicates;
		for (VAL::pred_decl_list::const_iterator predicateIterator = predicates->begin(); predicateIterator != predicates->end(); predicateIterator++) {

			VAL::pred_decl *tempPredicate = *predicateIterator;

			// compare pedicate name with last proposition name
			if (tempPredicate->getPred()->symbol::getName() == last_prop.name) {

				// iterate the predicate symbols
				for (VAL::var_symbol_list::const_iterator varSymbolIterator = tempPredicate->getArgs()->begin();
						 varSymbolIterator != tempPredicate->getArgs()->end(); varSymbolIterator++) {

					// add labels to predicateLabels
					const VAL::var_symbol *tempVarSymbol = *varSymbolIterator;
					predicateLabels.push_back(tempVarSymbol->pddl_typed_symbol::getName());
				}
			}
		}

		// pack parameters
		int index = 0;
		for (VAL::parameter_symbol_list::const_iterator vi = p->args->begin(); vi != p->args->end(); vi++) {

			const VAL::parameter_symbol* var = *vi;

			diagnostic_msgs::KeyValue param;
			param.key = predicateLabels[index];
			param.value = var->pddl_typed_symbol::getName();
			last_prop.typed_parameters.push_back(param);

			++index;
		}
	}

	/*---------*/
	/* Effects */
	/*---------*/

	void VALVisitorProblem::visit_effect_lists(VAL::effect_lists * e) {

		problem_eff_neg = false;
		e->add_effects.pc_list<VAL::simple_effect*>::visit(this);

		problem_eff_neg = true;
		e->del_effects.pc_list<VAL::simple_effect*>::visit(this);
		problem_eff_neg = false;

		e->forall_effects.pc_list<VAL::forall_effect*>::visit(this);
		e->cond_effects.pc_list<VAL::cond_effect*>::visit(this);
		e->cond_assign_effects.pc_list<VAL::cond_effect*>::visit(this);
		e->assign_effects.pc_list<VAL::assignment*>::visit(this);
		e->timed_effects.pc_list<VAL::timed_effect*>::visit(this);
	}

	void VALVisitorProblem::visit_timed_effect(VAL::timed_effect * e) {
		problem_eff_time = e->ts;
		e->effs->visit(this);
	}

	void VALVisitorProblem::visit_simple_effect(VAL::simple_effect * e) {

		e->prop->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 1;
		item.attribute_name = last_prop.name;
		item.is_negative = problem_eff_neg;

		for(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {
			diagnostic_msgs::KeyValue param;
			param.key = last_prop.typed_parameters[a].key;
			param.value = last_prop.typed_parameters[a].value;
			item.values.push_back(param);
		}

		facts.push_back(item);
	}

	void VALVisitorProblem::visit_assignment(VAL::assignment *e) {

		e->getFTerm()->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 1;
		item.attribute_name = last_func_term.name;
		item.is_negative = false;

		for(unsigned int a = 0; a < last_func_term.typed_parameters.size(); a++) {
			diagnostic_msgs::KeyValue param;
			param.key = last_func_term.typed_parameters[a].key;
			param.value = last_func_term.typed_parameters[a].value;
			item.values.push_back(param);
		}

		expression.str("");
		e->getExpr()->visit(this);
		item.function_value = std::atof(expression.str().c_str());

		functions.push_back(item);
	}

	void VALVisitorProblem::visit_forall_effect(VAL::forall_effect * e) {
		ROS_ERROR("Not yet implemented forall effects in intial state parser.");
	}

	void VALVisitorProblem::visit_cond_effect(VAL::cond_effect * e) {
		ROS_ERROR("Not yet implemented conditional effects in intial state parser.");
	}

	/*-------*/
	/* Goals */
	/*-------*/

	void VALVisitorProblem::visit_conj_goal(VAL::conj_goal * g){
		g->getGoals()->visit(this);
	}

	void VALVisitorProblem::visit_timed_goal(VAL::timed_goal *c){
		problem_cond_time = c->getTime();
		c->getGoal()->visit(this);
	}

	void VALVisitorProblem::visit_neg_goal(VAL::neg_goal *c) {
		problem_cond_neg = !problem_cond_neg;
		c->getGoal()->visit(this);
		problem_cond_neg = !problem_cond_neg;
	}

	void VALVisitorProblem::visit_simple_goal(VAL::simple_goal* g) {

		g->getProp()->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 1;
		item.attribute_name = last_prop.name;
		item.is_negative = problem_cond_neg;

		for(unsigned int a = 0; a < last_prop.typed_parameters.size(); a++) {
			diagnostic_msgs::KeyValue param;
			param.key = last_prop.typed_parameters[a].key;
			param.value = last_prop.typed_parameters[a].value;
			item.values.push_back(param);
		}

		goals.push_back(item);
	}

	void VALVisitorProblem::visit_qfied_goal(VAL::qfied_goal *) {}
	void VALVisitorProblem::visit_disj_goal(VAL::disj_goal *) {}
	void VALVisitorProblem::visit_imply_goal(VAL::imply_goal *) {}
	void VALVisitorProblem::visit_comparison(VAL::comparison *c) {}

	/*---------*/
	/* metrics */
	/*---------*/

	void VALVisitorProblem::visit_metric_spec(VAL::metric_spec * s){

		expression.str("");
		s->expr->visit(this);

		rosplan_knowledge_msgs::KnowledgeItem item;
		item.knowledge_type = 2;
		diagnostic_msgs::KeyValue param;

		if (s->opt == 0){
			param.key = "minimize";
		}
		else {
			param.key = "maximize";
		}

		param.value = expression.str();
		item.values.push_back(param);
		metric = item;
	}

	/*-------------*/
	/* expressions */
	/*-------------*/

	void VALVisitorProblem::visit_plus_expression(VAL::plus_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_minus_expression(VAL::minus_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_mul_expression(VAL::mul_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_div_expression(VAL::div_expression * s){
		s->getLHS()->visit(this);
		s->getRHS()->visit(this);
	}
	void VALVisitorProblem::visit_uminus_expression(VAL::uminus_expression * s){
		s->getExpr()->visit(this);

	}
	void VALVisitorProblem::visit_int_expression(VAL::int_expression * s){
		expression << s->double_value();
	}
	void VALVisitorProblem::visit_float_expression(VAL::float_expression * s){
		expression << s->double_value();
	}
	void VALVisitorProblem::visit_special_val_expr(VAL::special_val_expr * s){
        string tempExpression;
        switch(s->getKind()) {
            case 0:
                tempExpression = "hasht";
                break;
            case 1:
                tempExpression = "duration-var";
                break;
            case 2:
                tempExpression = "total-time";
        }
		expression << tempExpression;
	}
	void VALVisitorProblem::visit_violation_term(VAL::violation_term * v){
		expression << v->getName();
	}
	void VALVisitorProblem::visit_func_term(VAL::func_term * s) {

		last_func_term.typed_parameters.clear();

		// func_term name
		last_func_term.name = s->getFunction()->getName();
		expression << last_func_term.name;

		std::vector<std::string> parameterLabels;

		// parse domain for parameter labels
		for (VAL::func_decl_list::const_iterator fit = domain->functions->begin(); fit != domain->functions->end(); fit++) {
			if ((*fit)->getFunction()->symbol::getName() == last_func_term.name) {
				VAL::var_symbol_list::const_iterator vit = (*fit)->getArgs()->begin();
				for(; vit != (*fit)->getArgs()->end(); vit++) {
					parameterLabels.push_back((*vit)->pddl_typed_symbol::getName());
				}
			}
		}

		// func_term variables
		int index = 0;
		for (VAL::parameter_symbol_list::const_iterator vi = s->getArgs()->begin(); vi != s->getArgs()->end(); vi++) {

			diagnostic_msgs::KeyValue param;
			param.key = parameterLabels[index];
			param.value = (*vi)->getName();
			last_func_term.typed_parameters.push_back(param);
			index++;

			expression << " " << (*vi)->getName();
		}
	}

	/*----------------------*/
	/* unused visit methods */
	/*----------------------*/

	void VALVisitorProblem::visit_operator_(VAL::operator_ *) {}
	void VALVisitorProblem::visit_derivation_rule(VAL::derivation_rule *o) {}

} // close namespace
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <errno.h>

#include "CephxClientHandler.h"
#include "CephxProtocol.h"

#include "../KeyRing.h"

#include "common/config.h"

#define DOUT_SUBSYS auth
#undef dout_prefix
#define dout_prefix *_dout << "cephx client: "

int CephxClientHandler::build_request(bufferlist& bl)
{
  ldout(cct, 10) << "build_request" << dendl;

  ldout(cct, 10) << "validate_tickets: want=" << want << " need=" << need << " have=" << have << dendl;
  validate_tickets();

  ldout(cct, 10) << "want=" << want << " need=" << need << " have=" << have << dendl;

  CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);

  if (need & CEPH_ENTITY_TYPE_AUTH) {
    /* authenticate */
    CephXRequestHeader header;
    header.request_type = CEPHX_GET_AUTH_SESSION_KEY;
    ::encode(header, bl);

    CryptoKey secret;
    keyring->get_secret(cct->_conf->name, secret);

    CephXAuthenticate req;
    get_random_bytes((char *)&req.client_challenge, sizeof(req.client_challenge));
    std::string error;
    cephx_calc_client_server_challenge(secret, server_challenge,
				       req.client_challenge, &req.key, error);
    if (!error.empty()) {
      ldout(cct, 20) << "cephx_calc_client_server_challenge error: " << error << dendl;
      return -EIO;
    }

    req.old_ticket = ticket_handler.ticket;

    if (req.old_ticket.blob.length()) {
      ldout(cct, 20) << "old ticket len=" << req.old_ticket.blob.length() << dendl;
    }

    ::encode(req, bl);

    ldout(cct, 10) << "get auth session key: client_challenge " << req.client_challenge << dendl;
    return 0;
  }

  if (need) {
    /* get service tickets */
    ldout(cct, 10) << "get service keys: want=" << want << " need=" << need << " have=" << have << dendl;

    CephXRequestHeader header;
    header.request_type = CEPHX_GET_PRINCIPAL_SESSION_KEY;
    ::encode(header, bl);

    authorizer = ticket_handler.build_authorizer(global_id);
    if (!authorizer)
      return -EINVAL;
    bl.claim_append(authorizer->bl);

    CephXServiceTicketRequest req;
    req.keys = need;
    ::encode(req, bl);
  }

  return 0;
}

int CephxClientHandler::handle_response(int ret, bufferlist::iterator& indata)
{
  ldout(cct, 10) << "handle_response ret = " << ret << dendl;

  if (ret < 0)
    return ret; // hrm!

  if (starting) {
    CephXServerChallenge ch;
    ::decode(ch, indata);
    server_challenge = ch.server_challenge;
    ldout(cct, 10) << " got initial server challenge " << server_challenge << dendl;
    starting = false;

    tickets.invalidate_ticket(CEPH_ENTITY_TYPE_AUTH);
    return -EAGAIN;
  }

  struct CephXResponseHeader header;
  ::decode(header, indata);

  switch (header.request_type) {
  case CEPHX_GET_AUTH_SESSION_KEY:
    {
      ldout(cct, 10) << " get_auth_session_key" << dendl;
      CryptoKey secret;
      keyring->get_secret(cct->_conf->name, secret);

      if (!tickets.verify_service_ticket_reply(secret, indata)) {
	ldout(cct, 0) << "could not verify service_ticket reply" << dendl;
	return -EPERM;
      }
      ldout(cct, 10) << " want=" << want << " need=" << need << " have=" << have << dendl;
      validate_tickets();
      if (need)
	ret = -EAGAIN;
      else
	ret = 0;
    }
    break;

  case CEPHX_GET_PRINCIPAL_SESSION_KEY:
    {
      CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);
      ldout(cct, 10) << " get_principal_session_key session_key " << ticket_handler.session_key << dendl;

      if (!tickets.verify_service_ticket_reply(ticket_handler.session_key, indata)) {
        ldout(cct, 0) << "could not verify service_ticket reply" << dendl;
        return -EPERM;
      }
      validate_tickets();
      if (!need) {
	ret = 0;
      }
    }
    break;

  case CEPHX_GET_ROTATING_KEY:
    {
      ldout(cct, 10) << " get_rotating_key" << dendl;
      if (rotating_secrets) {
	RotatingSecrets secrets;
	CryptoKey secret_key;
	keyring->get_secret(cct->_conf->name, secret_key);
	std::string error;
	decode_decrypt(secrets, secret_key, indata, error);
	if (error.empty()) {
	  rotating_secrets->set_secrets(secrets);
	} else {
	  ldout(cct, 0) << "could not set rotating key: decode_decrypt failed. error:"
	    << error << dendl;
	  error.clear();
	}
      }
    }
    break;

  default:
   ldout(cct, 0) << " unknown request_type " << header.request_type << dendl;
   assert(0);
  }
  return ret;
}

AuthAuthorizer *CephxClientHandler::build_authorizer(uint32_t service_id)
{
  ldout(cct, 10) << "build_authorizer for service " << ceph_entity_type_name(service_id) << dendl;
  return tickets.build_authorizer(service_id);
}

bool CephxClientHandler::build_rotating_request(bufferlist& bl)
{
  ldout(cct, 10) << "build_rotating_request" << dendl;
  CephXRequestHeader header;
  header.request_type = CEPHX_GET_ROTATING_KEY;
  ::encode(header, bl);
  return true;
}

void CephxClientHandler::validate_tickets()
{
  tickets.validate_tickets(want, have, need);
}

bool CephxClientHandler::need_tickets()
{
  validate_tickets();

  ldout(cct, 20) << "need_tickets: want=" << want << " need=" << need << " have=" << have << dendl;

  return (need != 0);
}

<commit_msg>cephx: don't leak Authorizers on each request<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2009 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software
 * Foundation.  See file COPYING.
 *
 */

#include <errno.h>

#include "CephxClientHandler.h"
#include "CephxProtocol.h"

#include "../KeyRing.h"

#include "common/config.h"

#define DOUT_SUBSYS auth
#undef dout_prefix
#define dout_prefix *_dout << "cephx client: "

int CephxClientHandler::build_request(bufferlist& bl)
{
  ldout(cct, 10) << "build_request" << dendl;

  ldout(cct, 10) << "validate_tickets: want=" << want << " need=" << need << " have=" << have << dendl;
  validate_tickets();

  ldout(cct, 10) << "want=" << want << " need=" << need << " have=" << have << dendl;

  CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);

  if (need & CEPH_ENTITY_TYPE_AUTH) {
    /* authenticate */
    CephXRequestHeader header;
    header.request_type = CEPHX_GET_AUTH_SESSION_KEY;
    ::encode(header, bl);

    CryptoKey secret;
    keyring->get_secret(cct->_conf->name, secret);

    CephXAuthenticate req;
    get_random_bytes((char *)&req.client_challenge, sizeof(req.client_challenge));
    std::string error;
    cephx_calc_client_server_challenge(secret, server_challenge,
				       req.client_challenge, &req.key, error);
    if (!error.empty()) {
      ldout(cct, 20) << "cephx_calc_client_server_challenge error: " << error << dendl;
      return -EIO;
    }

    req.old_ticket = ticket_handler.ticket;

    if (req.old_ticket.blob.length()) {
      ldout(cct, 20) << "old ticket len=" << req.old_ticket.blob.length() << dendl;
    }

    ::encode(req, bl);

    ldout(cct, 10) << "get auth session key: client_challenge " << req.client_challenge << dendl;
    return 0;
  }

  if (need) {
    /* get service tickets */
    ldout(cct, 10) << "get service keys: want=" << want << " need=" << need << " have=" << have << dendl;

    CephXRequestHeader header;
    header.request_type = CEPHX_GET_PRINCIPAL_SESSION_KEY;
    ::encode(header, bl);

    authorizer = ticket_handler.build_authorizer(global_id);
    if (!authorizer)
      return -EINVAL;
    bl.claim_append(authorizer->bl);
    delete authorizer;

    CephXServiceTicketRequest req;
    req.keys = need;
    ::encode(req, bl);
  }

  return 0;
}

int CephxClientHandler::handle_response(int ret, bufferlist::iterator& indata)
{
  ldout(cct, 10) << "handle_response ret = " << ret << dendl;

  if (ret < 0)
    return ret; // hrm!

  if (starting) {
    CephXServerChallenge ch;
    ::decode(ch, indata);
    server_challenge = ch.server_challenge;
    ldout(cct, 10) << " got initial server challenge " << server_challenge << dendl;
    starting = false;

    tickets.invalidate_ticket(CEPH_ENTITY_TYPE_AUTH);
    return -EAGAIN;
  }

  struct CephXResponseHeader header;
  ::decode(header, indata);

  switch (header.request_type) {
  case CEPHX_GET_AUTH_SESSION_KEY:
    {
      ldout(cct, 10) << " get_auth_session_key" << dendl;
      CryptoKey secret;
      keyring->get_secret(cct->_conf->name, secret);

      if (!tickets.verify_service_ticket_reply(secret, indata)) {
	ldout(cct, 0) << "could not verify service_ticket reply" << dendl;
	return -EPERM;
      }
      ldout(cct, 10) << " want=" << want << " need=" << need << " have=" << have << dendl;
      validate_tickets();
      if (need)
	ret = -EAGAIN;
      else
	ret = 0;
    }
    break;

  case CEPHX_GET_PRINCIPAL_SESSION_KEY:
    {
      CephXTicketHandler& ticket_handler = tickets.get_handler(CEPH_ENTITY_TYPE_AUTH);
      ldout(cct, 10) << " get_principal_session_key session_key " << ticket_handler.session_key << dendl;

      if (!tickets.verify_service_ticket_reply(ticket_handler.session_key, indata)) {
        ldout(cct, 0) << "could not verify service_ticket reply" << dendl;
        return -EPERM;
      }
      validate_tickets();
      if (!need) {
	ret = 0;
      }
    }
    break;

  case CEPHX_GET_ROTATING_KEY:
    {
      ldout(cct, 10) << " get_rotating_key" << dendl;
      if (rotating_secrets) {
	RotatingSecrets secrets;
	CryptoKey secret_key;
	keyring->get_secret(cct->_conf->name, secret_key);
	std::string error;
	decode_decrypt(secrets, secret_key, indata, error);
	if (error.empty()) {
	  rotating_secrets->set_secrets(secrets);
	} else {
	  ldout(cct, 0) << "could not set rotating key: decode_decrypt failed. error:"
	    << error << dendl;
	  error.clear();
	}
      }
    }
    break;

  default:
   ldout(cct, 0) << " unknown request_type " << header.request_type << dendl;
   assert(0);
  }
  return ret;
}

AuthAuthorizer *CephxClientHandler::build_authorizer(uint32_t service_id)
{
  ldout(cct, 10) << "build_authorizer for service " << ceph_entity_type_name(service_id) << dendl;
  return tickets.build_authorizer(service_id);
}

bool CephxClientHandler::build_rotating_request(bufferlist& bl)
{
  ldout(cct, 10) << "build_rotating_request" << dendl;
  CephXRequestHeader header;
  header.request_type = CEPHX_GET_ROTATING_KEY;
  ::encode(header, bl);
  return true;
}

void CephxClientHandler::validate_tickets()
{
  tickets.validate_tickets(want, have, need);
}

bool CephxClientHandler::need_tickets()
{
  validate_tickets();

  ldout(cct, 20) << "need_tickets: want=" << want << " need=" << need << " have=" << have << dendl;

  return (need != 0);
}

<|endoftext|>


<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#pragma once

#include "math/Vector3.hpp"

namespace ouzel
{
    class Quaternion
    {
    public:
        float x = 0.0F;
        float y = 0.0F;
        float z = 0.0F;
        float w = 0.0F;

        Quaternion()
        {
        }

        Quaternion(float initX, float initY, float initZ, float initW):
            x(initX), y(initY), z(initZ), w(initW)
        {
        }

        Quaternion(const Quaternion& copy):
            x(copy.x), y(copy.y), z(copy.z), w(copy.w)
        {
        }

        static Quaternion identity()
        {
            return Quaternion(0.0F, 0.0F, 0.0F, 1.0F);
        }

        Quaternion operator*(const Quaternion& q) const
        {
            return Quaternion( x * q.w + y * q.z - z * q.y + w * q.x,
                              -x * q.z + y * q.w + z * q.x + w * q.y,
                               x * q.y - y * q.x + z * q.w + w * q.z,
                              -x * q.x - y * q.y - z * q.z + w * q.w);
        }

        const Quaternion& operator*=(const Quaternion& q)
        {
            float tempX =  x * q.w + y * q.z - z * q.y + w * q.x;
            float tempY = -x * q.z + y * q.w + z * q.x + w * q.y;
            float tempZ =  x * q.y - y * q.x + z * q.w + w * q.z;
            float tempW = -x * q.x - y * q.y - z * q.z + w * q.w;

            x = tempX;
            y = tempY;
            z = tempZ;
            w = tempW;

            return *this;
        }

        Quaternion operator*(float scalar) const
        {
            return Quaternion(x * scalar,
                              y * scalar,
                              z * scalar,
                              w * scalar);
        }

        const Quaternion& operator*=(float scalar)
        {
            x *= scalar;
            y *= scalar;
            z *= scalar;
            w *= scalar;

            return *this;
        }

        Quaternion operator/(float scalar) const
        {
            return Quaternion(x / scalar,
                              y / scalar,
                              z / scalar,
                              w / scalar);
        }

        const Quaternion& operator/=(float scalar)
        {
            x /= scalar;
            y /= scalar;
            z /= scalar;
            w /= scalar;

            return *this;
        }

        inline Quaternion operator-() const
        {
            return Quaternion(-x, -y, -z, -w);
        }

        inline Quaternion operator+(const Quaternion& q) const
        {
            Quaternion result(*this);
            result.x += q.x;
            result.y += q.y;
            result.z += q.z;
            result.w += q.w;

            return result;
        }

        inline Quaternion& operator+=(const Quaternion& q)
        {
            x += q.x;
            y += q.y;
            z += q.z;
            w += q.w;

            return *this;
        }

        inline Quaternion operator-(const Quaternion& q) const
        {
            Quaternion result(*this);
            result.x -= q.x;
            result.y -= q.y;
            result.z -= q.z;
            result.w -= q.w;

            return result;
        }

        inline Quaternion& operator-=(const Quaternion& q)
        {
            x -= q.x;
            y -= q.y;
            z -= q.z;
            w -= q.w;

            return *this;
        }

        inline bool operator==(const Quaternion& q) const
        {
            return x == q.x && y == q.y && z == q.z && w == q.w;
        }

        inline bool operator!=(const Quaternion& q) const
        {
            return x != q.x || y != q.y || z != q.z || w != q.w;
        }

        inline void negate()
        {
            x = -x;
            y = -y;
            z = -z;
            w = -w;
        }

        inline void conjugate()
        {
            x = -x;
            y = -y;
            z = -z;
        }

        inline void invert()
        {
            float n2 = x * x + y * y + z * z + w * w; // norm squared

            if (n2 == 0.0F) return;

            // conjugate divided by norm squared
            x = -x / n2;
            y = -y / n2;
            z = -z / n2;
            w = w / n2;
        }

        float getNorm();
        void normalize();
        void rotate(float angle, Vector3 axis);
        void getRotation(float& angle, Vector3& axis);

        void setEulerAngles(const Vector3& angles);
        Vector3 getEulerAngles() const;
        float getEulerAngleX() const;
        float getEulerAngleY() const;
        float getEulerAngleZ() const;

        inline Vector3 operator*(const Vector3& vector) const
        {
            return rotateVector(vector);
        }

        inline Vector3 rotateVector(const Vector3& vector) const
        {
            Vector3 q(x, y, z);
            Vector3 t = 2.0F * Vector3::cross(q, vector);
            Vector3 result = vector + (w * t) + Vector3::cross(q, t);
            return result;
        }

        inline Vector3 getRightVector() const
        {
            return rotateVector(Vector3(1.0F, 0.0F, 0.0F));
        }

        inline Vector3 getUpVector() const
        {
            return rotateVector(Vector3(0.0F, 1.0F, 0.0F));
        }

        inline Vector3 getForwardVector() const
        {
            return rotateVector(Vector3(0.0F, 0.0F, 1.0F));
        }

        Quaternion& lerp(const Quaternion& q1, const Quaternion& q2, float t)
        {
            const float scale = 1.0F - t;
            return (*this = (q1 * scale) + (q2 * t));
        }
    };
}
<commit_msg>Simplify rotateVector<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved.

#pragma once

#include "math/Vector3.hpp"

namespace ouzel
{
    class Quaternion
    {
    public:
        float x = 0.0F;
        float y = 0.0F;
        float z = 0.0F;
        float w = 0.0F;

        Quaternion()
        {
        }

        Quaternion(float initX, float initY, float initZ, float initW):
            x(initX), y(initY), z(initZ), w(initW)
        {
        }

        Quaternion(const Quaternion& copy):
            x(copy.x), y(copy.y), z(copy.z), w(copy.w)
        {
        }

        static Quaternion identity()
        {
            return Quaternion(0.0F, 0.0F, 0.0F, 1.0F);
        }

        Quaternion operator*(const Quaternion& q) const
        {
            return Quaternion( x * q.w + y * q.z - z * q.y + w * q.x,
                              -x * q.z + y * q.w + z * q.x + w * q.y,
                               x * q.y - y * q.x + z * q.w + w * q.z,
                              -x * q.x - y * q.y - z * q.z + w * q.w);
        }

        const Quaternion& operator*=(const Quaternion& q)
        {
            float tempX =  x * q.w + y * q.z - z * q.y + w * q.x;
            float tempY = -x * q.z + y * q.w + z * q.x + w * q.y;
            float tempZ =  x * q.y - y * q.x + z * q.w + w * q.z;
            float tempW = -x * q.x - y * q.y - z * q.z + w * q.w;

            x = tempX;
            y = tempY;
            z = tempZ;
            w = tempW;

            return *this;
        }

        Quaternion operator*(float scalar) const
        {
            return Quaternion(x * scalar,
                              y * scalar,
                              z * scalar,
                              w * scalar);
        }

        const Quaternion& operator*=(float scalar)
        {
            x *= scalar;
            y *= scalar;
            z *= scalar;
            w *= scalar;

            return *this;
        }

        Quaternion operator/(float scalar) const
        {
            return Quaternion(x / scalar,
                              y / scalar,
                              z / scalar,
                              w / scalar);
        }

        const Quaternion& operator/=(float scalar)
        {
            x /= scalar;
            y /= scalar;
            z /= scalar;
            w /= scalar;

            return *this;
        }

        inline Quaternion operator-() const
        {
            return Quaternion(-x, -y, -z, -w);
        }

        inline Quaternion operator+(const Quaternion& q) const
        {
            Quaternion result(*this);
            result.x += q.x;
            result.y += q.y;
            result.z += q.z;
            result.w += q.w;

            return result;
        }

        inline Quaternion& operator+=(const Quaternion& q)
        {
            x += q.x;
            y += q.y;
            z += q.z;
            w += q.w;

            return *this;
        }

        inline Quaternion operator-(const Quaternion& q) const
        {
            Quaternion result(*this);
            result.x -= q.x;
            result.y -= q.y;
            result.z -= q.z;
            result.w -= q.w;

            return result;
        }

        inline Quaternion& operator-=(const Quaternion& q)
        {
            x -= q.x;
            y -= q.y;
            z -= q.z;
            w -= q.w;

            return *this;
        }

        inline bool operator==(const Quaternion& q) const
        {
            return x == q.x && y == q.y && z == q.z && w == q.w;
        }

        inline bool operator!=(const Quaternion& q) const
        {
            return x != q.x || y != q.y || z != q.z || w != q.w;
        }

        inline void negate()
        {
            x = -x;
            y = -y;
            z = -z;
            w = -w;
        }

        inline void conjugate()
        {
            x = -x;
            y = -y;
            z = -z;
        }

        inline void invert()
        {
            float n2 = x * x + y * y + z * z + w * w; // norm squared

            if (n2 == 0.0F) return;

            // conjugate divided by norm squared
            x = -x / n2;
            y = -y / n2;
            z = -z / n2;
            w = w / n2;
        }

        float getNorm();
        void normalize();
        void rotate(float angle, Vector3 axis);
        void getRotation(float& angle, Vector3& axis);

        void setEulerAngles(const Vector3& angles);
        Vector3 getEulerAngles() const;
        float getEulerAngleX() const;
        float getEulerAngleY() const;
        float getEulerAngleZ() const;

        inline Vector3 operator*(const Vector3& vector) const
        {
            return rotateVector(vector);
        }

        inline Vector3 rotateVector(const Vector3& vector) const
        {
            Vector3 q(x, y, z);
            Vector3 t = 2.0F * Vector3::cross(q, vector);
            return vector + (w * t) + Vector3::cross(q, t);
        }

        inline Vector3 getRightVector() const
        {
            return rotateVector(Vector3(1.0F, 0.0F, 0.0F));
        }

        inline Vector3 getUpVector() const
        {
            return rotateVector(Vector3(0.0F, 1.0F, 0.0F));
        }

        inline Vector3 getForwardVector() const
        {
            return rotateVector(Vector3(0.0F, 0.0F, 1.0F));
        }

        Quaternion& lerp(const Quaternion& q1, const Quaternion& q2, float t)
        {
            const float scale = 1.0F - t;
            return (*this = (q1 * scale) + (q2 * t));
        }
    };
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGLWidget.h"

#if SK_SUPPORT_GPU

SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
    fDebugger = debugger;
}

SkGLWidget::~SkGLWidget() {
}

void SkGLWidget::setSampleCount(int sampleCount) {
    QGLFormat currentFormat = format();
    currentFormat.setSampleBuffers(sampleCount > 0);
    currentFormat.setSamples(sampleCount);
    setFormat(currentFormat);
}

void SkGLWidget::initializeGL() {
    if (!fCurIntf) {
        fCurIntf.reset(GrGLCreateNativeInterface());
    }
    if (!fCurIntf) {
        return;
    }
    // The call may come multiple times, for example after setSampleCount().  The QGLContext will be
    // different, but we do not have a mechanism to catch the destroying of QGLContext, so that
    // proper resource cleanup could be made.
    if (fCurContext) {
        fCurContext->abandonContext();
    }
    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));
}

void SkGLWidget::createRenderTarget() {
    if (!fCurContext) {
        return;
    }

    glDisable(GL_SCISSOR_TEST);
    glStencilMask(0xffffffff);
    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);
    fCurContext->resetContext();

    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    SkAutoTUnref<GrRenderTarget> curRenderTarget(
            fCurContext->textureProvider()->wrapBackendRenderTarget(desc));
    SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
    fGpuDevice.reset(SkGpuDevice::Create(curRenderTarget, &props,
                                         SkGpuDevice::kUninit_InitContents));
    fCanvas.reset(new SkCanvas(fGpuDevice));
}

void SkGLWidget::resizeGL(int w, int h) {
    SkASSERT(w == this->width() && h == this->height());
    this->createRenderTarget();
}

void SkGLWidget::paintGL() {
    if (!this->isHidden() && fCanvas) {
        fCurContext->resetContext();
        fDebugger->draw(fCanvas.get());
        // TODO(chudy): Implement an optional flush button in Gui.
        fCanvas->flush();
        Q_EMIT drawComplete();
    }
}

GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRoundToInt(this->width());
    desc.fHeight = SkScalarRoundToInt(this->height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
    GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
    GrGLint buffer;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    return desc;
}

#endif
<commit_msg>Fix old debugger GOLD_TRYBOT_URL= https://gold.skia.org/search2?unt=true&query=source_type%3Dgm&master=false&issue=1935623002<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGLWidget.h"

#if SK_SUPPORT_GPU

SkGLWidget::SkGLWidget(SkDebugger* debugger) : QGLWidget() {
    fDebugger = debugger;
}

SkGLWidget::~SkGLWidget() {
}

void SkGLWidget::setSampleCount(int sampleCount) {
    QGLFormat currentFormat = format();
    currentFormat.setSampleBuffers(sampleCount > 0);
    currentFormat.setSamples(sampleCount);
    setFormat(currentFormat);
}

void SkGLWidget::initializeGL() {
    if (!fCurIntf) {
        fCurIntf.reset(GrGLCreateNativeInterface());
    }
    if (!fCurIntf) {
        return;
    }
    // The call may come multiple times, for example after setSampleCount().  The QGLContext will be
    // different, but we do not have a mechanism to catch the destroying of QGLContext, so that
    // proper resource cleanup could be made.
    if (fCurContext) {
        fCurContext->abandonContext();
    }
    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    fCurContext.reset(GrContext::Create(kOpenGL_GrBackend, (GrBackendContext) fCurIntf.get()));
}

void SkGLWidget::createRenderTarget() {
    if (!fCurContext) {
        return;
    }

    glDisable(GL_SCISSOR_TEST);
    glStencilMask(0xffffffff);
    glClearStencil(0);
    glClear(GL_STENCIL_BUFFER_BIT);
    fCurContext->resetContext();

    fGpuDevice.reset(nullptr);
    fCanvas.reset(nullptr);

    GrBackendRenderTargetDesc desc = this->getDesc(this->width(), this->height());
    desc.fOrigin = kBottomLeft_GrSurfaceOrigin;
    sk_sp<GrRenderTarget> curRenderTarget(
            fCurContext->textureProvider()->wrapBackendRenderTarget(desc));
    SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
    fGpuDevice.reset(SkGpuDevice::Make(std::move(curRenderTarget), &props,
                                       SkGpuDevice::kUninit_InitContents).release());
    fCanvas.reset(new SkCanvas(fGpuDevice));
}

void SkGLWidget::resizeGL(int w, int h) {
    SkASSERT(w == this->width() && h == this->height());
    this->createRenderTarget();
}

void SkGLWidget::paintGL() {
    if (!this->isHidden() && fCanvas) {
        fCurContext->resetContext();
        fDebugger->draw(fCanvas.get());
        // TODO(chudy): Implement an optional flush button in Gui.
        fCanvas->flush();
        Q_EMIT drawComplete();
    }
}

GrBackendRenderTargetDesc SkGLWidget::getDesc(int w, int h) {
    GrBackendRenderTargetDesc desc;
    desc.fWidth = SkScalarRoundToInt(this->width());
    desc.fHeight = SkScalarRoundToInt(this->height());
    desc.fConfig = kSkia8888_GrPixelConfig;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_SAMPLES, &desc.fSampleCnt);
    GR_GL_GetIntegerv(fCurIntf, GR_GL_STENCIL_BITS, &desc.fStencilBits);
    GrGLint buffer;
    GR_GL_GetIntegerv(fCurIntf, GR_GL_FRAMEBUFFER_BINDING, &buffer);
    desc.fRenderTargetHandle = buffer;

    return desc;
}

#endif
<|endoftext|>


<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#include "Component.hpp"
#include "Actor.hpp"
#include "math/MathUtils.hpp"

namespace ouzel
{
    namespace scene
    {
        Component::Component(uint32_t initClass):
            cls(initClass)
        {
        }

        Component::~Component()
        {
            if (actor) actor->removeComponent(this);
        }

        void Component::draw(const Matrix4F&,
                             float,
                             const Matrix4F&,
                             bool)
        {
        }

        bool Component::pointOn(const Vector2F& position) const
        {
            return boundingBox.containsPoint(Vector3F(position));
        }

        inline void gatherPolygonProjectionExtents(const std::vector<Vector2F>& vertList,
                                                   const Vector2F& v,
                                                   float& outMin, float& outMax)
        {
            outMin = outMax = v.dot(vertList[0]);

            size_t vertListSize = vertList.size();
            for (size_t i = 1 ; i < vertListSize; ++i)
            {
                float d = v.dot(vertList[i]);
                if (d < outMin) outMin = d;
                else if (d > outMax) outMax = d;
            }
        }

        inline bool findSeparatingAxis(const std::vector<Vector2F>& aVertList,
                                       const std::vector<Vector2F>& bVertList)
        {
            Vector2F v;

            size_t aVertListSize = aVertList.size();
            size_t prev = aVertListSize - 1;
            for (size_t cur = 0; cur < aVertListSize; ++cur)
            {
                Vector2F edge = aVertList[cur] - aVertList[prev];

                v.v[0] = edge.v[1];
                v.v[1] = -edge.v[0];

                float aMin;
                float aMax;
                float bMin;
                float bMax;
                gatherPolygonProjectionExtents(aVertList, v, aMin, aMax);
                gatherPolygonProjectionExtents(bVertList, v, bMin, bMax);

                if (aMax < bMin) return true;
                if (bMax < aMin) return true;

                prev = cur;
            }

            return false;
        }

        bool Component::shapeOverlaps(const std::vector<Vector2F>& edges) const
        {
            std::vector<Vector2F> boundingBoxEdges = {
                Vector2F(boundingBox.min),
                Vector2F(boundingBox.max.v[0], boundingBox.min.v[1]),
                Vector2F(boundingBox.max),
                Vector2F(boundingBox.min.v[0], boundingBox.max.v[1])
            };

            if (findSeparatingAxis(boundingBoxEdges, edges))
                return false;

            if (findSeparatingAxis(edges, boundingBoxEdges))
                return false;

            return true;
        }

        void Component::removeFromActor()
        {
            if (actor) actor->removeComponent(this);
        }

        void Component::setActor(Actor* newActor)
        {
            actor = newActor;
        }

        void Component::setLayer(Layer* newLayer)
        {
            layer = newLayer;
        }

        void Component::updateTransform()
        {
        }
    } // namespace scene
} // namespace ouzel
<commit_msg>Use iterators to calculate polygon overlap<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#include "Component.hpp"
#include "Actor.hpp"
#include "math/MathUtils.hpp"

namespace ouzel
{
    namespace scene
    {
        Component::Component(uint32_t initClass):
            cls(initClass)
        {
        }

        Component::~Component()
        {
            if (actor) actor->removeComponent(this);
        }

        void Component::draw(const Matrix4F&,
                             float,
                             const Matrix4F&,
                             bool)
        {
        }

        bool Component::pointOn(const Vector2F& position) const
        {
            return boundingBox.containsPoint(Vector3F(position));
        }

        static inline void gatherPolygonProjectionExtents(const std::vector<Vector2F>& vertList,
                                                          const Vector2F& v,
                                                          float& outMin, float& outMax)
        {
            auto i = vertList.begin();
            if (i != vertList.end())
            {
                outMin = outMax = v.dot(*i);
                ++i;

                for (; i != vertList.end(); ++i)
                {
                    float d = v.dot(*i);
                    if (d < outMin) outMin = d;
                    else if (d > outMax) outMax = d;
                }
            }
        }

        static inline bool findSeparatingAxis(const std::vector<Vector2F>& aVertList,
                                              const std::vector<Vector2F>& bVertList)
        {
            Vector2F v;
            auto prev = aVertList.end() - 1;
            for (auto cur = aVertList.begin(); cur != aVertList.end(); ++cur)
            {
                Vector2F edge = *cur - *prev;
                v.v[0] = edge.v[1];
                v.v[1] = -edge.v[0];

                float aMin;
                float aMax;
                float bMin;
                float bMax;
                gatherPolygonProjectionExtents(aVertList, v, aMin, aMax);
                gatherPolygonProjectionExtents(bVertList, v, bMin, bMax);

                if (aMax < bMin) return true;
                if (bMax < aMin) return true;

                prev = cur;
            }

            return false;
        }

        bool Component::shapeOverlaps(const std::vector<Vector2F>& edges) const
        {
            std::vector<Vector2F> boundingBoxEdges = {
                Vector2F(boundingBox.min),
                Vector2F(boundingBox.max.v[0], boundingBox.min.v[1]),
                Vector2F(boundingBox.max),
                Vector2F(boundingBox.min.v[0], boundingBox.max.v[1])
            };

            if (findSeparatingAxis(boundingBoxEdges, edges))
                return false;

            if (findSeparatingAxis(edges, boundingBoxEdges))
                return false;

            return true;
        }

        void Component::removeFromActor()
        {
            if (actor) actor->removeComponent(this);
        }

        void Component::setActor(Actor* newActor)
        {
            actor = newActor;
        }

        void Component::setLayer(Layer* newLayer)
        {
            layer = newLayer;
        }

        void Component::updateTransform()
        {
        }
    } // namespace scene
} // namespace ouzel
<|endoftext|>


<commit_before>#include "logger.h"
#include <iostream>
#include <QTime>
#include <QCoreApplication>
#include <QDate>

Logger::Logger(QObject *parent) : QObject(parent){
    //setup the default log file
    QDate date;
    QString current_date = date.currentDate().toString("yyyy-MM-dd");
    QString log_file_name = current_date + ".log";
    setLogDir("log");
    setLogFile("log\\" + log_file_name);
}

void Logger::setLogDir(QString dir){
    //create a dir for log save, default under applicationDirPath/log
    QString app_dir_path = QCoreApplication::applicationDirPath();
    log_dir.mkdir(app_dir_path + "\\" + dir);
}

void Logger::setLogFile(QString file){
    //setup log file location
    QString app_dir_path = QCoreApplication::applicationDirPath();
    log_file.setFileName(app_dir_path + "\\" + file);
    //if log file not exists, new one
    if(!log_file.exists()){
        //only new, not do anything
        log_file.open(QIODevice::WriteOnly | QIODevice::Text);
        log_file.close();
    }
}

void Logger::log(QString log_type, QString log_msg){
    //set the file open as R/W, text and append
    log_file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append);
    //append use QTextStream
    QTextStream in(&log_file);
    //log format is "hh:mm:ss[<log_type>]: <log_msg>", time is the currentTime
    QTime time;
    in<<time.currentTime().toString("hh:mm:ss")<<" ["<<log_type<<"]: "<<log_msg<<"\n";
    //log finished and close IO
    log_file.close();
}
<commit_msg>add comments in logger<commit_after>#include "logger.h"
#include <iostream>
#include <QTime>
#include <QCoreApplication>
#include <QDate>

Logger::Logger(QObject *parent) : QObject(parent){
    //setup the default log file
    QDate date;
    QString current_date = date.currentDate().toString("yyyy-MM-dd");
    QString log_file_name = current_date + ".log";
    setLogDir("log");
    setLogFile("log\\" + log_file_name);
}

/*
 * Logger: Set Log Dir
 * Input: QString dir path for file save
 * Return: NONE
 */
void Logger::setLogDir(QString dir){
    //create a dir for log save, default under applicationDirPath/log
    QString app_dir_path = QCoreApplication::applicationDirPath();
    log_dir.mkdir(app_dir_path + "\\" + dir);
}

/*
 * Logger: Set Log File
 * Input: QString file name for log
 * Return: NONE
 */
void Logger::setLogFile(QString file){
    //setup log file location
    QString app_dir_path = QCoreApplication::applicationDirPath();
    log_file.setFileName(app_dir_path + "\\" + file);
    //if log file not exists, new one
    if(!log_file.exists()){
        //only new, not do anything
        log_file.open(QIODevice::WriteOnly | QIODevice::Text);
        log_file.close();
    }
}

/*
 * Logger: Log Information
 * Input: QString log type: [INFO],[ERROR],[DEBUG],etc. QString log message
 * Return: NONE
 */
void Logger::log(QString log_type, QString log_msg){
    //set the file open as R/W, text and append
    log_file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append);
    //append use QTextStream
    QTextStream in(&log_file);
    //log format is "hh:mm:ss[<log_type>]: <log_msg>", time is the currentTime
    QTime time;
    in<<time.currentTime().toString("hh:mm:ss")<<" ["<<log_type<<"]: "<<log_msg<<"\n";
    //log finished and close IO
    log_file.close();
}
<|endoftext|>