<commit_before>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *
 *    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 <assert.h>
#include <stdio.h>
#include <unistd.h>

#include <iostream>

#include "SetupPayload.cpp"
#include "Base45.cpp"
#include "QRCodeSetupPayloadGenerator.cpp"
#include "QRCodeSetupPayloadParser.cpp"

using namespace chip;
using namespace std;

#define EXPECT_EQ(x, y)                                                                                \
    ((x) != (y)) ? cerr << endl << __FILE__ << ":" << __LINE__ << ":error EXPECT_EQ(" << x << ", " << y << ")\n", 1 : 0

int testPayloadByteArrayRep()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    QRCodeSetupPayloadGenerator generator(payload);
    string result   = generator.payloadBinaryRepresentation();
    string expected = "000000000000000000100000000000010000000000000000100000000000000000010000000000000011001010";

    return EXPECT_EQ(result, expected);
}

int testPayloadBase45Rep()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    QRCodeSetupPayloadGenerator generator(payload);
    string result   = generator.payloadBase45Representation();
    string expected = "B20800G00G8G000";

    return EXPECT_EQ(result, expected);
}

int testBase45()
{
    int surprises = 0;

    uint8_t input[] = { 10, 10, 10 };

    surprises += EXPECT_EQ(base45Encode(input, 0), "");

    surprises += EXPECT_EQ(base45Encode(input, 1), "A0");

    surprises += EXPECT_EQ(base45Encode(input, 2), "5C1");

    surprises += EXPECT_EQ(base45Encode(input, 3), "5C1A0");

    surprises += EXPECT_EQ(base45Encode((uint8_t *) "Hello World!", sizeof("Hello World!") - 1), "8 C VDN44I3E.VD/94");

    vector<uint8_t> decoded = vector<uint8_t>();
    surprises += EXPECT_EQ(base45Decode("8 C VDN44I3E.VD/94", decoded), CHIP_NO_ERROR);

    string hello_world;
    for (size_t _ = 0; _ < decoded.size(); _++)
    {
        hello_world += (char) decoded[_];
    }
    surprises += EXPECT_EQ(hello_world, "Hello World!");

    // short input
    surprises += EXPECT_EQ(base45Decode("A0", decoded), CHIP_NO_ERROR);
    surprises += EXPECT_EQ(decoded.size(), 2);

    // empty == empty
    surprises += EXPECT_EQ(base45Decode("", decoded), CHIP_NO_ERROR);
    surprises += EXPECT_EQ(decoded.size(), 0);
    // too short
    surprises += EXPECT_EQ(base45Decode("A", decoded), CHIP_ERROR_INVALID_MESSAGE_LENGTH);

    // outside valid chars
    surprises += EXPECT_EQ(base45Decode("0\001", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("\0010", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("[0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("0[", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);

    // BOGUS chars
    surprises += EXPECT_EQ(base45Decode("!0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("\"0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("#0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("&0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("'0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("(0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(")0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(",0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(";0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("<0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("=0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(">0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("@0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);

    return surprises;
}

int testBitsetLen()
{
    return EXPECT_EQ(kTotalPayloadDataSizeInBits % 8, 0);
}

int testSetupPayloadVerify()
{
    int surprises = 0;
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;
    surprises += EXPECT_EQ(payload.isValid(), true);

    // test invalid version
    SetupPayload test_payload = payload;
    test_payload.version      = 2 << kVersionFieldLengthInBits;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    // test invalid rendezvousInformation
    test_payload                       = payload;
    test_payload.rendezvousInformation = 512;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    // test invalid discriminator
    test_payload               = payload;
    test_payload.discriminator = 2 << kPayloadDiscriminatorFieldLengthInBits;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    // test invalid stetup PIN
    test_payload              = payload;
    test_payload.setUpPINCode = 2 << kSetupPINCodeFieldLengthInBits;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    return surprises;
}

int testInvalidQRCodePayload_WrongCharacterSet()
{
    int surprises        = 0;
    string invalidString = "adas12AA";

    QRCodeSetupPayloadParser parser = QRCodeSetupPayloadParser(invalidString);
    SetupPayload payload;
    CHIP_ERROR err = parser.populatePayload(payload);
    bool didFail   = err != CHIP_NO_ERROR;
    surprises      = EXPECT_EQ(didFail, true);
    surprises      = EXPECT_EQ(payload.isValid(), false);
    return surprises;
}

int testInvalidQRCodePayload_WrongLength()
{
    int surprises                   = 0;
    string invalidString            = "AA12";
    QRCodeSetupPayloadParser parser = QRCodeSetupPayloadParser(invalidString);
    SetupPayload payload;
    CHIP_ERROR err = parser.populatePayload(payload);
    bool didFail   = err != CHIP_NO_ERROR;
    surprises      = EXPECT_EQ(didFail, true);
    surprises      = EXPECT_EQ(payload.isValid(), false);
    return surprises;
}

int testPayloadEquality()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    SetupPayload equalPayload;
    equalPayload.version               = 5;
    equalPayload.vendorID              = 12;
    equalPayload.productID             = 1;
    equalPayload.requiresCustomFlow    = 0;
    equalPayload.rendezvousInformation = 1;
    equalPayload.discriminator         = 128;
    equalPayload.setUpPINCode          = 2048;

    bool result = payload == equalPayload;
    return EXPECT_EQ(result, true);
}

int testPayloadInEquality()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    SetupPayload unequalPayload;
    unequalPayload.version               = 5;
    unequalPayload.vendorID              = 12;
    unequalPayload.productID             = 1;
    unequalPayload.requiresCustomFlow    = 0;
    unequalPayload.rendezvousInformation = 1;
    unequalPayload.discriminator         = 28;
    unequalPayload.setUpPINCode          = 121233;

    bool result = payload == unequalPayload;
    return EXPECT_EQ(result, false);
}

int testQRCodeToPayloadGeneration()
{
    int surprises = 0;
    SetupPayload payload;
    payload.version               = 3;
    payload.vendorID              = 100;
    payload.productID             = 12;
    payload.requiresCustomFlow    = 1;
    payload.rendezvousInformation = 4;
    payload.discriminator         = 233;
    payload.setUpPINCode          = 5221133;

    QRCodeSetupPayloadGenerator generator(payload);
    string base45Rep = generator.payloadBase45Representation();

    SetupPayload resultingPayload;
    QRCodeSetupPayloadParser parser(base45Rep);

    CHIP_ERROR err  = parser.populatePayload(resultingPayload);
    bool didSucceed = err == CHIP_NO_ERROR;
    surprises       = EXPECT_EQ(didSucceed, true);
    surprises       = EXPECT_EQ(resultingPayload.isValid(), true);

    bool result = payload == resultingPayload;
    surprises += EXPECT_EQ(result, true);
    return surprises;
}

int main(int argc, char ** argv)
{
    bool result = testBitsetLen() + testPayloadByteArrayRep() + testPayloadBase45Rep() + testBase45() + testSetupPayloadVerify() +
        testPayloadEquality() + testPayloadInEquality() + testQRCodeToPayloadGeneration() +
        testInvalidQRCodePayload_WrongCharacterSet() + testInvalidQRCodePayload_WrongLength();
    if (result == 0)
    {
        printf("\n** All QRCode tests pass **\n");
    }
    else
    {
        printf("\n**== QRCode tests FAILED ==**\n");
    }
    return result;
}
<commit_msg>PR Feedback<commit_after>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *
 *    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 <assert.h>
#include <stdio.h>
#include <unistd.h>

#include <iostream>

#include "SetupPayload.cpp"
#include "Base45.cpp"
#include "QRCodeSetupPayloadGenerator.cpp"
#include "QRCodeSetupPayloadParser.cpp"

using namespace chip;
using namespace std;

#define EXPECT_EQ(x, y)                                                                                \
    ((x) != (y)) ? cerr << endl << __FILE__ << ":" << __LINE__ << ":error EXPECT_EQ(" << x << ", " << y << ")\n", 1 : 0

int testPayloadByteArrayRep()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    QRCodeSetupPayloadGenerator generator(payload);
    string result   = generator.payloadBinaryRepresentation();
    string expected = "000000000000000000100000000000010000000000000000100000000000000000010000000000000011001010";

    return EXPECT_EQ(result, expected);
}

int testPayloadBase45Rep()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    QRCodeSetupPayloadGenerator generator(payload);
    string result   = generator.payloadBase45Representation();
    string expected = "B20800G00G8G000";

    return EXPECT_EQ(result, expected);
}

int testBase45()
{
    int surprises = 0;

    uint8_t input[] = { 10, 10, 10 };

    surprises += EXPECT_EQ(base45Encode(input, 0), "");

    surprises += EXPECT_EQ(base45Encode(input, 1), "A0");

    surprises += EXPECT_EQ(base45Encode(input, 2), "5C1");

    surprises += EXPECT_EQ(base45Encode(input, 3), "5C1A0");

    surprises += EXPECT_EQ(base45Encode((uint8_t *) "Hello World!", sizeof("Hello World!") - 1), "8 C VDN44I3E.VD/94");

    vector<uint8_t> decoded = vector<uint8_t>();
    surprises += EXPECT_EQ(base45Decode("8 C VDN44I3E.VD/94", decoded), CHIP_NO_ERROR);

    string hello_world;
    for (size_t _ = 0; _ < decoded.size(); _++)
    {
        hello_world += (char) decoded[_];
    }
    surprises += EXPECT_EQ(hello_world, "Hello World!");

    // short input
    surprises += EXPECT_EQ(base45Decode("A0", decoded), CHIP_NO_ERROR);
    surprises += EXPECT_EQ(decoded.size(), 2);

    // empty == empty
    surprises += EXPECT_EQ(base45Decode("", decoded), CHIP_NO_ERROR);
    surprises += EXPECT_EQ(decoded.size(), 0);
    // too short
    surprises += EXPECT_EQ(base45Decode("A", decoded), CHIP_ERROR_INVALID_MESSAGE_LENGTH);

    // outside valid chars
    surprises += EXPECT_EQ(base45Decode("0\001", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("\0010", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("[0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("0[", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);

    // BOGUS chars
    surprises += EXPECT_EQ(base45Decode("!0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("\"0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("#0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("&0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("'0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("(0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(")0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(",0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(";0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("<0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("=0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode(">0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);
    surprises += EXPECT_EQ(base45Decode("@0", decoded), CHIP_ERROR_INVALID_INTEGER_VALUE);

    return surprises;
}

int testBitsetLen()
{
    return EXPECT_EQ(kTotalPayloadDataSizeInBits % 8, 0);
}

int testSetupPayloadVerify()
{
    int surprises = 0;
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;
    surprises += EXPECT_EQ(payload.isValid(), true);

    // test invalid version
    SetupPayload test_payload = payload;
    test_payload.version      = 2 << kVersionFieldLengthInBits;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    // test invalid rendezvousInformation
    test_payload                       = payload;
    test_payload.rendezvousInformation = 512;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    // test invalid discriminator
    test_payload               = payload;
    test_payload.discriminator = 2 << kPayloadDiscriminatorFieldLengthInBits;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    // test invalid stetup PIN
    test_payload              = payload;
    test_payload.setUpPINCode = 2 << kSetupPINCodeFieldLengthInBits;
    surprises += EXPECT_EQ(test_payload.isValid(), false);

    return surprises;
}

int testInvalidQRCodePayload_WrongCharacterSet()
{
    int surprises        = 0;
    string invalidString = "adas12AA";

    QRCodeSetupPayloadParser parser = QRCodeSetupPayloadParser(invalidString);
    SetupPayload payload;
    CHIP_ERROR err = parser.populatePayload(payload);
    bool didFail   = err != CHIP_NO_ERROR;
    surprises      = EXPECT_EQ(didFail, true);
    surprises      = EXPECT_EQ(payload.isValid(), false);
    return surprises;
}

int testInvalidQRCodePayload_WrongLength()
{
    int surprises                   = 0;
    string invalidString            = "AA12";
    QRCodeSetupPayloadParser parser = QRCodeSetupPayloadParser(invalidString);
    SetupPayload payload;
    CHIP_ERROR err = parser.populatePayload(payload);
    bool didFail   = err != CHIP_NO_ERROR;
    surprises      = EXPECT_EQ(didFail, true);
    surprises      = EXPECT_EQ(payload.isValid(), false);
    return surprises;
}

int testPayloadEquality()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    SetupPayload equalPayload;
    equalPayload.version               = 5;
    equalPayload.vendorID              = 12;
    equalPayload.productID             = 1;
    equalPayload.requiresCustomFlow    = 0;
    equalPayload.rendezvousInformation = 1;
    equalPayload.discriminator         = 128;
    equalPayload.setUpPINCode          = 2048;

    bool result = payload == equalPayload;
    return EXPECT_EQ(result, true);
}

int testPayloadInEquality()
{
    SetupPayload payload;

    payload.version               = 5;
    payload.vendorID              = 12;
    payload.productID             = 1;
    payload.requiresCustomFlow    = 0;
    payload.rendezvousInformation = 1;
    payload.discriminator         = 128;
    payload.setUpPINCode          = 2048;

    SetupPayload unequalPayload;
    unequalPayload.version               = 5;
    unequalPayload.vendorID              = 12;
    unequalPayload.productID             = 1;
    unequalPayload.requiresCustomFlow    = 0;
    unequalPayload.rendezvousInformation = 1;
    unequalPayload.discriminator         = 28;
    unequalPayload.setUpPINCode          = 121233;

    bool result = payload == unequalPayload;
    return EXPECT_EQ(result, false);
}

int testQRCodeToPayloadGeneration()
{
    int surprises = 0;
    SetupPayload payload;
    payload.version               = 3;
    payload.vendorID              = 100;
    payload.productID             = 12;
    payload.requiresCustomFlow    = 1;
    payload.rendezvousInformation = 4;
    payload.discriminator         = 233;
    payload.setUpPINCode          = 5221133;

    QRCodeSetupPayloadGenerator generator(payload);
    string base45Rep = generator.payloadBase45Representation();

    SetupPayload resultingPayload;
    QRCodeSetupPayloadParser parser(base45Rep);

    CHIP_ERROR err  = parser.populatePayload(resultingPayload);
    bool didSucceed = err == CHIP_NO_ERROR;
    surprises       = EXPECT_EQ(didSucceed, true);
    surprises       = EXPECT_EQ(resultingPayload.isValid(), true);

    bool result = payload == resultingPayload;
    surprises += EXPECT_EQ(result, true);
    return surprises;
}

int main(int argc, char ** argv)
{
    int result = testBitsetLen() + testPayloadByteArrayRep() + testPayloadBase45Rep() + testBase45() + testSetupPayloadVerify() +
        testPayloadEquality() + testPayloadInEquality() + testQRCodeToPayloadGeneration() +
        testInvalidQRCodePayload_WrongCharacterSet() + testInvalidQRCodePayload_WrongLength();
    if (result == 0)
    {
        printf("\n** All QRCode tests pass **\n");
    }
    else
    {
        printf("\n**== QRCode tests FAILED ==**\n");
    }
    return result;
}
<|endoftext|>


<commit_before>#include "rosplan_knowledge_base/KnowledgeComparitor.h"

#include <boost/algorithm/string.hpp>

/* implementation of KnowledgeComparitor.h */
namespace KCL_rosplan {

	/**
	 * returns true iff inequality is true
	 */
	bool KnowledgeComparitor::inequalityTrue(const rosplan_knowledge_msgs::KnowledgeItem &a, const std::vector<rosplan_knowledge_msgs::KnowledgeItem> &modelFunctions) {

		double lhs = KnowledgeComparitor::evaluateExpression(a.ineq.LHS, modelFunctions);
		double rhs = KnowledgeComparitor::evaluateExpression(a.ineq.RHS, modelFunctions);

		switch(a.ineq.comparison_type) {
			case rosplan_knowledge_msgs::DomainInequality::GREATER:   return lhs>rhs;
			case rosplan_knowledge_msgs::DomainInequality::GREATEREQ: return lhs>=rhs;
			case rosplan_knowledge_msgs::DomainInequality::LESS:      return lhs<rhs;
			case rosplan_knowledge_msgs::DomainInequality::LESSEQ:    return lhs<=rhs;
			case rosplan_knowledge_msgs::DomainInequality::EQUALS:    return lhs==rhs;
		}
		ROS_ERROR("KCL: (%s) Knowledge Comapritor does not recognise comparison type.", ros::this_node::getName().c_str());
		return false;
	}

	/**
	 * evaluates the prefix expression
	 */
	double KnowledgeComparitor::evaluateExpression(const rosplan_knowledge_msgs::ExprComposite &expr, const std::vector<rosplan_knowledge_msgs::KnowledgeItem> &modelFunctions) {

		std::vector<rosplan_knowledge_msgs::ExprBase> tokens = expr.tokens;

		bool pending_operand = false;
		std::vector<rosplan_knowledge_msgs::ExprBase> operator_stack;
		std::vector<rosplan_knowledge_msgs::ExprBase> operand_stack;
		for(int i=0;i<tokens.size();i++) {
			rosplan_knowledge_msgs::ExprBase token = tokens[i];
			switch(token.expr_type) {
				case rosplan_knowledge_msgs::ExprBase::OPERATOR:
					operator_stack.push_back(token);
					pending_operand = false;
					break;
				case rosplan_knowledge_msgs::ExprBase::CONSTANT:
				case rosplan_knowledge_msgs::ExprBase::FUNCTION:
				case rosplan_knowledge_msgs::ExprBase::SPECIAL:

					if(pending_operand) {
						while (operand_stack.size()>0) {
							rosplan_knowledge_msgs::ExprBase lhs = token;
							rosplan_knowledge_msgs::ExprBase rhs = operand_stack.back();
							operand_stack.pop_back();
							rosplan_knowledge_msgs::ExprBase op = operator_stack.back();
							operator_stack.back();
							double value = KnowledgeComparitor::evaluateOperation(
									KnowledgeComparitor::getValue(lhs, modelFunctions),
									KnowledgeComparitor::getValue(rhs, modelFunctions),
									op);
							token.expr_type = rosplan_knowledge_msgs::ExprBase::CONSTANT;
							token.constant = value;
						}
					}
					pending_operand = true;
					operand_stack.push_back(token);
					break;
			}
		}

		rosplan_knowledge_msgs::ExprBase result = operand_stack.back();
		operand_stack.pop_back();
		return getValue(result, modelFunctions);
	}

	/*
	 * evaluate numeric expression between two ExprBase messages.
	 */
	double KnowledgeComparitor::evaluateOperation(const double &lhs, const double &rhs, const rosplan_knowledge_msgs::ExprBase &op) {

		switch(op.op) {
			case rosplan_knowledge_msgs::ExprBase::ADD: return lhs+rhs;
			case rosplan_knowledge_msgs::ExprBase::SUB: return lhs-rhs;
			case rosplan_knowledge_msgs::ExprBase::MUL: return lhs*rhs;
			case rosplan_knowledge_msgs::ExprBase::DIV: return lhs/rhs;
			case rosplan_knowledge_msgs::ExprBase::UMINUS: return -lhs;
		}
		ROS_ERROR("KCL: (%s) Knowledge Comapritor does not recognise operator type.", ros::this_node::getName().c_str());
		return 0;
	}

	/*
	 * Find numeric value of an ExprBase message, i.e. evaluate the value of PDDL function
	 */
	double KnowledgeComparitor::getValue(const rosplan_knowledge_msgs::ExprBase &expr, const std::vector<rosplan_knowledge_msgs::KnowledgeItem> &modelFunctions) {
		switch(expr.expr_type) {
			case rosplan_knowledge_msgs::ExprBase::CONSTANT:
				return expr.constant;
			case rosplan_knowledge_msgs::ExprBase::FUNCTION:
				std::vector<rosplan_knowledge_msgs::KnowledgeItem>::const_iterator fit = modelFunctions.begin();
				for(; fit!=modelFunctions.end(); fit++) {
					if(expr.function.name == fit->attribute_name && expr.function.typed_parameters.size() == fit->values.size()) {
						// parameters
						bool match = true;
						for(size_t i=0;i<fit->values.size();i++) {
							if("" != expr.function.typed_parameters[i].value && !(boost::iequals(expr.function.typed_parameters[i].value, fit->values[i].value))) {
								match = false;
							}
						}
						if(match) {
							return fit->function_value;
						}
					}
				}
				return 0;
		}
		ROS_ERROR("KCL: (%s) Knowledge Comapritor cannot get value for base expression.", ros::this_node::getName().c_str());
		return 0;
	}

	/**
	 * returns true iff a matches the knowledge in b.
	 */
	bool KnowledgeComparitor::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) {

		int matches = 0;
		if(a.knowledge_type != b.knowledge_type) return false;

		switch(a.knowledge_type) {

		case rosplan_knowledge_msgs::KnowledgeItem::INSTANCE:
			{
				// check instance knowledge
				if(0!=a.instance_type.compare(b.instance_type)) return false;
				if(a.instance_name!="" && !boost::iequals(a.instance_name, b.instance_name)) return false;
				return true;
			}
			break;

		case rosplan_knowledge_msgs::KnowledgeItem::FUNCTION:

 			// compare functions (use _inequalityTrue_ to check function values)
            //       KnowledgeComparitor::inequalityTrue
			//if(a.function_value != b.function_value) return false;

		// check function or fact label and parameters all match
		case rosplan_knowledge_msgs::KnowledgeItem::FACT:
			{
				// label
				if(a.attribute_name=="") return true;
				if(!boost::iequals(a.attribute_name, b.attribute_name)) return false;

				// negative fact
				if(a.is_negative != b.is_negative) return false;

				// parameters
				if(a.values.size() != b.values.size()) return false;
				for(size_t i=0;i<a.values.size();i++) {
					if("" == a.values[i].value) {
						++matches;
					} else if(boost::iequals(a.values[i].value, b.values[i].value)) {
						++matches;
					}
				}
				return (matches == a.values.size());
			}
			break;
		}
	}

	/**
	 * returns true is the knowledge item contains the instance, as instance or attribute parameter.
	 */
	bool KnowledgeComparitor::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) {

		if(0==a.instance_name.compare(name))
			return true;

		for(size_t i=0;i<a.values.size();i++) {
			if(boost::iequals(a.values[i].value, name))
				return true;
		}

		return false;
	}

} // close namespace
<commit_msg>Update rosplan_knowledge_base/src/KnowledgeComparitor.cpp<commit_after>#include "rosplan_knowledge_base/KnowledgeComparitor.h"

#include <boost/algorithm/string.hpp>

/* implementation of KnowledgeComparitor.h */
namespace KCL_rosplan {

	/**
	 * returns true iff inequality is true
	 */
	bool KnowledgeComparitor::inequalityTrue(const rosplan_knowledge_msgs::KnowledgeItem &a, const std::vector<rosplan_knowledge_msgs::KnowledgeItem> &modelFunctions) {

		double lhs = KnowledgeComparitor::evaluateExpression(a.ineq.LHS, modelFunctions);
		double rhs = KnowledgeComparitor::evaluateExpression(a.ineq.RHS, modelFunctions);

		switch(a.ineq.comparison_type) {
			case rosplan_knowledge_msgs::DomainInequality::GREATER:   return lhs>rhs;
			case rosplan_knowledge_msgs::DomainInequality::GREATEREQ: return lhs>=rhs;
			case rosplan_knowledge_msgs::DomainInequality::LESS:      return lhs<rhs;
			case rosplan_knowledge_msgs::DomainInequality::LESSEQ:    return lhs<=rhs;
			case rosplan_knowledge_msgs::DomainInequality::EQUALS:    return lhs==rhs;
		}
		ROS_ERROR("KCL: (%s) Knowledge Comapritor does not recognise comparison type.", ros::this_node::getName().c_str());
		return false;
	}

	/**
	 * evaluates the prefix expression
	 */
	double KnowledgeComparitor::evaluateExpression(const rosplan_knowledge_msgs::ExprComposite &expr, const std::vector<rosplan_knowledge_msgs::KnowledgeItem> &modelFunctions) {

		std::vector<rosplan_knowledge_msgs::ExprBase> tokens = expr.tokens;

		bool pending_operand = false;
		std::vector<rosplan_knowledge_msgs::ExprBase> operator_stack;
		std::vector<rosplan_knowledge_msgs::ExprBase> operand_stack;
		for(int i=0;i<tokens.size();i++) {
			rosplan_knowledge_msgs::ExprBase token = tokens[i];
			switch(token.expr_type) {
				case rosplan_knowledge_msgs::ExprBase::OPERATOR:
					operator_stack.push_back(token);
					pending_operand = false;
					break;
				case rosplan_knowledge_msgs::ExprBase::CONSTANT:
				case rosplan_knowledge_msgs::ExprBase::FUNCTION:
				case rosplan_knowledge_msgs::ExprBase::SPECIAL:

					if(pending_operand) {
						while (operand_stack.size()>0) {
							rosplan_knowledge_msgs::ExprBase lhs = token;
							rosplan_knowledge_msgs::ExprBase rhs = operand_stack.back();
							operand_stack.pop_back();
							rosplan_knowledge_msgs::ExprBase op = operator_stack.back();
							operator_stack.back();
							double value = KnowledgeComparitor::evaluateOperation(
									KnowledgeComparitor::getValue(lhs, modelFunctions),
									KnowledgeComparitor::getValue(rhs, modelFunctions),
									op);
							token.expr_type = rosplan_knowledge_msgs::ExprBase::CONSTANT;
							token.constant = value;
						}
					}
					pending_operand = true;
					operand_stack.push_back(token);
					break;
			}
		}

		rosplan_knowledge_msgs::ExprBase result = operand_stack.back();
		operand_stack.pop_back();
		return getValue(result, modelFunctions);
	}

	/*
	 * evaluate numeric expression between two ExprBase messages.
	 */
	double KnowledgeComparitor::evaluateOperation(const double &lhs, const double &rhs, const rosplan_knowledge_msgs::ExprBase &op) {

		switch(op.op) {
			case rosplan_knowledge_msgs::ExprBase::ADD: return lhs+rhs;
			case rosplan_knowledge_msgs::ExprBase::SUB: return lhs-rhs;
			case rosplan_knowledge_msgs::ExprBase::MUL: return lhs*rhs;
			case rosplan_knowledge_msgs::ExprBase::DIV: return lhs/rhs;
			case rosplan_knowledge_msgs::ExprBase::UMINUS: return -lhs;
		}
		ROS_ERROR("KCL: (%s) Knowledge Comapritor does not recognise operator type.", ros::this_node::getName().c_str());
		return 0;
	}

	/*
	 * Find numeric value of an ExprBase message, i.e. evaluate the value of PDDL function
	 */
	double KnowledgeComparitor::getValue(const rosplan_knowledge_msgs::ExprBase &expr, const std::vector<rosplan_knowledge_msgs::KnowledgeItem> &modelFunctions) {
		switch(expr.expr_type) {
			case rosplan_knowledge_msgs::ExprBase::CONSTANT:
				return expr.constant;
			case rosplan_knowledge_msgs::ExprBase::FUNCTION:
				std::vector<rosplan_knowledge_msgs::KnowledgeItem>::const_iterator fit = modelFunctions.begin();
				for(; fit!=modelFunctions.end(); fit++) {
					if(expr.function.name == fit->attribute_name && expr.function.typed_parameters.size() == fit->values.size()) {
						// parameters
						bool match = true;
						for(size_t i=0;i<fit->values.size();i++) {
							if("" != expr.function.typed_parameters[i].value && !(boost::iequals(expr.function.typed_parameters[i].value, fit->values[i].value))) {
								match = false;
							}
						}
						if(match) {
							return fit->function_value;
						}
					}
				}
				return 0;
		}
		ROS_ERROR("KCL: (%s) Knowledge Comapritor cannot get value for base expression.", ros::this_node::getName().c_str());
		return 0;
	}

	/**
	 * returns true iff a matches the knowledge in b.
	 */
	bool KnowledgeComparitor::containsKnowledge(const rosplan_knowledge_msgs::KnowledgeItem &a, const rosplan_knowledge_msgs::KnowledgeItem &b) {

		int matches = 0;
		if(a.knowledge_type != b.knowledge_type) return false;

		switch(a.knowledge_type) {

		case rosplan_knowledge_msgs::KnowledgeItem::INSTANCE:
			{
				// check instance knowledge
				if(0!=a.instance_type.compare(b.instance_type)) return false;
				if(a.instance_name!="" && !boost::iequals(a.instance_name, b.instance_name)) return false;
				return true;
			}
			break;

		case rosplan_knowledge_msgs::KnowledgeItem::FUNCTION:

 			// compare functions (use _inequalityTrue_ to check function values)
			//if(a.function_value != b.function_value) return false;

		// check function or fact label and parameters all match
		case rosplan_knowledge_msgs::KnowledgeItem::FACT:
			{
				// label
				if(a.attribute_name=="") return true;
				if(!boost::iequals(a.attribute_name, b.attribute_name)) return false;

				// negative fact
				if(a.is_negative != b.is_negative) return false;

				// parameters
				if(a.values.size() != b.values.size()) return false;
				for(size_t i=0;i<a.values.size();i++) {
					if("" == a.values[i].value) {
						++matches;
					} else if(boost::iequals(a.values[i].value, b.values[i].value)) {
						++matches;
					}
				}
				return (matches == a.values.size());
			}
			break;
		}
	}

	/**
	 * returns true is the knowledge item contains the instance, as instance or attribute parameter.
	 */
	bool KnowledgeComparitor::containsInstance(const rosplan_knowledge_msgs::KnowledgeItem &a, std::string &name) {

		if(0==a.instance_name.compare(name))
			return true;

		for(size_t i=0;i<a.values.size();i++) {
			if(boost::iequals(a.values[i].value, name))
				return true;
		}

		return false;
	}

} // close namespace
<|endoftext|>


<commit_before>/*
   Copyright 2011 StormMQ Limited

   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 <TestHarness.h>
#include "Thread/Thread.h"
#include "Thread/Mutex.h"
#include "Thread/ConditionVariable.h"

#include "debug_helper.h"

SUITE(Thread)
{
    class ThreadFixture
    {
    public:
        ThreadFixture() : saved_from_thread(0)
        {
            amqp_mutex_initialize(&mutex);
            amqp_condition_initialize(&cv);
        }

        ~ThreadFixture()
        {
            amqp_condition_destroy(&cv);
            amqp_mutex_destroy(&mutex);
        }

        const char *saved_from_thread;

        amqp_mutex_t mutex;
        amqp_condition_variable_t cv;

        static const char *pattern;
        static void handler(void *argument);
    private:
    };

    const char *ThreadFixture::pattern = "HeLlO wOrLd";
    void ThreadFixture::handler(void *argument)
    {
        ThreadFixture *fixture = (ThreadFixture *) argument;
        amqp_mutex_lock(&fixture->mutex);

        fixture->saved_from_thread = ThreadFixture::pattern;

        amqp_condition_notify(&fixture->cv);

        amqp_mutex_unlock(&fixture->mutex);
    }

    // Not really proof that the threading wrappers do the right thing.
    TEST_FIXTURE(ThreadFixture, exercise_thread_api)
    {
        CHECK_EQUAL((void *) 0, saved_from_thread);

        amqp_mutex_lock(&mutex);
        amqp_thread_t *thread = amqp_thread_start(ThreadFixture::handler, this);
        amqp_condition_wait(&cv, &mutex);
        amqp_mutex_unlock(&mutex);

        amqp_thread_destroy(thread);

        CHECK_EQUAL(pattern, saved_from_thread);
    }
}
<commit_msg>Remove duplication.<commit_after>/*
   Copyright 2011 StormMQ Limited

   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 <TestHarness.h>
#include "Thread/Thread.h"

#include "debug_helper.h"

SUITE(Thread)
{
    class ThreadFixture
    {
    public:
        ThreadFixture() : saved_from_thread(0)
        {
            amqp_mutex_initialize(&mutex);
            amqp_condition_initialize(&cv);
        }

        ~ThreadFixture()
        {
            amqp_condition_destroy(&cv);
            amqp_mutex_destroy(&mutex);
        }

        const char *saved_from_thread;

        amqp_mutex_t mutex;
        amqp_condition_variable_t cv;

        static const char *pattern;
        static void handler(void *argument);
    private:
    };

    const char *ThreadFixture::pattern = "HeLlO wOrLd";
    void ThreadFixture::handler(void *argument)
    {
        ThreadFixture *fixture = (ThreadFixture *) argument;
        amqp_mutex_lock(&fixture->mutex);

        fixture->saved_from_thread = ThreadFixture::pattern;

        amqp_condition_notify(&fixture->cv);

        amqp_mutex_unlock(&fixture->mutex);
    }

    // Not really proof that the threading wrappers do the right thing.
    TEST_FIXTURE(ThreadFixture, exercise_thread_api)
    {
        CHECK_EQUAL((void *) 0, saved_from_thread);

        amqp_mutex_lock(&mutex);
        amqp_thread_t *thread = amqp_thread_start(ThreadFixture::handler, this);
        amqp_condition_wait(&cv, &mutex);
        amqp_mutex_unlock(&mutex);

        amqp_thread_destroy(thread);

        CHECK_EQUAL(pattern, saved_from_thread);
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: jglaser

/*! \file SnapshotSystemData.cc
    \brief Implements SnapshotSystemData related functions
 */

#include "SnapshotSystemData.h"
#include <pybind11/pybind11.h>
namespace py = pybind11;

template<class Real>
void SnapshotSystemData<Real>::replicate(unsigned int nx, unsigned int ny, unsigned int nz)
    {
    assert(nx > 0);
    assert(ny > 0);
    assert(nz > 0);

    // Update global box
    BoxDim old_box = global_box;
    Scalar3 L = global_box.getL();
    L.x *= (Scalar)nx;
    L.y *= (Scalar)ny;
    L.z *= (Scalar)nz;
    global_box.setL(L);

    unsigned int old_n = particle_data.size;
    unsigned int n = nx * ny * nz;

    // replicate snapshots
    particle_data.replicate(nx, ny, nz, old_box, global_box);
    bond_data.replicate(n, old_n);
    angle_data.replicate(n, old_n);
    dihedral_data.replicate(n, old_n);
    improper_data.replicate(n, old_n);
    constraint_data.replicate(n, old_n);
    pair_data.replicate(n, old_n);
    }

template<class Real> void SnapshotSystemData<Real>::wrap()
    {
    for (unsigned int i = 0; i < particle_data.size; i++)
        {
        auto const frac = global_box.makeFraction(particle_data.pos[i]);
        auto modulus_positive = [](auto x){ return std::fmod(std::fmod(x, Real(1.0)) + Real(1.0), Real(1.0)); };
        auto const wrapped = vec3<Real>(
            modulus_positive(frac.x),
            modulus_positive(frac.y),
            modulus_positive(frac.z)
            );
        particle_data.pos[i] = global_box.makeCoordinates(wrapped);
        auto const img = make_int3(
            static_cast<int>(std::floor(frac.x)),
            static_cast<int>(std::floor(frac.y)),
            static_cast<int>(std::floor(frac.z))
            );
        particle_data.image[i] = img;
        }
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_box(std::shared_ptr<MPIConfiguration> mpi_conf)
    {
#ifdef ENABLE_MPI
    if (mpi_conf->getNRanks() > 1)
        {
        bcast(global_box, 0, mpi_conf->getCommunicator());
        bcast(dimensions, 0, mpi_conf->getCommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast(unsigned int root,
                                         std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    if (exec_conf->getNRanks() > 1)
        {
        bcast(global_box, root, exec_conf->getMPICommunicator());
        bcast(dimensions, root, exec_conf->getMPICommunicator());

        particle_data.bcast(root, exec_conf->getMPICommunicator());
        bcast(map, root, exec_conf->getMPICommunicator());
        bond_data.bcast(root, exec_conf->getMPICommunicator());
        angle_data.bcast(root, exec_conf->getMPICommunicator());
        dihedral_data.bcast(root, exec_conf->getMPICommunicator());
        improper_data.bcast(root, exec_conf->getMPICommunicator());
        constraint_data.bcast(root, exec_conf->getMPICommunicator());
        pair_data.bcast(root, exec_conf->getMPICommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_all(unsigned int root,
                                             std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    MPI_Comm hoomd_world = exec_conf->getHOOMDWorldMPICommunicator();
    int n_ranks;
    MPI_Comm_size(hoomd_world, &n_ranks);
    if (n_ranks > 0)
        {
        bcast(global_box, root, hoomd_world);
        bcast(dimensions, root, hoomd_world);

        particle_data.bcast(root, hoomd_world);
        bcast(map, root, hoomd_world);

        bond_data.bcast(root, hoomd_world);
        angle_data.bcast(root, hoomd_world);
        dihedral_data.bcast(root, hoomd_world);
        improper_data.bcast(root, hoomd_world);
        constraint_data.bcast(root, hoomd_world);
        pair_data.bcast(root, hoomd_world);
        }
#endif
    }

// instantiate both float and double snapshots
template struct PYBIND11_EXPORT SnapshotSystemData<float>;
template struct PYBIND11_EXPORT SnapshotSystemData<double>;

void export_SnapshotSystemData(py::module& m)
    {
    py::class_<SnapshotSystemData<float>, std::shared_ptr<SnapshotSystemData<float>>>(
        m,
        "SnapshotSystemData_float")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<float>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<float>::global_box)
        .def_readonly("particles", &SnapshotSystemData<float>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<float>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<float>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<float>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<float>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<float>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<float>::pair_data)
        .def("replicate", &SnapshotSystemData<float>::replicate)
        .def("wrap", &SnapshotSystemData<float>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<float>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<float>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<float>::broadcast_all);

    py::class_<SnapshotSystemData<double>, std::shared_ptr<SnapshotSystemData<double>>>(
        m,
        "SnapshotSystemData_double")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<double>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<double>::global_box)
        .def_readonly("particles", &SnapshotSystemData<double>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<double>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<double>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<double>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<double>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<double>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<double>::pair_data)
        .def("replicate", &SnapshotSystemData<double>::replicate)
        .def("wrap", &SnapshotSystemData<double>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<double>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<double>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<double>::broadcast_all);
    }
<commit_msg>Fix compiler warnings<commit_after>// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

// Maintainer: jglaser

/*! \file SnapshotSystemData.cc
    \brief Implements SnapshotSystemData related functions
 */

#include "SnapshotSystemData.h"
#include <pybind11/pybind11.h>
namespace py = pybind11;

template<class Real>
void SnapshotSystemData<Real>::replicate(unsigned int nx, unsigned int ny, unsigned int nz)
    {
    assert(nx > 0);
    assert(ny > 0);
    assert(nz > 0);

    // Update global box
    BoxDim old_box = global_box;
    Scalar3 L = global_box.getL();
    L.x *= (Scalar)nx;
    L.y *= (Scalar)ny;
    L.z *= (Scalar)nz;
    global_box.setL(L);

    unsigned int old_n = particle_data.size;
    unsigned int n = nx * ny * nz;

    // replicate snapshots
    particle_data.replicate(nx, ny, nz, old_box, global_box);
    bond_data.replicate(n, old_n);
    angle_data.replicate(n, old_n);
    dihedral_data.replicate(n, old_n);
    improper_data.replicate(n, old_n);
    constraint_data.replicate(n, old_n);
    pair_data.replicate(n, old_n);
    }

template<class Real> void SnapshotSystemData<Real>::wrap()
    {
    for (unsigned int i = 0; i < particle_data.size; i++)
        {
        auto const frac = global_box.makeFraction(particle_data.pos[i]);
        auto modulus_positive = [](Real x){ return std::fmod(std::fmod(x, Real(1.0)) + Real(1.0), Real(1.0)); };
        auto const wrapped = vec3<Real>(
            modulus_positive(static_cast<Real>(frac.x)),
            modulus_positive(static_cast<Real>(frac.y)),
            modulus_positive(static_cast<Real>(frac.z))
            );
        particle_data.pos[i] = global_box.makeCoordinates(wrapped);
        auto const img = make_int3(
            static_cast<int>(std::floor(frac.x)),
            static_cast<int>(std::floor(frac.y)),
            static_cast<int>(std::floor(frac.z))
            );
        particle_data.image[i] = img;
        }
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_box(std::shared_ptr<MPIConfiguration> mpi_conf)
    {
#ifdef ENABLE_MPI
    if (mpi_conf->getNRanks() > 1)
        {
        bcast(global_box, 0, mpi_conf->getCommunicator());
        bcast(dimensions, 0, mpi_conf->getCommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast(unsigned int root,
                                         std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    if (exec_conf->getNRanks() > 1)
        {
        bcast(global_box, root, exec_conf->getMPICommunicator());
        bcast(dimensions, root, exec_conf->getMPICommunicator());

        particle_data.bcast(root, exec_conf->getMPICommunicator());
        bcast(map, root, exec_conf->getMPICommunicator());
        bond_data.bcast(root, exec_conf->getMPICommunicator());
        angle_data.bcast(root, exec_conf->getMPICommunicator());
        dihedral_data.bcast(root, exec_conf->getMPICommunicator());
        improper_data.bcast(root, exec_conf->getMPICommunicator());
        constraint_data.bcast(root, exec_conf->getMPICommunicator());
        pair_data.bcast(root, exec_conf->getMPICommunicator());
        }
#endif
    }

template<class Real>
void SnapshotSystemData<Real>::broadcast_all(unsigned int root,
                                             std::shared_ptr<ExecutionConfiguration> exec_conf)
    {
#ifdef ENABLE_MPI
    MPI_Comm hoomd_world = exec_conf->getHOOMDWorldMPICommunicator();
    int n_ranks;
    MPI_Comm_size(hoomd_world, &n_ranks);
    if (n_ranks > 0)
        {
        bcast(global_box, root, hoomd_world);
        bcast(dimensions, root, hoomd_world);

        particle_data.bcast(root, hoomd_world);
        bcast(map, root, hoomd_world);

        bond_data.bcast(root, hoomd_world);
        angle_data.bcast(root, hoomd_world);
        dihedral_data.bcast(root, hoomd_world);
        improper_data.bcast(root, hoomd_world);
        constraint_data.bcast(root, hoomd_world);
        pair_data.bcast(root, hoomd_world);
        }
#endif
    }

// instantiate both float and double snapshots
template struct PYBIND11_EXPORT SnapshotSystemData<float>;
template struct PYBIND11_EXPORT SnapshotSystemData<double>;

void export_SnapshotSystemData(py::module& m)
    {
    py::class_<SnapshotSystemData<float>, std::shared_ptr<SnapshotSystemData<float>>>(
        m,
        "SnapshotSystemData_float")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<float>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<float>::global_box)
        .def_readonly("particles", &SnapshotSystemData<float>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<float>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<float>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<float>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<float>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<float>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<float>::pair_data)
        .def("replicate", &SnapshotSystemData<float>::replicate)
        .def("wrap", &SnapshotSystemData<float>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<float>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<float>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<float>::broadcast_all);

    py::class_<SnapshotSystemData<double>, std::shared_ptr<SnapshotSystemData<double>>>(
        m,
        "SnapshotSystemData_double")
        .def(py::init<>())
        .def_readwrite("_dimensions", &SnapshotSystemData<double>::dimensions)
        .def_readwrite("_global_box", &SnapshotSystemData<double>::global_box)
        .def_readonly("particles", &SnapshotSystemData<double>::particle_data)
        .def_readonly("bonds", &SnapshotSystemData<double>::bond_data)
        .def_readonly("angles", &SnapshotSystemData<double>::angle_data)
        .def_readonly("dihedrals", &SnapshotSystemData<double>::dihedral_data)
        .def_readonly("impropers", &SnapshotSystemData<double>::improper_data)
        .def_readonly("constraints", &SnapshotSystemData<double>::constraint_data)
        .def_readonly("pairs", &SnapshotSystemData<double>::pair_data)
        .def("replicate", &SnapshotSystemData<double>::replicate)
        .def("wrap", &SnapshotSystemData<double>::wrap)
        .def("_broadcast_box", &SnapshotSystemData<double>::broadcast_box)
        .def("_broadcast", &SnapshotSystemData<double>::broadcast)
        .def("_broadcast_all", &SnapshotSystemData<double>::broadcast_all);
    }
<|endoftext|>


<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/PluginManager.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <memory>
#include <Nazara/Core/Debug.hpp>

namespace
{
	using PluginLoad = int (*)();
	using PluginUnload = void (*)();

	NzString s_pluginFiles[] =
	{
		"NazaraAssimp",  // nzPlugin_Assimp
		"NazaraFreetype" // nzPlugin_FreeType
	};
}

void NzPluginManager::AddDirectory(const NzString& directoryPath)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return;
	}

	s_directories.insert(NzFile::AbsolutePath(directoryPath));
}

bool NzPluginManager::Initialize()
{
	if (s_initialized)
		return true;

	AddDirectory(".");
	AddDirectory("plugins");

	s_initialized = true;
	return true;
}

bool NzPluginManager::Mount(nzPlugin plugin)
{
	return Mount(s_pluginFiles[plugin]);
}

bool NzPluginManager::Mount(const NzString& pluginPath, bool appendExtension)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return false;
	}

	NzString path = pluginPath;
	if (appendExtension && !path.EndsWith(NAZARA_DYNLIB_EXTENSION))
		path += NAZARA_DYNLIB_EXTENSION;

	bool exists = false;
	if (!NzFile::IsAbsolute(path))
	{
		for (const NzString& dir : s_directories)
		{
			NzString testPath;
			testPath.Reserve(dir.GetSize() + path.GetSize() + 10);

			testPath = dir;
			testPath += NAZARA_DIRECTORY_SEPARATOR;
			testPath += path;

			if (NzFile::Exists(testPath))
			{
				path = testPath;
				exists = true;
				break;
			}
		}
	}
	else if (NzFile::Exists(path))
		exists = true;

	if (!exists)
	{
		NazaraError("Failed to find plugin file");
		return false;
	}

	std::unique_ptr<NzDynLib> library(new NzDynLib);
	if (!library->Load(path))
	{
		NazaraError("Failed to load plugin");
		return false;
	}

	PluginLoad func = reinterpret_cast<PluginLoad>(library->GetSymbol("NzPluginLoad"));
	if (!func)
	{
		NazaraError("Failed to get symbol NzPluginLoad");
		return false;
	}

	if (!func())
	{
		NazaraError("Plugin failed to load");
		return false;
	}

	s_plugins[pluginPath] = library.release();

	return true;
}

void NzPluginManager::RemoveDirectory(const NzString& directoryPath)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return;
	}

	s_directories.erase(NzFile::AbsolutePath(directoryPath));
}

void NzPluginManager::Unmount(nzPlugin plugin)
{
	Unmount(s_pluginFiles[plugin]);
}

void NzPluginManager::Unmount(const NzString& pluginPath)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return;
	}

	auto it = s_plugins.find(pluginPath);
	if (it == s_plugins.end())
	{
		NazaraError("Plugin not loaded");
		return;
	}

	PluginUnload func = reinterpret_cast<PluginUnload>(it->second->GetSymbol("NzPluginUnload"));
	if (func)
		func();

	it->second->Unload();
	delete it->second;

	s_plugins.erase(it);
}

void NzPluginManager::Uninitialize()
{
	if (!s_initialized)
		return;

	s_directories.clear();

	for (auto& pair : s_plugins)
	{
		PluginUnload func = reinterpret_cast<PluginUnload>(pair.second->GetSymbol("NzPluginUnload"));
		if (func)
			func();

		pair.second->Unload();
		delete pair.second;
	}

	s_plugins.clear();

	s_initialized = false;
}

std::set<NzString> NzPluginManager::s_directories;
std::unordered_map<NzString, NzDynLib*> NzPluginManager::s_plugins;
bool NzPluginManager::s_initialized = false;
<commit_msg>Fixed PluginManager initialization<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Core module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#include <Nazara/Core/PluginManager.hpp>
#include <Nazara/Core/Directory.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Error.hpp>
#include <Nazara/Core/File.hpp>
#include <memory>
#include <Nazara/Core/Debug.hpp>

namespace
{
	using PluginLoad = int (*)();
	using PluginUnload = void (*)();

	NzString s_pluginFiles[] =
	{
		"NazaraAssimp",  // nzPlugin_Assimp
		"NazaraFreetype" // nzPlugin_FreeType
	};
}

void NzPluginManager::AddDirectory(const NzString& directoryPath)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return;
	}

	s_directories.insert(NzFile::AbsolutePath(directoryPath));
}

bool NzPluginManager::Initialize()
{
	if (s_initialized)
		return true;

	s_initialized = true;

	AddDirectory(".");
	AddDirectory("plugins");

	return true;
}

bool NzPluginManager::Mount(nzPlugin plugin)
{
	return Mount(s_pluginFiles[plugin]);
}

bool NzPluginManager::Mount(const NzString& pluginPath, bool appendExtension)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return false;
	}

	NzString path = pluginPath;
	if (appendExtension && !path.EndsWith(NAZARA_DYNLIB_EXTENSION))
		path += NAZARA_DYNLIB_EXTENSION;

	bool exists = false;
	if (!NzFile::IsAbsolute(path))
	{
		for (const NzString& dir : s_directories)
		{
			NzString testPath;
			testPath.Reserve(dir.GetSize() + path.GetSize() + 10);

			testPath = dir;
			testPath += NAZARA_DIRECTORY_SEPARATOR;
			testPath += path;

			if (NzFile::Exists(testPath))
			{
				path = testPath;
				exists = true;
				break;
			}
		}
	}
	else if (NzFile::Exists(path))
		exists = true;

	if (!exists)
	{
		NazaraError("Failed to find plugin file");
		return false;
	}

	std::unique_ptr<NzDynLib> library(new NzDynLib);
	if (!library->Load(path))
	{
		NazaraError("Failed to load plugin");
		return false;
	}

	PluginLoad func = reinterpret_cast<PluginLoad>(library->GetSymbol("NzPluginLoad"));
	if (!func)
	{
		NazaraError("Failed to get symbol NzPluginLoad");
		return false;
	}

	if (!func())
	{
		NazaraError("Plugin failed to load");
		return false;
	}

	s_plugins[pluginPath] = library.release();

	return true;
}

void NzPluginManager::RemoveDirectory(const NzString& directoryPath)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return;
	}

	s_directories.erase(NzFile::AbsolutePath(directoryPath));
}

void NzPluginManager::Unmount(nzPlugin plugin)
{
	Unmount(s_pluginFiles[plugin]);
}

void NzPluginManager::Unmount(const NzString& pluginPath)
{
	if (!Initialize())
	{
		NazaraError("Failed to initialize PluginManager");
		return;
	}

	auto it = s_plugins.find(pluginPath);
	if (it == s_plugins.end())
	{
		NazaraError("Plugin not loaded");
		return;
	}

	PluginUnload func = reinterpret_cast<PluginUnload>(it->second->GetSymbol("NzPluginUnload"));
	if (func)
		func();

	it->second->Unload();
	delete it->second;

	s_plugins.erase(it);
}

void NzPluginManager::Uninitialize()
{
	if (!s_initialized)
		return;

	s_initialized = false;

	s_directories.clear();

	for (auto& pair : s_plugins)
	{
		PluginUnload func = reinterpret_cast<PluginUnload>(pair.second->GetSymbol("NzPluginUnload"));
		if (func)
			func();

		pair.second->Unload();
		delete pair.second;
	}

	s_plugins.clear();
}

std::set<NzString> NzPluginManager::s_directories;
std::unordered_map<NzString, NzDynLib*> NzPluginManager::s_plugins;
bool NzPluginManager::s_initialized = false;
<|endoftext|>


<commit_before>#include "PlayerController.h"
#include "Player.h"

USING_NS_CC;

#define TURN_LEFT 1
#define TURN_RIGHT 2

#define MIDDLE_LINE_POS_X 0

PlayerController::PlayerController(Player * player)
	:_pPlayer(nullptr)
	, _fStepLength(10.0f), _fElapsed(0.0f), _fPerTime(1/60.0f)
	, _bMovePlayerMode(true)
{
	this->_pPlayer = player;
	CC_SAFE_RETAIN(this->_pPlayer);
}

PlayerController::~PlayerController()
{
	CC_SAFE_RELEASE_NULL(this->_pPlayer);
}

PlayerController * PlayerController::create(Player * player)
{
	PlayerController *pRet = new(std::nothrow) PlayerController(player);
	if (pRet && pRet->init())
	{
		pRet->autorelease();
		return pRet;
	}
	else
	{
		delete pRet;
		pRet = NULL;
		return NULL;
	}

}

bool PlayerController::init()
{
	Director::getInstance()->getScheduler()->scheduleUpdate(this, 0, false);
	return true;
}

void PlayerController::reveiveTouchBegin(Vec2 pos, Node * pRenderNode)
{
	this->_touchBeginPos = std::move(pos);
}

void PlayerController::reveiveTouchEnd(Vec2 pos, Node * pRenderNode)
{
	this->_touchEndPos = std::move(pos);

	Vec2 diff = _touchEndPos - _touchBeginPos;

	diff.normalize();

	auto temp = Vec2(1, 0);//horizontal line

	auto result = Vec2::dot(diff, temp);

	//תֵƫƾڷֵ϶ΪЧƶ
	const float Threshold = std::sqrt(2) / 2;//պƶˮƽλ45Ƚǣ-135㣩ʱֵΪsqrt(2)/2ƽıε

	if (std::abs(result) > Threshold)
	{
		if (result > 0) // right
		{
			//ƶ  ִƶ Gets an action from the running action list by its tag.
			if (_pPlayer->getCurPlayerSprite()->getPositionX() <= MIDDLE_LINE_POS_X
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_LEFT)
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_RIGHT)
				)
			{
				auto action = MoveBy::create(0.2f, Vec3(10, 0, 0));
				action->setTag(TURN_RIGHT);
				this->_pPlayer->getCurPlayerSprite()->runAction(action);
			}
		}
		else //left
		{
			//ƶ  ִƶ Gets an action from the running action list by its tag.
			if (_pPlayer->getCurPlayerSprite()->getPositionX() >= MIDDLE_LINE_POS_X
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_LEFT)
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_RIGHT)
				)
			{
				auto action = MoveBy::create(0.2f, Vec3(-10, 0, 0));
				action->setTag(TURN_LEFT);
				this->_pPlayer->getCurPlayerSprite()->runAction(action);
			}
		}
	}
	else //up or down
	{

#define MOVE_FORWARD(POS_X) \
		auto cameraMask = _pPlayer->getCurPlayerSprite()->getCameraMask();\
		\
		std::vector<Camera*> cameras = pRenderNode->getScene()->getCameras();\
		\
		auto func = [cameraMask](decltype(*cameras.begin()) targetCamera) ->bool\
			{\
				return ((unsigned short)targetCamera->getCameraFlag() & cameraMask) != 0;\
			};\
		\
		auto it = std::find_if(cameras.begin(), cameras.end(), func);\
		\
		while (it != cameras.end())\
		{\
			auto temp = (*it)->getPosition3D();\
			temp.add(Vec3(0, 0, POS_X));\
			(*it)->setPosition3D(temp);\
			std::find_if(++it, cameras.end(), func);\
		}\
		_pPlayer->getCurPlayerSprite()->setPositionZ(_pPlayer->getCurPlayerSprite()->getPositionZ()+POS_X);

		if (diff.y > 0)
		{
			MOVE_FORWARD(-5);
		}
		else
		{
			MOVE_FORWARD(5);
		}
	}
}

void PlayerController::beganMovePlayer(void)
{
	_bMovePlayerMode = true;
}

void PlayerController::stopMovePlayer(void)
{
	_bMovePlayerMode = false;
}

void PlayerController::update(float delta)
{
	if (_bMovePlayerMode)
	{
		_fElapsed += delta;
		if (_fElapsed >= _fPerTime)
		{
			auto moveStep = Vec3(0.0f, 0.0f, -_fStepLength);
			_pPlayer->getCurPlayerSprite()->setPosition3D(_pPlayer->getCurPlayerSprite()->getPosition3D() + moveStep);

			auto temp = _pPlayer->getCurPlayerSprite()->getCameraMask();

			for each (auto pCamera in _pPlayer->getCurPlayerSprite()->getScene()->getCameras())
			{
				if ((static_cast<unsigned short>(pCamera->getCameraFlag()) & temp) != 0)
				{
					pCamera->setPosition3D(pCamera->getPosition3D() + moveStep);
				}
			}

			_fElapsed = 0.0f;

		}
	}

}<commit_msg>makesure the number is float type that i expected<commit_after>#include "PlayerController.h"
#include "Player.h"

USING_NS_CC;

#define TURN_LEFT 1
#define TURN_RIGHT 2

#define MIDDLE_LINE_POS_X 0

PlayerController::PlayerController(Player * player)
	:_pPlayer(nullptr)
	, _fStepLength(1.0f), _fElapsed(0.0f), _fPerTime(1/60.0f)
	, _bMovePlayerMode(true)
{
	this->_pPlayer = player;
	CC_SAFE_RETAIN(this->_pPlayer);
}

PlayerController::~PlayerController()
{
	CC_SAFE_RELEASE_NULL(this->_pPlayer);
}

PlayerController * PlayerController::create(Player * player)
{
	PlayerController *pRet = new(std::nothrow) PlayerController(player);
	if (pRet && pRet->init())
	{
		pRet->autorelease();
		return pRet;
	}
	else
	{
		delete pRet;
		pRet = NULL;
		return NULL;
	}

}

bool PlayerController::init()
{
	Director::getInstance()->getScheduler()->scheduleUpdate(this, 0, false);
	return true;
}

void PlayerController::reveiveTouchBegin(Vec2 pos, Node * pRenderNode)
{
	this->_touchBeginPos = std::move(pos);
}

void PlayerController::reveiveTouchEnd(Vec2 pos, Node * pRenderNode)
{
	this->_touchEndPos = std::move(pos);

	Vec2 diff = _touchEndPos - _touchBeginPos;

	diff.normalize();

	auto temp = Vec2(1, 0);//horizontal line

	auto result = Vec2::dot(diff, temp);

	//תֵƫƾڷֵ϶ΪЧƶ
	const float Threshold = std::sqrt(2) / 2;//պƶˮƽλ45Ƚǣ-135㣩ʱֵΪsqrt(2)/2ƽıε

	if (std::abs(result) > Threshold)
	{
		if (result > 0) // right
		{
			//ƶ  ִƶ Gets an action from the running action list by its tag.
			if (_pPlayer->getCurPlayerSprite()->getPositionX() <= MIDDLE_LINE_POS_X
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_LEFT)
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_RIGHT)
				)
			{
				auto action = MoveBy::create(0.2f, Vec3(10.0f, 0, 0));
				action->setTag(TURN_RIGHT);
				this->_pPlayer->getCurPlayerSprite()->runAction(action);
			}
		}
		else //left
		{
			//ƶ  ִƶ Gets an action from the running action list by its tag.
			if (_pPlayer->getCurPlayerSprite()->getPositionX() >= MIDDLE_LINE_POS_X
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_LEFT)
				&& !_pPlayer->getCurPlayerSprite()->getActionByTag(TURN_RIGHT)
				)
			{
				auto action = MoveBy::create(0.2f, Vec3(-10.0f, 0, 0));
				action->setTag(TURN_LEFT);
				this->_pPlayer->getCurPlayerSprite()->runAction(action);
			}
		}
	}
	else //up or down
	{

#define MOVE_FORWARD(POS_X) \
		auto cameraMask = _pPlayer->getCurPlayerSprite()->getCameraMask();\
		\
		std::vector<Camera*> cameras = pRenderNode->getScene()->getCameras();\
		\
		auto func = [cameraMask](decltype(*cameras.begin()) targetCamera) ->bool\
			{\
				return ((unsigned short)targetCamera->getCameraFlag() & cameraMask) != 0;\
			};\
		\
		auto it = std::find_if(cameras.begin(), cameras.end(), func);\
		\
		while (it != cameras.end())\
		{\
			auto temp = (*it)->getPosition3D();\
			temp.add(Vec3(0, 0, POS_X));\
			(*it)->setPosition3D(temp);\
			std::find_if(++it, cameras.end(), func);\
		}\
		_pPlayer->getCurPlayerSprite()->setPositionZ(_pPlayer->getCurPlayerSprite()->getPositionZ()+POS_X);

		if (diff.y > 0)
		{
			MOVE_FORWARD(-5);
		}
		else
		{
			MOVE_FORWARD(5);
		}
	}
}

void PlayerController::beganMovePlayer(void)
{
	_bMovePlayerMode = true;
}

void PlayerController::stopMovePlayer(void)
{
	_bMovePlayerMode = false;
}

void PlayerController::update(float delta)
{
	if (_bMovePlayerMode)
	{
		_fElapsed += delta;
		if (_fElapsed >= _fPerTime)
		{
			auto moveStep = Vec3(0.0f, 0.0f, -_fStepLength);
			_pPlayer->getCurPlayerSprite()->setPosition3D(_pPlayer->getCurPlayerSprite()->getPosition3D() + moveStep);

			auto temp = _pPlayer->getCurPlayerSprite()->getCameraMask();

			for each (auto pCamera in _pPlayer->getCurPlayerSprite()->getScene()->getCameras())
			{
				if ((static_cast<unsigned short>(pCamera->getCameraFlag()) & temp) != 0)
				{
					pCamera->setPosition3D(pCamera->getPosition3D() + moveStep);
				}
			}

			_fElapsed = 0.0f;

		}
	}

}<|endoftext|>


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

#include "UnionFindTest.h"

namespace cura
{

CPPUNIT_TEST_SUITE_REGISTRATION(UnionFindTest);

void UnionFindTest::setUp()
{
    union_find = UnionFind<char>(); //Recreate the UnionFind data structure.
}

void UnionFindTest::tearDown()
{
    //Nothing to tear down.
}

void UnionFindTest::findSimpleTest()
{
    union_find.add('A');
    size_t result = union_find.find('A');
    CPPUNIT_ASSERT_MESSAGE("The set of the first element may not be -1.", result != (size_t)-1);
}

}<commit_msg>Also test if the result was the same as add()<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include "UnionFindTest.h"

namespace cura
{

CPPUNIT_TEST_SUITE_REGISTRATION(UnionFindTest);

void UnionFindTest::setUp()
{
    union_find = UnionFind<char>(); //Recreate the UnionFind data structure.
}

void UnionFindTest::tearDown()
{
    //Nothing to tear down.
}

void UnionFindTest::findSimpleTest()
{
    size_t original = union_find.add('A');
    size_t result = union_find.find('A');
    CPPUNIT_ASSERT_MESSAGE("The set of the first element may not be -1.", result != (size_t)-1);
    CPPUNIT_ASSERT_MESSAGE("Find must return the original key that was returned when adding.", result == original);
}

}<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTimeStamp.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkTimeStamp.h"
#include "itkFastMutexLock.h"

#if defined(_WIN32)
  #include "itkWindows.h"

#elif defined(__APPLE__)
// OSAtomic.h optimizations only used in 10.5 and later
  #include <AvailabilityMacros.h>
  #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
    #include <libkern/OSAtomic.h>
  #endif

#elif defined(__GLIBCPP__) || defined(__GLIBCXX__)
  #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2))
  # include <ext/atomicity.h>
  #else
  # include <bits/atomicity.h>
  #endif

#endif

namespace itk
{

#if defined(__GLIBCXX__) // g++ 3.4+

using __gnu_cxx::__exchange_and_add;

#endif

/**
 * Instance creation.
 */
TimeStamp*
TimeStamp
::New()
{
  return new Self;
}

/**
 * Make sure the new time stamp is greater than all others so far.
 */
void
TimeStamp
::Modified()
{
  // Windows optimization
#if defined(WIN32) || defined(_WIN32)
  static LONG itkTimeStampTime = 0;
  m_ModifiedTime = (unsigned long)InterlockedIncrement(&itkTimeStampTime);

  // Mac optimization
#elif defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
 #if __LP64__
  // "m_ModifiedTime" is "unsigned long", a type that changess sizes
  // depending on architecture.  The atomic increment is safe, since it
  // operates on a variable of the exact type needed.  The cast does not
  // change the size, but does change signedness, which is not ideal.
  static volatile int64_t itkTimeStampTime = 0;
  m_ModifiedTime = (unsigned long)OSAtomicIncrement64Barrier(&itkTimeStampTime);
 #else
  static volatile int32_t itkTimeStampTime = 0;
  m_ModifiedTime = (unsigned long)OSAtomicIncrement32Barrier(&itkTimeStampTime);
 #endif

// gcc optimization
#elif defined(__GLIBCPP__) || defined(__GLIBCXX__)
  static volatile _Atomic_word itkTimeStampTime = 0;
  m_ModifiedTime = (unsigned long)__exchange_and_add(&itkTimeStampTime, 1)+1;

// General case
#else
  /**
   * Initialize static member
   */
  static unsigned long itkTimeStampTime = 0;

  /** Used for mutex locking */
  static SimpleFastMutexLock TimeStampMutex;

  TimeStampMutex.Lock();
  m_ModifiedTime = ++itkTimeStampTime;
  TimeStampMutex.Unlock();
#endif

}

} // end namespace itk
<commit_msg>PERF: even though __exchange_and_add returns the old (non-incremented) value, we don't really need to add +1 since all we want is a strictly incremental counter<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTimeStamp.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

  Portions of this code are covered under the VTK copyright.
  See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkTimeStamp.h"
#include "itkFastMutexLock.h"

#if defined(_WIN32)
  #include "itkWindows.h"

#elif defined(__APPLE__)
// OSAtomic.h optimizations only used in 10.5 and later
  #include <AvailabilityMacros.h>
  #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
    #include <libkern/OSAtomic.h>
  #endif

#elif defined(__GLIBCPP__) || defined(__GLIBCXX__)
  #if (__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2))
  # include <ext/atomicity.h>
  #else
  # include <bits/atomicity.h>
  #endif

#endif

namespace itk
{

#if defined(__GLIBCXX__) // g++ 3.4+

using __gnu_cxx::__exchange_and_add;

#endif

/**
 * Instance creation.
 */
TimeStamp*
TimeStamp
::New()
{
  return new Self;
}

/**
 * Make sure the new time stamp is greater than all others so far.
 */
void
TimeStamp
::Modified()
{
  // Windows optimization
#if defined(WIN32) || defined(_WIN32)
  static LONG itkTimeStampTime = 0;
  m_ModifiedTime = (unsigned long)InterlockedIncrement(&itkTimeStampTime);

  // Mac optimization
#elif defined(__APPLE__) && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)
 #if __LP64__
  // "m_ModifiedTime" is "unsigned long", a type that changess sizes
  // depending on architecture.  The atomic increment is safe, since it
  // operates on a variable of the exact type needed.  The cast does not
  // change the size, but does change signedness, which is not ideal.
  static volatile int64_t itkTimeStampTime = 0;
  m_ModifiedTime = (unsigned long)OSAtomicIncrement64Barrier(&itkTimeStampTime);
 #else
  static volatile int32_t itkTimeStampTime = 0;
  m_ModifiedTime = (unsigned long)OSAtomicIncrement32Barrier(&itkTimeStampTime);
 #endif

// gcc optimization
#elif defined(__GLIBCPP__) || defined(__GLIBCXX__)
  // We start from 1 since __exchange_and_add returns the old (non-incremented)
  // value. This is not really necessary but will make the absolute value of the
  // timestamp more consistent across platforms.
  static volatile _Atomic_word itkTimeStampTime = 1;
  m_ModifiedTime = (unsigned long)__exchange_and_add(&itkTimeStampTime, 1);

// General case
#else
  /**
   * Initialize static member
   */
  static unsigned long itkTimeStampTime = 0;

  /** Used for mutex locking */
  static SimpleFastMutexLock TimeStampMutex;

  TimeStampMutex.Lock();
  m_ModifiedTime = ++itkTimeStampTime;
  TimeStampMutex.Unlock();
#endif

}

} // end namespace itk
<|endoftext|>