<commit_before>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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 "resize.hpp"
#include "default_opset.hpp"
#include "exceptions.hpp"

namespace ngraph
{
    namespace onnx_import
    {
        namespace op
        {
            namespace set_1
            {
                NodeVector resize(const onnx_import::Node& node)
                {
                    const auto inputs = node.get_ng_inputs();
                    const auto data = inputs.at(0);
                    const auto scales = inputs.at(1);

                    const auto data_shape = data->get_output_partial_shape(0);
                    const auto scales_shape = scales->get_output_partial_shape(0);

                    const auto mode = node.get_attribute_value<std::string>("mode", "nearest");

                    std::unordered_set<std::string> supported_modes = {"nearest", "linear"};
                    bool is_mode_supported =
                        (std::find(supported_modes.begin(), supported_modes.end(), mode) !=
                         supported_modes.end());

                    if (!is_mode_supported)
                    {
                        std::string supported_modes_str = "";
                        for (const auto& mode_name : supported_modes)
                        {
                            supported_modes_str += (mode_name + ", ");
                        }
                        CHECK_VALID_NODE(node,
                                         is_mode_supported,
                                         mode,
                                         " - this type of interpolation mode is not supported."
                                         " Choose one of the following modes: ",
                                         supported_modes_str);
                    }

                    CHECK_VALID_NODE(
                        node,
                        (scales_shape.is_static() || data_shape.rank().is_static()),
                        " Data rank or shape of Scales input is required to be static.");

                    size_t axes_size = scales_shape.is_static() ? scales_shape.to_shape().at(0)
                                                                : data_shape.rank().get_length();
                    AxisSet axes;
                    for (int ax = 0; ax < axes_size; ++ax)
                    {
                        axes.insert(ax);
                    }

                    auto attrs = default_opset::Interpolate::InterpolateAttrs();
                    attrs.axes = axes;
                    attrs.mode = as_enum<default_opset::Interpolate::InterpolateMode>(mode);
                    attrs.align_corners = false;

                    if (scales->is_constant() && data_shape.is_static())
                    {
                        const auto scales_const =
                            as_type_ptr<default_opset::Constant>(scales->shared_from_this());

                        auto scales_vector = scales_const->cast_vector<float>();
                        auto data_static_shape = data_shape.to_shape();

                        std::vector<int64_t> output_shape;
                        for (size_t i = 0; i < data_static_shape.size(); ++i)
                        {
                            output_shape.push_back(
                                std::floor(data_static_shape.at(i) * scales_vector.at(i)));
                        }
                        auto output_shape_const = default_opset::Constant::create(
                            element::u64, Shape({output_shape.size()}), output_shape);

                        return {std::make_shared<default_opset::Interpolate>(
                            data, output_shape_const, attrs)};
                    }

                    auto shape_of_data = std::make_shared<default_opset::Convert>(
                        std::make_shared<default_opset::ShapeOf>(data), ngraph::element::f32);
                    auto multiply =
                        std::make_shared<default_opset::Multiply>(shape_of_data, scales);
                    auto output_shape = std::make_shared<default_opset::Convert>(
                        std::make_shared<default_opset::Floor>(multiply), ngraph::element::i64);
                    return {
                        std::make_shared<default_opset::Interpolate>(data, output_shape, attrs)};
                }

            } // namespace set_1

        } // namespace op

    } // namespace onnx_import

} // namespace ngraph
<commit_msg>Revert "Fix onnx_import build issue."<commit_after>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// 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 "resize.hpp"
#include "default_opset.hpp"
#include "exceptions.hpp"

namespace ngraph
{
    namespace onnx_import
    {
        namespace op
        {
            namespace set_1
            {
                NodeVector resize(const onnx_import::Node& node)
                {
                    const auto inputs = node.get_ng_inputs();
                    const auto data = inputs.at(0);
                    const auto scales = inputs.at(1);

                    const auto data_shape = data->get_output_partial_shape(0);
                    const auto scales_shape = scales->get_output_partial_shape(0);

                    const auto mode = node.get_attribute_value<std::string>("mode", "nearest");

                    std::unordered_set<std::string> supported_modes = {"nearest", "linear"};
                    bool is_mode_supported =
                        (std::find(supported_modes.begin(), supported_modes.end(), mode) !=
                         supported_modes.end());

                    if (!is_mode_supported)
                    {
                        std::string supported_modes_str = "";
                        for (const auto& mode_name : supported_modes)
                        {
                            supported_modes_str += (mode_name + ", ");
                        }
                        CHECK_VALID_NODE(node,
                                         is_mode_supported,
                                         mode,
                                         " - this type of interpolation mode is not supported."
                                         " Choose one of the following modes: ",
                                         supported_modes_str);
                    }

                    CHECK_VALID_NODE(
                        node,
                        (scales_shape.is_static() || data_shape.rank().is_static()),
                        " Data rank or shape of Scales input is required to be static.");

                    size_t axes_size = scales_shape.is_static() ? scales_shape.to_shape().at(0)
                                                                : data_shape.rank().get_length();
                    AxisSet axes;
                    for (int ax = 0; ax < axes_size; ++ax)
                    {
                        axes.insert(ax);
                    }

                    auto attrs = ngraph::op::InterpolateAttrs();
                    attrs.axes = axes;
                    attrs.mode = mode;
                    attrs.align_corners = false;

                    if (scales->is_constant() && data_shape.is_static())
                    {
                        const auto scales_const =
                            as_type_ptr<default_opset::Constant>(scales->shared_from_this());

                        auto scales_vector = scales_const->cast_vector<float>();
                        auto data_static_shape = data_shape.to_shape();

                        std::vector<int64_t> output_shape;
                        for (size_t i = 0; i < data_static_shape.size(); ++i)
                        {
                            output_shape.push_back(
                                std::floor(data_static_shape.at(i) * scales_vector.at(i)));
                        }
                        auto output_shape_const = default_opset::Constant::create(
                            element::u64, Shape({output_shape.size()}), output_shape);

                        return {std::make_shared<default_opset::Interpolate>(
                            data, output_shape_const, attrs)};
                    }

                    auto shape_of_data = std::make_shared<default_opset::Convert>(
                        std::make_shared<default_opset::ShapeOf>(data), ngraph::element::f32);
                    auto multiply =
                        std::make_shared<default_opset::Multiply>(shape_of_data, scales);
                    auto output_shape = std::make_shared<default_opset::Convert>(
                        std::make_shared<default_opset::Floor>(multiply), ngraph::element::i64);
                    return {
                        std::make_shared<default_opset::Interpolate>(data, output_shape, attrs)};
                }

            } // namespace set_1

        } // namespace op

    } // namespace onnx_import

} // namespace ngraph
<|endoftext|>


<commit_before>#include <cstdint>
#include <kernel/definitions.hpp>
#include <yatf.h>

namespace {

} // namespace

TEST(sprintf, can_format_int) {
    char buffer[32];
    sprintf(buffer, "%d", 21);
    REQUIRE_EQ((const char *)buffer, "21");
    sprintf(buffer, "%d", -910);
    REQUIRE_EQ((const char *)buffer, "-910");
    sprintf(buffer, "%d", 0);
    REQUIRE_EQ((const char *)buffer, "0");
}

TEST(sprintf, can_format_unsigned_int) {
    char buffer[32];
    sprintf(buffer, "%u", 21);
    REQUIRE_EQ((const char *)buffer, "21");
    sprintf(buffer, "%u", 125);
    REQUIRE_EQ((const char *)buffer, "125");
    sprintf(buffer, "%u", 0);
    REQUIRE_EQ((const char *)buffer, "0");
}

TEST(sprintf, can_format_char) {
    char buffer[32];
    sprintf(buffer, "%c", 'c');
    REQUIRE_EQ((const char *)buffer, "c");
    sprintf(buffer, "%c", 'a');
    REQUIRE_EQ((const char *)buffer, "a");
    sprintf(buffer, "%c", 0);
    REQUIRE_EQ((const char *)buffer, "");
}

TEST(sprintf, can_format_string) {
    char buffer[32];
    sprintf(buffer, "%s", "test string");
    REQUIRE_EQ((const char *)buffer, "test string");
    sprintf(buffer, "testing");
    REQUIRE_EQ((const char *)buffer, "testing");
}

TEST(sprintf, can_pad) {
    char buffer[32];
    sprintf(buffer, "%06d", 324);
    REQUIRE_EQ((const char *)buffer, "000324");
    sprintf(buffer, "0x%03x", 0x21);
    REQUIRE_EQ((const char *)buffer, "0x021");
}

<commit_msg>Next tests<commit_after>#include <cstdint>
#include <kernel/definitions.hpp>
#include <yatf.h>

namespace {

} // namespace

TEST(sprintf, can_format_percent_sign) {
    char buffer[32];
    sprintf(buffer, "%%");
    REQUIRE_EQ((const char *)buffer, "%");
}

TEST(sprintf, can_format_int) {
    char buffer[32];
    sprintf(buffer, "%d", 21);
    REQUIRE_EQ((const char *)buffer, "21");
    sprintf(buffer, "%d", -910);
    REQUIRE_EQ((const char *)buffer, "-910");
    sprintf(buffer, "%d", 0);
    REQUIRE_EQ((const char *)buffer, "0");
    sprintf(buffer, "%+d", 124);
    REQUIRE_EQ((const char *)buffer, "+124");
}

TEST(sprintf, can_format_unsigned_int) {
    char buffer[32];
    sprintf(buffer, "%u", 21);
    REQUIRE_EQ((const char *)buffer, "21");
    sprintf(buffer, "%u", 125);
    REQUIRE_EQ((const char *)buffer, "125");
    sprintf(buffer, "%u", 0);
    REQUIRE_EQ((const char *)buffer, "0");
}

TEST(sprintf, can_format_char) {
    char buffer[32];
    sprintf(buffer, "%c", 'c');
    REQUIRE_EQ((const char *)buffer, "c");
    sprintf(buffer, "%c", 'a');
    REQUIRE_EQ((const char *)buffer, "a");
    sprintf(buffer, "%c", 0);
    REQUIRE_EQ((const char *)buffer, "");
}

TEST(sprintf, can_format_string) {
    char buffer[32];
    sprintf(buffer, "%s", "test string");
    REQUIRE_EQ((const char *)buffer, "test string");
    sprintf(buffer, "testing");
    REQUIRE_EQ((const char *)buffer, "testing");
}

TEST(sprintf, can_format_pointer) {
    char buffer[32];
    sprintf(buffer, "%p", 0x21);
    REQUIRE_EQ((const char *)buffer, "0x0000000000000021");
}

TEST(sprintf, can_pad) {
    char buffer[32];
    sprintf(buffer, "%06d", 324);
    REQUIRE_EQ((const char *)buffer, "000324");
    sprintf(buffer, "%#05x", 0x21);
    REQUIRE_EQ((const char *)buffer, "0x021");
    sprintf(buffer, "%6d", 324);
    REQUIRE_EQ((const char *)buffer, "   324");
    sprintf(buffer, "%6c", 'c');
    REQUIRE_EQ((const char *)buffer, "     c");
    sprintf(buffer, "%-6c", 'c');
    REQUIRE_EQ((const char *)buffer, "c     ");
    sprintf(buffer, "% 6c", 'c');
    REQUIRE_EQ((const char *)buffer, "     c");
}

<|endoftext|>


<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef HW_CPU_HPP
#define HW_CPU_HPP

#include <cstdint>

namespace hw
{
  class CPU
  {
  public:
    // read the intel manual
    static uint64_t
    read_msr(uint32_t addr)
    {
      uint32_t EAX = 0, EDX = 0;
      asm volatile("rdmsr": "=a" (EAX),"=d"(EDX) : "c" (addr));
      return ((uint64_t)EDX << 32) | EAX;
    }

    static void
    write_msr(uint32_t addr, uint32_t eax, uint32_t edx)
    {
      asm volatile("wrmsr" : : "a" (eax),"d"(edx), "c" (addr));
    }

    static uint64_t rdtsc()
    {
      uint64_t ret;
      __asm__ volatile ("rdtsc":"=A"(ret));
      return ret;
    }
  };
}

#endif
<commit_msg>cpu: Write 64-bit MSR value<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.

#pragma once
#ifndef HW_CPU_HPP
#define HW_CPU_HPP

#include <cstdint>

namespace hw
{
  class CPU
  {
  public:
    // read the intel manual
    static uint64_t
    read_msr(uint32_t addr)
    {
      uint32_t EAX = 0, EDX = 0;
      asm volatile("rdmsr": "=a" (EAX),"=d"(EDX) : "c" (addr));
      return ((uint64_t)EDX << 32) | EAX;
    }

    static void
    write_msr(uint32_t addr, uint32_t eax, uint32_t edx)
    {
      asm volatile("wrmsr" : : "a" (eax),"d"(edx), "c" (addr));
    }
    static void
    write_msr(uint32_t addr, uint64_t value)
    {
      union {
        uint64_t value;
        uint32_t reg[2];
      } msr {value};
      asm volatile("wrmsr" : : "a" (msr.reg[0]),"d"(msr.reg[1]), "c" (addr));
    }

    static uint64_t rdtsc()
    {
      uint64_t ret;
      __asm__ volatile ("rdtsc":"=A"(ret));
      return ret;
    }
  };
}

#endif
<|endoftext|>


<commit_before>#include "message_factory.hpp"
#include "main.hpp"
#include "tetronimo.hpp"
#include <cstdio>

MessageFactory::MessageFactory()
{ }

MessageFactory::~MessageFactory()
{ }

std::string const* MessageFactory::CreateInitMessage(std::string const& matchToken) const {
    Json::Value root;
    Json::FastWriter writer;

    Json::Value comm_type ("MatchConnect");
    Json::Value match_token (matchToken);
    Json::Value team_name (USERNAME);
    Json::Value password (PASSWORD);

    root["comm_type"] = comm_type;
    root["match_token"] = match_token;
    root["team_name"] = team_name;
    root["password"] = password;

    std::string const* serialized = new std::string(writer.write(root));
    return serialized;
}

bool MessageFactory::ParseInitReply(std::string const& reply) {
    bool success = true;

    // Parse message
    Json::Value root;
    Json::Reader reader;
    success = reader.parse(reply, root);
    if (!success)
        return success;

    // Extract comm type (expect "MatchConnectResp")
    std::string commType = root.get("comm_type", "not found").asString();
    success = (commType.compare("MatchConnectResp") == 0);
    //if (commType.compare("ErrorResp") == 0)
        //PrintErrorMessage(reply);
    if (!success)
        return success;

    // Extract resp (expect "ok")
    std::string resp = root.get("resp", "not ok").asString();
    success = (resp.compare("ok") == 0);
    if (!success)
        return success;

    // Extract client token (expect some value)
    std::string token = root.get("client_token", "not found").asString();
    success = (token.compare("not found") != 0);
    if (!success)
        return success;

    // Record client token, return success
    m_clientToken = token;
    return success;
}

std::string const* MessageFactory::CreateMoveMessage(std::string const& moveS) const {
    Json::Value root;
    Json::FastWriter writer;

    Json::Value comm_type ("GameMove");
    Json::Value client_token (m_clientToken);
    Json::Value move (moveS);

    root["comm_type"] = comm_type;
    root["client_token"] = client_token;
    root["move"] = move;

    std::string const* serialized = new std::string(writer.write(root));
    return serialized;
}

bool MessageFactory::ParseMoveReply(std::string const& reply) const {
    bool success = true;

    // Parse message
    Json::Value root;
    Json::Reader reader;
    success = reader.parse(reply, root);
    if (!success)
        return success;

    // Extract comm type (expect "GameMoveResp")
    std::string commType = root.get("comm_type", "not found").asString();
    success = (commType.compare("GameMoveResp") == 0);
    //if (commType.compare("ErrorResp") == 0)
        //PrintErrorMessage(reply);
    if (!success)
        return success;

    // Extract resp (expect "ok")
    std::string resp = root.get("resp", "not ok").asString();
    success = (resp.compare("ok") == 0);

    return success;
}

State const* MessageFactory::ParseStateMessage(std::string const& stateS) const { // Parse message
    Json::Value root;
    Json::Reader reader;
    if (!reader.parse(stateS, root))
        return new ErrorState("Parse failure on state message.");

    // Extract comm type
    std::string commType = root.get("comm_type", "not found").asString();
    if (commType.compare("GameBoardState") == 0)
        return ParseGameBoardStateMessage(root);
    else if (commType.compare("GamePieceState") == 0)
        return ParseGamePieceStateMessage(root);
    else if (commType.compare("MatchEnd") == 0)
        return ParseMatchEndStateMessage(root);
    else if (commType.compare("GameEnd") == 0)
        return ParseGameEndStateMessage(root);
    else
        return new ErrorState("Could not match message state type.");
}

State const* MessageFactory::ParseGameBoardStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();
    Json::Value states = root.get("states", "not found");
    if (states.asString().compare("not found") == 0)
        return new ErrorState("states not found in GameBoardState");

    Json::Value mine = states.get(USERNAME, "not found");
    if (mine.asString().compare("not found") == 0)
        return new ErrorState("username not found in GameBoardState/state");
    int myPiece = mine.get("piece_number", -1).asInt();
    Json::Value myBoardV = mine.get("board_state", "0");
    if (myBoardV.asString().size() != BOARD_DESC_SIZE)
        return new ErrorState("Invalid board description in GameBoardState/state/username");
    char const* myBoard = myBoardV.asCString();
    Json::Value myClearedV = mine.get("cleared_rows", "not found");
    if (myClearedV.asString().compare("not found") == 0)
        return new ErrorState("cleared_rows not found in GameBoardState/state/username");
    std::vector<int>* myCleared = new std::vector<int>();
    for (unsigned i = 0; i < myClearedV.size(); ++i)
        myCleared->push_back(myClearedV[i].asInt());

    Json::Value theirs = states.get("Test Client", "not found");
    if (theirs.asString().compare("not found") == 0)
        return new ErrorState("opponent not found in GameBoardState/state");
    int theirPiece = theirs.get("piece_number", -1).asInt();
    Json::Value theirBoardV = theirs.get("board_state", "0");
    if (theirBoardV.asString().size() != BOARD_DESC_SIZE)
        return new ErrorState("Invalid board description in GameBoardState/state/opponent");
    char const* theirBoard = theirBoardV.asCString();
    Json::Value theirClearedV = theirs.get("cleared_rows", "not found");
    if (theirClearedV.asString().compare("not found") == 0)
        return new ErrorState("cleared_rows not found in GameBoardState/state/opponent");
    std::vector<int>* theirCleared = new std::vector<int>();
    for (unsigned i = 0; i < theirClearedV.size(); ++i)
        theirCleared->push_back(theirClearedV[i].asInt());

    return new GameBoardState(sequence, timestamp, myBoard, theirBoard,
                                    myPiece, theirPiece, myCleared, theirCleared);
}

State const* MessageFactory::ParseGamePieceStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();
    Json::Value states = root.get("states", "not found");
    if (states.asString().compare("not found") == 0)
        return new ErrorState("states not found in GamePieceState");

    Json::Value queueV = root.get("queue", "not found");
    if (queueV.asString().compare("not found") == 0)
        return new ErrorState("queue not found in GamePieceState");
    std::vector<Tetronimo>* queue = new std::vector<Tetronimo>();
    for (unsigned i = 0; i < queueV.size(); ++i) {
        std::string piece = queueV[i].asString();
        if (piece.size() != 1)
            return new ErrorState("Invalid piece descriptor in GamePieceState/queue");
        Tetronimo t (piece.at(0));
        queue->push_back(t);
    }

    Json::Value mine = states.get(USERNAME, "not found");
    if (mine.asString().compare("not found") == 0)
        return new ErrorState("username not found in GamePieceState/state");
    std::string myPieceS = mine.get("piece", "not found").asString();
    if (myPieceS.size() != 1)
        return new ErrorState("Invalid piece descriptor in GamePieceState/state/username");
    char myPiece = myPieceS.at(0);
    int myOrient = mine.get("orient", -1).asInt();
    int myCol = mine.get("col", -1).asInt();
    int myRow = mine.get("row", -1).asInt();
    Tetronimo* myTet = new Tetronimo(myPiece, myOrient, myCol, myRow);

    Json::Value theirs = states.get("Test Client", "not found");
    if (theirs.asString().compare("not found") == 0)
        return new ErrorState("opponent not found in GamePieceState/state");
    std::string theirPieceS = theirs.get("piece", "not found").asString();
    if (theirPieceS.size() != 1)
        return new ErrorState("Invalid piece descriptor in GamePieceState/state/opponent");
    char theirPiece = theirPieceS.at(0);
    int theirOrient = theirs.get("orient", -1).asInt();
    int theirCol = theirs.get("col", -1).asInt();
    int theirRow = theirs.get("row", -1).asInt();
    Tetronimo* theirTet = new Tetronimo(theirPiece, theirOrient, theirCol, theirRow);

    return new GamePieceState(sequence, timestamp, myTet, theirTet, queue);
}

State const* MessageFactory::ParseMatchEndStateMessage(Json::Value const& root) const {
    return new MatchEnd();
}

State const* MessageFactory::ParseGameEndStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();

    std::string winner = root.get("winner", "not found").asString();
    bool won = false;
    if (winner.compare(USERNAME) == 0)
        won = true;

    Json::Value scores = root.get("scores", "not found");
    int myScore = scores.get(USERNAME, -1).asInt();
    int theirScore = scores.get("Test Client", -1).asInt();

    return new GameEnd(sequence, timestamp, won, myScore, theirScore);
}

<commit_msg>Removed exception-causing string conversion code<commit_after>#include "message_factory.hpp"
#include "main.hpp"
#include "tetronimo.hpp"
#include <cstdio>

MessageFactory::MessageFactory()
{ }

MessageFactory::~MessageFactory()
{ }

std::string const* MessageFactory::CreateInitMessage(std::string const& matchToken) const {
    Json::Value root;
    Json::FastWriter writer;

    Json::Value comm_type ("MatchConnect");
    Json::Value match_token (matchToken);
    Json::Value team_name (USERNAME);
    Json::Value password (PASSWORD);

    root["comm_type"] = comm_type;
    root["match_token"] = match_token;
    root["team_name"] = team_name;
    root["password"] = password;

    std::string const* serialized = new std::string(writer.write(root));
    return serialized;
}

bool MessageFactory::ParseInitReply(std::string const& reply) {
    bool success = true;

    // Parse message
    Json::Value root;
    Json::Reader reader;
    success = reader.parse(reply, root);
    if (!success)
        return success;

    // Extract comm type (expect "MatchConnectResp")
    std::string commType = root.get("comm_type", "not found").asString();
    success = (commType.compare("MatchConnectResp") == 0);
    //if (commType.compare("ErrorResp") == 0)
        //PrintErrorMessage(reply);
    if (!success)
        return success;

    // Extract resp (expect "ok")
    std::string resp = root.get("resp", "not ok").asString();
    success = (resp.compare("ok") == 0);
    if (!success)
        return success;

    // Extract client token (expect some value)
    std::string token = root.get("client_token", "not found").asString();
    success = (token.compare("not found") != 0);
    if (!success)
        return success;

    // Record client token, return success
    m_clientToken = token;
    return success;
}

std::string const* MessageFactory::CreateMoveMessage(std::string const& moveS) const {
    Json::Value root;
    Json::FastWriter writer;

    Json::Value comm_type ("GameMove");
    Json::Value client_token (m_clientToken);
    Json::Value move (moveS);

    root["comm_type"] = comm_type;
    root["client_token"] = client_token;
    root["move"] = move;

    std::string const* serialized = new std::string(writer.write(root));
    return serialized;
}

bool MessageFactory::ParseMoveReply(std::string const& reply) const {
    bool success = true;

    // Parse message
    Json::Value root;
    Json::Reader reader;
    success = reader.parse(reply, root);
    if (!success)
        return success;

    // Extract comm type (expect "GameMoveResp")
    std::string commType = root.get("comm_type", "not found").asString();
    success = (commType.compare("GameMoveResp") == 0);
    //if (commType.compare("ErrorResp") == 0)
        //PrintErrorMessage(reply);
    if (!success)
        return success;

    // Extract resp (expect "ok")
    std::string resp = root.get("resp", "not ok").asString();
    success = (resp.compare("ok") == 0);

    return success;
}

State const* MessageFactory::ParseStateMessage(std::string const& stateS) const { // Parse message
    Json::Value root;
    Json::Reader reader;
    if (!reader.parse(stateS, root))
        return new ErrorState("Parse failure on state message.");

    // Extract comm type
    std::string commType = root.get("comm_type", "not found").asString();
    if (commType.compare("GameBoardState") == 0)
        return ParseGameBoardStateMessage(root);
    else if (commType.compare("GamePieceState") == 0)
        return ParseGamePieceStateMessage(root);
    else if (commType.compare("MatchEnd") == 0)
        return ParseMatchEndStateMessage(root);
    else if (commType.compare("GameEnd") == 0)
        return ParseGameEndStateMessage(root);
    else
        return new ErrorState("Could not match message state type.");
}

State const* MessageFactory::ParseGameBoardStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();
    Json::Value states = root.get("states", "not found");

    Json::Value mine = states.get(USERNAME, "not found");
    int myPiece = mine.get("piece_number", -1).asInt();
    Json::Value myBoardV = mine.get("board_state", "0");
    if (myBoardV.asString().size() != BOARD_DESC_SIZE)
        return new ErrorState("Invalid board description in GameBoardState/state/username");
    char const* myBoard = myBoardV.asCString();
    Json::Value myClearedV = mine.get("cleared_rows", "not found");
    std::vector<int>* myCleared = new std::vector<int>();
    for (unsigned i = 0; i < myClearedV.size(); ++i)
        myCleared->push_back(myClearedV[i].asInt());

    Json::Value theirs = states.get("Test Client", "not found");
    int theirPiece = theirs.get("piece_number", -1).asInt();
    Json::Value theirBoardV = theirs.get("board_state", "0");
    if (theirBoardV.asString().size() != BOARD_DESC_SIZE)
        return new ErrorState("Invalid board description in GameBoardState/state/opponent");
    char const* theirBoard = theirBoardV.asCString();
    Json::Value theirClearedV = theirs.get("cleared_rows", "not found");
    std::vector<int>* theirCleared = new std::vector<int>();
    for (unsigned i = 0; i < theirClearedV.size(); ++i)
        theirCleared->push_back(theirClearedV[i].asInt());

    return new GameBoardState(sequence, timestamp, myBoard, theirBoard,
                                    myPiece, theirPiece, myCleared, theirCleared);
}

State const* MessageFactory::ParseGamePieceStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();
    Json::Value states = root.get("states", "not found");

    Json::Value queueV = root.get("queue", "not found");
    std::vector<Tetronimo>* queue = new std::vector<Tetronimo>();
    for (unsigned i = 0; i < queueV.size(); ++i) {
        std::string piece = queueV[i].asString();
        if (piece.size() != 1)
            return new ErrorState("Invalid piece descriptor in GamePieceState/queue");
        Tetronimo t (piece.at(0));
        queue->push_back(t);
    }

    Json::Value mine = states.get(USERNAME, "not found");
    std::string myPieceS = mine.get("piece", "not found").asString();
    if (myPieceS.size() != 1)
        return new ErrorState("Invalid piece descriptor in GamePieceState/state/username");
    char myPiece = myPieceS.at(0);
    int myOrient = mine.get("orient", -1).asInt();
    int myCol = mine.get("col", -1).asInt();
    int myRow = mine.get("row", -1).asInt();
    Tetronimo* myTet = new Tetronimo(myPiece, myOrient, myCol, myRow);

    Json::Value theirs = states.get("Test Client", "not found");
    std::string theirPieceS = theirs.get("piece", "not found").asString();
    if (theirPieceS.size() != 1)
        return new ErrorState("Invalid piece descriptor in GamePieceState/state/opponent");
    char theirPiece = theirPieceS.at(0);
    int theirOrient = theirs.get("orient", -1).asInt();
    int theirCol = theirs.get("col", -1).asInt();
    int theirRow = theirs.get("row", -1).asInt();
    Tetronimo* theirTet = new Tetronimo(theirPiece, theirOrient, theirCol, theirRow);

    return new GamePieceState(sequence, timestamp, myTet, theirTet, queue);
}

State const* MessageFactory::ParseMatchEndStateMessage(Json::Value const& root) const {
    return new MatchEnd();
}

State const* MessageFactory::ParseGameEndStateMessage(Json::Value const& root) const {
    int sequence = root.get("sequence", -1).asInt();
    double timestamp = root.get("timestamp", 0.0).asDouble();

    std::string winner = root.get("winner", "not found").asString();
    bool won = false;
    if (winner.compare(USERNAME) == 0)
        won = true;

    Json::Value scores = root.get("scores", "not found");
    int myScore = scores.get(USERNAME, -1).asInt();
    int theirScore = scores.get("Test Client", -1).asInt();

    return new GameEnd(sequence, timestamp, won, myScore, theirScore);
}

<|endoftext|>


<commit_before>#ifndef INTERLEAVER_RANDOM_HPP
#define	INTERLEAVER_RANDOM_HPP

#include <algorithm>
#include <time.h>

#include "Interleaver.hpp"

template <typename T>
class Interleaver_random : public Interleaver<T>
{
public:
	Interleaver_random(int size) : Interleaver<T>(size) { gen_lookup_tables(); }

protected:
	void gen_lookup_tables()
	{
		for (auto i = 0; i < (int)this->pi.size(); i++)
			this->pi[i] = i;

		std::random_device rd;
		std::mt19937 g(rd());

		std::shuffle(this->pi.begin(), this->pi.end(), g);

		for (auto i = 0; i < (int)this->pi_inv.size(); i++)
			this->pi_inv[this->pi[i]] = i;
	}
};

#endif	/* INTERLEAVER_RANDOM_HPP */

<commit_msg>Fix clang error compilation by including random header.<commit_after>#ifndef INTERLEAVER_RANDOM_HPP
#define	INTERLEAVER_RANDOM_HPP

#include <algorithm>
#include <time.h>
#include <random>

#include "Interleaver.hpp"

template <typename T>
class Interleaver_random : public Interleaver<T>
{
public:
	Interleaver_random(int size) : Interleaver<T>(size) { gen_lookup_tables(); }

protected:
	void gen_lookup_tables()
	{
		for (auto i = 0; i < (int)this->pi.size(); i++)
			this->pi[i] = i;

		std::random_device rd;
		std::mt19937 g(rd());

		std::shuffle(this->pi.begin(), this->pi.end(), g);

		for (auto i = 0; i < (int)this->pi_inv.size(); i++)
			this->pi_inv[this->pi[i]] = i;
	}
};

#endif	/* INTERLEAVER_RANDOM_HPP */

<|endoftext|>


<commit_before>#include "AliHBTPositionRandomizer.h"
//___________________________________________________
////////////////////////////////////////////////////////////////////////////////
//
// class AliHBTPositionRandomizer
//
// These class randomizes particle vertex positions
// Piotr.Skowronski@cern.ch
//
////////////////////////////////////////////////////////////////////////////////

#include <TRandom.h>
#include "AliAOD.h"
#include "AliVAODParticle.h"

ClassImp(AliHBTPositionRandomizer)

/*********************************************************************/

AliHBTPositionRandomizer::AliHBTPositionRandomizer():
 fReader(0x0),
 fRandomizer(0x0),
 fModel(0),
 fAddToExistingPos(kFALSE),
 fOnlyParticlesFromVertex(kFALSE),
 fRandomizeTracks(kFALSE),
 fVX(0.0),
 fVY(0.0),
 fVZ(0.0)
{
//constructor
}
/*********************************************************************/

AliHBTPositionRandomizer::AliHBTPositionRandomizer(AliReader* reader):
 fReader(reader),
 fRandomizer(new AliHBTRndmGaussBall(8.0)),
 fModel(0),
 fAddToExistingPos(kFALSE),
 fOnlyParticlesFromVertex(kFALSE),
 fRandomizeTracks(kFALSE),
 fVX(0.0),
 fVY(0.0),
 fVZ(0.0)
{
//constructor
}
/*********************************************************************/

AliHBTPositionRandomizer::AliHBTPositionRandomizer(const AliHBTPositionRandomizer& in):
 AliReader(in),
 fReader(),
 fRandomizer(0x0),
 fModel(0),
 fAddToExistingPos(kFALSE),
 fOnlyParticlesFromVertex(kFALSE),
 fRandomizeTracks(kFALSE),
 fVX(0.0),
 fVY(0.0),
 fVZ(0.0)
{
  //cpy constructor
  in.Copy(*this);
}
/*********************************************************************/
AliHBTPositionRandomizer::~AliHBTPositionRandomizer()
{
  //dtor
  delete fReader;
  delete fRandomizer;
}
/*********************************************************************/
AliHBTPositionRandomizer& AliHBTPositionRandomizer::operator=(const AliHBTPositionRandomizer& in)
{
  //assigment operator
  in.Copy(*this);
  return *this;
}
/*********************************************************************/

AliAOD* AliHBTPositionRandomizer::GetEventSim() const
{
 // gets from fReader and randomizes current particle event
 if (fReader == 0x0)
  {
    Error("GetEventSim","Reader is null");
    return 0x0;
  }
 AliAOD *e =  fReader->GetEventSim();
 if (e->IsRandomized() == kFALSE) Randomize(e);
 return e;
}
/*********************************************************************/

AliAOD* AliHBTPositionRandomizer::GetEventRec() const
{
 // gets from fReader and randomizes current track event
 if (fReader == 0x0)
  {
    Error("GetEventRec","Reader is null");
    return 0x0;
  }
 AliAOD *e =  fReader->GetEventRec();
 if (fRandomizeTracks) if (e->IsRandomized() == kFALSE) Randomize(e);
 return e;
}
/*********************************************************************/

AliAOD* AliHBTPositionRandomizer::GetEventSim(Int_t n)
{
//returns event n
 if (fReader == 0x0) return 0x0;
 AliAOD *e =  fReader->GetEventSim(n);
 if (e->IsRandomized() == kFALSE) Randomize(e);
 return e;
}

/*********************************************************************/
void AliHBTPositionRandomizer::Randomize(AliAOD* event) const
{
// randomizes postions of all particles in the event
  static const Double_t kfmtocm = 1.e-13;
  if (AliVAODParticle::GetDebug() > 5) Info("Randomize(AliAOD*)","");
  if (event == 0x0) return;

  for (Int_t i = 0; i < event->GetNumberOfParticles(); i++)
   {
     AliVAODParticle* p = event->GetParticle(i);
     Double_t x,y,z,t=0.0;
     fRandomizer->Randomize(x,y,z,p);

     Double_t nx = x*kfmtocm;
     Double_t ny = y*kfmtocm;
     Double_t nz = z*kfmtocm;
     Double_t nt = t*kfmtocm;

     if (fAddToExistingPos)
      {
       nx += p->Vx();
       ny += p->Vy();
       nz += p->Vz();
       nt += p->T();
      }
     p->SetProductionVertex(nx,ny,nz,nt);
   }
  event->SetRandomized();
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetGaussianBall(Double_t r)
{
 //Sets Gaussian Ball Model
  SetGaussianBall(r,r,r);
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetGaussianBall(Double_t rx, Double_t ry, Double_t rz)
{
 //Sets Gaussian Ball Model
  delete fRandomizer;
  fRandomizer = new AliHBTRndmGaussBall(rx,ry,rz);
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetCyllinderSurface(Double_t r, Double_t l)
{
 //Sets Cylinder Surface Model
  delete fRandomizer;
  fRandomizer = new  AliHBTRndmCyllSurf(r,l);
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetEventVertex(Double_t x, Double_t y,Double_t z)
{
//sets event vertex position
  fVX = x;
  fVY = y;
  fVZ = z;
}
/*********************************************************************/
//_____________________________________________________________________
///////////////////////////////////////////////////////////////////////
//                                                                   //
//  class AliHBTRndmGaussBall                                        //
//                                                                   //
///////////////////////////////////////////////////////////////////////

AliHBTRndmGaussBall::AliHBTRndmGaussBall():
 fRx(0.0),
 fRy(0.0),
 fRz(0.0)
{
  //constructor
}
/*********************************************************************/

AliHBTRndmGaussBall::AliHBTRndmGaussBall(Float_t r):
 fRx(r),
 fRy(r),
 fRz(r)
{
  //constructor
}
/*********************************************************************/

AliHBTRndmGaussBall::AliHBTRndmGaussBall(Float_t rx, Float_t ry, Float_t rz):
 fRx(rx),
 fRy(ry),
 fRz(rz)
{
  //constructor
}
/*********************************************************************/

void AliHBTRndmGaussBall::Randomize(Double_t& x,Double_t& y,Double_t&z, AliVAODParticle*/*particle*/) const
{
//randomizez gauss for each coordinate separately
  x = gRandom->Gaus(0.0,fRx);
  y = gRandom->Gaus(0.0,fRy);
  z = gRandom->Gaus(0.0,fRz);
}
/*********************************************************************/
//_____________________________________________________________________
///////////////////////////////////////////////////////////////////////
//                                                                   //
//  class AliHBTRndmGaussBall                                        //
//                                                                   //
///////////////////////////////////////////////////////////////////////

void AliHBTRndmCyllSurf::Randomize(Double_t& x,Double_t& y,Double_t&z, AliVAODParticle* particle) const
{
//Randomizes x,y,z
   Double_t r = fR + gRandom->Gaus(0.0, 1.0);
   Double_t sf = r/particle->Pt();//scaling factor for position transformation ->
                             //we move direction of string momentum but legth defined by r
   x = sf*particle->Px();
   y = sf*particle->Py();
   z = gRandom->Uniform(-fL,fL);
}
<commit_msg>Addtional check<commit_after>#include "AliHBTPositionRandomizer.h"
//___________________________________________________
////////////////////////////////////////////////////////////////////////////////
//
// class AliHBTPositionRandomizer
//
// These class randomizes particle vertex positions
// Piotr.Skowronski@cern.ch
//
////////////////////////////////////////////////////////////////////////////////

#include <TRandom.h>
#include "AliAOD.h"
#include "AliVAODParticle.h"

ClassImp(AliHBTPositionRandomizer)

/*********************************************************************/

AliHBTPositionRandomizer::AliHBTPositionRandomizer():
 fReader(0x0),
 fRandomizer(0x0),
 fModel(0),
 fAddToExistingPos(kFALSE),
 fOnlyParticlesFromVertex(kFALSE),
 fRandomizeTracks(kFALSE),
 fVX(0.0),
 fVY(0.0),
 fVZ(0.0)
{
//constructor
}
/*********************************************************************/

AliHBTPositionRandomizer::AliHBTPositionRandomizer(AliReader* reader):
 fReader(reader),
 fRandomizer(new AliHBTRndmGaussBall(8.0)),
 fModel(0),
 fAddToExistingPos(kFALSE),
 fOnlyParticlesFromVertex(kFALSE),
 fRandomizeTracks(kFALSE),
 fVX(0.0),
 fVY(0.0),
 fVZ(0.0)
{
//constructor
}
/*********************************************************************/

AliHBTPositionRandomizer::AliHBTPositionRandomizer(const AliHBTPositionRandomizer& in):
 AliReader(in),
 fReader(),
 fRandomizer(0x0),
 fModel(0),
 fAddToExistingPos(kFALSE),
 fOnlyParticlesFromVertex(kFALSE),
 fRandomizeTracks(kFALSE),
 fVX(0.0),
 fVY(0.0),
 fVZ(0.0)
{
  //cpy constructor
  in.Copy(*this);
}
/*********************************************************************/
AliHBTPositionRandomizer::~AliHBTPositionRandomizer()
{
  //dtor
  delete fReader;
  delete fRandomizer;
}
/*********************************************************************/
AliHBTPositionRandomizer& AliHBTPositionRandomizer::operator=(const AliHBTPositionRandomizer& in)
{
  //assigment operator
  in.Copy(*this);
  return *this;
}
/*********************************************************************/

AliAOD* AliHBTPositionRandomizer::GetEventSim() const
{
 // gets from fReader and randomizes current particle event
 if (fReader == 0x0)
  {
    Error("GetEventSim","Reader is null");
    return 0x0;
  }
 AliAOD *e =  fReader->GetEventSim();
 if (e)
   if (e->IsRandomized() == kFALSE)
     Randomize(e);
 return e;
}
/*********************************************************************/

AliAOD* AliHBTPositionRandomizer::GetEventRec() const
{
 // gets from fReader and randomizes current track event
 if (fReader == 0x0)
  {
    Error("GetEventRec","Reader is null");
    return 0x0;
  }
 AliAOD *e =  fReader->GetEventRec();
 if (fRandomizeTracks && e) if (e->IsRandomized() == kFALSE) Randomize(e);
 return e;
}
/*********************************************************************/

AliAOD* AliHBTPositionRandomizer::GetEventSim(Int_t n)
{
//returns event n
 if (fReader == 0x0) return 0x0;
 AliAOD *e =  fReader->GetEventSim(n);
 if (e->IsRandomized() == kFALSE) Randomize(e);
 return e;
}

/*********************************************************************/
void AliHBTPositionRandomizer::Randomize(AliAOD* event) const
{
// randomizes postions of all particles in the event
  static const Double_t kfmtocm = 1.e-13;
  if (AliVAODParticle::GetDebug() > 5) Info("Randomize(AliAOD*)","");
  if (event == 0x0) return;

  for (Int_t i = 0; i < event->GetNumberOfParticles(); i++)
   {
     AliVAODParticle* p = event->GetParticle(i);
     Double_t x,y,z,t=0.0;
     fRandomizer->Randomize(x,y,z,p);

     Double_t nx = x*kfmtocm;
     Double_t ny = y*kfmtocm;
     Double_t nz = z*kfmtocm;
     Double_t nt = t*kfmtocm;

     if (fAddToExistingPos)
      {
       nx += p->Vx();
       ny += p->Vy();
       nz += p->Vz();
       nt += p->T();
      }
     p->SetProductionVertex(nx,ny,nz,nt);
   }
  event->SetRandomized();
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetGaussianBall(Double_t r)
{
 //Sets Gaussian Ball Model
  SetGaussianBall(r,r,r);
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetGaussianBall(Double_t rx, Double_t ry, Double_t rz)
{
 //Sets Gaussian Ball Model
  delete fRandomizer;
  fRandomizer = new AliHBTRndmGaussBall(rx,ry,rz);
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetCyllinderSurface(Double_t r, Double_t l)
{
 //Sets Cylinder Surface Model
  delete fRandomizer;
  fRandomizer = new  AliHBTRndmCyllSurf(r,l);
}
/*********************************************************************/

void AliHBTPositionRandomizer::SetEventVertex(Double_t x, Double_t y,Double_t z)
{
//sets event vertex position
  fVX = x;
  fVY = y;
  fVZ = z;
}
/*********************************************************************/
//_____________________________________________________________________
///////////////////////////////////////////////////////////////////////
//                                                                   //
//  class AliHBTRndmGaussBall                                        //
//                                                                   //
///////////////////////////////////////////////////////////////////////

AliHBTRndmGaussBall::AliHBTRndmGaussBall():
 fRx(0.0),
 fRy(0.0),
 fRz(0.0)
{
  //constructor
}
/*********************************************************************/

AliHBTRndmGaussBall::AliHBTRndmGaussBall(Float_t r):
 fRx(r),
 fRy(r),
 fRz(r)
{
  //constructor
}
/*********************************************************************/

AliHBTRndmGaussBall::AliHBTRndmGaussBall(Float_t rx, Float_t ry, Float_t rz):
 fRx(rx),
 fRy(ry),
 fRz(rz)
{
  //constructor
}
/*********************************************************************/

void AliHBTRndmGaussBall::Randomize(Double_t& x,Double_t& y,Double_t&z, AliVAODParticle*/*particle*/) const
{
//randomizez gauss for each coordinate separately
  x = gRandom->Gaus(0.0,fRx);
  y = gRandom->Gaus(0.0,fRy);
  z = gRandom->Gaus(0.0,fRz);
}
/*********************************************************************/
//_____________________________________________________________________
///////////////////////////////////////////////////////////////////////
//                                                                   //
//  class AliHBTRndmGaussBall                                        //
//                                                                   //
///////////////////////////////////////////////////////////////////////

void AliHBTRndmCyllSurf::Randomize(Double_t& x,Double_t& y,Double_t&z, AliVAODParticle* particle) const
{
//Randomizes x,y,z
   Double_t r = fR + gRandom->Gaus(0.0, 1.0);
   Double_t sf = r/particle->Pt();//scaling factor for position transformation ->
                             //we move direction of string momentum but legth defined by r
   x = sf*particle->Px();
   y = sf*particle->Py();
   z = gRandom->Uniform(-fL,fL);
}
<|endoftext|>


<commit_before>#include "catch/catch.hpp"
#include "RaZ/Entity.hpp"
#include "RaZ/Math/Transform.hpp"
#include "RaZ/Render/Mesh.hpp"
#include "RaZ/System.hpp"

class TestSystem : public Raz::System {
public:
  TestSystem() { m_acceptedComponents.setBit(Raz::Component::getId<Raz::Transform>()); } // [ 0 1 ]

  void update(float /* deltaTime */) override {}
};

TEST_CASE("System basic checks") {
  TestSystem testSystem {};

  Raz::EntityPtr mesh = Raz::Entity::create(0);
  mesh->addComponent<Raz::Mesh>();

  // If the system is supposed to contain the entity, link it
  // This operation is normally made into a World
  if (!(mesh->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.linkEntity(mesh);

  REQUIRE_FALSE(testSystem.containsEntity(mesh));

  Raz::EntityPtr transform = Raz::Entity::create(1);
  transform->addComponent<Raz::Transform>();

  if (!(transform->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.linkEntity(transform);

  REQUIRE(testSystem.containsEntity(transform));

  // Removing our Transform component, the entity shouldn't be processed by the system anymore
  transform->removeComponent<Raz::Transform>();

  // Unlink the entity if none of the components match
  if ((transform->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.unlinkEntity(transform);

  REQUIRE_FALSE(testSystem.containsEntity(transform));

  // Creating an entity without components
  const Raz::EntityPtr emptyEntity = Raz::Entity::create(2);

  // The entity will not be linked since there's no component to be matched
  if (!(emptyEntity->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.linkEntity(emptyEntity);

  REQUIRE_FALSE(testSystem.containsEntity(emptyEntity));
}
<commit_msg>[Fix] Added a Window in System unit tests to create GL context (MSVC)<commit_after>#include "catch/catch.hpp"
#include "RaZ/Entity.hpp"
#include "RaZ/Math/Transform.hpp"
#include "RaZ/Render/Mesh.hpp"
#include "RaZ/System.hpp"

class TestSystem : public Raz::System {
public:
  TestSystem() { m_acceptedComponents.setBit(Raz::Component::getId<Raz::Transform>()); } // [ 0 1 ]

  void update(float /* deltaTime */) override {}
};

TEST_CASE("System basic checks") {
  TestSystem testSystem {};

  // Window created to setup the OpenGL context, which Raz::Mesh needs to be instantiated
  // TODO: this window should not be created anymore when renderer will be externalized
  Raz::Window window(1, 1);

  Raz::EntityPtr mesh = Raz::Entity::create(0);
  mesh->addComponent<Raz::Mesh>();

  // If the system is supposed to contain the entity, link it
  // This operation is normally made into a World
  if (!(mesh->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.linkEntity(mesh);

  REQUIRE_FALSE(testSystem.containsEntity(mesh));

  Raz::EntityPtr transform = Raz::Entity::create(1);
  transform->addComponent<Raz::Transform>();

  if (!(transform->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.linkEntity(transform);

  REQUIRE(testSystem.containsEntity(transform));

  // Removing our Transform component, the entity shouldn't be processed by the system anymore
  transform->removeComponent<Raz::Transform>();

  // Unlink the entity if none of the components match
  if ((transform->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.unlinkEntity(transform);

  REQUIRE_FALSE(testSystem.containsEntity(transform));

  // Creating an entity without components
  const Raz::EntityPtr emptyEntity = Raz::Entity::create(2);

  // The entity will not be linked since there's no component to be matched
  if (!(emptyEntity->getEnabledComponents() & testSystem.getAcceptedComponents()).isEmpty())
    testSystem.linkEntity(emptyEntity);

  REQUIRE_FALSE(testSystem.containsEntity(emptyEntity));
}
<|endoftext|>


<commit_before>// $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Oystein Djuvsland                                     *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/**
 * @file   AliHLTCaloClusterizer.cxx
 * @author Oystein Djuvsland
 * @date
 * @brief  Clusterizer for PHOS HLT
 */

// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

#include "AliHLTCaloClusterizer.h"
#include "AliHLTLogging.h"
#include "TMath.h"
#include "AliHLTCaloRecPointDataStruct.h"
#include "AliHLTCaloDigitDataStruct.h"
#include "AliHLTCaloDigitContainerDataStruct.h"
#include "AliHLTCaloConstantsHandler.h"

ClassImp(AliHLTCaloClusterizer);

AliHLTCaloClusterizer::AliHLTCaloClusterizer(TString det):
  AliHLTCaloConstantsHandler(det),
  fRecPointArray(0),
  fRecPointDataPtr(0),
  fFirstRecPointPtr(0),
  fArraySize(0),
  fAvailableSize(0),
  fUsedSize(0),
  fNRecPoints(0),
  fDigitIndexPtr(0),
  fEmcClusteringThreshold(0),
  fEmcMinEnergyThreshold(0),
  fEmcTimeGate(0),
  fDigitsInCluster(0),
  fDigitsPointerArray(0),
  fDigitContainerPtr(0),
  fMaxDigitIndexDiff(0),
  fNDigits(0)
{
  //See header file for documentation
  //fEmcClusteringThreshold = 0.2;
  //fEmcMinEnergyThreshold = 0.03;

  fEmcClusteringThreshold = 0.1;
  fEmcMinEnergyThreshold = 0.01;
  fEmcTimeGate = 1.e-6 ;

  fMaxDigitIndexDiff = 2*fCaloConstants->GetNZROWSMOD();

  fArraySize = 10;
  fRecPointArray = new AliHLTCaloRecPointDataStruct*[fArraySize];

  fAvailableSize = sizeof(AliHLTCaloRecPointDataStruct) * 20;
  fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(new UChar_t[fAvailableSize]);
  fFirstRecPointPtr = fRecPointDataPtr;

}//end

AliHLTCaloClusterizer::~AliHLTCaloClusterizer()
{
  //See header file for documentation
}

void
AliHLTCaloClusterizer::SetRecPointDataPtr(AliHLTCaloRecPointDataStruct* recPointDataPtr)
{
  // See header file for documentation
  fRecPointDataPtr = recPointDataPtr;
}

Int_t
AliHLTCaloClusterizer::ClusterizeEvent(Int_t nDigits)
{
  //see header file for documentation
  Int_t nRecPoints = 0;
  fNRecPoints = 0;
  fUsedSize = 0;
  fNDigits = nDigits;
  fRecPointDataPtr = fFirstRecPointPtr;
  //Clusterization starts
  for(Int_t i = 0; i < nDigits; i++)
    {
      fDigitsInCluster = 0;

      if(fDigitsPointerArray[i]->fEnergy < fEmcClusteringThreshold)
	{
	  continue;
	}
      CheckArray();
      CheckBuffer();

      // First digit is placed at the fDigits member variable in the recpoint
      fDigitIndexPtr = &(fRecPointDataPtr->fDigits);
      fUsedSize += sizeof(AliHLTCaloRecPointDataStruct);

      fRecPointDataPtr->fAmp = 0;
      fRecPointDataPtr->fModule = fDigitsPointerArray[i]->fModule;

      // Assigning the digit to this rec point
      fRecPointDataPtr->fDigits = i;
      fUsedSize += sizeof(AliHLTCaloRecPointDataStruct);

      // Incrementing the pointer to be ready for new entry
      fDigitIndexPtr++;

      fRecPointDataPtr->fAmp += fDigitsPointerArray[i]->fEnergy;
      fDigitsPointerArray[i]->fEnergy = 0;
      fDigitsInCluster++;
      nRecPoints++;

      // Scanning for the neighbours
      if(ScanForNeighbourDigits(i, fRecPointDataPtr) != 0)
      {
	 return -1;
      }

      //fUsedSize += sizeof(AliHLTCaloRecPointDataStruct) + (fDigitsInCluster-1)*sizeof(AliHLTCaloDigitDataStruct);

      fRecPointDataPtr->fMultiplicity = fDigitsInCluster;
      fRecPointArray[fNRecPoints] = fRecPointDataPtr;

      fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(fDigitIndexPtr);

      fNRecPoints++;

    }//end of clusterization

   return nRecPoints;
}

Int_t
AliHLTCaloClusterizer::ScanForNeighbourDigits(Int_t index, AliHLTCaloRecPointDataStruct* recPoint)
{
  //see header file for documentation
  Int_t max = TMath::Min(fNDigits, (Int_t)fMaxDigitIndexDiff+index);
  Int_t min = TMath::Max(0, (Int_t)(index - (Int_t)fMaxDigitIndexDiff));

  max = fNDigits;
  min = 0;
  for(Int_t j = min; j < max; j++)
    {
      if(fDigitsPointerArray[j]->fEnergy > fEmcMinEnergyThreshold)
	{
	  if(j != index)
	    {
	      if(AreNeighbours(fDigitsPointerArray[index],
			       fDigitsPointerArray[j]))
		{
// 		  if((fAvailableSize - fUsedSize) < sizeof(Int_t))
// 		     {
// 			UChar_t *tmp = new UChar_t[fAvailableSize*2];
// 			memcpy(tmp, fRecPointDataPtr, fAvailableSize);
// 			for(Int_t n = 0; n < fNRecPoints; n++)
// 			{
// 			   fRecPointArray[n] = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(reinterpret_cast<UChar_t*>(fRecPointArray[n]) - reinterpret_cast<UChar_t*>(fFirstRecPointPtr) + reinterpret_cast<UChar_t*>(tmp));
// 			}
// 			fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(tmp);
// 			fFirstRecPointPtr = fRecPointDataPtr;
// 			fUsedSize = 0;
// 		     }
		  CheckBuffer();
		  // Assigning index to digit
		  *fDigitIndexPtr = j;
		  fUsedSize += sizeof(Int_t);

		  // Incrementing digit pointer to be ready for new entry
		  fDigitIndexPtr++;

		  recPoint->fAmp += fDigitsPointerArray[j]->fEnergy;
		  fDigitsPointerArray[j]->fEnergy = 0;
		  fDigitsInCluster++;
		  ScanForNeighbourDigits(j, recPoint);
		}
	    }
	}
    }
  return 0;
}

Int_t
AliHLTCaloClusterizer::AreNeighbours(AliHLTCaloDigitDataStruct* digit1,
					    AliHLTCaloDigitDataStruct* digit2)
{
  //see header file for documentation
  if ( (digit1->fModule == digit2->fModule) /*&& (coord1[1]==coord2[1])*/ ) // inside the same PHOS module
    {
      Int_t rowdiff = TMath::Abs( digit1->fZ - digit2->fZ );
      Int_t coldiff = TMath::Abs( digit1->fX - digit2->fX );
      if (( coldiff <= 1   &&  rowdiff == 0 ) || ( coldiff == 0 &&  rowdiff <= 1 ))
	{
//	  cout << "Are neighbours: digit (E = "  << digit1->fEnergy << ") with x = " << digit1->fX << " and z = " << digit1->fZ <<
//	    " is neighbour with digit (E = " << digit2->fEnergy << ") with x = " << digit2->fX << " and z = " << digit2->fZ << endl;

	  if(TMath::Abs(digit1->fTime - digit2->fTime ) < fEmcTimeGate)
	    {
	      return 1;
	    }
	}

   /*   Float_t rowdiff = TMath::Abs( digit1->fZ - digit2->fZ );
      Float_t coldiff = TMath::Abs( digit1->fX - digit2->fX );
      if (( coldiff <= 2.4   &&  rowdiff < 0.4 ) || ( coldiff < 0.4 &&  rowdiff <= 2.4 ))
	{
	  //	  cout << "Are neighbours: digit (E = "  << digit1->fEnergy << ") with x = " << digit1->fX << " and z = " << digit1->fZ <<
	  //	    " is neighbour with digit (E = " << digit2->fEnergy << ") with x = " << digit2->fX << " and z = " << digit2->fZ << endl;

	  if(TMath::Abs(digit1->fTime - digit2->fTime ) < fEmcTimeGate)
	    {
	      return 1;
	    }
	}
   */
      else
	{
//	    cout << "Not neighbours: digit (E = "  << digit1->fEnergy << ") with x = " << digit1->fX << " and z = " << digit1->fZ <<
//	    " is not neighbour with digit (E = " << digit2->fEnergy << ") with x = " << digit2->fX << " and z = " << digit2->fZ << endl;
	}
    }
  return 0;
}

Int_t AliHLTCaloClusterizer::CheckArray()
{
      if(fArraySize == fNRecPoints)
	{
	   fArraySize *= 2;
	   AliHLTCaloRecPointDataStruct **tmp = new AliHLTCaloRecPointDataStruct*[fArraySize];
	   memcpy(tmp, fRecPointArray, fArraySize/2 * sizeof(AliHLTCaloRecPointDataStruct*));
	   delete fRecPointArray;
	   fRecPointArray = tmp;
	}
   return 0;
}

Int_t AliHLTCaloClusterizer::CheckBuffer()
{
   // See header file for class documentation
	if((fAvailableSize - fUsedSize) < sizeof(AliHLTCaloRecPointDataStruct))
	{
	    Int_t recPointOffset = reinterpret_cast<UChar_t*>(fRecPointDataPtr) - reinterpret_cast<UChar_t*>(fFirstRecPointPtr);
	    fAvailableSize *= 2;
	    UChar_t *tmp = new UChar_t[fAvailableSize];
	    memcpy(tmp, fRecPointDataPtr, fAvailableSize/2);
	    for(Int_t n = 0; n < fNRecPoints; n++)
	    {
	       fRecPointArray[n] = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(reinterpret_cast<UChar_t*>(fRecPointArray[n]) - reinterpret_cast<UChar_t*>(fFirstRecPointPtr) + reinterpret_cast<UChar_t*>(tmp));
	    }
	    delete fRecPointDataPtr;
	    fFirstRecPointPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(tmp);
	    fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(tmp + recPointOffset);
	    fUsedSize = 0;
	}
   return 0;
}

Int_t AliHLTCaloClusterizer::CheckDigits(AliHLTCaloRecPointDataStruct** recArray, AliHLTCaloDigitDataStruct** digitArray, Int_t nRP)
{
  AliHLTCaloRecPointDataStruct **recpoints = recArray;
  AliHLTCaloDigitDataStruct **digits = digitArray;
  Int_t nRecPoints = nRP;

  if(recArray == 0)
  {
     recpoints = fRecPointArray;
  }
  if(digitArray == 0)
  {
     digits = fDigitsPointerArray;
  }
  if(nRP == 0)
  {
     nRecPoints = fNRecPoints;
  }
  for(Int_t i = 0; i < nRecPoints; i++)
  {

     AliHLTCaloRecPointDataStruct *recPoint = recpoints[i];

     //AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[0];
     Int_t multiplicity = recPoint->fMultiplicity;
     Int_t *digitIndexPtr = &(recPoint->fDigits);
     for(Int_t j = 0; j < multiplicity; j++)
     {
	//AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[j];
//	AliHLTCaloDigitDataStruct *digit = digits[*digitIndexPtr];
	digitIndexPtr++;
	//recPoint = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(digitIndexPtr);
     }
  }

     return 0;
}

Int_t AliHLTCaloClusterizer::CheckDigits(AliHLTCaloRecPointDataStruct** recArray, AliHLTCaloDigitDataStruct* digitArray, Int_t nRP)
{
  AliHLTCaloRecPointDataStruct **recpoints = recArray;
  AliHLTCaloDigitDataStruct *digits = digitArray;
  Int_t nRecPoints = nRP;

  if(recArray == 0)
  {
     recpoints = fRecPointArray;
  }
    if(nRP == 0)
  {
     nRecPoints = fNRecPoints;
  }
  for(Int_t i = 0; i < nRecPoints; i++)
  {

     AliHLTCaloRecPointDataStruct *recPoint = recpoints[i];

     //AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[0];
     Int_t multiplicity = recPoint->fMultiplicity;
     Int_t *digitIndexPtr = &(recPoint->fDigits);
     for(Int_t j = 0; j < multiplicity; j++)
     {
	//AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[j];
	AliHLTCaloDigitDataStruct digit = digits[*digitIndexPtr];
	digitIndexPtr++;
	//recPoint = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(digitIndexPtr);
     }
  }
   return 0;

}
<commit_msg>- fixing problem in handling resizing of memory buffer<commit_after>// $Id$

/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * All rights reserved.                                                   *
 *                                                                        *
 * Primary Authors: Oystein Djuvsland                                     *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/**
 * @file   AliHLTCaloClusterizer.cxx
 * @author Oystein Djuvsland
 * @date
 * @brief  Clusterizer for PHOS HLT
 */

// see header file for class documentation
// or
// refer to README to build package
// or
// visit http://web.ift.uib.no/~kjeks/doc/alice-hlt

#include "AliHLTCaloClusterizer.h"
#include "AliHLTLogging.h"
#include "TMath.h"
#include "AliHLTCaloRecPointDataStruct.h"
#include "AliHLTCaloDigitDataStruct.h"
#include "AliHLTCaloDigitContainerDataStruct.h"
#include "AliHLTCaloConstantsHandler.h"

ClassImp(AliHLTCaloClusterizer);

AliHLTCaloClusterizer::AliHLTCaloClusterizer(TString det):
  AliHLTCaloConstantsHandler(det),
  fRecPointArray(0),
  fRecPointDataPtr(0),
  fFirstRecPointPtr(0),
  fArraySize(0),
  fAvailableSize(0),
  fUsedSize(0),
  fNRecPoints(0),
  fDigitIndexPtr(0),
  fEmcClusteringThreshold(0),
  fEmcMinEnergyThreshold(0),
  fEmcTimeGate(0),
  fDigitsInCluster(0),
  fDigitsPointerArray(0),
  fDigitContainerPtr(0),
  fMaxDigitIndexDiff(0),
  fNDigits(0)
{
  //See header file for documentation
  //fEmcClusteringThreshold = 0.2;
  //fEmcMinEnergyThreshold = 0.03;

  fEmcClusteringThreshold = 0.1;
  fEmcMinEnergyThreshold = 0.01;
  fEmcTimeGate = 1.e-6 ;

  fMaxDigitIndexDiff = 2*fCaloConstants->GetNZROWSMOD();

  fArraySize = 10;
  fRecPointArray = new AliHLTCaloRecPointDataStruct*[fArraySize];

  fAvailableSize = sizeof(AliHLTCaloRecPointDataStruct) * 20;
  fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(new UChar_t[fAvailableSize]);
  fFirstRecPointPtr = fRecPointDataPtr;

}//end

AliHLTCaloClusterizer::~AliHLTCaloClusterizer()
{
  //See header file for documentation
}

void
AliHLTCaloClusterizer::SetRecPointDataPtr(AliHLTCaloRecPointDataStruct* recPointDataPtr)
{
  // See header file for documentation
  fRecPointDataPtr = recPointDataPtr;
}

Int_t
AliHLTCaloClusterizer::ClusterizeEvent(Int_t nDigits)
{
  //see header file for documentation
  Int_t nRecPoints = 0;
  fNRecPoints = 0;
  fUsedSize = 0;
  fNDigits = nDigits;
  fRecPointDataPtr = fFirstRecPointPtr;
  //Clusterization starts
  for(Int_t i = 0; i < nDigits; i++)
    {
      fDigitsInCluster = 0;

      if(fDigitsPointerArray[i]->fEnergy < fEmcClusteringThreshold)
	{
	  continue;
	}
      CheckArray();
      CheckBuffer();

      // First digit is placed at the fDigits member variable in the recpoint
      fDigitIndexPtr = &(fRecPointDataPtr->fDigits);
      fUsedSize += sizeof(AliHLTCaloRecPointDataStruct);

      fRecPointDataPtr->fAmp = 0;
      fRecPointDataPtr->fModule = fDigitsPointerArray[i]->fModule;

      // Assigning the digit to this rec point
      fRecPointDataPtr->fDigits = i;
      fUsedSize += sizeof(AliHLTCaloRecPointDataStruct);

      // Incrementing the pointer to be ready for new entry
      fDigitIndexPtr++;

      fRecPointDataPtr->fAmp += fDigitsPointerArray[i]->fEnergy;
      fDigitsPointerArray[i]->fEnergy = 0;
      fDigitsInCluster++;
      nRecPoints++;

      // Scanning for the neighbours
      if(ScanForNeighbourDigits(i, fRecPointDataPtr) != 0)
      {
	 return -1;
      }

      //fUsedSize += sizeof(AliHLTCaloRecPointDataStruct) + (fDigitsInCluster-1)*sizeof(AliHLTCaloDigitDataStruct);

      fRecPointDataPtr->fMultiplicity = fDigitsInCluster;
      fRecPointArray[fNRecPoints] = fRecPointDataPtr;

      fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(fDigitIndexPtr);

      fNRecPoints++;

    }//end of clusterization

   return nRecPoints;
}

Int_t
AliHLTCaloClusterizer::ScanForNeighbourDigits(Int_t index, AliHLTCaloRecPointDataStruct* recPoint)
{
  //see header file for documentation
  Int_t max = TMath::Min(fNDigits, (Int_t)fMaxDigitIndexDiff+index);
  Int_t min = TMath::Max(0, (Int_t)(index - (Int_t)fMaxDigitIndexDiff));

  max = fNDigits;
  min = 0;
  for(Int_t j = min; j < max; j++)
    {
      if(fDigitsPointerArray[j]->fEnergy > fEmcMinEnergyThreshold)
	{
	  if(j != index)
	    {
	      if(AreNeighbours(fDigitsPointerArray[index],
			       fDigitsPointerArray[j]))
		{
// 		  if((fAvailableSize - fUsedSize) < sizeof(Int_t))
// 		     {
// 			UChar_t *tmp = new UChar_t[fAvailableSize*2];
// 			memcpy(tmp, fRecPointDataPtr, fAvailableSize);
// 			for(Int_t n = 0; n < fNRecPoints; n++)
// 			{
// 			   fRecPointArray[n] = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(reinterpret_cast<UChar_t*>(fRecPointArray[n]) - reinterpret_cast<UChar_t*>(fFirstRecPointPtr) + reinterpret_cast<UChar_t*>(tmp));
// 			}
// 			fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(tmp);
// 			fFirstRecPointPtr = fRecPointDataPtr;
// 			fUsedSize = 0;
// 		     }
		  CheckBuffer();
		  // Assigning index to digit
		  *fDigitIndexPtr = j;
		  fUsedSize += sizeof(Int_t);

		  // Incrementing digit pointer to be ready for new entry
		  fDigitIndexPtr++;

		  recPoint->fAmp += fDigitsPointerArray[j]->fEnergy;
		  fDigitsPointerArray[j]->fEnergy = 0;
		  fDigitsInCluster++;
		  ScanForNeighbourDigits(j, recPoint);
		}
	    }
	}
    }
  return 0;
}

Int_t
AliHLTCaloClusterizer::AreNeighbours(AliHLTCaloDigitDataStruct* digit1,
					    AliHLTCaloDigitDataStruct* digit2)
{
  //see header file for documentation
  if ( (digit1->fModule == digit2->fModule) /*&& (coord1[1]==coord2[1])*/ ) // inside the same PHOS module
    {
      Int_t rowdiff = TMath::Abs( digit1->fZ - digit2->fZ );
      Int_t coldiff = TMath::Abs( digit1->fX - digit2->fX );
      if (( coldiff <= 1   &&  rowdiff == 0 ) || ( coldiff == 0 &&  rowdiff <= 1 ))
	{
//	  cout << "Are neighbours: digit (E = "  << digit1->fEnergy << ") with x = " << digit1->fX << " and z = " << digit1->fZ <<
//	    " is neighbour with digit (E = " << digit2->fEnergy << ") with x = " << digit2->fX << " and z = " << digit2->fZ << endl;

	  if(TMath::Abs(digit1->fTime - digit2->fTime ) < fEmcTimeGate)
	    {
	      return 1;
	    }
	}

   /*   Float_t rowdiff = TMath::Abs( digit1->fZ - digit2->fZ );
      Float_t coldiff = TMath::Abs( digit1->fX - digit2->fX );
      if (( coldiff <= 2.4   &&  rowdiff < 0.4 ) || ( coldiff < 0.4 &&  rowdiff <= 2.4 ))
	{
	  //	  cout << "Are neighbours: digit (E = "  << digit1->fEnergy << ") with x = " << digit1->fX << " and z = " << digit1->fZ <<
	  //	    " is neighbour with digit (E = " << digit2->fEnergy << ") with x = " << digit2->fX << " and z = " << digit2->fZ << endl;

	  if(TMath::Abs(digit1->fTime - digit2->fTime ) < fEmcTimeGate)
	    {
	      return 1;
	    }
	}
   */
      else
	{
//	    cout << "Not neighbours: digit (E = "  << digit1->fEnergy << ") with x = " << digit1->fX << " and z = " << digit1->fZ <<
//	    " is not neighbour with digit (E = " << digit2->fEnergy << ") with x = " << digit2->fX << " and z = " << digit2->fZ << endl;
	}
    }
  return 0;
}

Int_t AliHLTCaloClusterizer::CheckArray()
{
      if(fArraySize == fNRecPoints)
	{
	   fArraySize *= 2;
	   AliHLTCaloRecPointDataStruct **tmp = new AliHLTCaloRecPointDataStruct*[fArraySize];
	   memcpy(tmp, fRecPointArray, fArraySize/2 * sizeof(AliHLTCaloRecPointDataStruct*));
	   delete fRecPointArray;
	   fRecPointArray = tmp;
	}
   return 0;
}

Int_t AliHLTCaloClusterizer::CheckBuffer()
{
   // See header file for class documentation
	if((fAvailableSize - fUsedSize) < sizeof(AliHLTCaloRecPointDataStruct))
	{
	    Int_t recPointOffset = reinterpret_cast<UChar_t*>(fRecPointDataPtr) - reinterpret_cast<UChar_t*>(fFirstRecPointPtr);
	    UChar_t *tmp = new UChar_t[fAvailableSize*2];
	    memcpy(tmp, fFirstRecPointPtr, fAvailableSize);
	    fAvailableSize *= 2;
	    for(Int_t n = 0; n < fNRecPoints; n++)
	    {
	       fRecPointArray[n] = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(reinterpret_cast<UChar_t*>(fRecPointArray[n]) - reinterpret_cast<UChar_t*>(fFirstRecPointPtr) + reinterpret_cast<UChar_t*>(tmp));
	    }
	    delete fFirstRecPointPtr;
	    fFirstRecPointPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(tmp);
	    fRecPointDataPtr = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(tmp + recPointOffset);
	    fUsedSize = 0;
	}
   return 0;
}

Int_t AliHLTCaloClusterizer::CheckDigits(AliHLTCaloRecPointDataStruct** recArray, AliHLTCaloDigitDataStruct** digitArray, Int_t nRP)
{
  AliHLTCaloRecPointDataStruct **recpoints = recArray;
  AliHLTCaloDigitDataStruct **digits = digitArray;
  Int_t nRecPoints = nRP;

  if(recArray == 0)
  {
     recpoints = fRecPointArray;
  }
  if(digitArray == 0)
  {
     digits = fDigitsPointerArray;
  }
  if(nRP == 0)
  {
     nRecPoints = fNRecPoints;
  }
  for(Int_t i = 0; i < nRecPoints; i++)
  {

     AliHLTCaloRecPointDataStruct *recPoint = recpoints[i];

     //AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[0];
     Int_t multiplicity = recPoint->fMultiplicity;
     Int_t *digitIndexPtr = &(recPoint->fDigits);
     for(Int_t j = 0; j < multiplicity; j++)
     {
	//AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[j];
//	AliHLTCaloDigitDataStruct *digit = digits[*digitIndexPtr];
	digitIndexPtr++;
	//recPoint = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(digitIndexPtr);
     }
  }

     return 0;
}

Int_t AliHLTCaloClusterizer::CheckDigits(AliHLTCaloRecPointDataStruct** recArray, AliHLTCaloDigitDataStruct* digitArray, Int_t nRP)
{
  AliHLTCaloRecPointDataStruct **recpoints = recArray;
  AliHLTCaloDigitDataStruct *digits = digitArray;
  Int_t nRecPoints = nRP;

  if(recArray == 0)
  {
     recpoints = fRecPointArray;
  }
    if(nRP == 0)
  {
     nRecPoints = fNRecPoints;
  }
  for(Int_t i = 0; i < nRecPoints; i++)
  {

     AliHLTCaloRecPointDataStruct *recPoint = recpoints[i];

     //AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[0];
     Int_t multiplicity = recPoint->fMultiplicity;
     Int_t *digitIndexPtr = &(recPoint->fDigits);
     for(Int_t j = 0; j < multiplicity; j++)
     {
	//AliHLTCaloRecPointDataStruct *recPoint = fRecPointArray[j];
	AliHLTCaloDigitDataStruct digit = digits[*digitIndexPtr];
	digitIndexPtr++;
	//recPoint = reinterpret_cast<AliHLTCaloRecPointDataStruct*>(digitIndexPtr);
     }
  }
   return 0;

}
<|endoftext|>