<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved.

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.
==============================================================================*/

// See docs in ../ops/array_ops.cc

#define EIGEN_USE_THREADS

#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#endif  // GOOGLE_CUDA

#include "tensorflow/core/kernels/one_hot_op.h"

#include <memory>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;

template <typename Device, typename T, typename TI>
class OneHotOp : public OpKernel {
 public:
  explicit OneHotOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_));
  }

  void Compute(OpKernelContext* ctx) override {
    const Tensor& indices = ctx->input(0);
    const Tensor& depth = ctx->input(1);
    const Tensor& on_value = ctx->input(2);
    const Tensor& off_value = ctx->input(3);
    const TensorShape& indices_shape = indices.shape();

    const int indices_dims = indices_shape.dims();
    const int output_dims = indices_dims + 1;

    // Preliminary validation of sizes.
    OP_REQUIRES(
        ctx, axis_ == -1 || (axis_ >= 0 && axis_ < output_dims),
        errors::InvalidArgument("Expected axis to be -1 or between [0, ",
                                output_dims, ").  But received: ", axis_));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(depth.shape()),
                errors::InvalidArgument("depth must be a scalar, but got: ",
                                        depth.shape().DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(on_value.shape()),
                errors::InvalidArgument("on_value must be a scalar, but got: ",
                                        on_value.shape().DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(off_value.shape()),
                errors::InvalidArgument("off_value must be a scalar, but got: ",
                                        off_value.shape().DebugString()));

    const int axis = (axis_ == -1) ? indices_dims : axis_;

    // The one-hot dimension.
    const int32 depth_v = depth.scalar<int32>()();

    TensorShape output_shape = indices_shape;
    output_shape.InsertDim(axis, depth_v);

    auto on_value_t = on_value.scalar<T>();
    auto off_value_t = off_value.scalar<T>();

    Tensor* output;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output));

    // prefix_dim_size == # of elements before the axis
    // depth_v == # of elements per axis
    // suffix_dim_size == # of elements after the axis
    TI prefix_dim_size = 1;
    for (int i = 0; i < axis; ++i) {
      prefix_dim_size *= indices_shape.dim_size(i);
    }
    TI suffix_dim_size =
        indices_shape.num_elements() / prefix_dim_size;

    // Split indices into matrix of size prefix_dim_size x suffix_dim_size
    auto indices_t =
        indices.shaped<TI, 2>({prefix_dim_size, suffix_dim_size});
    // Split output into 3-Tensor of size:
    //   prefix_dim_size x depth x suffix_dim_size.
    auto output_t =
        output->shaped<T, 3>({prefix_dim_size, depth_v, suffix_dim_size});

    functor::OneHot<Device, T, TI>::Compute(ctx->eigen_device<Device>(), indices_t,
                                        on_value_t, off_value_t, &output_t);
  }

 private:
  int32 axis_;

  TF_DISALLOW_COPY_AND_ASSIGN(OneHotOp);
};

#define REGISTER_ONE_HOT_INDEX(type, index_type)                  \
  REGISTER_KERNEL_BUILDER(Name("OneHot")                          \
                              .Device(DEVICE_CPU)                 \
                              .TypeConstraint<index_type>("TI")   \
                              .TypeConstraint<type>("T")          \
                              .HostMemory("depth"),               \
                          OneHotOp<CPUDevice, type, index_type>);

#define REGISTER_ONE_HOT(type)          \
  REGISTER_ONE_HOT_INDEX(type, int32);  \
  REGISTER_ONE_HOT_INDEX(type, int64)

TF_CALL_ALL_TYPES(REGISTER_ONE_HOT);

#if GOOGLE_CUDA

// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC_INDEX(T, TI)                                       \
  template <>                                                               \
  void OneHot<GPUDevice, T, TI>::Compute(                                   \
      const GPUDevice& d, const typename TTypes<TI>::ConstMatrix& indices,  \
      const typename TTypes<T>::ConstScalar& on_value,                      \
      const typename TTypes<T>::ConstScalar& off_value,                     \
      typename TTypes<T, 3>::Tensor* output);                               \
  extern template struct OneHot<GPUDevice, T, TI>;

#define DECLARE_GPU_SPEC(T)          \
  DECLARE_GPU_SPEC_INDEX(T, int32);  \
  DECLARE_GPU_SPEC_INDEX(T, int64);  \

TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPEC);

#undef DECLARE_GPU_SPEC_INDEX
#undef DECLARE_GPU_SPEC

}  // namespace functor

#define REGISTER_ONE_HOT_GPU_INDEX(type, index_type)              \
  REGISTER_KERNEL_BUILDER(Name("OneHot")                          \
                              .Device(DEVICE_GPU)                 \
                              .TypeConstraint<index_type>("TI")   \
                              .TypeConstraint<type>("T")          \
                              .HostMemory("depth"),               \
                          OneHotOp<GPUDevice, type, index_type>);

#define REGISTER_ONE_HOT_GPU(type)          \
  REGISTER_ONE_HOT_GPU_INDEX(type, int32);  \
  REGISTER_ONE_HOT_GPU_INDEX(type, int64);  \

TF_CALL_GPU_NUMBER_TYPES(REGISTER_ONE_HOT_GPU);

#undef REGISTER_ONE_HOT_GPU_INDEX
#undef REGISTER_ONE_HOT_GPU

#endif  // GOOGLE_CUDA

}  // namespace tensorflow
<commit_msg>Add commit that accidentally got removed<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved.

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.
==============================================================================*/

// See docs in ../ops/array_ops.cc

#define EIGEN_USE_THREADS

#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#endif  // GOOGLE_CUDA

#include "tensorflow/core/kernels/one_hot_op.h"

#include <memory>
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"

namespace tensorflow {

typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;

template <typename Device, typename T, typename TI>
class OneHotOp : public OpKernel {
 public:
  explicit OneHotOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
    OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_));
  }

  void Compute(OpKernelContext* ctx) override {
    const Tensor& indices = ctx->input(0);
    const Tensor& depth = ctx->input(1);
    const Tensor& on_value = ctx->input(2);
    const Tensor& off_value = ctx->input(3);
    const TensorShape& indices_shape = indices.shape();

    const int indices_dims = indices_shape.dims();
    const int output_dims = indices_dims + 1;

    // Preliminary validation of sizes.
    OP_REQUIRES(
        ctx, axis_ == -1 || (axis_ >= 0 && axis_ < output_dims),
        errors::InvalidArgument("Expected axis to be -1 or between [0, ",
                                output_dims, ").  But received: ", axis_));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(depth.shape()),
                errors::InvalidArgument("depth must be a scalar, but got: ",
                                        depth.shape().DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(on_value.shape()),
                errors::InvalidArgument("on_value must be a scalar, but got: ",
                                        on_value.shape().DebugString()));
    OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(off_value.shape()),
                errors::InvalidArgument("off_value must be a scalar, but got: ",
                                        off_value.shape().DebugString()));

    const int axis = (axis_ == -1) ? indices_dims : axis_;

    // The one-hot dimension.
    const int32 depth_v = depth.scalar<int32>()();

    TensorShape output_shape = indices_shape;
    output_shape.InsertDim(axis, depth_v);

    auto on_value_t = on_value.scalar<T>();
    auto off_value_t = off_value.scalar<T>();

    Tensor* output;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &output));

    // prefix_dim_size == # of elements before the axis
    // depth_v == # of elements per axis
    // suffix_dim_size == # of elements after the axis
    TI prefix_dim_size = 1;
    for (int i = 0; i < axis; ++i) {
      prefix_dim_size *= indices_shape.dim_size(i);
    }
    TI suffix_dim_size =
        indices_shape.num_elements() / prefix_dim_size;

    // Split indices into matrix of size prefix_dim_size x suffix_dim_size
    auto indices_t =
        indices.shaped<TI, 2>({prefix_dim_size, suffix_dim_size});
    // Split output into 3-Tensor of size:
    //   prefix_dim_size x depth x suffix_dim_size.
    auto output_t =
        output->shaped<T, 3>({prefix_dim_size, depth_v, suffix_dim_size});

    functor::OneHot<Device, T, TI>::Compute(ctx->eigen_device<Device>(), indices_t,
                                        on_value_t, off_value_t, &output_t);
  }

 private:
  int32 axis_;

  TF_DISALLOW_COPY_AND_ASSIGN(OneHotOp);
};

#define REGISTER_ONE_HOT_INDEX(type, index_type)                  \
  REGISTER_KERNEL_BUILDER(Name("OneHot")                          \
                              .Device(DEVICE_CPU)                 \
                              .TypeConstraint<index_type>("TI")   \
                              .TypeConstraint<type>("T")          \
                              .HostMemory("depth"),               \
                          OneHotOp<CPUDevice, type, index_type>);

#define REGISTER_ONE_HOT(type)          \
  REGISTER_ONE_HOT_INDEX(type, int32);  \
  REGISTER_ONE_HOT_INDEX(type, int64)

TF_CALL_ALL_TYPES(REGISTER_ONE_HOT);

#if GOOGLE_CUDA

// Forward declarations of the functor specializations for GPU.
namespace functor {
#define DECLARE_GPU_SPEC_INDEX(T, TI)                                       \
  template <>                                                               \
  void OneHot<GPUDevice, T, TI>::Compute(                                   \
      const GPUDevice& d, const typename TTypes<TI>::ConstMatrix& indices,  \
      const typename TTypes<T>::ConstScalar& on_value,                      \
      const typename TTypes<T>::ConstScalar& off_value,                     \
      typename TTypes<T, 3>::Tensor* output);                               \
  extern template struct OneHot<GPUDevice, T, TI>;

#define DECLARE_GPU_SPEC(T)          \
  DECLARE_GPU_SPEC_INDEX(T, int32);  \
  DECLARE_GPU_SPEC_INDEX(T, int64);  \

TF_CALL_GPU_NUMBER_TYPES(DECLARE_GPU_SPEC);

#undef DECLARE_GPU_SPEC_INDEX
#undef DECLARE_GPU_SPEC

}  // namespace functor

// Registration of the GPU implementations.
#define REGISTER_ONE_HOT_GPU_INDEX(type, index_type)              \
  REGISTER_KERNEL_BUILDER(Name("OneHot")                          \
                              .Device(DEVICE_GPU)                 \
                              .TypeConstraint<index_type>("TI")   \
                              .TypeConstraint<type>("T")          \
                              .HostMemory("depth"),               \
                          OneHotOp<GPUDevice, type, index_type>);

#define REGISTER_ONE_HOT_GPU(type)          \
  REGISTER_ONE_HOT_GPU_INDEX(type, int32);  \
  REGISTER_ONE_HOT_GPU_INDEX(type, int64);  \

TF_CALL_GPU_NUMBER_TYPES(REGISTER_ONE_HOT_GPU);

#undef REGISTER_ONE_HOT_GPU_INDEX
#undef REGISTER_ONE_HOT_GPU

#endif  // GOOGLE_CUDA

}  // namespace tensorflow
<|endoftext|>


<commit_before>#include "items/inventory.h"
#include "entity_system.h"
#include "dataconsts.h"
#include "random.h"

#include "components/basic_info.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/lua.h"
#include "components/position.h"
#include "components/owner.h"
#include "itemdb.h"

#include "srv_equip_item.h"
#include "srv_set_item.h"
#include "srv_set_money.h"

#include <limits>

using namespace RoseCommon;
using namespace Items;

namespace {
// only for items, not cart/castle gear
inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) {
    const auto& item = entitySystem.get_component<ItemDef>(entity);
    const EquippedPosition pos = static_cast<EquippedPosition>(spot);
    if (pos >= EquippedPosition::MAX_EQUIP_ITEMS) {
        return true; // we don't care of the spot if we are not equipping anything
    }
    const EquippedPosition
    switch (item.type) {
        case ItemType::GOGGLES:
            return pos == EquippedPosition::GOGGLES;
        case ItemType::HELMET:
            return pos == EquippedPosition::HELMET;
        case ItemType::ARMOR:
            return pos == EquippedPosition::ARMOR;
        case ItemType::GAUNTLET:
            return pos == EquippedPosition::GAUNTLET;
        case ItemType::BOOTS:
            return pos == EquippedPosition::BOOTS;
        case ItemType::BACKPACK:
            return pos == EquippedPosition::BACKPACK;
        case ItemType::RING:
            return pos == EquippedPosition::RING;
        case ItemType::WEAPON_R:
            return pos == EquippedPosition::WEAPON_R;
        case ItemType::WEAPON_L:
            return pos == EquippedPosition::WEAPON_L;
        default:
            return false;
    }
}

inline bool is_spot_equipped(size_t spot) {
    return spot < EquippedPosition::MAX_EQUIP_ITEMS;
}
}

size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    size_t res = decltype(inv.getInventory())::offset();
    bool stackable = false;
    ItemType type = 0;
    uint16_t id = 0;
    if (item != entt::null) {
        const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
        stackable = i.is_stackable;
        type = i.type;
        id = i.id;
    }

    for (const auto item : inv.getInventory()) {
        if (item == entt::null) {
            return res;
        } else if (stackable) {
            const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
            const auto& it = entitySystem.get_component<Component::Item>(item);
            if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) {
                return res;
            }
        }
        ++res;
    }
    return 0;
}

ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
    const size_t pos = get_first_available_spot(entitySystem, entity, item);
    if (pos == 0) {
        return ReturnValue::NO_SPACE;
    }
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    if (inv.items[pos] == entt::null) {
        inv.items[pos] = item;
    } else {
        // add the stack
        auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]);
        auto& it = entitySystem.get_component<Component::Item>(item);
        if (i.count + it.count < RoseCommon::MAX_STACK) {
            // below max stack
            i.count += it.count;
        } else {
            // split the stack in two or more
            const uint32_t stack_tmp1 = i.count;
            const uint32_t stack_tmp2 = it.count;
            it.count -= RoseCommon::MAX_STACK - i.count;
            i.count = RoseCommon::MAX_STACK;
            if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) {
                it.count = stack_tmp2;
                i.count = stack_tmp1;
                return ReturnValue::NO_SPACE;
            }
        }
    }
    RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return ReturnValue::OK;
}

RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) {
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    RoseCommon::Entity item = inv.items[pos];
    auto& i = entitySystem.get_component<Component::Item>(item);
    const auto& it = entitySystem.get_component<ItemDef>(item);
    if (i.count < quantity) {
        return entt::null;
    }
    if (i.count > quantity) {
        const auto type = it.type;
        const auto id = it.id;
        i.count -= quantity;
        RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity);
        RoseCommon::Packet::SrvSetItem::IndexAndItem index;
        index.set_index(pos);
        index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
        auto packet = RoseCommon::Packet::SrvSetItem::create();
        packet.add_items(index);
        entitySystem.send_to(entity, packet);
        return newItem;
    }
    if (is_spot_equipped(pos)) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(item);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_unequip(item)) {
                return entt::null;
            }
        }
    }
    inv.items[pos] = entt::null;
    RoseCommon::Packet::SrvSetItem::IndexAndItem index;
    index.set_index(pos);
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return item;
}

void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) {
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    std::swap(inv.items[pos1], inv.items[pos2]);
}

ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) {
    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);

    if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) {
        return ReturnValue::WRONG_INDEX;
    }
    if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) {
        return ReturnValue::WRONG_INDEX;
    }

    const RoseCommon::Entity equipped = inv.items[to];
    const RoseCommon::Entity to_equip = inv.items[from];
    if (!is_spot_correct(entitySystem, to_equip, to)) {
        return ReturnValue::REQUIREMENTS_NOT_MET;
    }
    if (equipped != entt::null) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_unequip(entity)) {
                //return ReturnValue::REQUIREMENTS_NOT_MET;
            }
        }
    }
    if (from != entt::null) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_equip(entity)) {
                //return ReturnValue::REQUIREMENTS_NOT_MET;
            }
        }
    }
    swap_item(entitySystem, entity, from, to);
    const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
    {
        const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to,
                entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to]));
        entitySystem.send_nearby(entity, packet);
    }

    RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip));
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    index.set_index(from);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return ReturnValue::OK;
}

ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) {
    const size_t to = get_first_available_spot(entitySystem, entity);
    if (to == 0) {
        return ReturnValue::NO_SPACE;
    }

    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) {
        return ReturnValue::WRONG_INDEX;
    }

    const RoseCommon::Entity equipped = inv.items[from];
    if (equipped != entt::null) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_unequip(entity)) {
                //return ReturnValue::REQUIREMENTS_NOT_MET;
            }
        }
    }
    swap_item(entitySystem, entity, from, to);
    const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
    {
        const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {});
        entitySystem.send_nearby(entity, packet);
    }

    RoseCommon::Packet::SrvSetItem::IndexAndItem index;
    index.set_index(to);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    index.set_index(from);
    index.set_item({});
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return ReturnValue::OK;
}

void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) {
    Component::BasicInfo bi;
    bi.id = entitySystem.get_free_id();
    if (owner != entt::null) {
        const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner);
        bi.teamId = basicInfo.teamId;
        auto& Cowner = entitySystem.add_component<Component::Owner>(item);
        Cowner.owner = owner;
    } else {
        bi.teamId = bi.id;
    }
    entitySystem.add_component(item, std::move(bi));

    entitySystem.update_position(item, x, y);

    entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) {
        entitySystem.delete_entity(item);
    });
}

bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) {
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    if (zuly < 0 && inv.zuly + zuly < 0) {
        return false;
    } else if (zuly < 0) {
        inv.zuly += zuly;
    } else {
        inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly),
                                        static_cast<uint64_t>(std::numeric_limits<int64_t>::max())));
    }
    entitySystem.send_to(entity,
                         RoseCommon::Packet::SrvSetMoney::create(inv.zuly));
    return true;
}

void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("equip_item_packet()");
    logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo());
    const auto from = packet.get_slotFrom();
    const auto to = packet.get_slotTo();
    const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag
        unequip_item(entitySystem, entity, to):
        equip_item(entitySystem, entity, from, to);
    (void) res;
}

void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("equip_item_packet()");
    logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity());
    const auto index = packet.get_index();
    const auto quantity = packet.get_quantity();
    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);

    if (index > inv.items.size()) {
        logger->warn("wrong index {} for item drop, client {}", index, entity);
        return;
    }
    RoseCommon::Entity item = entt::null;
    if (index == 0) { // we drop zulies
        if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) {
            item = entitySystem.create_zuly(packet.get_quantity());
        } else {
            return; // we don't have enough zuly to remove
        }
    } else {
        item = remove_item(entitySystem, entity, index, quantity);
    }
    const auto& pos = entitySystem.get_component<Component::Position>(entity);
    const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE);
    drop_item(entitySystem, item, x, y, entity);
}
<commit_msg>Update inventory.cpp<commit_after>#include "items/inventory.h"
#include "entity_system.h"
#include "dataconsts.h"
#include "random.h"

#include "components/basic_info.h"
#include "components/inventory.h"
#include "components/item.h"
#include "components/lua.h"
#include "components/position.h"
#include "components/owner.h"
#include "itemdb.h"

#include "srv_equip_item.h"
#include "srv_set_item.h"
#include "srv_set_money.h"

#include <limits>

using namespace RoseCommon;
using namespace Items;

namespace {
// only for items, not cart/castle gear
inline bool is_spot_correct(const EntitySystem& entitySystem, RoseCommon::Entity entity, size_t spot) {
    const auto& item = entitySystem.get_component<ItemDef>(entity);
    const EquippedPosition pos = static_cast<EquippedPosition>(spot);
    if (pos >= EquippedPosition::MAX_EQUIP_ITEMS) {
        return true; // we don't care of the spot if we are not equipping anything
    }
    const EquippedPosition
    switch (item.type) {
        case ItemType::ITEM_GOGGLES:
            return pos == EquippedPosition::GOGGLES;
        case ItemType::ITEM_HELMET:
            return pos == EquippedPosition::HELMET;
        case ItemType::ITEM_ARMOR:
            return pos == EquippedPosition::ARMOR;
        case ItemType::ITEM_GAUNTLET:
            return pos == EquippedPosition::GAUNTLET;
        case ItemType::ITEM_BOOTS:
            return pos == EquippedPosition::BOOTS;
        case ItemType::ITEM_BACKPACK:
            return pos == EquippedPosition::BACKPACK;
        case ItemType::ITEM_RING:
            return pos == EquippedPosition::RING;
        case ItemType::ITEM_WEAPON_R:
            return pos == EquippedPosition::WEAPON_R;
        case ItemType::ITEM_WEAPON_L:
            return pos == EquippedPosition::WEAPON_L;
        default:
            return false;
    }
}

inline bool is_spot_equipped(size_t spot) {
    return spot < EquippedPosition::MAX_EQUIP_ITEMS;
}
}

size_t Items::get_first_available_spot(const EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    size_t res = decltype(inv.getInventory())::offset();
    bool stackable = false;
    ItemType type = 0;
    uint16_t id = 0;
    if (item != entt::null) {
        const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
        stackable = i.is_stackable;
        type = i.type;
        id = i.id;
    }

    for (const auto item : inv.getInventory()) {
        if (item == entt::null) {
            return res;
        } else if (stackable) {
            const auto& i = entitySystem.get_component<RoseCommon::ItemDef>(item);
            const auto& it = entitySystem.get_component<Component::Item>(item);
            if (i.type == type && i.id == id && it.count < RoseCommon::MAX_STACK) {
                return res;
            }
        }
        ++res;
    }
    return 0;
}

ReturnValue Items::add_item(EntitySystem& entitySystem, RoseCommon::Entity entity, RoseCommon::Entity item) {
    const size_t pos = get_first_available_spot(entitySystem, entity, item);
    if (pos == 0) {
        return ReturnValue::NO_SPACE;
    }
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    if (inv.items[pos] == entt::null) {
        inv.items[pos] = item;
    } else {
        // add the stack
        auto& i = entitySystem.get_component<Component::Item>(inv.items[pos]);
        auto& it = entitySystem.get_component<Component::Item>(item);
        if (i.count + it.count < RoseCommon::MAX_STACK) {
            // below max stack
            i.count += it.count;
        } else {
            // split the stack in two or more
            const uint32_t stack_tmp1 = i.count;
            const uint32_t stack_tmp2 = it.count;
            it.count -= RoseCommon::MAX_STACK - i.count;
            i.count = RoseCommon::MAX_STACK;
            if (add_item(entitySystem, entity, item) == ReturnValue::NO_SPACE) {
                it.count = stack_tmp2;
                i.count = stack_tmp1;
                return ReturnValue::NO_SPACE;
            }
        }
    }
    RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(pos);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return ReturnValue::OK;
}

RoseCommon::Entity Items::remove_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos, uint32_t quantity) {
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    RoseCommon::Entity item = inv.items[pos];
    auto& i = entitySystem.get_component<Component::Item>(item);
    const auto& it = entitySystem.get_component<ItemDef>(item);
    if (i.count < quantity) {
        return entt::null;
    }
    if (i.count > quantity) {
        const auto type = it.type;
        const auto id = it.id;
        i.count -= quantity;
        RoseCommon::Entity newItem = entitySystem.create_item(type, id, quantity);
        RoseCommon::Packet::SrvSetItem::IndexAndItem index;
        index.set_index(pos);
        index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(item));
        auto packet = RoseCommon::Packet::SrvSetItem::create();
        packet.add_items(index);
        entitySystem.send_to(entity, packet);
        return newItem;
    }
    if (is_spot_equipped(pos)) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(item);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_unequip(item)) {
                return entt::null;
            }
        }
    }
    inv.items[pos] = entt::null;
    RoseCommon::Packet::SrvSetItem::IndexAndItem index;
    index.set_index(pos);
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return item;
}

void Items::swap_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t pos1, size_t pos2) {
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    std::swap(inv.items[pos1], inv.items[pos2]);
}

ReturnValue Items::equip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from, size_t to) {
    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);

    if (from < decltype(inv.getInventory())::offset() || from >= decltype(inv.getInventory())::size()) {
        return ReturnValue::WRONG_INDEX;
    }
    if (to < decltype(inv.getEquipped())::offset() || to >= decltype(inv.getEquipped())::size()) {
        return ReturnValue::WRONG_INDEX;
    }

    const RoseCommon::Entity equipped = inv.items[to];
    const RoseCommon::Entity to_equip = inv.items[from];
    if (!is_spot_correct(entitySystem, to_equip, to)) {
        return ReturnValue::REQUIREMENTS_NOT_MET;
    }
    if (equipped != entt::null) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_unequip(entity)) {
                //return ReturnValue::REQUIREMENTS_NOT_MET;
            }
        }
    }
    if (from != entt::null) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(to_equip);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_equip(entity)) {
                //return ReturnValue::REQUIREMENTS_NOT_MET;
            }
        }
    }
    swap_item(entitySystem, entity, from, to);
    const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
    {
        const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, to,
                entitySystem.item_to_equipped<RoseCommon::Packet::SrvEquipItem>(inv.items[to]));
        entitySystem.send_nearby(entity, packet);
    }

    RoseCommon::Packet::SrvSetItem::IndexAndItem index; index.set_index(to);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(to_equip));
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    index.set_index(from);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return ReturnValue::OK;
}

ReturnValue Items::unequip_item(EntitySystem& entitySystem, RoseCommon::Entity entity, size_t from) {
    const size_t to = get_first_available_spot(entitySystem, entity);
    if (to == 0) {
        return ReturnValue::NO_SPACE;
    }

    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    if (from < decltype(inv.getEquipped())::offset() || from >= decltype(inv.getEquipped())::size()) {
        return ReturnValue::WRONG_INDEX;
    }

    const RoseCommon::Entity equipped = inv.items[from];
    if (equipped != entt::null) {
        const auto& lua = entitySystem.get_component<Component::ItemLua>(equipped);
        if (const auto tmp = lua.api.lock(); tmp) {
            if (!tmp->on_unequip(entity)) {
                //return ReturnValue::REQUIREMENTS_NOT_MET;
            }
        }
    }
    swap_item(entitySystem, entity, from, to);
    const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(entity);
    {
        const auto packet = RoseCommon::Packet::SrvEquipItem::create(basicInfo.id, from, {});
        entitySystem.send_nearby(entity, packet);
    }

    RoseCommon::Packet::SrvSetItem::IndexAndItem index;
    index.set_index(to);
    index.set_item(entitySystem.item_to_item<RoseCommon::Packet::SrvSetItem>(equipped));
    auto packet = RoseCommon::Packet::SrvSetItem::create();
    packet.add_items(index);
    index.set_index(from);
    index.set_item({});
    packet.add_items(index);
    entitySystem.send_to(entity, packet);
    return ReturnValue::OK;
}

void Items::drop_item(EntitySystem& entitySystem, RoseCommon::Entity item, float x, float y, RoseCommon::Entity owner) {
    Component::BasicInfo bi;
    bi.id = entitySystem.get_free_id();
    if (owner != entt::null) {
        const auto& basicInfo = entitySystem.get_component<Component::BasicInfo>(owner);
        bi.teamId = basicInfo.teamId;
        auto& Cowner = entitySystem.add_component<Component::Owner>(item);
        Cowner.owner = owner;
    } else {
        bi.teamId = bi.id;
    }
    entitySystem.add_component(item, std::move(bi));

    entitySystem.update_position(item, x, y);

    entitySystem.add_timer(5min, [item](EntitySystem& entitySystem) {
        entitySystem.delete_entity(item);
    });
}

bool Items::add_zuly(EntitySystem& entitySystem, RoseCommon::Entity entity, int64_t zuly) {
    auto& inv = entitySystem.get_component<Component::Inventory>(entity);
    if (zuly < 0 && inv.zuly + zuly < 0) {
        return false;
    } else if (zuly < 0) {
        inv.zuly += zuly;
    } else {
        inv.zuly = static_cast<int64_t>(std::min(static_cast<uint64_t>(inv.zuly) + static_cast<uint64_t>(zuly),
                                        static_cast<uint64_t>(std::numeric_limits<int64_t>::max())));
    }
    entitySystem.send_to(entity,
                         RoseCommon::Packet::SrvSetMoney::create(inv.zuly));
    return true;
}

void Items::equip_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliEquipItem& packet) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("equip_item_packet()");
    logger->trace("from {} to {}", packet.get_slotFrom(), packet.get_slotTo());
    const auto from = packet.get_slotFrom();
    const auto to = packet.get_slotTo();
    const auto res = from == 0 ? // we want to unequip something, 0 being a "fake" no-item flag
        unequip_item(entitySystem, entity, to):
        equip_item(entitySystem, entity, from, to);
    (void) res;
}

void Items::drop_item_packet(EntitySystem& entitySystem, RoseCommon::Entity entity, const RoseCommon::Packet::CliDropItem& packet) {
    auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();
    logger->trace("equip_item_packet()");
    logger->trace("drop {}x{}", packet.get_index(), packet.get_quantity());
    const auto index = packet.get_index();
    const auto quantity = packet.get_quantity();
    const auto& inv = entitySystem.get_component<Component::Inventory>(entity);

    if (index > inv.items.size()) {
        logger->warn("wrong index {} for item drop, client {}", index, entity);
        return;
    }
    RoseCommon::Entity item = entt::null;
    if (index == 0) { // we drop zulies
        if (add_zuly(entitySystem, entity, -static_cast<int64_t>(packet.get_quantity()))) {
            item = entitySystem.create_zuly(packet.get_quantity());
        } else {
            return; // we don't have enough zuly to remove
        }
    } else {
        item = remove_item(entitySystem, entity, index, quantity);
    }
    const auto& pos = entitySystem.get_component<Component::Position>(entity);
    const auto [x, y] = Core::Random::getInstance().random_in_circle(pos.x, pos.y, DROP_RANGE);
    drop_item(entitySystem, item, x, y, entity);
}
<|endoftext|>


<commit_before>#include "example.h"
#include <cerrno>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <functional>
#include <gflags/gflags.h>
#include <iostream>
#include <pitch_detection.h>
#include <random>
#include <string>
#include <utility>
#include <vector>

DEFINE_double(frequency, -1.0, "Sinewave frequency in Hz");
DEFINE_validator(frequency, [](const char *flagname, double value) {
	if (value >= 0.0)
		return true;
	return false;
});

DEFINE_double(noise, 0.0, "Noise to introduce in %");
DEFINE_validator(noise, [](const char *flagname, double value) {
	if ((value >= 0.0) && (value <= 100.0))
		return true;
	return false;
});

DEFINE_uint64(sample_rate, 48000, "Sample rate in Hz");
DEFINE_validator(sample_rate, [](const char *flagname, uint64_t value) {
	if (value >= 0)
		return true;
	return false;
});

DEFINE_string(algo, "mpm", "Algorithm to test");
DEFINE_validator(algo, [](const char *flagname, const std::string &value) {
	if (pitch_types.find(value) != pitch_types.end()) {
		return true;
	}
	return false;
});

DEFINE_uint64(size, 4096, "Sine wave size (single channel)");
DEFINE_validator(size, [](const char *flagname, uint64_t value) {
	if (value >= 0)
		return true;

	return false;
});

DEFINE_bool(plot, false, "Output sinewave data to stderr");
DEFINE_bool(quiet, false, "Suppress most outputs");

static std::vector<double>
generate_sinewave(
    size_t size, double frequency, int sample_rate, double noise_perc);

int
main(int argc, char **argv)
{
	gflags::SetUsageMessage("help\n");
	gflags::ParseCommandLineFlags(&argc, &argv, true);

	auto data = generate_sinewave(
	    2 * FLAGS_size, FLAGS_frequency, FLAGS_sample_rate, FLAGS_noise);

	if (FLAGS_plot)
		for (auto x: data)
			std::cout << x << std::endl;

	if (!FLAGS_quiet && (FLAGS_algo == "mpm") && !(FLAGS_size && !(FLAGS_size & (FLAGS_size - 1))))
		std::cerr << "FFTS performs better with power-of-two sizes"
		          << std::endl;

	double pitch =
	    pitch_algorithms[pitch_types[FLAGS_algo]](data, FLAGS_sample_rate);

	std::cerr << "Size: " << FLAGS_size << "\tfreq: " << FLAGS_frequency
	          << "\tpitch: " << pitch << std::endl;
	return 0;
}

static std::vector<double>
generate_sinewave(
    size_t size, double frequency, int sample_rate, double noise_perc)
{
	int num_elements_to_skip = int(noise_perc / 100.0 * size / 2);

	std::random_device rnd_device;
	std::mt19937 mersenne_engine{rnd_device()}; // Generates random integers
	std::uniform_int_distribution<int> dist{0, int(size / 2) - 1};

	auto gen = [&dist, &mersenne_engine]() { return dist(mersenne_engine); };

	std::vector<int> elements_to_skip(num_elements_to_skip);
	generate(begin(elements_to_skip), end(elements_to_skip), gen);

	size_t lut_size = size / 4;

	std::vector<int> lut{};
	double *_tone_single_channel = (double *)malloc(sizeof(double) * size / 2);

	double doublef = (double)frequency;
	double delta_phi = doublef * lut_size * 1.0 / sample_rate;
	double phase = 0.0;

	for (int i = 0; i < signed(lut_size); ++i) {
		lut.push_back((int)roundf(0x7FFF * sinf(2.0 * M_PI * i / lut_size)));
	}

	for (int i = 0; i < signed(size / 2); ++i) {
		int val = double(lut[(int)phase]);
		_tone_single_channel[i] = val;
		phase += delta_phi;
		if (phase >= lut_size)
			phase -= lut_size;
	}

	std::vector<double> tone_single_channel(
	    _tone_single_channel, _tone_single_channel + size / 2);

	for (auto skip : elements_to_skip) {
		tone_single_channel.at(skip) = 0;
	}

	return tone_single_channel;
}
<commit_msg>Add option to plot with lags<commit_after>#include "example.h"
#include <cerrno>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <float.h>
#include <fstream>
#include <functional>
#include <gflags/gflags.h>
#include <iostream>
#include <pitch_detection.h>
#include <random>
#include <string>
#include <utility>
#include <vector>

DEFINE_double(frequency, -1.0, "Sinewave frequency in Hz");
DEFINE_validator(frequency, [](const char *flagname, double value) {
	if (value >= 0.0)
		return true;
	return false;
});

DEFINE_double(noise, 0.0, "Noise to introduce in %");
DEFINE_validator(noise, [](const char *flagname, double value) {
	if ((value >= 0.0) && (value <= 100.0))
		return true;
	return false;
});

DEFINE_uint64(sample_rate, 48000, "Sample rate in Hz");
DEFINE_validator(sample_rate, [](const char *flagname, uint64_t value) {
	if (value >= 0)
		return true;
	return false;
});

DEFINE_string(algo, "mpm", "Algorithm to test");
DEFINE_validator(algo, [](const char *flagname, const std::string &value) {
	if (pitch_types.find(value) != pitch_types.end()) {
		return true;
	}
	return false;
});

DEFINE_int32(size, 4096, "Sine wave size (single channel)");
DEFINE_validator(size, [](const char *flagname, int value) {
	if (value >= 0)
		return true;

	return false;
});

DEFINE_bool(plot, false, "Output sinewave data to stdout");
DEFINE_bool(plot_lags, false, "Output sinewave data with lags to stdout");
DEFINE_bool(quiet, false, "Suppress most outputs");

static std::vector<double>
generate_sinewave(
    size_t size, double frequency, int sample_rate, double noise_perc);

int
main(int argc, char **argv)
{
	gflags::SetUsageMessage("help\n");
	gflags::ParseCommandLineFlags(&argc, &argv, true);

	auto data = generate_sinewave(
	    2 * FLAGS_size, FLAGS_frequency, FLAGS_sample_rate, FLAGS_noise);

	if (FLAGS_plot) {
		if (FLAGS_plot_lags) {
			std::cerr << "--plot and --plot_lags are mutually exclusive"
			          << ::std::endl;

			return -1;
		}

		for (auto x : data)
			std::cout << x << std::endl;
	}

	if (FLAGS_plot_lags) {
		std::vector<double> orig(2 * FLAGS_size);
		std::vector<double> quarter_lag(2 * FLAGS_size);
		std::vector<double> half_lag(2 * FLAGS_size);
		std::vector<double> full_lag(2 * FLAGS_size);

		for (int i = 0; i < 2 * FLAGS_size; ++i) {
			if (i < FLAGS_size)
				orig[i] = data[i];
			if ((i > FLAGS_size / 4) && (i < FLAGS_size / 4 + FLAGS_size)) {
				quarter_lag[i] = data[i - FLAGS_size / 4];
			}
			if ((i > FLAGS_size / 2) && (i < FLAGS_size / 2 + FLAGS_size)) {
				half_lag[i] = data[i - FLAGS_size / 2];
			}
			if (i > FLAGS_size) {
				full_lag[i] = data[i - FLAGS_size];
			}
		}

		for (int i = 0; i < 2 * FLAGS_size; ++i) {
			std::cout << orig[i] << "\t" << quarter_lag[i] << "\t"
			          << half_lag[i] << "\t" << full_lag[i] << std::endl;
		}
	}

	if (!FLAGS_quiet && (FLAGS_algo == "mpm") &&
	    !(FLAGS_size && !(FLAGS_size & (FLAGS_size - 1))))
		std::cerr << "FFTS performs better with power-of-two sizes"
		          << std::endl;

	double pitch =
	    pitch_algorithms[pitch_types[FLAGS_algo]](data, FLAGS_sample_rate);

	std::cerr << "Size: " << FLAGS_size << "\tfreq: " << FLAGS_frequency
	          << "\tpitch: " << pitch << std::endl;
	return 0;
}

static std::vector<double>
generate_sinewave(
    size_t size, double frequency, int sample_rate, double noise_perc)
{
	int num_elements_to_skip = int(noise_perc / 100.0 * size / 2);

	std::random_device rnd_device;
	std::mt19937 mersenne_engine{rnd_device()}; // Generates random integers
	std::uniform_int_distribution<int> dist(0, int(size / 2) - 1);

	auto gen = [&dist, &mersenne_engine]() { return dist(mersenne_engine); };

	std::vector<int> elements_to_skip(num_elements_to_skip);
	std::generate(begin(elements_to_skip), end(elements_to_skip), gen);

	size_t lut_size = size / 4;

	std::vector<int> lut{};
	double *_tone_single_channel = (double *)malloc(sizeof(double) * size / 2);

	double doublef = (double)frequency;
	double delta_phi = doublef * lut_size * 1.0 / sample_rate;
	double phase = 0.0;

	for (int i = 0; i < signed(lut_size); ++i) {
		lut.push_back((int)roundf(0x7FFF * sinf(2.0 * M_PI * i / lut_size)));
	}

	double min = DBL_MAX;
	double max = -DBL_MAX;
	for (int i = 0; i < signed(size / 2); ++i) {
		int val = double(lut[(int)phase]);
		if (val > max) {
			max = val;
		}
		if (val < min) {
			min = val;
		}
		_tone_single_channel[i] = val;
		phase += delta_phi;
		if (phase >= lut_size)
			phase -= lut_size;
	}

	std::uniform_real_distribution<double> amplitude_dist(min, max);
	auto amplitude_gen = [&amplitude_dist, &mersenne_engine]() {
		return amplitude_dist(mersenne_engine);
	};

	std::vector<double> tone_single_channel(
	    _tone_single_channel, _tone_single_channel + size / 2);

	for (auto skip : elements_to_skip) {
		tone_single_channel.at(skip) = amplitude_gen();
	}

	return tone_single_channel;
}
<|endoftext|>


<commit_before>//
//  AppDelegate.cpp
//  ee_x_test
//
//  Created by Zinge on 5/17/17.
//
//

#include "AppDelegate.hpp"

#include <cocos2d.h>

#include <ee/Ads.hpp>
#include <ee/Cocos.hpp>
#include <ee/Coroutine.hpp>

#include "AdMob.hpp"
#include "AppLovin.hpp"
#include "CrashlyticsAgent.hpp"
#include "FacebookAds.hpp"
#include "IronSource.hpp"
#include "MultiNativeAdTestScene.hpp"
#include "NotificationAgent.hpp"
#include "TwitterShareTestScene.hpp"
#include "UnityAds.hpp"
#include "Utils.hpp"
#include "VideoPlayerTestScene.hpp"
#include "Vungle.hpp"

namespace eetest {
namespace {
const auto DesignResolution = cocos2d::Size(480, 320);
} // namespace

namespace {
void testMultiAds() {
    auto ad = std::make_shared<ee::MultiRewardedAd>();

    ee::runOnUiThread([ad] {
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getAppLovin()->createRewardedAd()));
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getIronSource()->createRewardedAd(getIronSourceRewardedAdId())));
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getUnityAds()->createRewardedAd(getUnityRewardedAdId())));
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getVungle()->createRewardedAd(getVungleRewardedAdId())));
    });

    scheduleForever(2.0f, 3.0f, [ad] {
        logCurrentThread();
        ee::runOnUiThread(ee::makeAwaiter([ad]() -> ee::Task<> {
            logCurrentThread();
            auto result = co_await ad->show();
            logCurrentThread();
            getLogger().info("Result = %d", static_cast<int>(result));
        }));
    });
}
} // namespace

AppDelegate::AppDelegate() {}

AppDelegate::~AppDelegate() {}

void AppDelegate::initGLContextAttrs() {
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 16, 8};
#else  // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    cocos2d::GLView::setGLContextAttrs(glContextAttrs);
}

bool AppDelegate::applicationDidFinishLaunching() {
    cocos2d::log(__PRETTY_FUNCTION__);

    auto director = cocos2d::Director::getInstance();
    auto glView = director->getOpenGLView();
    if (glView == nullptr) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) ||                               \
    (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) ||                                 \
    (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
        glView = cocos2d::GLViewImpl::createWithRect(
            "HelloCpp", cocos2d::Rect(0, 0, DesignResolution.width,
                                      DesignResolution.height));
#else
        glView = cocos2d::GLViewImpl::create("HelloCpp");
#endif
        director->setOpenGLView(glView);
    }

    director->setDisplayStats(true);
    director->setAnimationInterval(1.0f / 60);

    auto resolutionPolicy = (DesignResolution.height > DesignResolution.width
                                 ? ResolutionPolicy::FIXED_WIDTH
                                 : ResolutionPolicy::FIXED_HEIGHT);
    glView->setDesignResolutionSize(DesignResolution.width,
                                    DesignResolution.height, resolutionPolicy);
    auto&& frameSize = glView->getFrameSize();
    getLogger().info(cocos2d::StringUtils::format(
        "frameSize = %f %f", frameSize.width, frameSize.height));

    auto&& winSize = director->getWinSize();
    getLogger().info(cocos2d::StringUtils::format(
        "winSize = %f %f", winSize.width, winSize.height));

    constexpr float points = 1;
    auto metrics = ee::Metrics::fromPoint(points);
    auto dp = metrics.toDip();
    auto pixels = metrics.toPixel();
    getLogger().info(cocos2d::StringUtils::format("%f pt = %f pixels = %f dp",
                                                  points, pixels, dp));

    CrashlyticsAgent::getInstance()->initialize();
    CrashlyticsAgent::getInstance()->logDebug("debug_message");
    CrashlyticsAgent::getInstance()->logInfo("info_message");

    getLogger().info("Cocos thread ID: %s", getCurrentThreadId().c_str());
    ee::runOnUiThreadAndWait([] {
        getLogger().info("UI thread ID: %s", getCurrentThreadId().c_str());
    });

    getLogger().info("SHA1: %s", ee::getSHA1CertificateFingerprint().c_str());
    getLogger().info("Version name: %s", ee::getVersionName().c_str());
    getLogger().info("Version code: %s", ee::getVersionCode().c_str());
    getLogger().info("isTablet: %s", ee::isTablet() ? "true" : "false");
    getLogger().info("isConnected: %s",
                     ee::testConnection() ? "true" : "false");

    NotificationAgent::getInstance()->initialize();
    // testAdMobBannerAd();
    // testAdMobNativeAd();
    // testAdMobInterstitial();
    // testAdMobRewardedAd();
    // testAppLovin();
    // testUnityAdsRewardedAd();
    // testIronSourceRewardedAd();
    // testVungle();
    testMultiAds();
    // testFacebookInterstitialAd();
    // testFacebookNativeAd();

    cocos2d::log("Create scene");
    // director->runWithScene(VideoPlayerTestScene::create());
    // director->runWithScene(createMultiNativeAdTestScene());

    // Deprecated.
    // director->runWithScene(TwitterShareTestScene::create());

    return true;
}

void AppDelegate::applicationDidEnterBackground() {
    cocos2d::log(__PRETTY_FUNCTION__);
    cocos2d::Director::getInstance()->stopAnimation();
#ifndef EE_X_DESKTOP
    NotificationAgent::getInstance()->scheduleAll();
#endif // EE_X_DESKTOP
}

void AppDelegate::applicationWillEnterForeground() {
    cocos2d::log(__PRETTY_FUNCTION__);
    cocos2d::Director::getInstance()->startAnimation();
#ifndef EE_X_DESKTOP
    NotificationAgent::getInstance()->unscheduleAll();
#endif // EE_X_DESKTOP
}
} // namespace eetest
<commit_msg>Fix to use custom logger.<commit_after>//
//  AppDelegate.cpp
//  ee_x_test
//
//  Created by Zinge on 5/17/17.
//
//

#include "AppDelegate.hpp"

#include <cocos2d.h>

#include <ee/Ads.hpp>
#include <ee/Cocos.hpp>
#include <ee/Coroutine.hpp>

#include "AdMob.hpp"
#include "AppLovin.hpp"
#include "CrashlyticsAgent.hpp"
#include "FacebookAds.hpp"
#include "IronSource.hpp"
#include "MultiNativeAdTestScene.hpp"
#include "NotificationAgent.hpp"
#include "TwitterShareTestScene.hpp"
#include "UnityAds.hpp"
#include "Utils.hpp"
#include "VideoPlayerTestScene.hpp"
#include "Vungle.hpp"

namespace eetest {
namespace {
const auto DesignResolution = cocos2d::Size(480, 320);
} // namespace

namespace {
void testMultiAds() {
    auto ad = std::make_shared<ee::MultiRewardedAd>();

    ee::runOnUiThread([ad] {
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getAppLovin()->createRewardedAd()));
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getIronSource()->createRewardedAd(getIronSourceRewardedAdId())));
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getUnityAds()->createRewardedAd(getUnityRewardedAdId())));
        ad->addItem(std::make_shared<ee::GuardedRewardedAd>(
            getVungle()->createRewardedAd(getVungleRewardedAdId())));
    });

    scheduleForever(2.0f, 3.0f, [ad] {
        logCurrentThread();
        ee::runOnUiThread(ee::makeAwaiter([ad]() -> ee::Task<> {
            logCurrentThread();
            auto result = co_await ad->show();
            logCurrentThread();
            getLogger().info("Result = %d", static_cast<int>(result));
        }));
    });
}
} // namespace

AppDelegate::AppDelegate() {}

AppDelegate::~AppDelegate() {}

void AppDelegate::initGLContextAttrs() {
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 16, 8};
#else  // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
#endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
    cocos2d::GLView::setGLContextAttrs(glContextAttrs);
}

bool AppDelegate::applicationDidFinishLaunching() {
    cocos2d::log(__PRETTY_FUNCTION__);

    auto director = cocos2d::Director::getInstance();
    auto glView = director->getOpenGLView();
    if (glView == nullptr) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) ||                               \
    (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) ||                                 \
    (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
        glView = cocos2d::GLViewImpl::createWithRect(
            "HelloCpp", cocos2d::Rect(0, 0, DesignResolution.width,
                                      DesignResolution.height));
#else
        glView = cocos2d::GLViewImpl::create("HelloCpp");
#endif
        director->setOpenGLView(glView);
    }

    director->setDisplayStats(true);
    director->setAnimationInterval(1.0f / 60);

    auto resolutionPolicy = (DesignResolution.height > DesignResolution.width
                                 ? ResolutionPolicy::FIXED_WIDTH
                                 : ResolutionPolicy::FIXED_HEIGHT);
    glView->setDesignResolutionSize(DesignResolution.width,
                                    DesignResolution.height, resolutionPolicy);
    auto&& frameSize = glView->getFrameSize();
    getLogger().info("frameSize = %f %f", frameSize.width, frameSize.height);

    auto&& winSize = director->getWinSize();
    getLogger().info("winSize = %f %f", winSize.width, winSize.height);

    constexpr float points = 1;
    auto metrics = ee::Metrics::fromPoint(points);
    auto dp = metrics.toDip();
    auto pixels = metrics.toPixel();
    getLogger().info("%f pt = %f pixels = %f dp", points, pixels, dp);

    ee::Logger::setSystemLogger(getLogger());

    CrashlyticsAgent::getInstance()->initialize();
    CrashlyticsAgent::getInstance()->logDebug("debug_message");
    CrashlyticsAgent::getInstance()->logInfo("info_message");

    getLogger().info("Cocos thread ID: %s", getCurrentThreadId().c_str());
    ee::runOnUiThreadAndWait([] {
        getLogger().info("UI thread ID: %s", getCurrentThreadId().c_str());
    });

    getLogger().info("SHA1: %s", ee::getSHA1CertificateFingerprint().c_str());
    getLogger().info("Version name: %s", ee::getVersionName().c_str());
    getLogger().info("Version code: %s", ee::getVersionCode().c_str());
    getLogger().info("isTablet: %s", ee::isTablet() ? "true" : "false");
    getLogger().info("isConnected: %s",
                     ee::testConnection() ? "true" : "false");

    NotificationAgent::getInstance()->initialize();
    // testAdMobBannerAd();
    // testAdMobNativeAd();
    // testAdMobInterstitial();
    // testAdMobRewardedAd();
    // testAppLovin();
    // testUnityAdsRewardedAd();
    // testIronSourceRewardedAd();
    // testVungle();
    testMultiAds();
    // testFacebookInterstitialAd();
    // testFacebookNativeAd();

    cocos2d::log("Create scene");
    // director->runWithScene(VideoPlayerTestScene::create());
    // director->runWithScene(createMultiNativeAdTestScene());

    // Deprecated.
    // director->runWithScene(TwitterShareTestScene::create());

    return true;
}

void AppDelegate::applicationDidEnterBackground() {
    cocos2d::log(__PRETTY_FUNCTION__);
    cocos2d::Director::getInstance()->stopAnimation();
#ifndef EE_X_DESKTOP
    NotificationAgent::getInstance()->scheduleAll();
#endif // EE_X_DESKTOP
}

void AppDelegate::applicationWillEnterForeground() {
    cocos2d::log(__PRETTY_FUNCTION__);
    cocos2d::Director::getInstance()->startAnimation();
#ifndef EE_X_DESKTOP
    NotificationAgent::getInstance()->unscheduleAll();
#endif // EE_X_DESKTOP
}
} // namespace eetest
<|endoftext|>


<commit_before>/*
 * File:   AlarmClockTest.cpp
 * Author: Craig Cogdill
 * Created: October 15, 2015 10:45am
 * Modifier: Amanda Carbonari
 * Modified Date: January 5, 2015 3:45pm
 */

#include "AlarmClockTest.h"
#include "AlarmClock.h"
#include "StopWatch.h"
#include <chrono>
#include <iostream>

std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0);

namespace {
   typedef std::chrono::microseconds microseconds;
   typedef std::chrono::milliseconds milliseconds;
   typedef std::chrono::seconds seconds;

   unsigned int kFakeSleepLeeway = 100;

   template<typename T>
   void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) {
      while (!alerter.Expired());
   }

   template<typename Duration>
   unsigned int ConvertToMicroSeconds(Duration t) {
      return std::chrono::duration_cast<microseconds>(t).count();
   }

   template<typename Duration>
   unsigned int ConvertToMilliSeconds(Duration t) {
      return std::chrono::duration_cast<milliseconds>(t).count();
   }

   unsigned int FakeSleep(unsigned int usToSleep) {
      AlarmClockTest::mFakeSleepUs.store(usToSleep);
      std::this_thread::sleep_for(microseconds(10));
      return 0;
   }
}

TEST_F(AlarmClockTest, GetUsSleepTimeInUs) {
   int us = 123456;
   AlarmClock<microseconds> alerter(us);
   EXPECT_EQ(us, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, GetUsSleepTimeInMs) {
   int us = 123456;
   AlarmClock<microseconds> alerter(us);
   EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs());
}

TEST_F(AlarmClockTest, GetMsSleepTimeInMs) {
   int ms = 123456;
   AlarmClock<milliseconds> alerter(ms);
   EXPECT_EQ(ms, alerter.SleepTimeMs());
}

TEST_F(AlarmClockTest, GetMsSleepTimeInUs) {
   int ms = 123456;
   AlarmClock<milliseconds> alerter(ms);
   EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, GetSecSleepTimeInUs) {
   int sec = 1;
   AlarmClock<seconds> alerter(sec);
   EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, GetSecSleepTimeInMs) {
   int sec = 1;
   AlarmClock<seconds> alerter(sec);
   EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs());
}

TEST_F(AlarmClockTest, microsecondsLessThan500ms) {
   int us = 900;
   AlarmClock<microseconds> alerter(us, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, us);
}

TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) {
   int us = 600000;
   AlarmClock<microseconds> alerter(us, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, us);
}

TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) {
   int us = 724509;
   StopWatch sw;
   AlarmClock<microseconds> alerter(us, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, us);
}

TEST_F(AlarmClockTest, millisecondsLessThan500) {
   unsigned int ms = 100;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, oneSecondInMilliseconds) {
   unsigned int ms = 1000;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) {
   unsigned int ms = 1000;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, secondsSimple) {
   unsigned int sec = 1;
   AlarmClock<seconds> alerter(sec, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) {
   unsigned int sec = 1000;
   StopWatch sw;
   std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep));
   EXPECT_FALSE(acPtr->Expired());
   acPtr.reset();
   EXPECT_TRUE(sw.ElapsedSec() < 2);
}

TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) {
   // First run
   int ms = 750;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   // Reset after AlarmClock has expired
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) {
   int ms = 7500;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) {
   // First run
   int ms = 750;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   // Reset after AlarmClock has expired
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   // Reset again after it has expired
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) {
   int ms = 7500;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) {
   int ms = 750;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}
<commit_msg>Added missing includes<commit_after>/*
 * File:   AlarmClockTest.cpp
 * Author: Craig Cogdill
 * Created: October 15, 2015 10:45am
 * Modifier: Amanda Carbonari
 * Modified Date: January 5, 2015 3:45pm
 */

#include "AlarmClockTest.h"
#include "AlarmClock.h"
#include "StopWatch.h"
#include <chrono>
#include <iostream>
#include <thread>

std::atomic<unsigned int> AlarmClockTest::mFakeSleepUs(0);

namespace {
   typedef std::chrono::microseconds microseconds;
   typedef std::chrono::milliseconds milliseconds;
   typedef std::chrono::seconds seconds;

   unsigned int kFakeSleepLeeway = 100;

   template<typename T>
   void WaitForAlarmClockToExpire(AlarmClock<T>& alerter) {
      while (!alerter.Expired());
   }

   template<typename Duration>
   unsigned int ConvertToMicroSeconds(Duration t) {
      return std::chrono::duration_cast<microseconds>(t).count();
   }

   template<typename Duration>
   unsigned int ConvertToMilliSeconds(Duration t) {
      return std::chrono::duration_cast<milliseconds>(t).count();
   }

   unsigned int FakeSleep(unsigned int usToSleep) {
      AlarmClockTest::mFakeSleepUs.store(usToSleep);
      std::this_thread::sleep_for(microseconds(10));
      return 0;
   }
}

TEST_F(AlarmClockTest, GetUsSleepTimeInUs) {
   int us = 123456;
   AlarmClock<microseconds> alerter(us);
   EXPECT_EQ(us, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, GetUsSleepTimeInMs) {
   int us = 123456;
   AlarmClock<microseconds> alerter(us);
   EXPECT_EQ(ConvertToMilliSeconds(microseconds(us)), alerter.SleepTimeMs());
}

TEST_F(AlarmClockTest, GetMsSleepTimeInMs) {
   int ms = 123456;
   AlarmClock<milliseconds> alerter(ms);
   EXPECT_EQ(ms, alerter.SleepTimeMs());
}

TEST_F(AlarmClockTest, GetMsSleepTimeInUs) {
   int ms = 123456;
   AlarmClock<milliseconds> alerter(ms);
   EXPECT_EQ(ConvertToMicroSeconds(milliseconds(ms)), alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, GetSecSleepTimeInUs) {
   int sec = 1;
   AlarmClock<seconds> alerter(sec);
   EXPECT_EQ(ConvertToMicroSeconds(seconds(sec)), alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, GetSecSleepTimeInMs) {
   int sec = 1;
   AlarmClock<seconds> alerter(sec);
   EXPECT_EQ(ConvertToMilliSeconds(seconds(sec)), alerter.SleepTimeMs());
}

TEST_F(AlarmClockTest, microsecondsLessThan500ms) {
   int us = 900;
   AlarmClock<microseconds> alerter(us, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, us);
}

TEST_F(AlarmClockTest, microsecondsGreaterThan500ms) {
   int us = 600000;
   AlarmClock<microseconds> alerter(us, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, us);
}

TEST_F(AlarmClockTest, weirdNumberOfMicroseconds) {
   int us = 724509;
   StopWatch sw;
   AlarmClock<microseconds> alerter(us, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, us-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, us);
}

TEST_F(AlarmClockTest, millisecondsLessThan500) {
   unsigned int ms = 100;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, oneSecondInMilliseconds) {
   unsigned int ms = 1000;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, millisecondsNotDivisibleBy500) {
   unsigned int ms = 1000;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, secondsSimple) {
   unsigned int sec = 1;
   AlarmClock<seconds> alerter(sec, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
   EXPECT_GE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs()-kFakeSleepLeeway);
   EXPECT_LE(AlarmClockTest::mFakeSleepUs, alerter.SleepTimeUs());
}

TEST_F(AlarmClockTest, LongTimeout_ImmediatelyDestructed) {
   unsigned int sec = 1000;
   StopWatch sw;
   std::unique_ptr<AlarmClock<seconds>> acPtr(new AlarmClock<seconds>(sec, FakeSleep));
   EXPECT_FALSE(acPtr->Expired());
   acPtr.reset();
   EXPECT_TRUE(sw.ElapsedSec() < 2);
}

TEST_F(AlarmClockTest, milliseconds_ResetAfterExpired) {
   // First run
   int ms = 750;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   // Reset after AlarmClock has expired
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_ResetBeforeExpired) {
   int ms = 7500;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_MultipleResetsAfterExpired) {
   // First run
   int ms = 750;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   // Reset after AlarmClock has expired
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   // Reset again after it has expired
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_MultipleResetsBeforeExpired) {
   int ms = 7500;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}

TEST_F(AlarmClockTest, milliseconds_MultipleResetsMixed) {
   int ms = 750;
   AlarmClock<milliseconds> alerter(ms, FakeSleep);
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());

   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   alerter.Reset();
   EXPECT_FALSE(alerter.Expired());
   WaitForAlarmClockToExpire(alerter);
   EXPECT_TRUE(alerter.Expired());
}
<|endoftext|>


<commit_before>/*!
 * \brief       Program for frequency count of SVO{N} files.
 * \author      Diorge Brognara
 * \date        2016
 * \copyright   Copyright (C) Diorge Brognara 2016. All rights MIT Licensed.
*/

#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
#include <algorithm>
#include <sstream>
#include <vector>

/*! \var    typedef std::pair<std::string, std::string> TKey
 *  \brief  (S, O) key used in the mapping
*/
typedef std::pair<std::string, std::string> TKey;

/*! \var    typedef std::pair<TKey, int> TPair
    \brief  type_value used in the mapping
*/
typedef std::pair<TKey, int> TPair;

//! Data in each row in the SVO{N} file
struct SvoRow {
   std::string s;
   std::string v;
   std::string o;
   int n;
};

//! Definition of custom hash for std::pair<T1, T2>
struct hashPair {
   template <class T1, class T2>
   std::size_t operator () (const std::pair<T1, T2> &p) const {
      auto value = 0x345678;
      auto h1 = std::hash<T1>{}(p.first);
      auto h2 = std::hash<T2>{}(p.second);
      value = (100003 * value) ^ h1;
      value = (100003 * value) ^ h2;
      return value;
   }
};

//! Compares two TPair by greater integer value
bool compareTuples(TPair a, TPair b) {
   return a.second > b.second;
}

//! SVO{N} frequency counter program
/*!
 * \param argc Must be at least 2
 * \param argv Second element (first argument) must be a positive integer, other elements are discarded
 SVO input is expected on stdin. Output is on stdout.
*/
int main(int argc, char** argv) {
   if (argc < 2) {
      std::cout << "Unspecified N value" << std::endl;
      return -1;
   }

   std::unordered_map<TKey, int, hashPair> pairs;

   while (std::cin.peek() != std::char_traits<char>::eof()) {
      SvoRow row;
      std::getline(std::cin, row.s, '\t');
      std::getline(std::cin, row.v, '\t');
      std::getline(std::cin, row.o, '\t');
      std::string tempString;
      std::getline(std::cin, tempString);
      row.n = std::stoi(tempString);
      pairs[std::make_pair(row.s, row.o)] += row.n;
   }

   int n = std::stoi(argv[1]);
   n = std::min(n, (int)pairs.size());
   std::vector<TPair> ordered;
   ordered.resize(n);

   std::partial_sort_copy(pairs.begin(), pairs.end(),
                     ordered.begin(), ordered.end(), compareTuples);

   for (auto &elem : ordered) {
      std::cout << "(" << elem.first.first << ", " << elem.first.second
                  << ") = " << elem.second << "\n";
   }
}
<commit_msg>Added documentation file descriptor<commit_after>/*!
 * \file        naivefrequency.cpp
 * \brief       Program for frequency count of SVO{N} files.
 * \author      Diorge Brognara
 * \date        2016
 * \copyright   Copyright (C) Diorge Brognara 2016. All rights MIT Licensed.
*/

#include <iostream>
#include <string>
#include <unordered_map>
#include <utility>
#include <algorithm>
#include <sstream>
#include <vector>

/*! \var    typedef std::pair<std::string, std::string> TKey
 *  \brief  (S, O) key used in the mapping
*/
typedef std::pair<std::string, std::string> TKey;

/*! \var    typedef std::pair<TKey, int> TPair
    \brief  type_value used in the mapping
*/
typedef std::pair<TKey, int> TPair;

//! Data in each row in the SVO{N} file
struct SvoRow {
   std::string s;
   std::string v;
   std::string o;
   int n;
};

//! Definition of custom hash for std::pair<T1, T2>
struct hashPair {
   template <class T1, class T2>
   std::size_t operator () (const std::pair<T1, T2> &p) const {
      auto value = 0x345678;
      auto h1 = std::hash<T1>{}(p.first);
      auto h2 = std::hash<T2>{}(p.second);
      value = (100003 * value) ^ h1;
      value = (100003 * value) ^ h2;
      return value;
   }
};

//! Compares two TPair by greater integer value
bool compareTuples(TPair a, TPair b) {
   return a.second > b.second;
}

//! SVO{N} frequency counter program
/*!
 * \param argc Must be at least 2
 * \param argv Second element (first argument) must be a positive integer, other elements are discarded
 SVO input is expected on stdin. Output is on stdout.
*/
int main(int argc, char** argv) {
   if (argc < 2) {
      std::cout << "Unspecified N value" << std::endl;
      return -1;
   }

   std::unordered_map<TKey, int, hashPair> pairs;

   while (std::cin.peek() != std::char_traits<char>::eof()) {
      SvoRow row;
      std::getline(std::cin, row.s, '\t');
      std::getline(std::cin, row.v, '\t');
      std::getline(std::cin, row.o, '\t');
      std::string tempString;
      std::getline(std::cin, tempString);
      row.n = std::stoi(tempString);
      pairs[std::make_pair(row.s, row.o)] += row.n;
   }

   int n = std::stoi(argv[1]);
   n = std::min(n, (int)pairs.size());
   std::vector<TPair> ordered;
   ordered.resize(n);

   std::partial_sort_copy(pairs.begin(), pairs.end(),
                     ordered.begin(), ordered.end(), compareTuples);

   for (auto &elem : ordered) {
      std::cout << "(" << elem.first.first << ", " << elem.first.second
                  << ") = " << elem.second << "\n";
   }
}
<|endoftext|>


<commit_before>#include "StageCanvas.h"
#include "StagePanel.h"
#include "Symbol.h"
#include "Settings.h"

#include <easyanim.h>

namespace ecomplex
{
	BEGIN_EVENT_TABLE(StageCanvas, d2d::OrthoCanvas)
		EVT_TIMER(TIMER_ID, StageCanvas::onTimer)
	END_EVENT_TABLE()

	StageCanvas::StageCanvas(StagePanel* editPanel)
		: d2d::OrthoCanvas(editPanel)
		, m_timer(this, TIMER_ID)
		, m_editPanel(editPanel)
		, m_background(NULL)
		, m_stat(1)
	{
		m_timer.Start(1000 / 30);

		m_bgStyle.color.set(0.8f, 0.8f, 0.8f);
		m_clipboxStyle.color.set(0, 0.8f, 0);
	}

	StageCanvas::~StageCanvas()
	{
		if (m_background)
		{
			m_background->release();
		}
	}

	void StageCanvas::initGL()
	{
		d2d::OrthoCanvas::initGL();
		m_editPanel->getSymbol()->reloadTexture();
// 		d2d::DynamicTexture::Instance()->ReloadTexture();
// 		d2d::DynamicFont::Instance()->ReloadTexture();
		d2d::DynamicTexAndFont::Instance()->ReloadTexture();

		resetViewport();
	}

	void StageCanvas::onDraw()
	{
		m_stat.Begin();

		drawBackground();

  		std::vector<d2d::ISprite*> sprites;
  		m_editPanel->traverseSprites(d2d::FetchAllVisitor<d2d::ISprite>(sprites));

  		for (size_t i = 0, n = sprites.size(); i < n; ++i)
  		{
  			d2d::ISprite* sprite = sprites[i];
  			if (!sprite->visiable)
  				continue;
  			d2d::SpriteDraw::drawSprite(sprite);
  		}

  		d2d::PrimitiveDraw::rect(m_editPanel->getSymbol()->m_clipbox, m_clipboxStyle);

   		if (Settings::bVisibleBGCross)
   		{
   			const float EDGE = 100;
   			d2d::PrimitiveDraw::cross(d2d::Vector(0,0), EDGE, EDGE, d2d::LIGHT_GREY);
   		}

     	m_editPanel->drawEditTemp();

		m_stat.End();

#ifdef _DEBUG
//		d2d::DynamicTexture::Instance()->DebugDraw();
//		d2d::DynamicFont::Instance()->DebugDraw();
		d2d::DynamicTexAndFont::Instance()->DebugDraw();
#endif

		m_stat.DrawTime(m_screen);

		d2d::ShaderNew::Instance()->Flush();
	}

	void StageCanvas::onTimer(wxTimerEvent& event)
	{
		Refresh();
	}

	void StageCanvas::drawBackground() const
	{
		if (m_background)
		{
			d2d::Matrix mt;
			m_background->draw(mt, m_background->getRegion());
		}

		if (Settings::bVisibleBGRect)
		{
			d2d::PrimitiveDraw::rect(d2d::Vector(0, 0), 1024 * 0.5f, 768 * 0.5f, m_bgStyle);
		}
	}
}<commit_msg>[REMOVED] 不必要的Flush<commit_after>#include "StageCanvas.h"
#include "StagePanel.h"
#include "Symbol.h"
#include "Settings.h"

#include <easyanim.h>

namespace ecomplex
{
	BEGIN_EVENT_TABLE(StageCanvas, d2d::OrthoCanvas)
		EVT_TIMER(TIMER_ID, StageCanvas::onTimer)
	END_EVENT_TABLE()

	StageCanvas::StageCanvas(StagePanel* editPanel)
		: d2d::OrthoCanvas(editPanel)
		, m_timer(this, TIMER_ID)
		, m_editPanel(editPanel)
		, m_background(NULL)
		, m_stat(1)
	{
		m_timer.Start(1000 / 30);

		m_bgStyle.color.set(0.8f, 0.8f, 0.8f);
		m_clipboxStyle.color.set(0, 0.8f, 0);
	}

	StageCanvas::~StageCanvas()
	{
		if (m_background)
		{
			m_background->release();
		}
	}

	void StageCanvas::initGL()
	{
		d2d::OrthoCanvas::initGL();
		m_editPanel->getSymbol()->reloadTexture();
// 		d2d::DynamicTexture::Instance()->ReloadTexture();
// 		d2d::DynamicFont::Instance()->ReloadTexture();
		d2d::DynamicTexAndFont::Instance()->ReloadTexture();

		resetViewport();
	}

	void StageCanvas::onDraw()
	{
		m_stat.Begin();

		drawBackground();

  		std::vector<d2d::ISprite*> sprites;
  		m_editPanel->traverseSprites(d2d::FetchAllVisitor<d2d::ISprite>(sprites));

  		for (size_t i = 0, n = sprites.size(); i < n; ++i)
  		{
  			d2d::ISprite* sprite = sprites[i];
  			if (!sprite->visiable)
  				continue;
  			d2d::SpriteDraw::drawSprite(sprite);
  		}

  		d2d::PrimitiveDraw::rect(m_editPanel->getSymbol()->m_clipbox, m_clipboxStyle);

   		if (Settings::bVisibleBGCross)
   		{
   			const float EDGE = 100;
   			d2d::PrimitiveDraw::cross(d2d::Vector(0,0), EDGE, EDGE, d2d::LIGHT_GREY);
   		}

     	m_editPanel->drawEditTemp();

		m_stat.End();

#ifdef _DEBUG
//		d2d::DynamicTexture::Instance()->DebugDraw();
//		d2d::DynamicFont::Instance()->DebugDraw();
		d2d::DynamicTexAndFont::Instance()->DebugDraw();
#endif

		m_stat.DrawTime(m_screen);
	}

	void StageCanvas::onTimer(wxTimerEvent& event)
	{
		Refresh();
	}

	void StageCanvas::drawBackground() const
	{
		if (m_background)
		{
			d2d::Matrix mt;
			m_background->draw(mt, m_background->getRegion());
		}

		if (Settings::bVisibleBGRect)
		{
			d2d::PrimitiveDraw::rect(d2d::Vector(0, 0), 1024 * 0.5f, 768 * 0.5f, m_bgStyle);
		}
	}
}<|endoftext|>


<commit_before>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup()
{
	ofSetLogLevel(OF_LOG_VERBOSE);
	//    ofSetFrameRate(20);
	ofSetVerticalSync(true);
	ofSetupScreenOrtho();
	ofBackground(40);
	//	ofEnableBlendMode(OF_BLENDMODE_ADD);

	// GIF
	gifEncoder.setup(ofGetWidth(), ofGetHeight(), 0.02, 255);
    ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved);

	// shader
	FBOq		= 1;
	Zq			= 1;
	thresh		= 0;
	density		= 1;
	dithering	= 0;
	linearFilter= true;

	// slice
	clipPlaneDepth	= 1;//.50;
	azimuth			= .4;//0;
	elevation		= 1;//-.50;

	//	cam.setFov(1);
	blabels = true;

	// Init Volume
	initVolume();

	// camera
    cam.setDistance(1000);
    cam.enableMouseInput();
}

//--------------------------------------------------------------
void ofApp::initVolume()
{
	// Init Volume
	volume.loadVolume("volumes/Colin27T1_tight/");
//	volume.loadVolume("2014-05-16-12-26-30-216");
//	volume.setImageType(OF_IMAGE_COLOR_ALPHA);
//	volume.loadImageSequence("volumes/talairach_nii/");

//	volume.loadAsRGBA("volumes/Colin27T1_tight/");
//	volume.loadColorPow2("volumes/Colin27T1_tight/");

	bPow2	= volume.getVoxelsRef().isPow2();
	format	= volume.getVoxelsRef().getGlFormat();

	// Init Volume Rendering
//    volumeRender.setup(&volume, ofVec3f(1,1,1), bPow2, format);
    volumeRender.setup(&volume);
	volumeRender.setRenderSettings(FBOq, Zq, density, thresh);
	volumeRender.setDithering(dithering);
	volumeRender.setClipDepth(clipPlaneDepth);
	volumeRender.setElevation(elevation);
	volumeRender.setAzimuth(azimuth);
}

//--------------------------------------------------------------
void ofApp::draw()
{
		//ofSetColor(255);
		cam.begin();
		volumeRender.update();
		cam.end();

		volumeRender.draw(0, ofGetHeight(), ofGetWidth(), -ofGetHeight());
		if (blabels){
			drawLabels();
		}
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{

    switch(key)
    {
		case 'w':
			selectVoxels();
			break;
		case ' ':
			//			gifEncoder.toggleRecording();
            break;
        case 's':
            cout << "Start saving..." << endl;
//			date=ofGetTimestampString();
//			gifEncoder.save(date+".gif");
			volume.saveVolume("i_.png");
            break;
		case 'h':
			blabels=!blabels;
			break;
		case 'f':
			ofToggleFullscreen();
			break;
		case 'a':
//			volume.mirror(false, true, false);
//			volume.setImageType(OF_IMAGE_COLOR_ALPHA);
			volume.grabScreen(ofGetMouseX(), ofGetMouseY());
//			volume.setColor(ofColor::magenta);
			volumeRender.setVolume(&volume);

			break;

		case 't':
			volumeRender.setThreshold(volumeRender.getThreshold()-0.01);
			break;
		case 'T':
			volumeRender.setThreshold(volumeRender.getThreshold()+0.01);
			break;
		case 'd':
			volumeRender.setDensity(volumeRender.getDensity()-0.01);
			break;
		case 'D':
			volumeRender.setDensity(volumeRender.getDensity()+0.01);
			break;
		case 'q':
			volumeRender.setXyQuality(volumeRender.getXyQuality()-0.01);
			break;
		case 'Q':
			volumeRender.setXyQuality(volumeRender.getXyQuality()+0.01);
			break;
		case 'z':
			volumeRender.setZQuality(volumeRender.getZQuality()-0.01);
			break;
		case 'Z':
			volumeRender.setZQuality(volumeRender.getZQuality()+0.01);
			break;
		case 'l':
			volumeRender.setVolumeTextureFilterMode(GL_LINEAR);
			linearFilter = true;
			break;

		case 'I':
			clipPlaneDepth += 0.01;
			volumeRender.setClipDepth(clipPlaneDepth);
			break;
		case 'i':
			clipPlaneDepth -= 0.01;
			volumeRender.setClipDepth(clipPlaneDepth);
			break;

		case 'O':
			elevation += 0.01;
			volumeRender.setElevation(elevation);
			break;
		case 'o':
			elevation -= 0.01;
			volumeRender.setElevation(elevation);
			break;

		case 'P':
			azimuth += 0.01;
			volumeRender.setAzimuth(azimuth);
			break;
		case 'p':
			azimuth -= 0.01;
			volumeRender.setAzimuth(azimuth);
			break;
		case 'n':
			volumeRender.setVolumeTextureFilterMode(GL_NEAREST);
			linearFilter = false;
			break;
		case OF_KEY_UP:
			cam.getTarget().boom(-5);
			break;
		case OF_KEY_DOWN:
			cam.getTarget().boom(5);
			break;
		case OF_KEY_LEFT:
			cam.getTarget().truck(-5);
			break;
		case OF_KEY_RIGHT:
			cam.getTarget().truck(5);
			break;
    }

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key)
{

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y )
{

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button)
{

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button)
{

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button)
{

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h)
{

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg)
{

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo)
{

}

//--------------------------------------------------------------
void ofApp::exit(){
    gifEncoder.exit();
}

//--------------------------------------------------------------
void ofApp::drawLabels()
{
    ofSetColor(0,0,0,64);
    ofRect(0,0,270,190);
    ofSetColor(255,255,255,255);

    ofDrawBitmapString(
					   "fps: " + ofToString(ofGetFrameRate())+ "\n" +
					   "volume dimensions: " + ofToString(volumeRender.getVolumeWidth()) +
					   "x" + ofToString(volumeRender.getVolumeHeight()) +
					   "x" + ofToString(volumeRender.getVolumeDepth()) + "\n" +
					   "FBO quality (q/Q): " + ofToString(volumeRender.getRenderWidth()) +
					   "x" + ofToString(volumeRender.getRenderHeight()) + "\n" +
					   "Z quality (z/Z):	" + ofToString(volumeRender.getZQuality()) + "\n" +
					   "Threshold (t/T):	" + ofToString(volumeRender.getThreshold()) + "\n" +
					   "Density (d/D):		" + ofToString(volumeRender.getDensity()) + "\n" +
					   "Filter mode (l/n):  " + (linearFilter?"linear":"nearest") + "\n" +
					   "clipPlaneDepth:     " + ofToString(clipPlaneDepth) + "\n" +
					   "azimuth:            " + ofToString(azimuth) + "\n" +
					   "elevation:          " + ofToString(elevation)
					   ,20,20);

}

//--------------------------------------------------------------
void ofApp::selectVoxels()
{
/*	vector<ofxIntBox> boxes;

	ofxIntPoint position	= ofVec3f(ofRandom(100));
	ofxIntPoint size		= ofVec3f(ofRandom(10));

	ofxIntBox box(position, size);
	boxes.push_back(box);

	volume.selectVoxels(boxes);
*/
}
//--------------------------------------------------------------
void ofApp::paintRandomBoxes()
{
	/*
	ofxIntPoint position	= ofVec3f(ofRandom(100));
	ofxIntPoint size		= ofVec3f(ofRandom(10), ofRandom(5), ofRandom(5));

	ofxIntBox box(position, size);
	vector<ofxPoint> c = volume.getVoxelsinBox(box);
	cout << "c size= "<< c.size() << endl;
	for(int i=0; i<c.size(); i++){
		cout << "i= "<< i << endl;
		ofxIntPoint p(c[i].x, c[i].y, c[i].z);
		cout << "ip= "<< p << endl;
		volume.setColor(p.x,p.y,p.z, ofColor::white);
	}
	volumeRender.setVolume(&volume, bPow2, format);
	 */
}

//--------------------------------------------------------------
void ofApp::update()
{
	//    ofSetWindowTitle(ofToString(ofGetFrameRate()));
	//	gifEncoder.update();
}

//--------------------------------------------------------------
void ofApp::onGifSaved(string &fileName) {
    cout << "gif saved as " << fileName << endl;
	gifEncoder.reset();
}

<commit_msg>clean<commit_after>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup()
{
	ofSetLogLevel(OF_LOG_VERBOSE);
	//    ofSetFrameRate(20);
	ofSetVerticalSync(true);
	ofSetupScreenOrtho();
	ofBackground(40);
	//	ofEnableBlendMode(OF_BLENDMODE_ADD);

	// GIF
	gifEncoder.setup(ofGetWidth(), ofGetHeight(), 0.02, 255);
    ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved);

	// shader
	FBOq		= 1;
	Zq			= 1;
	thresh		= 0;
	density		= 1;
	dithering	= 0;
	linearFilter= true;

	// slice
	clipPlaneDepth	= 1;//.50;
	azimuth			= .4;//0;
	elevation		= 1;//-.50;

	//	cam.setFov(1);
	blabels = true;

	// Init Volume
	initVolume();

	// camera
    cam.setDistance(1000);
    cam.enableMouseInput();
}

//--------------------------------------------------------------
void ofApp::initVolume()
{
	// Init Volume
	volume.loadVolume("volumes/Colin27T1_tight/");
//	volume.loadVolume("2014-05-16-12-26-30-216");
//	volume.setImageType(OF_IMAGE_COLOR_ALPHA);
//	volume.loadImageSequence("volumes/talairach_nii/");

//	volume.loadAsRGBA("volumes/Colin27T1_tight/");
//	volume.loadColorPow2("volumes/Colin27T1_tight/");

//	bPow2	= volume.getVoxelsRef().isPow2();
//	format	= volume.getVoxelsRef().getGlFormat();

	// Init Volume Rendering
//    volumeRender.setup(&volume, ofVec3f(1,1,1), bPow2, format);
    volumeRender.setup(&volume);
	volumeRender.setRenderSettings(FBOq, Zq, density, thresh);
	volumeRender.setDithering(dithering);
	volumeRender.setClipDepth(clipPlaneDepth);
	volumeRender.setElevation(elevation);
	volumeRender.setAzimuth(azimuth);
}

//--------------------------------------------------------------
void ofApp::draw()
{
		//ofSetColor(255);
		cam.begin();
		volumeRender.update();
		cam.end();

		volumeRender.draw(0, ofGetHeight(), ofGetWidth(), -ofGetHeight());
		if (blabels){
			drawLabels();
		}
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key)
{

    switch(key)
    {
		case 'w':
			selectVoxels();
			break;
		case ' ':
			//			gifEncoder.toggleRecording();
            break;
        case 's':
            cout << "Start saving..." << endl;
//			date=ofGetTimestampString();
//			gifEncoder.save(date+".gif");
			volume.saveVolume("i_.png");
            break;
		case 'h':
			blabels=!blabels;
			break;
		case 'f':
			ofToggleFullscreen();
			break;
		case 'a':
//			volume.mirror(false, true, false);
//			volume.setImageType(OF_IMAGE_COLOR_ALPHA);
			volume.grabScreen(ofGetMouseX(), ofGetMouseY());
//			volume.setColor(ofColor::magenta);
			volumeRender.setVolume(&volume);

			break;

		case 't':
			volumeRender.setThreshold(volumeRender.getThreshold()-0.01);
			break;
		case 'T':
			volumeRender.setThreshold(volumeRender.getThreshold()+0.01);
			break;
		case 'd':
			volumeRender.setDensity(volumeRender.getDensity()-0.01);
			break;
		case 'D':
			volumeRender.setDensity(volumeRender.getDensity()+0.01);
			break;
		case 'q':
			volumeRender.setXyQuality(volumeRender.getXyQuality()-0.01);
			break;
		case 'Q':
			volumeRender.setXyQuality(volumeRender.getXyQuality()+0.01);
			break;
		case 'z':
			volumeRender.setZQuality(volumeRender.getZQuality()-0.01);
			break;
		case 'Z':
			volumeRender.setZQuality(volumeRender.getZQuality()+0.01);
			break;
		case 'l':
			volumeRender.setVolumeTextureFilterMode(GL_LINEAR);
			linearFilter = true;
			break;

		case 'I':
			clipPlaneDepth += 0.01;
			volumeRender.setClipDepth(clipPlaneDepth);
			break;
		case 'i':
			clipPlaneDepth -= 0.01;
			volumeRender.setClipDepth(clipPlaneDepth);
			break;

		case 'O':
			elevation += 0.01;
			volumeRender.setElevation(elevation);
			break;
		case 'o':
			elevation -= 0.01;
			volumeRender.setElevation(elevation);
			break;

		case 'P':
			azimuth += 0.01;
			volumeRender.setAzimuth(azimuth);
			break;
		case 'p':
			azimuth -= 0.01;
			volumeRender.setAzimuth(azimuth);
			break;
		case 'n':
			volumeRender.setVolumeTextureFilterMode(GL_NEAREST);
			linearFilter = false;
			break;
		case OF_KEY_UP:
			cam.getTarget().boom(-5);
			break;
		case OF_KEY_DOWN:
			cam.getTarget().boom(5);
			break;
		case OF_KEY_LEFT:
			cam.getTarget().truck(-5);
			break;
		case OF_KEY_RIGHT:
			cam.getTarget().truck(5);
			break;
    }

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key)
{

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y )
{

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button)
{

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button)
{

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button)
{

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h)
{

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg)
{

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo)
{

}

//--------------------------------------------------------------
void ofApp::exit(){
    gifEncoder.exit();
}

//--------------------------------------------------------------
void ofApp::drawLabels()
{
    ofSetColor(0,0,0,64);
    ofRect(0,0,270,190);
    ofSetColor(255,255,255,255);

    ofDrawBitmapString(
					   "fps: " + ofToString(ofGetFrameRate())+ "\n" +
					   "volume dimensions: " + ofToString(volumeRender.getVolumeWidth()) +
					   "x" + ofToString(volumeRender.getVolumeHeight()) +
					   "x" + ofToString(volumeRender.getVolumeDepth()) + "\n" +
					   "FBO quality (q/Q): " + ofToString(volumeRender.getRenderWidth()) +
					   "x" + ofToString(volumeRender.getRenderHeight()) + "\n" +
					   "Z quality (z/Z):	" + ofToString(volumeRender.getZQuality()) + "\n" +
					   "Threshold (t/T):	" + ofToString(volumeRender.getThreshold()) + "\n" +
					   "Density (d/D):		" + ofToString(volumeRender.getDensity()) + "\n" +
					   "Filter mode (l/n):  " + (linearFilter?"linear":"nearest") + "\n" +
					   "clipPlaneDepth:     " + ofToString(clipPlaneDepth) + "\n" +
					   "azimuth:            " + ofToString(azimuth) + "\n" +
					   "elevation:          " + ofToString(elevation)
					   ,20,20);

}

//--------------------------------------------------------------
void ofApp::selectVoxels()
{
/*	vector<ofxIntBox> boxes;

	ofxIntPoint position	= ofVec3f(ofRandom(100));
	ofxIntPoint size		= ofVec3f(ofRandom(10));

	ofxIntBox box(position, size);
	boxes.push_back(box);

	volume.selectVoxels(boxes);
*/
}
//--------------------------------------------------------------
void ofApp::paintRandomBoxes()
{
	/*
	ofxIntPoint position	= ofVec3f(ofRandom(100));
	ofxIntPoint size		= ofVec3f(ofRandom(10), ofRandom(5), ofRandom(5));

	ofxIntBox box(position, size);
	vector<ofxPoint> c = volume.getVoxelsinBox(box);
	cout << "c size= "<< c.size() << endl;
	for(int i=0; i<c.size(); i++){
		cout << "i= "<< i << endl;
		ofxIntPoint p(c[i].x, c[i].y, c[i].z);
		cout << "ip= "<< p << endl;
		volume.setColor(p.x,p.y,p.z, ofColor::white);
	}
	volumeRender.setVolume(&volume, bPow2, format);
	 */
}

//--------------------------------------------------------------
void ofApp::update()
{
	//    ofSetWindowTitle(ofToString(ofGetFrameRate()));
	//	gifEncoder.update();
}

//--------------------------------------------------------------
void ofApp::onGifSaved(string &fileName) {
    cout << "gif saved as " << fileName << endl;
	gifEncoder.reset();
}

<|endoftext|>