hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c42f483932d5bc212108ac55d25a064be197c33d | 18,478 | cxx | C++ | build2/cxx/init.cxx | yssource/build2 | 3f32c45ea6e4406ff6a320e24fccddab467af3e4 | [
"MIT"
] | null | null | null | build2/cxx/init.cxx | yssource/build2 | 3f32c45ea6e4406ff6a320e24fccddab467af3e4 | [
"MIT"
] | null | null | null | build2/cxx/init.cxx | yssource/build2 | 3f32c45ea6e4406ff6a320e24fccddab467af3e4 | [
"MIT"
] | null | null | null | // file : build2/cxx/init.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2019 Code Synthesis Ltd
// license : MIT; see accompanying LICENSE file
#include <build2/cxx/init.hxx>
#include <build2/scope.hxx>
#include <build2/context.hxx>
#include <build2/diagnostics.hxx>
#include <build2/cc/guess.hxx>
#include <build2/cc/module.hxx>
#include <build2/cxx/target.hxx>
#ifndef BUILD2_DEFAULT_CXX
# ifdef BUILD2_NATIVE_CXX
# define BUILD2_DEFAULT_CXX BUILD2_NATIVE_CXX
# else
# define BUILD2_DEFAULT_CXX ""
# endif
#endif
using namespace std;
using namespace butl;
namespace build2
{
namespace cxx
{
using cc::compiler_id;
using cc::compiler_type;
using cc::compiler_class;
using cc::compiler_info;
class config_module: public cc::config_module
{
public:
explicit
config_module (config_data&& d)
: config_data (move (d)), cc::config_module (move (d)) {}
virtual strings
translate_std (const compiler_info&,
scope&,
const string*) const override;
};
using cc::module;
strings config_module::
translate_std (const compiler_info& ci, scope& rs, const string* v) const
{
strings r;
compiler_type ct (ci.id.type);
compiler_class cl (ci.class_);
uint64_t mj (ci.version.major);
uint64_t mi (ci.version.minor);
uint64_t p (ci.version.patch);
// Features.
//
auto enter = [&rs] (const char* v) -> const variable&
{
return var_pool.rw (rs).insert<bool> (v, variable_visibility::project);
};
// NOTE: see also module sidebuild subproject if changing anything about
// modules here.
//bool concepts (false); auto& v_c (enter ("cxx.features.concepts"));
bool modules (false); auto& v_m (enter ("cxx.features.modules"));
// Translate "latest" and "experimental" to the compiler/version-
// appropriate option(s).
//
if (v != nullptr && (*v == "latest" || *v == "experimental"))
{
// Experimental is like latest with some extra stuff enabled via
// additional switches.
//
const char* o (nullptr);
switch (ct)
{
case compiler_type::msvc:
{
// VC14u3 and later has /std:c++latest.
//
if (mj > 19 || (mj == 19 && (mi > 0 || (mi == 0 && p >= 24215))))
o = "/std:c++latest";
break;
}
case compiler_type::gcc:
{
if (mj >= 8) o = "-std=c++2a"; // 20
else if (mj >= 5) o = "-std=c++1z"; // 17
else if (mj == 4 && mi >= 8) o = "-std=c++1y"; // 14
else if (mj == 4 && mi >= 4) o = "-std=c++0x"; // 11
break;
}
case compiler_type::clang:
{
// Remap Apple versions to vanilla Clang based on the following
// release point. Note that Apple no longer discloses the mapping
// so it's a guesswork and we try to be conservative. For details
// see:
//
// https://gist.github.com/yamaya/2924292
//
// 5.1 -> 3.4
// 6.0 -> 3.5
// 7.0 -> 3.7
// 7.3 -> 3.8
// 8.0 -> 3.9
// 9.0 -> 4.0 (later ones could be 5.0)
// 9.1 -> ?
// 10.0 -> ?
//
// Note that this mapping is also used to enable experimental
// features below.
//
if (ci.id.variant == "apple")
{
if (mj >= 9) {mj = 4; mi = 0;}
else if (mj == 8) {mj = 3; mi = 9;}
else if (mj == 7 && mi >= 3) {mj = 3; mi = 8;}
else if (mj == 7) {mj = 3; mi = 7;}
else if (mj == 6) {mj = 3; mi = 5;}
else if (mj == 5 && mi >= 1) {mj = 3; mi = 4;}
else {mj = 3; mi = 0;}
}
if (mj >= 5) o = "-std=c++2a"; // 20
else if (mj > 3 || (mj == 3 && mi >= 5)) o = "-std=c++1z"; // 17
else if (mj == 3 && mi >= 4) o = "-std=c++1y"; // 14
else /* ??? */ o = "-std=c++0x"; // 11
break;
}
case compiler_type::icc:
{
if (mj >= 17) o = "-std=c++1z"; // 17
else if (mj > 15 || (mj == 15 && p >= 3)) o = "-std=c++1y"; // 14
else /* ??? */ o = "-std=c++0x"; // 11
break;
}
}
if (o != nullptr)
r.push_back (o);
if (*v == "experimental")
{
// Unless disabled by the user, try to enable C++ modules. Here
// we use a tri-state:
//
// - false - disabled
// - unspecified - enabled if practically usable
// - true - enabled even if practically unusable
//
lookup l;
if (!(l = rs[v_m]) || cast<bool> (l))
{
switch (ct)
{
case compiler_type::msvc:
{
// While modules are supported in VC15u0 (19.10), there is a
// bug in separate interface/implementation unit support which
// makes them pretty much unusable. This has been fixed in
// VC15u3 (19.11). And VC15u5 (19.12) supports the 'export
// module M;' syntax.
//
if (mj > 19 || (mj == 19 && mi >= (l ? 10 : 12)))
{
r.push_back (
mj > 19 || mi > 11
? "/D__cpp_modules=201704" // p0629r0 (export module M;)
: "/D__cpp_modules=201703"); // n4647 ( module M;)
r.push_back ("/experimental:module");
modules = true;
}
break;
}
case compiler_type::gcc:
{
// Enable starting with GCC 9.0.0 (currently the c++-modules
// branch).
//
if (mj >= 9 &&
ci.version.build.find ("c++-modules") != string::npos)
{
// Currently defines __cpp_modules=201804 which is said to
// correspond to p0713 ('module;' leading marker).
//
r.push_back ("-fmodules-ts");
modules = true;
}
break;
}
case compiler_type::clang:
{
// Enable starting with Clang 6.0.0.
//
// Note that we are using Apple to vanilla Clang version re-
// map from above so may need to update things there as well.
//
// Also see Clang modules support hack in cc::compile.
//
if (mj >= 6)
{
r.push_back ("-D__cpp_modules=201704"); // p0629r0
r.push_back ("-fmodules-ts");
modules = true;
}
break;
}
case compiler_type::icc:
break; // No modules support yet.
}
}
}
}
else
{
// Otherwise translate the standard value.
//
switch (cl)
{
case compiler_class::msvc:
{
// C++ standard-wise, with VC you got what you got up until 14u2.
// Starting with 14u3 there is now the /std: switch which defaults
// to c++14 but can be set to c++latest. And from 15u3 it can be
// c++17.
//
// The question is also whether we should verify that the
// requested standard is provided by this VC version. And if so,
// from which version should we say VC supports 11, 14, and 17? We
// should probably be as loose as possible here since the author
// will always be able to tighten (but not loosen) this in the
// buildfile (i.e., detect unsupported versions).
//
// For now we are not going to bother doing this for C++03.
//
if (v == nullptr)
;
else if (*v != "98" && *v != "03")
{
bool sup (false);
if (*v == "11") // C++11 since VS2010/10.0.
{
sup = mj >= 16;
}
else if (*v == "14") // C++14 since VS2015/14.0.
{
sup = mj >= 19;
}
else if (*v == "17") // C++17 since VS2015/14.0u2.
{
// Note: the VC15 compiler version is 19.10.
//
sup = (mj > 19 ||
(mj == 19 && (mi > 0 || (mi == 0 && p >= 23918))));
}
if (!sup)
fail << "C++" << *v << " is not supported by "
<< ci.signature <<
info << "required by " << project (rs) << '@'
<< rs.out_path ();
if (mj > 19 || (mj == 19 && mi >= 11)) // 15u3
{
if (*v == "14") r.push_back ("/std:c++14");
else if (*v == "17") r.push_back ("/std:c++17");
}
else if (mj == 19 && (mi > 0 || (mi == 0 && p >= 24215))) // 14u3
{
if (*v == "14") r.push_back ("/std:c++14");
else if (*v == "17") r.push_back ("/std:c++latest");
}
}
break;
}
case compiler_class::gcc:
{
// Translate 11 to 0x, 14 to 1y, 17 to 1z, and 20 to 2a for
// compatibility with older versions of the compilers.
//
if (v == nullptr)
;
else
{
string o ("-std=");
if (*v == "98") o += "c++98";
else if (*v == "03") o += "c++03";
else if (*v == "11") o += "c++0x";
else if (*v == "14") o += "c++1y";
else if (*v == "17") o += "c++1z";
else if (*v == "20") o += "c++2a";
else o += *v; // In case the user specifies e.g., 'gnu++17'.
r.push_back (move (o));
}
break;
}
}
}
rs.assign (v_m) = modules;
//rs.assign (v_c) = concepts;
return r;
}
static const char* const hinters[] = {"c", nullptr};
// See cc::module for details on guess_init vs config_init.
//
bool
guess_init (scope& rs,
scope& bs,
const location& loc,
unique_ptr<module_base>& mod,
bool,
bool,
const variable_map& hints)
{
tracer trace ("cxx::guess_init");
l5 ([&]{trace << "for " << bs.out_path ();});
// We only support root loading (which means there can only be one).
//
if (&rs != &bs)
fail (loc) << "cxx.guess module must be loaded in project root";
// Load cc.core.vars so that we can cache all the cc.* variables.
//
if (!cast_false<bool> (rs["cc.core.vars.loaded"]))
load_module (rs, rs, "cc.core.vars", loc);
// Enter all the variables and initialize the module data.
//
auto& v (var_pool.rw (rs));
cc::config_data d {
cc::lang::cxx,
"cxx",
"c++",
BUILD2_DEFAULT_CXX,
".ii",
hinters,
// Note: some overridable, some not.
//
v.insert<path> ("config.cxx", true),
v.insert<string> ("config.cxx.id", true),
v.insert<string> ("config.cxx.version", true),
v.insert<string> ("config.cxx.target", true),
v.insert<strings> ("config.cxx.poptions", true),
v.insert<strings> ("config.cxx.coptions", true),
v.insert<strings> ("config.cxx.loptions", true),
v.insert<strings> ("config.cxx.libs", true),
v.insert<process_path> ("cxx.path"),
v.insert<dir_paths> ("cxx.sys_lib_dirs"),
v.insert<dir_paths> ("cxx.sys_inc_dirs"),
v.insert<strings> ("cxx.poptions"),
v.insert<strings> ("cxx.coptions"),
v.insert<strings> ("cxx.loptions"),
v.insert<strings> ("cxx.libs"),
v["cc.poptions"],
v["cc.coptions"],
v["cc.loptions"],
v["cc.libs"],
v.insert<strings> ("cxx.export.poptions"),
v.insert<strings> ("cxx.export.coptions"),
v.insert<strings> ("cxx.export.loptions"),
v.insert<vector<name>> ("cxx.export.libs"),
v["cc.export.poptions"],
v["cc.export.coptions"],
v["cc.export.loptions"],
v["cc.export.libs"],
v.insert<string> ("cxx.stdlib"),
v["cc.runtime"],
v["cc.stdlib"],
v["cc.type"],
v["cc.system"],
v["cc.module_name"],
v["cc.reprocess"],
// Ability to signal that source is already (partially) preprocessed.
// Valid values are 'none' (not preprocessed), 'includes' (no #include
// directives in source), 'modules' (as above plus no module
// declaration depends on preprocessor, e.g., #ifdef, etc), and 'all'
// (the source is fully preprocessed). Note that for 'all' the source
// can still contain comments and line continuations. Note also that
// for some compilers (e.g., VC) there is no way to signal that the
// source is already preprocessed.
//
v.insert<string> ("cxx.preprocessed"),
nullptr, // cxx.features.symexport (set in init() below).
v.insert<string> ("cxx.std", variable_visibility::project),
v.insert<string> ("cxx.id"),
v.insert<string> ("cxx.id.type"),
v.insert<string> ("cxx.id.variant"),
v.insert<string> ("cxx.class"),
v.insert<string> ("cxx.version"),
v.insert<uint64_t> ("cxx.version.major"),
v.insert<uint64_t> ("cxx.version.minor"),
v.insert<uint64_t> ("cxx.version.patch"),
v.insert<string> ("cxx.version.build"),
v.insert<string> ("cxx.signature"),
v.insert<string> ("cxx.checksum"),
v.insert<string> ("cxx.pattern"),
v.insert<target_triplet> ("cxx.target"),
v.insert<string> ("cxx.target.cpu"),
v.insert<string> ("cxx.target.vendor"),
v.insert<string> ("cxx.target.system"),
v.insert<string> ("cxx.target.version"),
v.insert<string> ("cxx.target.class")
};
// Alias some cc. variables as cxx.
//
v.insert_alias (d.c_runtime, "cxx.runtime");
v.insert_alias (d.c_module_name, "cxx.module_name");
assert (mod == nullptr);
config_module* m (new config_module (move (d)));
mod.reset (m);
m->guess (rs, loc, hints);
return true;
}
bool
config_init (scope& rs,
scope& bs,
const location& loc,
unique_ptr<module_base>&,
bool,
bool,
const variable_map& hints)
{
tracer trace ("cxx::config_init");
l5 ([&]{trace << "for " << bs.out_path ();});
// We only support root loading (which means there can only be one).
//
if (&rs != &bs)
fail (loc) << "cxx.config module must be loaded in project root";
// Load cxx.guess.
//
if (!cast_false<bool> (rs["cxx.guess.loaded"]))
load_module (rs, rs, "cxx.guess", loc, false, hints);
config_module& cm (*rs.modules.lookup<config_module> ("cxx.guess"));
cm.init (rs, loc, hints);
return true;
}
static const target_type* const hdr[] =
{
&hxx::static_type,
&h::static_type,
&ixx::static_type,
&txx::static_type,
&mxx::static_type,
nullptr
};
static const target_type* const inc[] =
{
&hxx::static_type,
&h::static_type,
&ixx::static_type,
&txx::static_type,
&mxx::static_type,
&cxx::static_type,
&c::static_type,
nullptr
};
bool
init (scope& rs,
scope& bs,
const location& loc,
unique_ptr<module_base>& mod,
bool,
bool,
const variable_map& hints)
{
tracer trace ("cxx::init");
l5 ([&]{trace << "for " << bs.out_path ();});
// We only support root loading (which means there can only be one).
//
if (&rs != &bs)
fail (loc) << "cxx module must be loaded in project root";
// Load cxx.config.
//
if (!cast_false<bool> (rs["cxx.config.loaded"]))
load_module (rs, rs, "cxx.config", loc, false, hints);
config_module& cm (*rs.modules.lookup<config_module> ("cxx.guess"));
auto& vp (var_pool.rw (rs));
bool modules (cast<bool> (rs["cxx.features.modules"]));
bool symexport (false);
if (modules)
{
auto& var (vp.insert<bool> ("cxx.features.symexport",
variable_visibility::project));
symexport = cast_false<bool> (rs[var]);
cm.x_symexport = &var;
}
cc::data d {
cm,
"cxx.compile",
"cxx.link",
"cxx.install",
"cxx.uninstall",
cm.ci_->id.type,
cm.ci_->id.variant,
cm.ci_->class_,
cm.ci_->version.major,
cm.ci_->version.minor,
cast<process_path> (rs[cm.x_path]),
cast<target_triplet> (rs[cm.x_target]),
cm.tstd,
modules,
symexport,
cast<dir_paths> (rs[cm.x_sys_lib_dirs]),
cast<dir_paths> (rs[cm.x_sys_inc_dirs]),
cm.sys_lib_dirs_extra,
cm.sys_inc_dirs_extra,
cxx::static_type,
modules ? &mxx::static_type : nullptr,
hdr,
inc
};
assert (mod == nullptr);
module* m;
mod.reset (m = new module (move (d)));
m->init (rs, loc, hints);
return true;
}
}
}
| 31.318644 | 79 | 0.464444 | [
"vector"
] |
c430527d889d47fbba015deacc1075fc0eb65d1d | 9,891 | cpp | C++ | server/draw_server.cpp | xqq/drawboard | 993f0f90c127c51ad5837656fc1383b2d9e7ddde | [
"MIT"
] | 10 | 2020-01-18T09:28:47.000Z | 2020-04-28T15:37:42.000Z | server/draw_server.cpp | xqq/drawboard | 993f0f90c127c51ad5837656fc1383b2d9e7ddde | [
"MIT"
] | 1 | 2020-04-28T15:29:52.000Z | 2020-04-28T15:35:03.000Z | server/draw_server.cpp | xqq/drawboard | 993f0f90c127c51ad5837656fc1383b2d9e7ddde | [
"MIT"
] | 2 | 2020-01-20T06:54:26.000Z | 2022-01-11T09:01:42.000Z | #if defined(_WIN32)
#include <winsock2.h>
#else
#include <netinet/in.h>
#endif
#include <iostream>
#include <ctime>
#include "common/log.hpp"
#include "socket/tcp_listener.hpp"
#include "socket/tcp_socket.hpp"
#include "common/packet.hpp"
#include "protocol/protocol_generated.h"
#include "draw_server.hpp"
using namespace std::placeholders;
DrawServer::DrawServer() : max_uid_(-1) {
srand(static_cast<uint32_t>(time(nullptr)));
transmit_worker_.SetTaskQueue(task_queue_);
transmit_worker_.SetSocketCluster(socket_cluster_);
listener_.reset(TcpListener::Create(std::bind(&DrawServer::onListenerAccepted, this, _1, _2),
std::bind(&DrawServer::onListenerError, this, _1)));
}
DrawServer::~DrawServer() {
Stop();
}
void DrawServer::Start(std::string bind_addr, uint16_t port) {
transmit_worker_.Start();
listener_->StartListen(std::move(bind_addr), port);
}
void DrawServer::Stop() {
task_queue_.Clear();
task_queue_.NotifyExit();
listener_->EndListen();
ShutdownSockets();
}
void DrawServer::ShutdownSockets() {
for (auto& iter : socket_cluster_) {
TcpSocket* socket = iter.second.get();
socket->Shutdown();
}
}
void DrawServer::onListenerAccepted(std::unique_ptr<TcpSocket> socket, struct sockaddr_in) {
Log::InfoF("[Server] onListenerAccepted\n");
socket->SetCallback(std::bind(&DrawServer::onClientConnected, this, _1),
std::bind(&DrawServer::onClientDisconnected, this, _1),
std::bind(&DrawServer::onClientDataArrival, this, _1, _2, _3),
std::bind(&DrawServer::onClientError, this, _1, _2));
uint32_t uid = ++max_uid_;
socket->SetUserData(reinterpret_cast<void*>(static_cast<uint64_t>(uid)));
TcpSocket* socket_ptr = socket.get();
socket_cluster_.insert({uid, std::move(socket)});
// determine user color
uint32_t color = RandomColor();
PostServerHello(socket_ptr, uid, color);
PostFullImage(socket_ptr);
BroadcastUserEnter(uid, color);
}
void DrawServer::onListenerError(const std::string& msg) {
Log::ErrorF("[Server] onListenerError: %s\n", msg.c_str());
}
void DrawServer::onClientConnected(TcpSocket* socket) {
// do nothing
}
void DrawServer::onClientDisconnected(TcpSocket* socket) {
uint32_t uid = static_cast<uint32_t>(reinterpret_cast<uint64_t>(socket->GetUserData()));
Log::InfoF("[Server] onClientDisconnected: uid %u left\n", uid);
socket->Shutdown();
socket_cluster_.erase(uid);
BroadcastUserLeave(uid);
}
void DrawServer::onClientDataArrival(TcpSocket* socket, ReadWriteBuffer* buffer, size_t nread) {
uint32_t uid = static_cast<uint32_t>(reinterpret_cast<uint64_t>(socket->GetUserData()));
ParseBuffer(buffer, [&](Packet&& packet) {
const PacketPayload* packet_payload = packet.payload;
switch (packet.header.packet_type()) {
case PacketType_StartDraw: {
auto payload = packet_payload->payload_as<StartDrawPayload>();
canvas_.BeginDraw(payload->uid(), payload->sequence_id(), payload->color());
BroadcastPacketExclude(packet, socket);
break;
}
case PacketType_EndDraw: {
auto payload = packet_payload->payload_as<EndDrawPayload>();
canvas_.EndDraw(payload->uid(), payload->sequence_id());
BroadcastPacketExclude(packet, socket);
break;
}
case PacketType_DrawPoints: {
auto payload = packet_payload->payload_as<DrawPointsPayload>();
auto points_vector = payload->points();
if (points_vector->size() == 0) {
break;
}
std::vector<Point> points(points_vector->size());
memcpy(points.data(), points_vector->data(), sizeof(Vec2) * points_vector->size());
canvas_.DrawPoints(payload->uid(), payload->sequence_id(), points);
BroadcastPacketExclude(packet, socket);
break;
}
case PacketType_DeleteBatch: {
auto payload = packet_payload->payload_as<DeleteBatchPayload>();
canvas_.ClearBatch(payload->uid(), payload->sequence_id());
BroadcastPacketExclude(packet, socket);
break;
}
case PacketType_ServerHello:
case PacketType_FullImage:
case PacketType_UserEnter:
case PacketType_UserLeave:
default:
// ignore
break;
}
});
}
void DrawServer::onClientError(TcpSocket* socket, const std::string& message) {
uint32_t uid = static_cast<uint32_t>(reinterpret_cast<uint64_t>(socket->GetUserData()));
Log::ErrorF("[Server] onClientError: uid = %u, msg = %s\n", uid, message.c_str());
socket->Shutdown();
socket_cluster_.erase(uid);
}
void DrawServer::PostPacket(TcpSocket* socket, PacketHeader* header, const uint8_t* payload, size_t payload_length) {
std::vector<uint8_t> packet_buffer(sizeof(*header) + payload_length);
size_t header_size = sizeof(*header);
memcpy(packet_buffer.data(), header, header_size);
memcpy(packet_buffer.data() + header_size, payload, payload_length);
Task t(TaskType::kPrivateSend, std::move(packet_buffer), socket);
task_queue_.Enqueue(std::move(t));
}
void DrawServer::PostServerHello(TcpSocket *socket, uint32_t uid, uint32_t color) {
flatbuffers::FlatBufferBuilder builder;
auto payload = CreateServerHelloPayload(builder, uid, color);
auto packet_payload = CreatePacketPayload(builder, Payload_ServerHelloPayload, payload.Union());
builder.Finish(packet_payload);
PacketHeader header(PacketType_ServerHello, builder.GetSize());
PostPacket(socket, &header, builder.GetBufferPointer(), builder.GetSize());
}
void DrawServer::PostFullImage(TcpSocket *socket) {
const PointMap* map = canvas_.GetMap();
std::vector<flatbuffers::Offset<DrawBatch>> draw_batch_offsets;
flatbuffers::FlatBufferBuilder builder;
for (auto& user_pair : *map) {
for (auto& batch_pair : user_pair.second) {
const BatchInfo* batch_info = &batch_pair.second;
std::vector<Vec2> points(batch_info->points.size());
memcpy(points.data(), batch_info->points.data(), sizeof(Vec2) * batch_info->points.size());
auto batch = CreateDrawBatchDirect(builder, user_pair.first, batch_pair.first, batch_info->color, &points);
draw_batch_offsets.push_back(batch);
}
}
auto payload = CreateFullImagePayloadDirect(builder, &draw_batch_offsets);
auto packet_payload = CreatePacketPayload(builder, Payload_FullImagePayload, payload.Union());
builder.Finish(packet_payload);
PacketHeader header(PacketType_FullImage, builder.GetSize());
PostPacket(socket, &header, builder.GetBufferPointer(), builder.GetSize());
}
void DrawServer::BroadcastPacketExclude(const Packet& packet, TcpSocket* exclude_socket) {
std::vector<uint8_t> packet_buffer(sizeof(packet.header) + packet.payload_buffer.size());
size_t header_size = sizeof(packet.header);
memcpy(packet_buffer.data(), &packet.header, header_size);
memcpy(packet_buffer.data() + header_size, packet.payload_buffer.data(), packet.payload_buffer.size());
Task t(TaskType::kBroadcastSendExclude, std::move(packet_buffer), exclude_socket);
task_queue_.Enqueue(std::move(t));
}
void DrawServer::BroadcastPacket(const Packet& packet) {
std::vector<uint8_t> packet_buffer(sizeof(packet.header) + packet.payload_buffer.size());
size_t header_size = sizeof(packet.header);
memcpy(packet_buffer.data(), &packet.header, header_size);
memcpy(packet_buffer.data() + header_size, packet.payload_buffer.data(), packet.payload_buffer.size());
Task t(TaskType::kBroadcastSend, std::move(packet_buffer));
task_queue_.Enqueue(std::move(t));
}
void DrawServer::BroadcastPacket(PacketHeader* header, const uint8_t* payload, size_t payload_length) {
std::vector<uint8_t> packet_buffer(sizeof(*header) + payload_length);
size_t header_size = sizeof(*header);
memcpy(packet_buffer.data(), header, header_size);
memcpy(packet_buffer.data() + header_size, payload, payload_length);
Task t(TaskType::kBroadcastSend, std::move(packet_buffer));
task_queue_.Enqueue(std::move(t));
}
void DrawServer::BroadcastUserEnter(uint32_t uid, uint32_t color) {
flatbuffers::FlatBufferBuilder builder;
auto payload = CreateUserEnterPayload(builder, uid, color);
auto packet_payload = CreatePacketPayload(builder, Payload_UserEnterPayload, payload.Union());
builder.Finish(packet_payload);
PacketHeader header(PacketType_UserEnter, builder.GetSize());
BroadcastPacket(&header, builder.GetBufferPointer(), builder.GetSize());
}
void DrawServer::BroadcastUserLeave(uint32_t uid) {
flatbuffers::FlatBufferBuilder builder;
auto payload = CreateUserEnterPayload(builder, uid);
auto packet_payload = CreatePacketPayload(builder, Payload_UserLeavePayload, payload.Union());
builder.Finish(packet_payload);
PacketHeader header(PacketType_UserLeave, builder.GetSize());
BroadcastPacket(&header, builder.GetBufferPointer(), builder.GetSize());
}
uint32_t DrawServer::RandomColor() {
uint8_t r = rand() % 256;
uint8_t g = rand() % 256;
uint8_t b = rand() % 256;
r = ((int)r + 255) / 2;
g = ((int)g + 255) / 2;
b = ((int)b + 255) / 2;
return 0xFF << 24 |
r << 16 |
g << 8 |
b;
}
std::vector<uint8_t> DrawServer::BufToVector(const uint8_t *buffer, size_t size) {
std::vector<uint8_t> vec(size);
memcpy(vec.data(), buffer, size);
return vec;
}
| 37.608365 | 119 | 0.675159 | [
"vector"
] |
c43f8a128e2ee95187e72958f6d386049a753250 | 7,570 | cpp | C++ | SemperEngine/Source/SemperEngine/Graphics/Renderers/Batcher2D.cpp | SemperParatusGithub/SemperEngine | 5cd8df60bfc2d04f00a781636fbd0e8152b88582 | [
"MIT"
] | 5 | 2020-12-11T13:52:56.000Z | 2021-06-28T16:17:15.000Z | SemperEngine/Source/SemperEngine/Graphics/Renderers/Batcher2D.cpp | SemperParatusGithub/SemperEngine | 5cd8df60bfc2d04f00a781636fbd0e8152b88582 | [
"MIT"
] | null | null | null | SemperEngine/Source/SemperEngine/Graphics/Renderers/Batcher2D.cpp | SemperParatusGithub/SemperEngine | 5cd8df60bfc2d04f00a781636fbd0e8152b88582 | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include "Batcher2D.h"
#include "Renderer.h" // includes VertexArray.h and Shader.h
#include "SemperEngine/Graphics/Backend/API/Texture.h"
namespace SemperEngine
{
struct QuadVertex
{
Vec4 position;
Vec4 color;
Vec2 texCoords;
float texIndex; // 0 = whiteTexture --> FlatColor
};
struct Batcher2DRenderData
{
SharedPtr<VertexArray> vertexArray;
SharedPtr<VertexBuffer> vertexBuffer;
SharedPtr<IndexBuffer> indexBuffer;
QuadVertex *buffer = nullptr;
QuadVertex *bufferPtr = nullptr;
U32 indexCount = 0;
glm::vec4 vertexPositions[4];
glm::vec2 textureCoords[4];
SharedPtr<Shader> shader;
SharedPtr<Texture2D> whiteTexture;
std::array<const Texture2D *, MaxCombinedTextureUnits> textures;
Batcher2DMetrics metrics;
};
static Batcher2DRenderData s_RenderData;
void Batcher2D::Init()
{
// Initialize quad data
s_RenderData.buffer = new QuadVertex[MaxVertexCount];
s_RenderData.vertexBuffer = VertexBuffer::Create(nullptr, MaxVertexCount * sizeof(QuadVertex), BufferUsage::Dynamic);
s_RenderData.vertexBuffer->AddAttribute({ "a_Position", VertexFormat::Float4, false });
s_RenderData.vertexBuffer->AddAttribute({ "a_Color", VertexFormat::Float4, false });
s_RenderData.vertexBuffer->AddAttribute({ "a_TexCoords", VertexFormat::Float2, false });
s_RenderData.vertexBuffer->AddAttribute({ "a_TexIndex", VertexFormat::Float1, false });
U32 *indices = new U32[MaxIndexCount];
U32 offset = 0;
for (int i = 0; i < MaxIndexCount; i += 6)
{
indices[i + 0] = 0 + offset;
indices[i + 1] = 1 + offset;
indices[i + 2] = 2 + offset;
indices[i + 3] = 2 + offset;
indices[i + 4] = 3 + offset;
indices[i + 5] = 0 + offset;
offset += 4;
}
s_RenderData.indexBuffer = IndexBuffer::Create(indices, IndexFormat::Uint32, MaxIndexCount * sizeof(U32), BufferUsage::Static);
s_RenderData.vertexArray = VertexArray::Create(s_RenderData.vertexBuffer.get(), s_RenderData.indexBuffer.get());
s_RenderData.vertexPositions[0] = { -0.5f, -0.5f, 0.0f, 1.0f };
s_RenderData.vertexPositions[1] = { 0.5f, -0.5f, 0.0f, 1.0f };
s_RenderData.vertexPositions[2] = { 0.5f, 0.5f, 0.0f, 1.0f };
s_RenderData.vertexPositions[3] = { -0.5f, 0.5f, 0.0f, 1.0f };
s_RenderData.textureCoords[0] = { 0.0f, 0.0f };
s_RenderData.textureCoords[1] = { 1.0f, 0.0f };
s_RenderData.textureCoords[2] = { 1.0f, 1.0f };
s_RenderData.textureCoords[3] = { 0.0f, 1.0f };
// General Initialization
s_RenderData.shader = Shader::Create(ShaderManager::LoadFromFile("Assets/Shaders/Batch.shader"));
s_RenderData.whiteTexture = Texture2D::Create("Assets/Textures/WhiteTexture.png");
for (auto &texture : s_RenderData.textures)
texture = s_RenderData.whiteTexture.get();
int samplers[MaxCombinedTextureUnits];
for (U32 i = 0; i < MaxCombinedTextureUnits; i++)
samplers[i] = i;
s_RenderData.shader->Bind();
s_RenderData.shader->SetUniformIntArray("u_Samplers", samplers, MaxCombinedTextureUnits);
}
void Batcher2D::Shutdown()
{
}
void Batcher2D::BeginScene(ConstRef<Mat4> projectionView)
{
s_RenderData.indexCount = 0;
s_RenderData.bufferPtr = s_RenderData.buffer;
s_RenderData.shader->Bind();
s_RenderData.shader->SetUniformMat4f("u_ProjectionView", projectionView);
}
void Batcher2D::BeginScene(ConstRef<OrthographicCamera> camera)
{
BeginScene(camera.GetProjectionView());
}
void Batcher2D::BeginScene(ConstRef<EditorCamera> camera)
{
BeginScene(camera.GetViewProjection());
}
void Batcher2D::EndScene()
{
Flush();
}
void Batcher2D::Flush()
{
for (std::size_t i = 0; i < s_RenderData.textures.size(); i++)
s_RenderData.textures[i]->Bind(static_cast<U32>(i));
for (std::size_t i = 0; i < s_RenderData.textures.size(); i++)
s_RenderData.textures[i] = s_RenderData.whiteTexture.get();
U32 size = static_cast<U32>(reinterpret_cast<U8 *>(s_RenderData.bufferPtr) - reinterpret_cast<U8 *>(s_RenderData.buffer));
s_RenderData.vertexBuffer->SetData(s_RenderData.buffer, size);
Renderer::DrawIndexed(s_RenderData.vertexArray, s_RenderData.shader, s_RenderData.indexCount);
s_RenderData.metrics.batches += 1;
}
void Batcher2D::DrawQuad(ConstRef<Transform> transform, ConstRef<Vec4> color)
{
if (s_RenderData.indexCount >= MaxIndexCount)
{
Flush();
BeginScene();
}
float textureIndex = 0.0f; // Render with white texture (flat color)
for (U32 i = 0; i < 4; i++)
{
s_RenderData.bufferPtr->position = transform.GetTransform() * s_RenderData.vertexPositions[i];
s_RenderData.bufferPtr->color = color;
s_RenderData.bufferPtr->texCoords = s_RenderData.textureCoords[i];
s_RenderData.bufferPtr->texIndex = textureIndex;
s_RenderData.bufferPtr++;
}
s_RenderData.indexCount += 6;
s_RenderData.metrics.triangles += 2;
s_RenderData.metrics.vertices += 4;
s_RenderData.metrics.indices += 6;
}
void Batcher2D::DrawQuad(ConstRef<Transform> transform, ConstRef<SharedPtr<Texture2D>> texture, ConstRef<glm::vec4> tintColor)
{
if (s_RenderData.indexCount >= MaxIndexCount)
{
Flush();
BeginScene();
}
float textureIndex = 0.0f;
for (std::size_t i = 1; i < s_RenderData.textures.size(); i++)
{
if (s_RenderData.textures[i]->GetHandle() == texture->GetHandle()) {
textureIndex = static_cast<float>(i);
break;
}
else if (s_RenderData.textures[i]->GetHandle() == s_RenderData.whiteTexture->GetHandle()) {
textureIndex = static_cast<float>(i);
s_RenderData.textures[i] = texture.get();
break;
}
}
for (U32 i = 0; i < 4; i++)
{
s_RenderData.bufferPtr->position = transform.GetTransform() * s_RenderData.vertexPositions[i];
s_RenderData.bufferPtr->color = tintColor;
s_RenderData.bufferPtr->texCoords = s_RenderData.textureCoords[i];
s_RenderData.bufferPtr->texIndex = textureIndex;
s_RenderData.bufferPtr++;
}
s_RenderData.indexCount += 6;
s_RenderData.metrics.triangles += 2;
s_RenderData.metrics.vertices += 4;
s_RenderData.metrics.indices += 6;
}
void Batcher2D::DrawSprite(ConstRef<Transform> transform, ConstRef<Sprite> sprite)
{
const auto &tintColor = sprite.GetColor();
float textureIndex = 0.0f;
if (s_RenderData.indexCount >= MaxIndexCount)
{
Flush();
BeginScene();
}
if (sprite.HasTexture() || sprite.HasSpriteSheet())
{
const auto &texture = sprite.GetTexture();
for (std::size_t i = 1; i < s_RenderData.textures.size(); i++)
{
if (s_RenderData.textures[i]->GetHandle() == texture->GetHandle()) {
textureIndex = static_cast<float>(i);
break;
}
else if (s_RenderData.textures[i]->GetHandle() == s_RenderData.whiteTexture->GetHandle()) {
textureIndex = static_cast<float>(i);
s_RenderData.textures[i] = texture.get();
break;
}
}
}
for (U32 i = 0; i < 4; i++)
{
s_RenderData.bufferPtr->position = transform.GetTransform() * s_RenderData.vertexPositions[i];
s_RenderData.bufferPtr->color = tintColor;
s_RenderData.bufferPtr->texCoords = sprite.GetTextureCoordinates()[i];
s_RenderData.bufferPtr->texIndex = textureIndex;
s_RenderData.bufferPtr++;
}
s_RenderData.indexCount += 6;
s_RenderData.metrics.triangles += 2;
s_RenderData.metrics.vertices += 4;
s_RenderData.metrics.indices += 6;
}
void Batcher2D::ResetMetrics()
{
s_RenderData.metrics = Batcher2DMetrics();
}
Batcher2DMetrics Batcher2D::GetMetrics()
{
return s_RenderData.metrics;
}
void Batcher2D::BeginScene()
{
s_RenderData.indexCount = 0;
s_RenderData.bufferPtr = s_RenderData.buffer;
}
} | 29.115385 | 129 | 0.70568 | [
"render",
"transform"
] |
c4455c9485426963c5bb1b5465400bf3a32fb2f0 | 3,253 | hpp | C++ | source/sill/glb/loader.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 15 | 2018-02-26T08:20:03.000Z | 2022-03-06T03:25:46.000Z | source/sill/glb/loader.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | 32 | 2018-02-26T08:26:38.000Z | 2020-09-12T17:09:38.000Z | source/sill/glb/loader.hpp | Breush/lava | 1b1b1f0785300b93b4a9f35fca4490502fea6552 | [
"MIT"
] | null | null | null | #pragma once
#include <lava/core/render-category.hpp>
namespace lava::glb {
struct Header {
uint8_t magic[4];
uint32_t version;
uint32_t length = 0u;
};
inline std::ostream& operator<<(std::ostream& os, const Header& header);
inline std::istream& operator>>(std::istream& is, Header& header);
struct Chunk {
enum class Type {
JSON,
BIN,
UNKNOWN,
};
uint32_t length = 0u;
Type type = Type::UNKNOWN;
std::vector<uint8_t> data;
};
inline std::ostream& operator<<(std::ostream& os, const Chunk& chunk);
inline std::istream& operator>>(std::istream& is, Chunk& chunk);
struct Node {
std::string name;
uint32_t meshIndex = -1u;
std::vector<uint32_t> children;
glm::mat4 transform = glm::mat4(1.f);
Node(const typename nlohmann::json::basic_json& json);
};
struct Mesh {
struct Primitive {
uint8_t mode = 4u;
uint32_t positionsAccessorIndex = -1u;
uint32_t normalsAccessorIndex = -1u;
uint32_t tangentsAccessorIndex = -1u;
uint32_t uv1sAccessorIndex = -1u;
uint32_t indicesAccessorIndex = -1u;
uint32_t materialIndex = -1u;
};
std::string name;
std::vector<Primitive> primitives;
Mesh(const typename nlohmann::json::basic_json& json);
};
struct Image {
uint32_t bufferView = -1u;
std::string mimeType;
Image(const typename nlohmann::json::basic_json& json);
};
struct Texture {
uint32_t sampler = -1u;
uint32_t source = -1u;
Texture(const typename nlohmann::json::basic_json& json);
};
struct Material {
uint32_t normalTextureIndex = -1u;
uint32_t occlusionTextureIndex = -1u;
uint32_t emissiveTextureIndex = -1u;
Material(const typename nlohmann::json::basic_json& json);
};
struct PbrMetallicRoughnessMaterial : public Material {
std::string name;
RenderCategory renderCategory = RenderCategory::Opaque;
uint32_t baseColorTextureIndex = -1u;
uint32_t metallicRoughnessTextureIndex = -1u;
glm::vec4 baseColorFactor = glm::vec4(1.f, 1.f, 1.f, 1.f);
float metallicFactor = 1.f;
float roughnessFactor = 1.f;
PbrMetallicRoughnessMaterial(const typename nlohmann::json::basic_json& json);
};
struct Accessor {
uint32_t bufferView = -1u;
uint32_t byteOffset = 0u;
uint32_t count = 0u;
Accessor(const typename nlohmann::json::basic_json& json);
template <class T>
VectorView<T> get(const typename nlohmann::json::basic_json& bufferViews, const std::vector<uint8_t>& buffer) const;
};
struct BufferView {
uint32_t byteLength = 0u;
uint32_t byteOffset = 0u;
uint32_t byteStride = 0u;
BufferView(const typename nlohmann::json::basic_json& json);
struct Data {
const uint8_t* data = nullptr;
uint32_t size = 0u;
};
VectorView<uint8_t> get(const std::vector<uint8_t>& buffer) const;
};
}
#include "./loader.inl"
| 27.567797 | 124 | 0.601599 | [
"mesh",
"render",
"vector",
"transform"
] |
c4488714263de2a1d2023bc8dfb1fbf704449e74 | 7,566 | cpp | C++ | src/native-emitter.cpp | tuananh/sax-parser | d97a52205339e12dab613438258d94be2d2956dd | [
"MIT"
] | 7 | 2020-05-28T09:52:27.000Z | 2021-06-30T18:08:35.000Z | src/native-emitter.cpp | tuananh/sax-parser | d97a52205339e12dab613438258d94be2d2956dd | [
"MIT"
] | 9 | 2020-05-30T15:25:51.000Z | 2021-11-09T09:31:17.000Z | src/native-emitter.cpp | tuananh/sax-parser | d97a52205339e12dab613438258d94be2d2956dd | [
"MIT"
] | 3 | 2020-06-04T07:57:02.000Z | 2021-11-08T22:33:14.000Z | #include "native-emitter.h"
#include <iostream>
#include <string>
#include "sax-parser.h"
using namespace saxparser;
Napi::FunctionReference SaxParser::constructor;
Napi::Object SaxParser::Init(Napi::Env env, Napi::Object exports)
{
Napi::HandleScope scope(env);
Napi::Function func = DefineClass(
env, "SaxParser", {InstanceMethod("parse", &SaxParser::Parse)});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("SaxParser", func);
return exports;
}
SaxParser::SaxParser(const Napi::CallbackInfo &info)
: Napi::ObjectWrap<SaxParser>(info)
{
// NOOP
}
inline std::string ParseStatusToString(xsxml::xml_parse_status s)
{
switch (s)
{
case xsxml::xml_parse_status::status_io_error:
return "ERR_IO";
case xsxml::xml_parse_status::status_out_of_memory:
return "ERR_OUT_OF_MEMORY";
case xsxml::xml_parse_status::status_internal_error:
return "ERR_INTERAL";
case xsxml::xml_parse_status::status_unrecognized_tag:
return "ERR_UNRECOGNIZE_TAG";
case xsxml::xml_parse_status::status_bad_pi:
return "ERR_BAD_PI";
case xsxml::xml_parse_status::status_bad_comment:
return "ERR_BAD_COMMENT";
case xsxml::xml_parse_status::status_bad_cdata:
return "ERR_BAD_CDATA";
case xsxml::xml_parse_status::status_bad_doctype:
return "ERR_BAD_DOCTYPE";
case xsxml::xml_parse_status::status_bad_pcdata:
return "ERR_BAD_PCDATA";
case xsxml::xml_parse_status::status_bad_start_element:
return "ERR_BAD_START_ELEMENT";
case xsxml::xml_parse_status::status_bad_attribute:
return "ERR_BAD_ATTRIBUTE";
case xsxml::xml_parse_status::status_bad_end_element:
return "ERR_BAD_END_ELEMENT";
case xsxml::xml_parse_status::status_end_element_mismatch:
return "ERR_END_ELEMENT_MISMATCH";
case xsxml::xml_parse_status::status_append_invalid_root:
return "ERR_APPEND_INVALID_ROOT";
case xsxml::xml_parse_status::status_no_document_element:
return "ERR_NO_DOCUMENT_ELEMENT";
case xsxml::xml_parse_status::status_bad_decl:
return "ERR_BAD_XML_DECLARATION";
case xsxml::xml_parse_status::status_ok:
return "OK"; // should not get here
default:
return "ERR_UNKNOWN";
}
}
class MySAXDelegator : public SAXDelegator
{
public:
MySAXDelegator(const Napi::CallbackInfo *info)
{
_cbInfo = info;
_env = info->Env();
_emit = info->This().As<Napi::Object>().Get("emit").As<Napi::Function>();
}
~MySAXDelegator()
{
_cbInfo = nullptr;
_env = nullptr;
}
void startElement(void *ctx, const char *name, const char **atts)
{
Napi::Object attribs = Napi::Object::New(_env);
while (*atts != nullptr)
{
const char *name = *atts++;
const char *val = *atts++;
attribs.Set(name, val);
}
this->emitEvent("startElement", std::string(name), attribs);
}
void endElement(void *ctx, const char *name, size_t len)
{
this->emitEvent("endElement", std::string(name, len));
}
void textHandler(void *ctx, const char *s, size_t len)
{
this->emitEvent("text", std::string(s, len));
}
void startAttribute(void *ctx, const char *name, size_t nameLen,
const char *value, size_t valueLen)
{
Napi::Object attrib = Napi::Object::New(_env);
attrib.Set(std::string(name, nameLen), std::string(value, valueLen));
this->emitEvent("startAttribute", attrib);
}
void endAttribute(void *ctx) { this->emitEvent("endAttribute"); }
void cdataHandler(void *ctx, const char *s, size_t len)
{
this->emitEvent("cdata", std::string(s, len));
}
void commentHandler(void *ctx, const char *s, size_t len)
{
this->emitEvent("comment", std::string(s, len));
}
void startDocument(void *ctx) { this->emitEvent("startDocument"); }
void endDocument(void *ctx)
{
this->emitEvent("endDocument");
// alias. use whatever suits you.
this->emitEvent("end");
this->emitEvent("finish");
this->emitEvent("done");
}
void doctypeHandler(void *ctx, const char *doctype, size_t len)
{
this->emitEvent("doctype", std::string(doctype, len));
}
void errorHandler(void *ctx, xsxml::xml_parse_status status, char *offset)
{
Napi::Object error = Napi::Object::New(_env);
error.Set("code", ParseStatusToString(status));
error.Set("offset", std::string(offset, 10)); // peak 10 chars
this->emitEvent("error", error);
}
void startDeclAttr(void *ctx, const char *name, size_t nameLen, const char *value, size_t valueLen)
{
Napi::Object declAttr = Napi::Object::New(_env);
declAttr.Set(std::string(name, nameLen), std::string(value, valueLen));
this->emitEvent("startXmlDeclAttr", declAttr);
}
void endDeclAttr(void *ctx)
{
this->emitEvent("endXmlDeclAttr");
}
void xmlDeclarationHandler(void *ctx, const char **attrs)
{
Napi::Object attribs = Napi::Object::New(_env);
while (*attrs != nullptr)
{
const char *name = *attrs++;
const char *val = *attrs++;
attribs.Set(name, val);
}
this->emitEvent("xmlDecl", attribs);
}
void piHandler(void *ctx, const char *target, size_t targetLen,
const char *instruction, size_t instructionLen)
{
Napi::Object pi = Napi::Object::New(_env);
pi.Set("target", std::string(target, targetLen));
pi.Set("instruction", std::string(instruction, instructionLen));
this->emitEvent("processingInstruction", pi);
}
private:
const Napi::CallbackInfo *_cbInfo;
Napi::Env _env = nullptr;
Napi::Function _emit;
void emitEvent(std::string eventName)
{
_emit.Call(_cbInfo->This(), {Napi::String::New(_env, eventName)});
}
void emitEvent(std::string eventName, std::string data)
{
_emit.Call(_cbInfo->This(), {Napi::String::New(_env, eventName),
Napi::String::New(_env, data)});
}
void emitEvent(std::string eventName, Napi::Object obj)
{
_emit.Call(_cbInfo->This(), {Napi::String::New(_env, eventName), obj});
}
void emitEvent(std::string eventName, std::string name, Napi::Object obj)
{
_emit.Call(_cbInfo->This(), {Napi::String::New(_env, eventName),
Napi::String::New(_env, name), obj});
}
};
void SaxParser::Parse(const Napi::CallbackInfo &info)
{
if (info.Length() < 1)
{
throw Napi::Error::New(info.Env(), "Expecting 1 argument.");
}
if (!info[0].IsString() && !info[0].IsBuffer())
{
throw Napi::Error::New(info.Env(),
"The parameter must be a string or buffer.");
}
SAXParser *parser = new SAXParser();
MySAXDelegator *delegator = new MySAXDelegator(&info);
parser->init("UTF-8");
parser->setDelegator(delegator);
if (info[0].IsString())
{
std::string input = info[0].As<Napi::String>().Utf8Value();
const char *xml = input.c_str();
parser->parse(xml, std::strlen(xml));
}
else if (info[0].IsBuffer())
{
Napi::Buffer<char> buffer = info[0].As<Napi::Buffer<char>>();
parser->parse(buffer.Data(), buffer.Length());
}
} | 32.612069 | 103 | 0.620539 | [
"object"
] |
c44a036bb9b1a34cf5237be918ff2dc494c93cd7 | 6,864 | cpp | C++ | src/renderer/DDGIRenderer.cpp | tippesi/Atlas-Engine | 9d135d79e24de0b826ad119b546b26802ca42207 | [
"BSD-3-Clause"
] | 41 | 2020-07-12T13:53:05.000Z | 2022-03-31T14:36:42.000Z | src/renderer/DDGIRenderer.cpp | tippesi/Atlas-Engine | 9d135d79e24de0b826ad119b546b26802ca42207 | [
"BSD-3-Clause"
] | 4 | 2019-12-19T11:36:45.000Z | 2022-03-18T00:23:51.000Z | src/renderer/DDGIRenderer.cpp | tippesi/Atlas-Engine | 9d135d79e24de0b826ad119b546b26802ca42207 | [
"BSD-3-Clause"
] | 4 | 2020-07-26T04:21:42.000Z | 2022-03-08T16:23:46.000Z | #include "DDGIRenderer.h"
#include "helper/GeometryHelper.h"
namespace Atlas {
namespace Renderer {
DDGIRenderer::DDGIRenderer() {
Helper::GeometryHelper::GenerateRectangleVertexArray(vertexArray);
rayHitBuffer = Buffer::Buffer(AE_SHADER_STORAGE_BUFFER, sizeof(vec4),
AE_BUFFER_DYNAMIC_STORAGE);
rayGenShader.AddStage(AE_COMPUTE_STAGE, "ddgi/rayGen.csh");
rayGenShader.Compile();
rayHitShader.AddStage(AE_COMPUTE_STAGE, "ddgi/rayHit.csh");
rayHitShader.Compile();
probeStateShader.AddStage(AE_COMPUTE_STAGE, "ddgi/probeState.csh");
probeStateShader.Compile();
probeUpdateShader.AddStage(AE_COMPUTE_STAGE, "ddgi/probeUpdate.csh");
probeUpdateShader.Compile();
copyEdgeShader.AddStage(AE_VERTEX_STAGE, "ddgi/dummy.vsh");
copyEdgeShader.AddStage(AE_FRAGMENT_STAGE, "ddgi/copyEdge.fsh");
copyEdgeShader.Compile();
}
void DDGIRenderer::Render(Viewport* viewport, RenderTarget* target,
Camera* camera, Scene::Scene* scene) {
}
void DDGIRenderer::TraceAndUpdateProbes(Scene::Scene* scene) {
if (!scene->irradianceVolume)
return;
auto volume = scene->irradianceVolume;
auto& internalVolume = volume->internal;
internalVolume.SwapTextures();
auto totalProbeCount = volume->probeCount.x *
volume->probeCount.y *
volume->probeCount.z;
auto rayCount = volume->rayCount;
auto rayCountInactive = volume->rayCountInactive;
auto totalRayCount = rayCount * totalProbeCount;
if (totalRayCount != rayHitBuffer.GetElementCount()) {
helper.SetRayBufferSize(totalRayCount);
rayHitBuffer.SetSize(totalRayCount);
helper.SetScene(scene, 8);
}
// Currently the BVH structure doesn't support fast rebuilds
//if (scene->HasChanged())
//helper.SetScene(scene, 8);
auto [irradianceArray, momentsArray] = internalVolume.GetCurrentProbes();
auto [lastIrradianceArray, lastMomentsArray] = internalVolume.GetLastProbes();
auto& rayDirBuffer = internalVolume.rayDirBuffer;
auto& rayDirInactiveBuffer = internalVolume.rayDirInactiveBuffer;
auto& probeStateBuffer = internalVolume.probeStateBuffer;
auto& probeStateTemporalBuffer = internalVolume.probeStateTemporalBuffer;
helper.UpdateLights();
probeStateBuffer.BindBase(9);
helper.DispatchRayGen(&rayGenShader, volume->probeCount,
[&]() {
auto theta = acosf(2.0f * float(rand()) / float(RAND_MAX) - 1.0f);
auto phi = glm::two_pi<float>() * float(rand()) / float(RAND_MAX);
auto dir = glm::vec3(
sinf(theta) * cosf(phi),
sinf(theta) * sinf(phi),
cosf(theta)
);
auto epsilon = glm::two_pi<float>() * float(rand()) / float(RAND_MAX);
auto rot = mat3(glm::rotate(epsilon, dir));
rayGenShader.GetUniform("rayCount")->SetValue(rayCount);
rayGenShader.GetUniform("rayCountInactive")->SetValue(rayCountInactive);
rayGenShader.GetUniform("randomRotation")->SetValue(rot);
rayGenShader.GetUniform("volumeMin")->SetValue(volume->aabb.min);
rayGenShader.GetUniform("volumeMax")->SetValue(volume->aabb.max);
rayGenShader.GetUniform("volumeProbeCount")->SetValue(volume->probeCount);
rayGenShader.GetUniform("cellSize")->SetValue(volume->cellSize);
rayDirBuffer.BindBase(4);
rayDirInactiveBuffer.BindBase(5);
}
);
lastIrradianceArray.Bind(GL_TEXTURE12);
lastMomentsArray.Bind(GL_TEXTURE13);
helper.DispatchHitClosest(&rayHitShader,
[&]() {
rayHitShader.GetUniform("seed")->SetValue(float(rand()) / float(RAND_MAX));
rayHitShader.GetUniform("volumeMin")->SetValue(volume->aabb.min);
rayHitShader.GetUniform("volumeMax")->SetValue(volume->aabb.max);
rayHitShader.GetUniform("volumeProbeCount")->SetValue(volume->probeCount);
rayHitShader.GetUniform("volumeBias")->SetValue(volume->bias);
rayHitShader.GetUniform("volumeGamma")->SetValue(volume->gamma);
rayHitShader.GetUniform("cellSize")->SetValue(volume->cellSize);
rayHitShader.GetUniform("volumeIrradianceRes")->SetValue(volume->irrRes);
rayHitShader.GetUniform("volumeMomentsRes")->SetValue(volume->momRes);
// Use this buffer instead of the default writeRays buffer of the helper
rayHitBuffer.BindBase(3);
}
);
rayHitBuffer.BindBase(0);
ivec3 probeCount = volume->probeCount;
// Update the probes
{
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
irradianceArray.Bind(GL_WRITE_ONLY, 0);
momentsArray.Bind(GL_WRITE_ONLY, 1);
probeUpdateShader.Bind();
probeUpdateShader.GetUniform("irrProbeRes")->SetValue(volume->irrRes);
probeUpdateShader.GetUniform("momProbeRes")->SetValue(volume->momRes);
probeUpdateShader.GetUniform("rayCount")->SetValue(rayCount);
probeUpdateShader.GetUniform("rayCountInactive")->SetValue(rayCountInactive);
probeUpdateShader.GetUniform("hysteresis")->SetValue(volume->hysteresis);
probeUpdateShader.GetUniform("cellSize")->SetValue(volume->cellSize);
probeUpdateShader.GetUniform("volumeGamma")->SetValue(volume->gamma);
probeUpdateShader.GetUniform("depthSharpness")->SetValue(volume->sharpness);
glDispatchCompute(probeCount.x, probeCount.y, probeCount.z);
}
// Update the states of the probes
{
probeStateShader.Bind();
probeStateShader.GetUniform("rayCount")->SetValue(rayCount);
probeStateShader.GetUniform("rayCountInactive")->SetValue(rayCountInactive);
probeStateShader.GetUniform("cellLength")->SetValue(glm::length(volume->cellSize));
probeStateShader.GetUniform("cellSize")->SetValue(volume->cellSize);
probeStateTemporalBuffer.BindBase(1);
glDispatchCompute(probeCount.x, probeCount.y, probeCount.z);
}
// Copy the probe edges
{
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
for (int32_t y = 0; y < probeCount.y; y++) {
irradianceFramebuffer.AddComponentTextureArray(GL_COLOR_ATTACHMENT0,
const_cast<Texture::Texture2DArray*>(&irradianceArray), y);
momentsFramebuffer.AddComponentTextureArray(GL_COLOR_ATTACHMENT0,
const_cast<Texture::Texture2DArray*>(&momentsArray), y);
vertexArray.Bind();
glViewport(0, 0, irradianceArray.width, irradianceArray.height);
irradianceFramebuffer.Bind();
copyEdgeShader.Bind();
copyEdgeShader.GetUniform("probeRes")->SetValue(volume->irrRes);
copyEdgeShader.GetUniform("volumeLayer")->SetValue(y);
irradianceArray.Bind(GL_TEXTURE0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glViewport(0, 0, momentsArray.width, momentsArray.height);
momentsFramebuffer.Bind();
copyEdgeShader.Bind();
copyEdgeShader.GetUniform("probeRes")->SetValue(volume->momRes);
copyEdgeShader.GetUniform("volumeLayer")->SetValue(y);
momentsArray.Bind(GL_TEXTURE0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
}
helper.InvalidateRayBuffer();
}
}
} | 32.377358 | 87 | 0.727418 | [
"render"
] |
c44f5b9dde5033c1e8c3824803afe57d7ef20d52 | 4,348 | cxx | C++ | src/persistency/SliceConfigTreeReader.cxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | null | null | null | src/persistency/SliceConfigTreeReader.cxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | null | null | null | src/persistency/SliceConfigTreeReader.cxx | TWLord/DUNEPrismTools | bde52eb1331ac10ba81cdf1bf63488707bfe5496 | [
"MIT"
] | 3 | 2018-01-09T20:57:33.000Z | 2019-11-24T03:48:28.000Z | #include "SliceConfigTreeReader.hxx"
#include "ROOTUtility.hxx"
SliceConfig::SliceConfig(std::string const &inputFile,
std::string const &inputDir) {
dir = inputDir;
if (dir.size() && (dir.back() != '/')) {
dir += "/";
}
LoadTree(inputFile);
}
std::string SliceConfig::TreeName() { return dir + "SliceConfigTree"; }
void SliceConfig::Reset() {
std::fill_n(XRange, 2, 0);
Coeff = 0;
}
void SliceConfig::SetBranchAddresses() {
tree->SetBranchAddress("XRange", &XRange);
tree->SetBranchAddress("Coeff", &Coeff);
}
std::pair<std::vector<double>, std::vector<double>>
SliceConfig::BuildXRangeBinsCoeffs(
std::vector<std::pair<double, double>> const &XRanges, double const *Coeffs,
bool SignFlipX) {
std::vector<double> XRangeBins;
std::vector<double> CoeffVector;
std::cout << "[INFO]: XRange bins: " << std::flush;
XRangeBins.push_back((SignFlipX ? -1 : 1) * XRanges[0].first);
CoeffVector.push_back(Coeffs[0]);
XRangeBins.push_back((SignFlipX ? -1 : 1) * XRanges[0].second);
std::cout << XRangeBins[0] << ", " << XRangeBins[1] << std::flush;
for (size_t i = 1; i < XRanges.size(); ++i) {
// If non-contiguous, must push an empty bit between.
if (fabs(XRangeBins.back() - ((SignFlipX ? -1 : 1) * XRanges[i].first)) >
1E-5) {
CoeffVector.push_back(0);
XRangeBins.push_back((SignFlipX ? -1 : 1) * XRanges[i].first);
std::cout << ", " << XRangeBins.back() << std::flush;
}
CoeffVector.push_back(Coeffs[i]);
XRangeBins.push_back((SignFlipX ? -1 : 1) * XRanges[i].second);
std::cout << ", " << XRangeBins.back() << std::flush;
}
std::cout << std::endl;
if (SignFlipX) {
std::vector<double> XRangeBins_rev;
XRangeBins_rev.resize(XRangeBins.size());
std::vector<double> CoeffVector_rev;
CoeffVector_rev.resize(CoeffVector.size());
size_t ctr = 0;
for (std::vector<double>::reverse_iterator xrb_it = XRangeBins.rbegin();
xrb_it < XRangeBins.rend(); ++xrb_it) {
XRangeBins_rev[ctr++] = (*xrb_it);
}
ctr = 0;
for (std::vector<double>::reverse_iterator cvr_it = CoeffVector.rbegin();
cvr_it < CoeffVector.rend(); ++cvr_it) {
CoeffVector_rev[ctr++] = (*cvr_it);
}
XRangeBins.swap(XRangeBins_rev);
CoeffVector.swap(CoeffVector_rev);
}
return std::make_pair(XRangeBins, CoeffVector);
}
void SliceConfig::ReadTree() {
if (!tree) {
std::cout << "[ERROR]: SliceConfig attempted to read input tree "
"but it was not initialized. "
<< std::endl;
throw;
}
XRanges.clear();
Coeffs.clear();
XRangeBins.push_back(XRange[1]);
std::cout << XRangeBins[0] << ", " << XRangeBins[1] << std::flush;
for (Long64_t i = 0; i < tree->GetEntries(); ++i) {
tree->GetEntry(i);
XRanges.push_back(std::make_pair(XRange[0], XRange[1]));
Coeffs.push_back(Coeff);
}
std::pair<std::vector<double>, std::vector<double>> XRBC =
BuildXRangeBinsCoeffs(XRanges, Coeffs.data());
XRangeBins = XRBC.first;
BinCoeffsVector = XRBC.second;
}
std::vector<std::pair<double, double>> SliceConfig::GetXRanges() {
if (!XRanges.size()) {
ReadTree();
}
return XRanges;
}
std::vector<double> SliceConfig::GetCoeffs() {
if (!Coeffs.size()) {
ReadTree();
}
return Coeffs;
}
std::vector<double> SliceConfig::GetXRangeBins() {
if (!XRangeBins.size()) {
ReadTree();
}
return XRangeBins;
}
std::vector<double> SliceConfig::GetBinCoeffs() {
if (!BinCoeffsVector.size()) {
ReadTree();
}
return BinCoeffsVector;
}
TH1D *SliceConfig::BuildSliceBinningHelper(std::string const &histName) {
TH1D *BinningHelper =
new TH1D(histName.c_str(), "", (GetXRangeBins().size() - 1),
GetXRangeBins().data());
BinningHelper->SetDirectory(nullptr);
for (size_t bin_it = 1; bin_it < GetXRangeBins().size(); ++bin_it) {
BinningHelper->SetBinContent(bin_it, GetCoeffs()[bin_it - 1]);
}
return BinningHelper;
}
SliceConfig *SliceConfig::MakeTreeWriter() {
SliceConfig *fdr = new SliceConfig();
fdr->tree = new TTree(fdr->TreeName().c_str(), "");
fdr->TreeOwned = false;
fdr->tree->Branch("XRange", &fdr->XRange, "XRange[2]/D");
fdr->tree->Branch("Coeff", &fdr->Coeff, "Coeff/D");
fdr->Reset();
return fdr;
}
SliceConfig::~SliceConfig() {}
| 27.694268 | 80 | 0.630865 | [
"vector"
] |
c451e20bea5083b29c172d9e8231fd7802bb8545 | 45,955 | cc | C++ | src/backup_volume_test.cc | darkstar62/tribble-backup | 4a50a641684b25a6ff9c2850cad2ede0fa487a00 | [
"BSD-3-Clause"
] | null | null | null | src/backup_volume_test.cc | darkstar62/tribble-backup | 4a50a641684b25a6ff9c2850cad2ede0fa487a00 | [
"BSD-3-Clause"
] | null | null | null | src/backup_volume_test.cc | darkstar62/tribble-backup | 4a50a641684b25a6ff9c2850cad2ede0fa487a00 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2013, All Rights Reserved.
// Author: Cory Maccarrone <darkstar6262@gmail.com>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "src/backup_volume.h"
#include "src/callback.h"
#include "src/common.h"
#include "src/fileset.h"
#include "src/fake_file.h"
#include "src/mock_encoder.h"
#include "src/mock_md5_generator.h"
#include "src/status.h"
#include "glog/logging.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using std::make_pair;
using std::map;
using std::string;
using std::unique_ptr;
using std::vector;
using testing::_;
using testing::DoAll;
using testing::InSequence;
using testing::Mock;
using testing::NotNull;
using testing::Return;
using testing::SetArrayArgument;
using testing::SetArgPointee;
namespace backup2 {
#ifdef _WIN32
static const char kTestGenericFilename[] = "C:/foo/bar";
static const char kTestProperFilename[] = "C:\\foo\\bar";
#else
static const char kTestGenericFilename[] = "/foo/bar";
static const char kTestProperFilename[] = "/foo/bar";
#endif // _WIN32
// Action to copy bytes into a void* field.
ACTION_P2(SetCharStringValue, val, length) {
memcpy(arg0, val, length);
}
// Matcher to compare binary data.
MATCHER_P2(BinaryDataEq, val, length,
string("Binary data is equal to ") + testing::PrintToString(*val)) {
return memcmp(arg, val, length) == 0;
}
class BackupVolumeTest : public testing::Test {
public:
static const char kGoodVersion[9];
static const int kBackupDescriptor1Offset = 0x12345;
};
const char BackupVolumeTest::kGoodVersion[9] = "BKP_0000";
TEST_F(BackupVolumeTest, ShortVersionHeader) {
FakeFile* file = new FakeFile;
file->Write("ABCD12", 6);
BackupVolume volume(file);
Status retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusShortRead, retval.code());
}
TEST_F(BackupVolumeTest, InvalidVersionHeader) {
FakeFile* file = new FakeFile;
file->Write("ABCD1234", 8);
BackupVolume volume(file);
Status retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
}
TEST_F(BackupVolumeTest, SuccessfulInit) {
// This test verifies that a successful init can be accomplished with valid
// input. We also test error conditions as we're building the file. It
// doesn't catch everything, but it does get a lot of it.
FakeFile* file = new FakeFile;
BackupVolume volume(file);
// Version string.
file->Write(kGoodVersion, 8);
Status retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusShortRead, retval.code());
// Create a ChunkHeader.
ChunkHeader chunk_header;
chunk_header.encoded_size = 16;
chunk_header.unencoded_size = 16;
chunk_header.encoding_type = kEncodingTypeRaw;
file->Write(&chunk_header, sizeof(chunk_header));
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
// Create the chunk.
file->Write("1234567890123456", 16);
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
// Create backup descriptor 1.
uint64_t desc1_offset;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 1;
file->Write(&descriptor1, sizeof(descriptor1));
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
// Create a descriptor 1 chunk.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = 8;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
// Create a descriptor 1 label.
string label_name = "foo bar yo";
BackupDescriptor1Label descriptor1_label;
descriptor1_label.id = 0x123;
descriptor1_label.name_size = label_name.size();
file->Write(&descriptor1_label, sizeof(descriptor1_label));
file->Write(&label_name.at(0), label_name.size());
// Create a descriptor 2.
BackupDescriptor2 descriptor2;
descriptor2.unencoded_size = 16;
descriptor2.encoded_size = 16;
descriptor2.num_files = 2;
descriptor2.description_size = 6;
descriptor2.label_id = 0x123;
file->Write(&descriptor2, sizeof(descriptor2));
file->Write("backup", 6);
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
// Create a BackupFile and BackupChunk.
BackupFile backup_file;
backup_file.file_size = 16;
backup_file.num_chunks = 1;
backup_file.filename_size = 7;
file->Write(&backup_file, sizeof(backup_file));
file->Write("/foobar", 7);
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
FileChunk file_chunk;
file_chunk.md5sum = chunk_header.md5sum;
file_chunk.volume_num = 0;
file_chunk.chunk_offset = 0;
file_chunk.unencoded_size = 16;
file->Write(&file_chunk, sizeof(file_chunk));
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
// Create another BackupFile, this one a symlink.
string symlink_filename = "/blah";
string symlink_target = "/dfjkhdfkjhsd";
BackupFile symlink_file;
symlink_file.file_size = 0;
symlink_file.num_chunks = 0;
symlink_file.filename_size = symlink_filename.size();
symlink_file.symlink_target_size = symlink_target.size();
file->Write(&symlink_file, sizeof(symlink_file));
file->Write(&symlink_filename.at(0), symlink_filename.size());
file->Write(&symlink_target.at(0), symlink_target.size());
retval = volume.Init();
EXPECT_FALSE(retval.ok());
EXPECT_EQ(kStatusCorruptBackup, retval.code());
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = true;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Attempt an init.
retval = volume.Init();
EXPECT_TRUE(retval.ok());
}
TEST_F(BackupVolumeTest, CreateAndClose) {
// This test verifies that a create and close results in a valid (but empty)
// backup volume.
FakeFile* file = new FakeFile;
// In an empty file, we have the version, backup 1 descriptor, and backup
// header only. Our file will have chunks and descriptor 1 chunk headers too.
// Version string.
file->Write(kGoodVersion, 8);
// Create backup descriptor 1.
uint64_t desc1_offset;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 0;
descriptor1.total_labels = 0;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = false;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
file->MakeCurrentDataExpectedResult();
// Create it as a backup would -- Init first, then on failure, Create.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_FALSE(volume.Init().ok());
EXPECT_TRUE(volume.Create(options).ok());
EXPECT_TRUE(volume.Close().ok());
// Validate the contents.
EXPECT_TRUE(file->CompareExpected());
}
TEST_F(BackupVolumeTest, CreateAddChunkAndClose) {
// This test verifies that a create, add-chunk, and close results in a valid
// backup volume without a descriptor 2.
FakeFile* file = new FakeFile;
// In an empty file, we have the version, backup 1 descriptor, and backup
// header only.
// Version string.
file->Write(kGoodVersion, 8);
// Create a ChunkHeader and chunk.
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
file->Write(&chunk_header, sizeof(chunk_header));
file->Write(&chunk_data.at(0), chunk_data.size());
// Create backup descriptor 1.
uint64_t desc1_offset;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 0;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunk.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = 8;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = false;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
file->MakeCurrentDataExpectedResult();
// Create it as a backup would -- Init first, then on failure, Create.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_FALSE(volume.Init().ok());
EXPECT_TRUE(volume.Create(options).ok());
// TODO(darkstar62): This should be a FakeFileEntry.
BackupFile* entry_metadata = new BackupFile;
FileEntry file_entry("/foo", entry_metadata);
uint64_t volume_offset = 0;
EXPECT_TRUE(volume.WriteChunk(chunk_header.md5sum, chunk_data,
chunk_header.encoded_size,
chunk_header.encoding_type,
&volume_offset).ok());
EXPECT_EQ(descriptor1_chunk.offset, volume_offset);
EXPECT_TRUE(volume.Close().ok());
// Validate the contents.
EXPECT_TRUE(file->CompareExpected());
}
TEST_F(BackupVolumeTest, CreateAddChunkAndCancel) {
// This test verifies that a create, add-chunk, and cancel results in a valid
// backup volume without a descriptor 2 and indicating canceled status.
FakeFile* file = new FakeFile;
// In an empty file, we have the version, backup 1 descriptor, and backup
// header only.
// Version string.
file->Write(kGoodVersion, 8);
// Create a ChunkHeader and chunk.
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
file->Write(&chunk_header, sizeof(chunk_header));
file->Write(&chunk_data.at(0), chunk_data.size());
// Create backup descriptor 1.
uint64_t desc1_offset;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 0;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunk.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = 8;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = false;
header.cancelled = true;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
file->MakeCurrentDataExpectedResult();
// Create it as a backup would -- Init first, then on failure, Create.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_FALSE(volume.Init().ok());
EXPECT_TRUE(volume.Create(options).ok());
// TODO(darkstar62): This should be a FakeFileEntry.
BackupFile* entry_metadata = new BackupFile;
FileEntry file_entry("/foo", entry_metadata);
uint64_t volume_offset = 0;
EXPECT_TRUE(volume.WriteChunk(chunk_header.md5sum, chunk_data,
chunk_header.encoded_size,
chunk_header.encoding_type,
&volume_offset).ok());
EXPECT_EQ(descriptor1_chunk.offset, volume_offset);
EXPECT_TRUE(volume.Cancel().ok());
// Validate the contents.
EXPECT_TRUE(file->CompareExpected());
}
TEST_F(BackupVolumeTest, CreateAddChunkAndCloseWithFileSet) {
// This test verifies that a create, add-chunk, and close results in a valid
// backup volume with a descriptor 2.
FakeFile* file = new FakeFile;
// In an empty file, we have the version, backup 1 descriptor, and backup
// header only.
// Version string.
file->Write(kGoodVersion, 8);
// Create a ChunkHeader and chunk.
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
file->Write(&chunk_header, sizeof(chunk_header));
file->Write(&chunk_data.at(0), chunk_data.size());
// Create backup descriptor 1.
uint64_t desc1_offset;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 2;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunk.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = 8;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
// Create a descriptor 1 label. We're going to specify 0 as the label ID, and
// the system should assign it. Seeing that there are no other labels in the
// system (and the default label is reserved), it should assign it 2.
string label_name1 = "Default";
BackupDescriptor1Label descriptor1_label1;
descriptor1_label1.id = 0x1;
descriptor1_label1.name_size = label_name1.size();
descriptor1_label1.last_backup_offset = 0;
descriptor1_label1.last_backup_volume_number = 0;
file->Write(&descriptor1_label1, sizeof(descriptor1_label1));
file->Write(&label_name1.at(0), label_name1.size());
// Create a descriptor 1 label. We're going to specify 0 as the label ID, and
// the system should assign it. Seeing that there are no other labels in the
// system (and the default label is reserved), it should assign it 2.
string label_name2 = "foo bar yo";
BackupDescriptor1Label descriptor1_label2;
descriptor1_label2.id = 0x2;
descriptor1_label2.name_size = label_name2.size();
uint64_t file_size = 0;
EXPECT_TRUE(file->size(&file_size).ok());
descriptor1_label2.last_backup_offset =
file_size + sizeof(descriptor1_label2) + label_name2.size();
descriptor1_label2.last_backup_volume_number = 0;
file->Write(&descriptor1_label2, sizeof(descriptor1_label2));
file->Write(&label_name2.at(0), label_name2.size());
// Create the descriptor 2.
string description = "backup";
BackupDescriptor2 descriptor2;
descriptor2.previous_backup_offset = 0;
descriptor2.previous_backup_volume_number = 0;
descriptor2.parent_backup_offset = 0;
descriptor2.parent_backup_volume_number = 0;
descriptor2.backup_type = kBackupTypeFull;
descriptor2.num_files = 1;
descriptor2.description_size = 6;
descriptor2.label_id = descriptor1_label2.id;
descriptor2.backup_date = 1234567;
descriptor2.unencoded_size = chunk_data.size();
file->Write(&descriptor2, sizeof(descriptor2));
file->Write(&description.at(0), description.size());
// Create a BackupFile, and a chunk to go with it.
string filename = kTestGenericFilename;
BackupFile backup_file;
backup_file.file_size = chunk_data.size();
backup_file.file_type = BackupFile::kFileTypeRegularFile;
backup_file.num_chunks = 1;
backup_file.filename_size = filename.size();
file->Write(&backup_file, sizeof(backup_file));
file->Write(&filename.at(0), filename.size());
// Create a FileChunk.
FileChunk file_chunk;
file_chunk.md5sum = chunk_header.md5sum;
file_chunk.volume_num = 0;
file_chunk.chunk_offset = 0;
file_chunk.unencoded_size = chunk_data.size();
file->Write(&file_chunk, sizeof(file_chunk));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = true;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
file->MakeCurrentDataExpectedResult();
// Create it as a backup would -- Init first, then on failure, Create.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_FALSE(volume.Init().ok());
EXPECT_TRUE(volume.Create(options).ok());
BackupFile* entry_metadata = new BackupFile;
entry_metadata->file_size = chunk_data.size();
entry_metadata->file_type = BackupFile::kFileTypeRegularFile;
FileEntry* file_entry = new FileEntry(kTestGenericFilename, entry_metadata);
file_entry->AddChunk(file_chunk);
FileSet file_set;
file_set.AddFile(file_entry);
file_set.set_description(description);
file_set.set_backup_type(kBackupTypeFull);
file_set.set_previous_backup_volume(0);
file_set.set_previous_backup_offset(0);
file_set.set_use_default_label(false);
file_set.set_label_id(0);
file_set.set_label_name(label_name2);
file_set.set_date(descriptor2.backup_date);
LOG(INFO) << entry_metadata->filename_size;
uint64_t volume_offset = 0;
EXPECT_TRUE(volume.WriteChunk(chunk_header.md5sum, chunk_data,
chunk_header.encoded_size,
chunk_header.encoding_type,
&volume_offset).ok());
EXPECT_EQ(descriptor1_chunk.offset, volume_offset);
LabelMap label_map;
Label new_label(1, "Default");
label_map.insert(make_pair(new_label.id(), new_label));
EXPECT_TRUE(volume.CloseWithFileSetAndLabels(&file_set, label_map).ok());
// Validate the contents.
EXPECT_TRUE(file->CompareExpected());
}
TEST_F(BackupVolumeTest, CreateAddChunkAndCloseWithFileSetSymlink) {
// This test verifies that a create, and close results in a valid
// backup volume with a descriptor 2. This test adds a symlink.
FakeFile* file = new FakeFile;
// In an empty file, we have the version, backup 1 descriptor, and backup
// header only.
// Version string.
file->Write(kGoodVersion, 8);
// Create backup descriptor 1.
uint64_t desc1_offset;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 0;
descriptor1.total_labels = 2;
file->Write(&descriptor1, sizeof(descriptor1));
// Create a descriptor 1 label. We're going to specify 0 as the label ID, and
// the system should assign it. Seeing that there are no other labels in the
// system (and the default label is reserved), it should assign it 2.
string label_name1 = "Default";
BackupDescriptor1Label descriptor1_label1;
descriptor1_label1.id = 0x1;
descriptor1_label1.name_size = label_name1.size();
descriptor1_label1.last_backup_offset = 0;
descriptor1_label1.last_backup_volume_number = 0;
file->Write(&descriptor1_label1, sizeof(descriptor1_label1));
file->Write(&label_name1.at(0), label_name1.size());
// Create a descriptor 1 label. We're going to specify 0 as the label ID, and
// the system should assign it. Seeing that there are no other labels in the
// system (and the default label is reserved), it should assign it 2.
string label_name2 = "foo bar yo";
BackupDescriptor1Label descriptor1_label2;
descriptor1_label2.id = 0x2;
descriptor1_label2.name_size = label_name2.size();
uint64_t file_size = 0;
EXPECT_TRUE(file->size(&file_size).ok());
descriptor1_label2.last_backup_offset =
file_size + sizeof(descriptor1_label2) + label_name2.size();
descriptor1_label2.last_backup_volume_number = 0;
file->Write(&descriptor1_label2, sizeof(descriptor1_label2));
file->Write(&label_name2.at(0), label_name2.size());
// Create the descriptor 2.
string description = "backup";
BackupDescriptor2 descriptor2;
descriptor2.previous_backup_offset = 0;
descriptor2.previous_backup_volume_number = 0;
descriptor2.parent_backup_offset = 0;
descriptor2.parent_backup_volume_number = 0;
descriptor2.backup_type = kBackupTypeFull;
descriptor2.num_files = 1;
descriptor2.description_size = 6;
descriptor2.label_id = descriptor1_label2.id;
descriptor2.backup_date = 1234567;
descriptor2.unencoded_size = 0;
file->Write(&descriptor2, sizeof(descriptor2));
file->Write(&description.at(0), description.size());
// Create a BackupFile, and a chunk to go with it.
string filename = kTestGenericFilename;
string symlink = "/foo/bar/yo";
BackupFile backup_file;
backup_file.file_size = 0;
backup_file.file_type = BackupFile::kFileTypeSymlink;
backup_file.num_chunks = 0;
backup_file.filename_size = filename.size();
backup_file.symlink_target_size = symlink.size();
file->Write(&backup_file, sizeof(backup_file));
file->Write(&filename.at(0), filename.size());
file->Write(&symlink.at(0), symlink.size());
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = true;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
file->MakeCurrentDataExpectedResult();
// Create it as a backup would -- Init first, then on failure, Create.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_FALSE(volume.Init().ok());
EXPECT_TRUE(volume.Create(options).ok());
BackupFile* entry_metadata = new BackupFile;
entry_metadata->file_size = 0;
entry_metadata->file_type = BackupFile::kFileTypeSymlink;
FileEntry* file_entry = new FileEntry(kTestGenericFilename, entry_metadata);
file_entry->set_symlink_target(symlink);
FileSet file_set;
file_set.AddFile(file_entry);
file_set.set_description(description);
file_set.set_backup_type(kBackupTypeFull);
file_set.set_previous_backup_volume(0);
file_set.set_previous_backup_offset(0);
file_set.set_use_default_label(false);
file_set.set_label_id(0);
file_set.set_label_name(label_name2);
file_set.set_date(descriptor2.backup_date);
LabelMap label_map;
Label new_label(1, "Default");
label_map.insert(make_pair(new_label.id(), new_label));
EXPECT_TRUE(volume.CloseWithFileSetAndLabels(&file_set, label_map).ok());
// Validate the contents.
EXPECT_TRUE(file->CompareExpected());
}
TEST_F(BackupVolumeTest, CreateAddChunkAndCloseWithFileSetRenameLabel1) {
// This test verifies that a create, add-chunk, and close results in a valid
// backup volume with a descriptor 2. This test also verifies renaming label
// 1 works correctly.
FakeFile* file = new FakeFile;
// In an empty file, we have the version, backup 1 descriptor, and backup
// header only.
// Version string.
file->Write(kGoodVersion, 8);
// Create a ChunkHeader and chunk.
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
file->Write(&chunk_header, sizeof(chunk_header));
file->Write(&chunk_data.at(0), chunk_data.size());
// Create backup descriptor 1.
uint64_t desc1_offset;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 1;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunk.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = 8;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
// Create a descriptor 1 label. This should test renaming label 1, whose name
// is "Default" by default.
string label_name1 = "Some other name";
BackupDescriptor1Label descriptor1_label1;
descriptor1_label1.id = 0x1;
descriptor1_label1.name_size = label_name1.size();
uint64_t file_size = 0;
EXPECT_TRUE(file->size(&file_size).ok());
descriptor1_label1.last_backup_offset =
file_size + sizeof(descriptor1_label1) + label_name1.size();
descriptor1_label1.last_backup_volume_number = 0;
file->Write(&descriptor1_label1, sizeof(descriptor1_label1));
file->Write(&label_name1.at(0), label_name1.size());
// Create the descriptor 2.
string description = "backup";
BackupDescriptor2 descriptor2;
descriptor2.previous_backup_offset = 0;
descriptor2.previous_backup_volume_number = 0;
descriptor2.parent_backup_offset = 0;
descriptor2.parent_backup_volume_number = 0;
descriptor2.backup_type = kBackupTypeFull;
descriptor2.num_files = 1;
descriptor2.description_size = 6;
descriptor2.label_id = descriptor1_label1.id;
descriptor2.backup_date = 1978346;
descriptor2.unencoded_size = chunk_data.size();
file->Write(&descriptor2, sizeof(descriptor2));
file->Write(&description.at(0), description.size());
// Create a BackupFile, and a chunk to go with it.
string filename = kTestGenericFilename;
BackupFile backup_file;
backup_file.file_size = chunk_data.size();
backup_file.file_type = BackupFile::kFileTypeRegularFile;
backup_file.num_chunks = 1;
backup_file.filename_size = filename.size();
file->Write(&backup_file, sizeof(backup_file));
file->Write(&filename.at(0), filename.size());
// Create a FileChunk.
FileChunk file_chunk;
file_chunk.md5sum = chunk_header.md5sum;
file_chunk.volume_num = 0;
file_chunk.chunk_offset = 0;
file_chunk.unencoded_size = chunk_data.size();
file->Write(&file_chunk, sizeof(file_chunk));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = true;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
file->MakeCurrentDataExpectedResult();
// Create it as a backup would -- Init first, then on failure, Create.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_FALSE(volume.Init().ok());
EXPECT_TRUE(volume.Create(options).ok());
BackupFile* entry_metadata = new BackupFile;
entry_metadata->file_size = chunk_data.size();
entry_metadata->file_type = BackupFile::kFileTypeRegularFile;
FileEntry* file_entry = new FileEntry(kTestGenericFilename, entry_metadata);
file_entry->AddChunk(file_chunk);
FileSet file_set;
file_set.AddFile(file_entry);
file_set.set_description(description);
file_set.set_backup_type(kBackupTypeFull);
file_set.set_previous_backup_volume(0);
file_set.set_previous_backup_offset(0);
file_set.set_use_default_label(false);
file_set.set_label_id(1);
file_set.set_label_name(label_name1);
file_set.set_date(descriptor2.backup_date);
LOG(INFO) << entry_metadata->filename_size;
uint64_t volume_offset = 0;
EXPECT_TRUE(volume.WriteChunk(chunk_header.md5sum, chunk_data,
chunk_header.encoded_size,
chunk_header.encoding_type,
&volume_offset).ok());
EXPECT_EQ(descriptor1_chunk.offset, volume_offset);
LabelMap label_map;
Label new_label(1, "Default");
label_map.insert(make_pair(new_label.id(), new_label));
EXPECT_TRUE(volume.CloseWithFileSetAndLabels(&file_set, label_map).ok());
// Validate the contents.
EXPECT_TRUE(file->CompareExpected());
}
TEST_F(BackupVolumeTest, CreateAddChunkAndCloseWithFileSetAndLabels) {
// This test verifies that a create, add-chunk, and close results in a valid
// backup volume with a descriptor 2. For this test, additional labels are
// added at the end.
FakeFile* file = new FakeFile;
// In an empty file, we have the version, backup 1 descriptor, and backup
// header only.
// Version string.
file->Write(kGoodVersion, 8);
// Create a ChunkHeader and chunk.
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
file->Write(&chunk_header, sizeof(chunk_header));
file->Write(&chunk_data.at(0), chunk_data.size());
// Create backup descriptor 1.
uint64_t desc1_offset = 0;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 2;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunk.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = 8;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
// Create a descriptor 1 label. We're going to specify 0 as the label ID, and
// the system should assign it. Seeing that there are no other labels in the
// system (and the default label is reserved), it should assign it 2.
string label_name1 = "Not Default";
string label_name2 = "foo bar yo";
BackupDescriptor1Label descriptor1_label1;
descriptor1_label1.id = 0x1;
descriptor1_label1.name_size = label_name1.size();
uint64_t file_size = 0;
EXPECT_TRUE(file->size(&file_size).ok());
descriptor1_label1.last_backup_offset =
file_size + sizeof(descriptor1_label1) * 2 + label_name1.size() +
label_name2.size();
descriptor1_label1.last_backup_volume_number = 0;
file->Write(&descriptor1_label1, sizeof(descriptor1_label1));
file->Write(&label_name1.at(0), label_name1.size());
// Create a descriptor 1 label. We're going to specify 0 as the label ID, and
// the system should assign it. Seeing that there are no other labels in the
// system (and the default label is reserved), it should assign it 2.
BackupDescriptor1Label descriptor1_label2;
descriptor1_label2.id = 0x2;
descriptor1_label2.name_size = label_name2.size();
descriptor1_label2.last_backup_offset = 0;
descriptor1_label2.last_backup_volume_number = 0;
file->Write(&descriptor1_label2, sizeof(descriptor1_label2));
file->Write(&label_name2.at(0), label_name2.size());
// Create the descriptor 2.
string description = "backup";
BackupDescriptor2 descriptor2;
descriptor2.previous_backup_offset = 0;
descriptor2.previous_backup_volume_number = 0;
descriptor2.parent_backup_offset = 0;
descriptor2.parent_backup_volume_number = 0;
descriptor2.backup_type = kBackupTypeFull;
descriptor2.num_files = 1;
descriptor2.description_size = 6;
descriptor2.label_id = descriptor1_label1.id;
descriptor2.backup_date = 983247;
descriptor2.unencoded_size = chunk_data.size();
file->Write(&descriptor2, sizeof(descriptor2));
file->Write(&description.at(0), description.size());
// Create a BackupFile, and a chunk to go with it.
string filename = kTestGenericFilename;
BackupFile backup_file;
backup_file.file_size = chunk_data.size();
backup_file.file_type = BackupFile::kFileTypeRegularFile;
backup_file.num_chunks = 1;
backup_file.filename_size = filename.size();
file->Write(&backup_file, sizeof(backup_file));
file->Write(&filename.at(0), filename.size());
// Create a FileChunk.
FileChunk file_chunk;
file_chunk.md5sum = chunk_header.md5sum;
file_chunk.volume_num = 0;
file_chunk.chunk_offset = 0;
file_chunk.unencoded_size = chunk_data.size();
file->Write(&file_chunk, sizeof(file_chunk));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = true;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
file->MakeCurrentDataExpectedResult();
// Create it as a backup would -- Init first, then on failure, Create.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_FALSE(volume.Init().ok());
EXPECT_TRUE(volume.Create(options).ok());
BackupFile* entry_metadata = new BackupFile;
entry_metadata->file_size = chunk_data.size();
entry_metadata->file_type = BackupFile::kFileTypeRegularFile;
FileEntry* file_entry = new FileEntry(kTestGenericFilename, entry_metadata);
file_entry->AddChunk(file_chunk);
FileSet file_set;
file_set.AddFile(file_entry);
file_set.set_description(description);
file_set.set_backup_type(kBackupTypeFull);
file_set.set_previous_backup_volume(0);
file_set.set_previous_backup_offset(0);
file_set.set_use_default_label(true);
file_set.set_label_id(12334); // Some values that shouldn't be used.
file_set.set_label_name("Ishcabibble");
file_set.set_date(descriptor2.backup_date);
LOG(INFO) << entry_metadata->filename_size;
uint64_t volume_offset = 0;
EXPECT_TRUE(volume.WriteChunk(chunk_header.md5sum, chunk_data,
chunk_header.encoded_size,
chunk_header.encoding_type,
&volume_offset).ok());
EXPECT_EQ(descriptor1_chunk.offset, volume_offset);
// Carry forward two labels, but change the name of the first. It should come
// out unchanged.
LabelMap label_map;
Label default_label(1, label_name1);
label_map.insert(make_pair(default_label.id(), default_label));
Label new_label(descriptor1_label2.id, label_name2);
new_label.set_last_offset(descriptor1_label2.last_backup_offset);
new_label.set_last_volume(
descriptor1_label2.last_backup_volume_number);
label_map.insert(make_pair(new_label.id(), new_label));
EXPECT_TRUE(volume.CloseWithFileSetAndLabels(&file_set, label_map).ok());
// Validate the contents.
EXPECT_TRUE(file->CompareExpected());
}
TEST_F(BackupVolumeTest, ReadChunks) {
// This test attempts to read several chunks from the file, some compressed,
// some not.
FakeFile* file = new FakeFile;
// Build up our fake file.
// Version string.
file->Write(kGoodVersion, 8);
// Create a ChunkHeader and chunk. This one is not compressed.
uint64_t chunk1_offset = 0;
EXPECT_TRUE(file->size(&chunk1_offset).ok());
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
file->Write(&chunk_header, sizeof(chunk_header));
file->Write(&chunk_data.at(0), chunk_data.size());
// Create a ChunkHeader and chunk. This one is compressed.
uint64_t chunk2_offset = 0;
EXPECT_TRUE(file->size(&chunk2_offset).ok());
string chunk_data2 = "1234567890123456";
string encoded_data2 = "ABC123";
ChunkHeader chunk_header2;
chunk_header2.encoded_size = encoded_data2.size();
chunk_header2.unencoded_size = chunk_data2.size();
chunk_header2.encoding_type = kEncodingTypeZlib;
chunk_header2.md5sum.hi = 456;
chunk_header2.md5sum.lo = 789;
file->Write(&chunk_header2, sizeof(chunk_header2));
file->Write(&encoded_data2.at(0), encoded_data2.size());
// Create backup descriptor 1.
uint64_t desc1_offset = 0;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 2;
descriptor1.total_labels = 1;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunks.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = chunk1_offset;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
BackupDescriptor1Chunk descriptor1_chunk2;
descriptor1_chunk2.md5sum = chunk_header2.md5sum;
descriptor1_chunk2.offset = chunk2_offset;
file->Write(&descriptor1_chunk2, sizeof(descriptor1_chunk2));
// Create a descriptor 1 label.
string label_name = "foo bar yo";
BackupDescriptor1Label descriptor1_label;
descriptor1_label.id = 0x123;
descriptor1_label.name_size = label_name.size();
file->Write(&descriptor1_label, sizeof(descriptor1_label));
file->Write(&label_name.at(0), label_name.size());
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = false;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_TRUE(volume.Init().ok());
FileChunk lookup_chunk1;
lookup_chunk1.md5sum.hi = 123;
lookup_chunk1.md5sum.lo = 456;
lookup_chunk1.volume_num = 0;
lookup_chunk1.chunk_offset = 0;
lookup_chunk1.unencoded_size = chunk_data.size();
FileChunk lookup_chunk2;
lookup_chunk2.md5sum.hi = 456;
lookup_chunk2.md5sum.lo = 789;
lookup_chunk2.volume_num = 0;
lookup_chunk2.chunk_offset = 16;
lookup_chunk2.unencoded_size = chunk_data2.size();
string read_chunk1;
EncodingType encoding_type1;
EXPECT_TRUE(volume.ReadChunk(lookup_chunk1, &read_chunk1,
&encoding_type1).ok());
EXPECT_EQ(chunk_data, read_chunk1);
EXPECT_EQ(chunk_header.encoding_type, encoding_type1);
string read_chunk2;
EncodingType encoding_type2;
EXPECT_TRUE(volume.ReadChunk(lookup_chunk2, &read_chunk2,
&encoding_type2).ok());
EXPECT_EQ(encoded_data2, read_chunk2);
EXPECT_EQ(chunk_header2.encoding_type, encoding_type2);
// Validate the labels too. We should only have 1, as this backup set was
// never written to with label 1.
LabelMap labels;
volume.GetLabels(&labels);
EXPECT_EQ(1, labels.size());
auto label_iter = labels.find(descriptor1_label.id);
EXPECT_NE(labels.end(), label_iter);
EXPECT_EQ(descriptor1_label.id, label_iter->first);
EXPECT_EQ(label_name, label_iter->second.name());
}
TEST_F(BackupVolumeTest, ReadBackupSets) {
// This test attempts to read several backup sets from the file.
FakeFile* file = new FakeFile;
// Build up our fake file.
string label1_name = "foo bar blah";
string label2_name = "another label";
uint64_t label1_id = 0x123;
// Version string.
file->Write(kGoodVersion, 8);
// Create a ChunkHeader and chunk. This one is not compressed.
uint64_t chunk1_offset = 0;
EXPECT_TRUE(file->size(&chunk1_offset).ok());
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
file->Write(&chunk_header, sizeof(chunk_header));
file->Write(&chunk_data.at(0), chunk_data.size());
// Create backup descriptor 1.
uint64_t desc1_offset = 0;
EXPECT_TRUE(file->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 1;
file->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunks.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = chunk1_offset;
file->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
// Create a descriptor 1 label.
BackupDescriptor1Label descriptor1_label;
descriptor1_label.id = label1_id;
descriptor1_label.name_size = label1_name.size();
file->Write(&descriptor1_label, sizeof(descriptor1_label));
file->Write(&label1_name.at(0), label1_name.size());
// Create the descriptor 2.
string description = "backup";
BackupDescriptor2 descriptor2;
descriptor2.previous_backup_offset = 0;
descriptor2.previous_backup_volume_number = 0;
descriptor2.backup_type = kBackupTypeFull;
descriptor2.num_files = 1;
descriptor2.label_id = label1_id;
descriptor2.description_size = description.size();
descriptor2.unencoded_size = chunk_data.size();
descriptor2.backup_date = 12345;
file->Write(&descriptor2, sizeof(descriptor2));
file->Write(&description.at(0), description.size());
// Create a BackupFile, and a chunk to go with it.
string filename = kTestGenericFilename;
BackupFile backup_file;
backup_file.file_size = chunk_data.size();
backup_file.num_chunks = 1;
backup_file.filename_size = filename.size();
file->Write(&backup_file, sizeof(backup_file));
file->Write(&filename.at(0), filename.size());
// Create a FileChunk.
FileChunk file_chunk;
file_chunk.md5sum = chunk_header.md5sum;
file_chunk.volume_num = 0;
file_chunk.chunk_offset = 0;
file_chunk.unencoded_size = chunk_data.size();
file->Write(&file_chunk, sizeof(file_chunk));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = true;
header.cancelled = false;
header.volume_number = 0;
file->Write(&header, sizeof(BackupDescriptorHeader));
// Reset for the test.
BackupVolume volume(file);
ConfigOptions options;
EXPECT_TRUE(volume.Init().ok());
int64_t next_volume = 0;
StatusOr<FileSet*> test_file_set = volume.LoadFileSet(&next_volume);
EXPECT_TRUE(test_file_set.ok()) << test_file_set.status().ToString();
EXPECT_EQ(-1, next_volume);
// Check the backup.
FileSet* file_set = test_file_set.value();
ASSERT_THAT(file_set, NotNull());
EXPECT_EQ("backup", file_set->description());
EXPECT_EQ(1, file_set->num_files());
EXPECT_EQ(kTestProperFilename,
(*(file_set->GetFiles().begin()))->proper_filename());
EXPECT_EQ(label1_id, file_set->label_id());
EXPECT_EQ(label1_name, file_set->label_name());
EXPECT_EQ(12345, file_set->date());
EXPECT_EQ(kBackupTypeFull, file_set->backup_type());
// Clean up.
delete file_set;
}
TEST_F(BackupVolumeTest, ReadBackupSetsMultiFile) {
// This test attempts to read several backup sets from the file, and requests
// a second backup set.
FakeFile* vol0 = new FakeFile;
// Build up our fake file.
// Version strings
vol0->Write(kGoodVersion, 8);
{
// Create a ChunkHeader and chunk. This one is not compressed, and is in
// volume 0.
uint64_t chunk1_offset = 0;
EXPECT_TRUE(vol0->size(&chunk1_offset).ok());
string chunk_data = "1234567890123456";
ChunkHeader chunk_header;
chunk_header.encoded_size = chunk_data.size();
chunk_header.unencoded_size = chunk_data.size();
chunk_header.encoding_type = kEncodingTypeRaw;
chunk_header.md5sum.hi = 123;
chunk_header.md5sum.lo = 456;
vol0->Write(&chunk_header, sizeof(chunk_header));
vol0->Write(&chunk_data.at(0), chunk_data.size());
// Create backup descriptor 1.
uint64_t desc1_offset = 0;
EXPECT_TRUE(vol0->size(&desc1_offset).ok());
BackupDescriptor1 descriptor1;
descriptor1.total_chunks = 1;
descriptor1.total_labels = 1;
vol0->Write(&descriptor1, sizeof(descriptor1));
// Create the descriptor 1 chunks.
BackupDescriptor1Chunk descriptor1_chunk;
descriptor1_chunk.md5sum = chunk_header.md5sum;
descriptor1_chunk.offset = chunk1_offset;
vol0->Write(&descriptor1_chunk, sizeof(descriptor1_chunk));
// Create a descriptor 1 label.
string label_name = "foo bar yo";
BackupDescriptor1Label descriptor1_label;
descriptor1_label.id = 0x123;
descriptor1_label.name_size = label_name.size();
vol0->Write(&descriptor1_label, sizeof(descriptor1_label));
vol0->Write(&label_name.at(0), label_name.size());
// Create the descriptor 2.
string description = "backup";
BackupDescriptor2 descriptor2;
descriptor2.previous_backup_offset = 0x12345;
descriptor2.previous_backup_volume_number = 1;
descriptor2.parent_backup_offset = 0;
descriptor2.parent_backup_volume_number = 0;
descriptor2.label_id = 0x123;
descriptor2.backup_type = kBackupTypeFull;
descriptor2.num_files = 1;
descriptor2.description_size = description.size();
descriptor2.unencoded_size = chunk_data.size();
descriptor2.backup_date = 12345;
vol0->Write(&descriptor2, sizeof(descriptor2));
vol0->Write(&description.at(0), description.size());
// Create a BackupFile, and a chunk to go with it.
string filename = kTestGenericFilename;
BackupFile backup_file;
backup_file.file_size = chunk_data.size();
backup_file.num_chunks = 1;
backup_file.filename_size = filename.size();
vol0->Write(&backup_file, sizeof(backup_file));
vol0->Write(&filename.at(0), filename.size());
// Create a FileChunk.
FileChunk file_chunk;
file_chunk.md5sum = chunk_header.md5sum;
file_chunk.volume_num = 0;
file_chunk.chunk_offset = 0;
file_chunk.unencoded_size = chunk_data.size();
vol0->Write(&file_chunk, sizeof(file_chunk));
// Create the backup header.
BackupDescriptorHeader header;
header.backup_descriptor_1_offset = desc1_offset;
header.backup_descriptor_2_present = true;
header.cancelled = false;
header.volume_number = 3;
vol0->Write(&header, sizeof(BackupDescriptorHeader));
}
// Reset for the test.
BackupVolume volume(vol0);
ConfigOptions options;
EXPECT_TRUE(volume.Init().ok());
int64_t next_volume = -5;
StatusOr<FileSet*> test_file_set = volume.LoadFileSet(&next_volume);
EXPECT_TRUE(test_file_set.ok()) << test_file_set.status().ToString();
EXPECT_EQ(1, next_volume);
// Check the first backup.
FileSet* file_set = test_file_set.value();
ASSERT_THAT(file_set, NotNull());
EXPECT_EQ("backup", file_set->description());
EXPECT_EQ(1, file_set->num_files());
EXPECT_EQ(kTestProperFilename,
(*(file_set->GetFiles().begin()))->proper_filename());
EXPECT_EQ(12345, file_set->date());
// Clean up.
delete file_set;
}
} // namespace backup2
| 35.51391 | 80 | 0.741399 | [
"vector"
] |
c45411c7e31dba9c664d7203c7f79f1461a76e89 | 4,112 | cpp | C++ | AI/nn/neuralnet.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | 2 | 2017-11-24T12:34:14.000Z | 2021-09-10T02:18:34.000Z | AI/nn/neuralnet.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | null | null | null | AI/nn/neuralnet.cpp | jjuiddong/Common | 2518fa05474222f84c474707b4511f190a34f574 | [
"MIT"
] | 6 | 2017-11-24T12:34:56.000Z | 2022-03-22T10:05:45.000Z |
#include "stdafx.h"
#include "neuralnet.h"
using namespace ai;
//------------------------------------------------------------------------
// sNeuron, sNeuronLayer
const double dBias = 0.f;
sNeuron::sNeuron(uint numInputs0)
: numInputs(numInputs0 + 1)
{
//we need an additional weight for the bias hence the +1
weight.reserve(numInputs0 + 1);
for (uint i = 0; i < numInputs0 + 1; ++i)
weight.push_back(RandomClamped());
result.resize(weight.size());
}
sNeuronLayer::sNeuronLayer(uint numNeurons0, uint numInputsPerNeuron0)
: numNeurons(numNeurons0)
{
for (uint i = 0; i < numNeurons0; ++i)
neurons.push_back(sNeuron(numInputsPerNeuron0));
}
//------------------------------------------------------------------------
// cNeuralNet
cNeuralNet::cNeuralNet(const uint numInputs, const uint numOutputs
, const uint numHidden, const uint neuronsPerHiddenLayer)
{
m_dActivationResponse = 1.f;
m_numInputs = numInputs;
m_numOutputs = numOutputs;
m_numHiddenLayers = numHidden;
m_neuronsPerHiddenLyr = neuronsPerHiddenLayer;
CreateNet();
}
cNeuralNet::~cNeuralNet()
{
}
// this method builds the ANN. The weights are all initially set to
// random values -1 < w < 1
void cNeuralNet::CreateNet()
{
if (m_numHiddenLayers > 0)
{
m_layers.push_back(sNeuronLayer(m_neuronsPerHiddenLyr, m_numInputs));
for (uint i = 0; i < m_numHiddenLayers - 1; ++i)
{
m_layers.push_back(sNeuronLayer(m_neuronsPerHiddenLyr,
m_neuronsPerHiddenLyr));
}
m_layers.push_back(sNeuronLayer(m_numOutputs, m_neuronsPerHiddenLyr));
}
else
{
m_layers.push_back(sNeuronLayer(m_numOutputs, m_numInputs));
}
}
// returns a vector containing the weights
vector<double> cNeuralNet::GetWeights() const
{
vector<double> weights;
for (uint i = 0; i < m_numHiddenLayers + 1; ++i)
for (uint j = 0; j < m_layers[i].numNeurons; ++j)
for (uint k = 0; k < m_layers[i].neurons[j].numInputs; ++k)
weights.push_back(m_layers[i].neurons[j].weight[k]);
return weights;
}
// given a vector of doubles this function replaces the weights in the NN
// with the new values
void cNeuralNet::PutWeights(const vector<double> &weights)
{
int cWeight = 0;
for (uint i = 0; i < m_numHiddenLayers + 1; ++i)
for (uint j = 0; j < m_layers[i].numNeurons; ++j)
for (uint k = 0; k < m_layers[i].neurons[j].numInputs; ++k)
m_layers[i].neurons[j].weight[k] = weights[cWeight++];
}
// returns the total number of weights needed for the net
int cNeuralNet::GetNumberOfWeights() const
{
int weights = 0;
for (uint i = 0; i < m_numHiddenLayers + 1; ++i)
for (uint j = 0; j < m_layers[i].numNeurons; ++j)
weights += m_layers[i].neurons[j].numInputs;
return weights;
}
// given an input vector this function calculates the output vector
vector<double> cNeuralNet::Update(INOUT vector<double> &inputs)
{
vector<double> outputs;
int cWeight = 0;
if (inputs.size() != m_numInputs)
return outputs;
for (uint i = 0; i < m_numHiddenLayers + 1; ++i)
{
if (i > 0)
inputs = outputs;
outputs.clear();
cWeight = 0;
//for each neuron sum the (inputs * corresponding weights).Throw
//the total at our sigmoid function to get the output.
for (uint j = 0; j < m_layers[i].numNeurons; ++j)
{
double netinput = 0;
const uint numInputs = m_layers[i].neurons[j].numInputs;
for (uint k = 0; k < numInputs - 1; ++k)
{
//netinput += m_layers[i].neurons[j].weight[k] * inputs[cWeight++];
const double v = m_layers[i].neurons[j].weight[k] * inputs[cWeight];
m_layers[i].neurons[j].result[k] = v;
netinput += v;
cWeight++;
}
netinput += m_layers[i].neurons[j].weight[numInputs - 1] * dBias;
// we can store the outputs from each layer as we generate them.
// The combined activation is first filtered through the sigmoid
// function
const double val = Sigmoid(netinput, m_dActivationResponse) - 0.5f;
outputs.push_back(val);
m_layers[i].neurons[j].output = val;
cWeight = 0;
}
}
return outputs;
}
// Sigmoid function
double cNeuralNet::Sigmoid(double netinput, double response)
{
return (1 / (1 + exp(-netinput / response)));
}
| 25.861635 | 74 | 0.663911 | [
"vector"
] |
c45654f10e589f5bab03c3b4c25273b9409a4927 | 11,103 | cpp | C++ | engine/atf_helpers.cpp | 0mp/kyua | 8713ff0cbf96564ae938b9b853038af5535b6882 | [
"BSD-3-Clause"
] | 106 | 2015-01-20T14:49:12.000Z | 2022-03-09T01:31:51.000Z | engine/atf_helpers.cpp | 0mp/kyua | 8713ff0cbf96564ae938b9b853038af5535b6882 | [
"BSD-3-Clause"
] | 81 | 2015-02-23T23:23:41.000Z | 2021-07-21T13:51:56.000Z | engine/atf_helpers.cpp | 0mp/kyua | 8713ff0cbf96564ae938b9b853038af5535b6882 | [
"BSD-3-Clause"
] | 27 | 2015-09-30T20:33:34.000Z | 2022-02-14T04:00:08.000Z | // Copyright 2010 The Kyua Authors.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
extern "C" {
#include <sys/stat.h>
#include <signal.h>
#include <unistd.h>
}
#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <atf-c++.hpp>
#include "utils/env.hpp"
#include "utils/fs/operations.hpp"
#include "utils/fs/path.hpp"
#include "utils/logging/operations.hpp"
#include "utils/optional.ipp"
#include "utils/test_utils.ipp"
#include "utils/text/operations.ipp"
namespace fs = utils::fs;
namespace logging = utils::logging;
namespace text = utils::text;
using utils::optional;
namespace {
/// Creates an empty file in the given directory.
///
/// \param test_case The test case currently running.
/// \param directory The name of the configuration variable that holds the path
/// to the directory in which to create the cookie file.
/// \param name The name of the cookie file to create.
static void
create_cookie(const atf::tests::tc* test_case, const char* directory,
const char* name)
{
if (!test_case->has_config_var(directory))
test_case->fail(std::string(name) + " not provided");
const fs::path control_dir(test_case->get_config_var(directory));
std::ofstream file((control_dir / name).c_str());
if (!file)
test_case->fail("Failed to create the control cookie");
file.close();
}
} // anonymous namespace
ATF_TEST_CASE_WITH_CLEANUP(check_cleanup_workdir);
ATF_TEST_CASE_HEAD(check_cleanup_workdir)
{
set_md_var("require.config", "control_dir");
}
ATF_TEST_CASE_BODY(check_cleanup_workdir)
{
std::ofstream cookie("workdir_cookie");
cookie << "1234\n";
cookie.close();
skip("cookie created");
}
ATF_TEST_CASE_CLEANUP(check_cleanup_workdir)
{
const fs::path control_dir(get_config_var("control_dir"));
std::ifstream cookie("workdir_cookie");
if (!cookie) {
std::ofstream((control_dir / "missing_cookie").c_str()).close();
std::exit(EXIT_FAILURE);
}
std::string value;
cookie >> value;
if (value != "1234") {
std::ofstream((control_dir / "invalid_cookie").c_str()).close();
std::exit(EXIT_FAILURE);
}
std::ofstream((control_dir / "cookie_ok").c_str()).close();
std::exit(EXIT_SUCCESS);
}
ATF_TEST_CASE_WITHOUT_HEAD(check_configuration_variables);
ATF_TEST_CASE_BODY(check_configuration_variables)
{
ATF_REQUIRE(has_config_var("first"));
ATF_REQUIRE_EQ("some value", get_config_var("first"));
ATF_REQUIRE(has_config_var("second"));
ATF_REQUIRE_EQ("some other value", get_config_var("second"));
}
ATF_TEST_CASE(check_list_config);
ATF_TEST_CASE_HEAD(check_list_config)
{
std::string description = "Found:";
if (has_config_var("var1"))
description += " var1=" + get_config_var("var1");
if (has_config_var("var2"))
description += " var2=" + get_config_var("var2");
set_md_var("descr", description);
}
ATF_TEST_CASE_BODY(check_list_config)
{
}
ATF_TEST_CASE_WITHOUT_HEAD(check_unprivileged);
ATF_TEST_CASE_BODY(check_unprivileged)
{
if (::getuid() == 0)
fail("Running as root, but I shouldn't be");
std::ofstream file("cookie");
if (!file)
fail("Failed to create the cookie; work directory probably owned by "
"root");
file.close();
}
ATF_TEST_CASE_WITHOUT_HEAD(crash);
ATF_TEST_CASE_BODY(crash)
{
std::abort();
}
ATF_TEST_CASE(crash_head);
ATF_TEST_CASE_HEAD(crash_head)
{
utils::abort_without_coredump();
}
ATF_TEST_CASE_BODY(crash_head)
{
}
ATF_TEST_CASE_WITH_CLEANUP(crash_cleanup);
ATF_TEST_CASE_HEAD(crash_cleanup)
{
}
ATF_TEST_CASE_BODY(crash_cleanup)
{
}
ATF_TEST_CASE_CLEANUP(crash_cleanup)
{
utils::abort_without_coredump();
}
ATF_TEST_CASE_WITHOUT_HEAD(create_cookie_in_control_dir);
ATF_TEST_CASE_BODY(create_cookie_in_control_dir)
{
create_cookie(this, "control_dir", "cookie");
}
ATF_TEST_CASE_WITHOUT_HEAD(create_cookie_in_workdir);
ATF_TEST_CASE_BODY(create_cookie_in_workdir)
{
std::ofstream file("cookie");
if (!file)
fail("Failed to create the cookie");
file.close();
}
ATF_TEST_CASE_WITH_CLEANUP(create_cookie_from_cleanup);
ATF_TEST_CASE_HEAD(create_cookie_from_cleanup)
{
}
ATF_TEST_CASE_BODY(create_cookie_from_cleanup)
{
}
ATF_TEST_CASE_CLEANUP(create_cookie_from_cleanup)
{
create_cookie(this, "control_dir", "cookie");
}
ATF_TEST_CASE_WITH_CLEANUP(expect_timeout);
ATF_TEST_CASE_HEAD(expect_timeout)
{
if (has_config_var("timeout"))
set_md_var("timeout", get_config_var("timeout"));
}
ATF_TEST_CASE_BODY(expect_timeout)
{
expect_timeout("Times out on purpose");
::sleep(10);
create_cookie(this, "control_dir", "cookie");
}
ATF_TEST_CASE_CLEANUP(expect_timeout)
{
create_cookie(this, "control_dir", "cookie.cleanup");
}
ATF_TEST_CASE_WITH_CLEANUP(output);
ATF_TEST_CASE_HEAD(output)
{
}
ATF_TEST_CASE_BODY(output)
{
std::cout << "Body message to stdout\n";
std::cerr << "Body message to stderr\n";
}
ATF_TEST_CASE_CLEANUP(output)
{
std::cout << "Cleanup message to stdout\n";
std::cerr << "Cleanup message to stderr\n";
}
ATF_TEST_CASE(output_in_list);
ATF_TEST_CASE_HEAD(output_in_list)
{
std::cerr << "Should not write anything!\n";
}
ATF_TEST_CASE_BODY(output_in_list)
{
}
ATF_TEST_CASE(pass);
ATF_TEST_CASE_HEAD(pass)
{
set_md_var("descr", "Always-passing test case");
}
ATF_TEST_CASE_BODY(pass)
{
}
ATF_TEST_CASE_WITH_CLEANUP(shared_workdir);
ATF_TEST_CASE_HEAD(shared_workdir)
{
}
ATF_TEST_CASE_BODY(shared_workdir)
{
atf::utils::create_file("shared_cookie", "");
}
ATF_TEST_CASE_CLEANUP(shared_workdir)
{
if (!atf::utils::file_exists("shared_cookie"))
utils::abort_without_coredump();
}
ATF_TEST_CASE(spawn_blocking_child);
ATF_TEST_CASE_HEAD(spawn_blocking_child)
{
set_md_var("require.config", "control_dir");
}
ATF_TEST_CASE_BODY(spawn_blocking_child)
{
pid_t pid = ::fork();
if (pid == -1)
fail("Cannot fork subprocess");
else if (pid == 0) {
for (;;)
::pause();
} else {
const fs::path name = fs::path(get_config_var("control_dir")) / "pid";
std::ofstream pidfile(name.c_str());
ATF_REQUIRE(pidfile);
pidfile << pid;
pidfile.close();
}
}
ATF_TEST_CASE_WITH_CLEANUP(timeout_body);
ATF_TEST_CASE_HEAD(timeout_body)
{
if (has_config_var("timeout"))
set_md_var("timeout", get_config_var("timeout"));
}
ATF_TEST_CASE_BODY(timeout_body)
{
::sleep(10);
create_cookie(this, "control_dir", "cookie");
}
ATF_TEST_CASE_CLEANUP(timeout_body)
{
create_cookie(this, "control_dir", "cookie.cleanup");
}
ATF_TEST_CASE_WITH_CLEANUP(timeout_cleanup);
ATF_TEST_CASE_HEAD(timeout_cleanup)
{
}
ATF_TEST_CASE_BODY(timeout_cleanup)
{
}
ATF_TEST_CASE_CLEANUP(timeout_cleanup)
{
::sleep(10);
create_cookie(this, "control_dir", "cookie");
}
ATF_TEST_CASE_WITHOUT_HEAD(validate_isolation);
ATF_TEST_CASE_BODY(validate_isolation)
{
ATF_REQUIRE(utils::getenv("HOME").get() != "fake-value");
ATF_REQUIRE(!utils::getenv("LANG"));
}
/// Wrapper around ATF_ADD_TEST_CASE to only add a test when requested.
///
/// The caller can set the TEST_CASES environment variable to a
/// whitespace-separated list of test case names to enable. If not empty, the
/// list acts as a filter for the tests to add.
///
/// \param tcs List of test cases into which to register the test.
/// \param filters List of filters to determine whether the test applies or not.
/// \param name Name of the test case being added.
#define ADD_TEST_CASE(tcs, filters, name) \
do { \
if (filters.empty() || filters.find(#name) != filters.end()) \
ATF_ADD_TEST_CASE(tcs, name); \
} while (false)
ATF_INIT_TEST_CASES(tcs)
{
logging::set_inmemory();
// TODO(jmmv): Instead of using "filters", we should make TEST_CASES
// explicitly list all the test cases to enable. This would let us get rid
// of some of the hacks below...
std::set< std::string > filters;
const optional< std::string > names_raw = utils::getenv("TEST_CASES");
if (names_raw) {
if (names_raw.get().empty())
return; // See TODO above.
const std::vector< std::string > names = text::split(
names_raw.get(), ' ');
std::copy(names.begin(), names.end(),
std::inserter(filters, filters.begin()));
}
if (filters.find("crash_head") != filters.end()) // See TODO above.
ATF_ADD_TEST_CASE(tcs, crash_head);
if (filters.find("output_in_list") != filters.end()) // See TODO above.
ATF_ADD_TEST_CASE(tcs, output_in_list);
ADD_TEST_CASE(tcs, filters, check_cleanup_workdir);
ADD_TEST_CASE(tcs, filters, check_configuration_variables);
ADD_TEST_CASE(tcs, filters, check_list_config);
ADD_TEST_CASE(tcs, filters, check_unprivileged);
ADD_TEST_CASE(tcs, filters, crash);
ADD_TEST_CASE(tcs, filters, crash_cleanup);
ADD_TEST_CASE(tcs, filters, create_cookie_in_control_dir);
ADD_TEST_CASE(tcs, filters, create_cookie_in_workdir);
ADD_TEST_CASE(tcs, filters, create_cookie_from_cleanup);
ADD_TEST_CASE(tcs, filters, expect_timeout);
ADD_TEST_CASE(tcs, filters, output);
ADD_TEST_CASE(tcs, filters, pass);
ADD_TEST_CASE(tcs, filters, shared_workdir);
ADD_TEST_CASE(tcs, filters, spawn_blocking_child);
ADD_TEST_CASE(tcs, filters, timeout_body);
ADD_TEST_CASE(tcs, filters, timeout_cleanup);
ADD_TEST_CASE(tcs, filters, validate_isolation);
}
| 26.754217 | 80 | 0.713321 | [
"vector"
] |
c45ca837fb6e42c5cc98768c705515eb56c0533c | 20,539 | cpp | C++ | external/icu4c/test/intltest/tchcfmt.cpp | gordonjohnpatrick/XobotOS | 888ed3b8cc8d8e0a54b1858bfa5a3572545f4d2f | [
"Apache-2.0"
] | 263 | 2015-01-04T16:39:18.000Z | 2022-01-05T17:52:38.000Z | external/icu4c/test/intltest/tchcfmt.cpp | DooMLoRD/XobotOS | f20db6295e878a2f298c5e3896528e240785805b | [
"Apache-2.0"
] | 3 | 2015-09-06T09:06:39.000Z | 2019-10-15T00:52:49.000Z | source/icu/source/test/intltest/tchcfmt.cpp | racker/omnibus | 7f619cee98d551acaef3aed28c85f1c150d0ed8a | [
"Apache-2.0"
] | 105 | 2015-01-11T11:45:12.000Z | 2022-02-22T07:26:36.000Z |
/********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2009, International Business Machines Corporation and
* others. All Rights Reserved.
********************************************************************/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "intltest.h"
#include "tchcfmt.h"
#include "cmemory.h"
#include "unicode/msgfmt.h"
#include "unicode/choicfmt.h"
#include <float.h>
// tests have obvious memory leaks!
void TestChoiceFormat::runIndexedTest(int32_t index, UBool exec,
const char* &name, char* /*par*/) {
switch (index) {
TESTCASE(0,TestSimpleExample);
TESTCASE(1,TestComplexExample);
TESTCASE(2,TestClosures);
TESTCASE(3,TestPatterns);
TESTCASE(4,TestChoiceFormatToPatternOverflow);
default: name = ""; break;
}
}
static UBool chkstatus( UErrorCode &status, const char* msg = NULL )
{
UBool ok = U_SUCCESS(status);
if (!ok) it_errln( msg );
return ok;
}
void
TestChoiceFormat::TestSimpleExample( void )
{
double limits[] = {1,2,3,4,5,6,7};
UnicodeString monthNames[] = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
ChoiceFormat* form = new ChoiceFormat(limits, monthNames, 7);
ParsePosition parse_pos;
// TODO Fix this ParsePosition stuff...
UnicodeString str;
UnicodeString res1, res2;
UErrorCode status;
FieldPosition fpos(0);
Formattable f;
int32_t ix;
//for (double i = 0.0; i <= 8.0; ++i) {
for (ix = 0; ix <= 8; ++ix) {
double i = ix; //nos
status = U_ZERO_ERROR;
fpos = 0;
str = "";
res1 = form->format(i, str, fpos, status );
if (!chkstatus( status, "*** test_simple_example format" )) {
delete form;
return;
}
//form->parse(res1, f, parse_pos);
res2 = " ??? ";
it_logln(UnicodeString("") + ix + UnicodeString(" -> ") + res1 + UnicodeString(" -> ") + res2);
}
//Testing ==operator
const double filelimits[] = {0,1,2};
const UnicodeString filepart[] = {"are no files","is one file","are {2} files"};
ChoiceFormat* formnew=new ChoiceFormat(filelimits, filepart, 3);
ChoiceFormat* formequal=new ChoiceFormat(limits, monthNames, 7);
if(*formnew == *form){
errln("ERROR: ==operator failed\n");
}
if(!(*form == *formequal)){
errln("ERROR: ==operator failed\n");
}
delete formequal;
delete formnew;
//Testing getLimits()
double *gotLimits=0;
int32_t count=0;
gotLimits=(double*)form->getLimits(count);
if(count != 7){
errln("getLimits didn't update the count correctly\n");
}
for(ix=0; ix<count; ix++){
if(gotLimits[ix] != limits[ix]){
errln((UnicodeString)"getLimits didn't get the limits correctly. Expected " + limits[ix] + " Got " + gotLimits[ix]);
}
}
//Testing getFormat()
count=0;
UnicodeString *gotFormats=0;
gotFormats=(UnicodeString*)form->getFormats(count);
if(count != 7){
errln("getFormats didn't update the count correctly\n");
}
for(ix=0; ix<count; ix++){
if(gotFormats[ix] != monthNames[ix]){
errln((UnicodeString)"getFormats didn't get the Formats correctly. Expected " + monthNames[ix] + " Got " + gotFormats[ix]);
}
}
delete form;
}
void
TestChoiceFormat::TestComplexExample( void )
{
UErrorCode status = U_ZERO_ERROR;
const double filelimits[] = {-1, 0,1,2};
const UnicodeString filepart[] = {"are corrupted files", "are no files","is one file","are {2} files"};
ChoiceFormat* fileform = new ChoiceFormat( filelimits, filepart, 4);
if (!fileform) {
it_errln("*** test_complex_example fileform");
return;
}
Format* filenumform = NumberFormat::createInstance( status );
if (!filenumform) {
dataerrln((UnicodeString)"*** test_complex_example filenumform - " + u_errorName(status));
delete fileform;
return;
}
if (!chkstatus( status, "*** test_simple_example filenumform" )) {
delete fileform;
delete filenumform;
return;
}
//const Format* testFormats[] = { fileform, NULL, filenumform };
//pattform->setFormats( testFormats, 3 );
MessageFormat* pattform = new MessageFormat("There {0} on {1}", status );
if (!pattform) {
it_errln("*** test_complex_example pattform");
delete fileform;
delete filenumform;
return;
}
if (!chkstatus( status, "*** test_complex_example pattform" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
pattform->setFormat( 0, *fileform );
pattform->setFormat( 2, *filenumform );
Formattable testArgs[] = {(int32_t)0, "Disk_A", (int32_t)0};
UnicodeString str;
UnicodeString res1, res2;
pattform->toPattern( res1 );
it_logln("MessageFormat toPattern: " + res1);
fileform->toPattern( res1 );
it_logln("ChoiceFormat toPattern: " + res1);
if (res1 == "-1#are corrupted files|0#are no files|1#is one file|2#are {2} files") {
it_logln("toPattern tested!");
}else{
it_errln("*** ChoiceFormat to Pattern result!");
}
FieldPosition fpos(0);
UnicodeString checkstr[] = {
"There are corrupted files on Disk_A",
"There are no files on Disk_A",
"There is one file on Disk_A",
"There are 2 files on Disk_A",
"There are 3 files on Disk_A"
};
// if (status != U_ZERO_ERROR) return; // TODO: analyze why we have such a bad bail out here!
if (U_FAILURE(status)) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
int32_t i;
int32_t start = -1;
for (i = start; i < 4; ++i) {
str = "";
status = U_ZERO_ERROR;
testArgs[0] = Formattable((int32_t)i);
testArgs[2] = testArgs[0];
res2 = pattform->format(testArgs, 3, str, fpos, status );
if (!chkstatus( status, "*** test_complex_example format" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
it_logln(i + UnicodeString(" -> ") + res2);
if (res2 != checkstr[i - start]) {
it_errln("*** test_complex_example res string");
it_errln(UnicodeString("*** ") + i + UnicodeString(" -> '") + res2 + UnicodeString("' unlike '") + checkstr[i] + UnicodeString("' ! "));
}
}
it_logln();
it_logln("------ additional testing in complex test ------");
it_logln();
//
int32_t retCount;
const double* retLimits = fileform->getLimits( retCount );
if ((retCount == 4) && (retLimits)
&& (retLimits[0] == -1.0)
&& (retLimits[1] == 0.0)
&& (retLimits[2] == 1.0)
&& (retLimits[3] == 2.0)) {
it_logln("getLimits tested!");
}else{
it_errln("*** getLimits unexpected result!");
}
const UnicodeString* retFormats = fileform->getFormats( retCount );
if ((retCount == 4) && (retFormats)
&& (retFormats[0] == "are corrupted files")
&& (retFormats[1] == "are no files")
&& (retFormats[2] == "is one file")
&& (retFormats[3] == "are {2} files")) {
it_logln("getFormats tested!");
}else{
it_errln("*** getFormats unexpected result!");
}
UnicodeString checkstr2[] = {
"There is no folder on Disk_A",
"There is one folder on Disk_A",
"There are many folders on Disk_A",
"There are many folders on Disk_A"
};
fileform->applyPattern("0#is no folder|1#is one folder|2#are many folders", status );
if (status == U_ZERO_ERROR)
it_logln("status applyPattern OK!");
if (!chkstatus( status, "*** test_complex_example pattform" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
pattform->setFormat( 0, *fileform );
fpos = 0;
for (i = 0; i < 4; ++i) {
str = "";
status = U_ZERO_ERROR;
testArgs[0] = Formattable((int32_t)i);
testArgs[2] = testArgs[0];
res2 = pattform->format(testArgs, 3, str, fpos, status );
if (!chkstatus( status, "*** test_complex_example format 2" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
it_logln(UnicodeString() + i + UnicodeString(" -> ") + res2);
if (res2 != checkstr2[i]) {
it_errln("*** test_complex_example res string");
it_errln(UnicodeString("*** ") + i + UnicodeString(" -> '") + res2 + UnicodeString("' unlike '") + checkstr2[i] + UnicodeString("' ! "));
}
}
const double limits_A[] = {1,2,3,4,5,6,7};
const UnicodeString monthNames_A[] = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"};
ChoiceFormat* form_A = new ChoiceFormat(limits_A, monthNames_A, 7);
ChoiceFormat* form_A2 = new ChoiceFormat(limits_A, monthNames_A, 7);
const double limits_B[] = {1,2,3,4,5,6,7};
const UnicodeString monthNames_B[] = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat_BBB"};
ChoiceFormat* form_B = new ChoiceFormat(limits_B, monthNames_B, 7);
if (!form_A || !form_B || !form_A2) {
it_errln("*** test-choiceFormat not allocatable!");
}else{
if (*form_A == *form_A2) {
it_logln("operator== tested.");
}else{
it_errln("*** operator==");
}
if (*form_A != *form_B) {
it_logln("operator!= tested.");
}else{
it_errln("*** operator!=");
}
ChoiceFormat* form_A3 = (ChoiceFormat*) form_A->clone();
if (!form_A3) {
it_errln("*** ChoiceFormat->clone is nil.");
}else{
if ((*form_A3 == *form_A) && (*form_A3 != *form_B)) {
it_logln("method clone tested.");
}else{
it_errln("*** ChoiceFormat clone or operator==, or operator!= .");
}
}
ChoiceFormat form_Assigned( *form_A );
UBool ok = (form_Assigned == *form_A) && (form_Assigned != *form_B);
form_Assigned = *form_B;
ok = ok && (form_Assigned != *form_A) && (form_Assigned == *form_B);
if (ok) {
it_logln("copy constructor and operator= tested.");
}else{
it_errln("*** copy constructor or operator= or operator == or operator != .");
}
delete form_A3;
}
delete form_A; delete form_A2; delete form_B;
const char* testPattern = "0#none|1#one|2#many";
ChoiceFormat form_pat( testPattern, status );
if (!chkstatus( status, "*** ChoiceFormat contructor( newPattern, status)" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
form_pat.toPattern( res1 );
if (res1 == "0#none|1#one|2#many") {
it_logln("ChoiceFormat contructor( newPattern, status) tested");
}else{
it_errln("*** ChoiceFormat contructor( newPattern, status) or toPattern result!");
}
double d_a2[] = { 3.0, 4.0 };
UnicodeString s_a2[] = { "third", "forth" };
form_pat.setChoices( d_a2, s_a2, 2 );
form_pat.toPattern( res1 );
it_logln(UnicodeString("ChoiceFormat adoptChoices toPattern: ") + res1);
if (res1 == "3#third|4#forth") {
it_logln("ChoiceFormat adoptChoices tested");
}else{
it_errln("*** ChoiceFormat adoptChoices result!");
}
str = "";
fpos = 0;
status = U_ZERO_ERROR;
double arg_double = 3.0;
res1 = form_pat.format( arg_double, str, fpos );
it_logln(UnicodeString("ChoiceFormat format:") + res1);
if (res1 != "third") it_errln("*** ChoiceFormat format (double, ...) result!");
str = "";
fpos = 0;
status = U_ZERO_ERROR;
int64_t arg_64 = 3;
res1 = form_pat.format( arg_64, str, fpos );
it_logln(UnicodeString("ChoiceFormat format:") + res1);
if (res1 != "third") it_errln("*** ChoiceFormat format (int64_t, ...) result!");
str = "";
fpos = 0;
status = U_ZERO_ERROR;
int32_t arg_long = 3;
res1 = form_pat.format( arg_long, str, fpos );
it_logln(UnicodeString("ChoiceFormat format:") + res1);
if (res1 != "third") it_errln("*** ChoiceFormat format (int32_t, ...) result!");
Formattable ft( (int32_t)3 );
str = "";
fpos = 0;
status = U_ZERO_ERROR;
res1 = form_pat.format( ft, str, fpos, status );
if (!chkstatus( status, "*** test_complex_example format (int32_t, ...)" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
it_logln(UnicodeString("ChoiceFormat format:") + res1);
if (res1 != "third") it_errln("*** ChoiceFormat format (Formattable, ...) result!");
Formattable fta[] = { (int32_t)3 };
str = "";
fpos = 0;
status = U_ZERO_ERROR;
res1 = form_pat.format( fta, 1, str, fpos, status );
if (!chkstatus( status, "*** test_complex_example format (int32_t, ...)" )) {
delete fileform;
delete filenumform;
delete pattform;
return;
}
it_logln(UnicodeString("ChoiceFormat format:") + res1);
if (res1 != "third") it_errln("*** ChoiceFormat format (Formattable[], cnt, ...) result!");
ParsePosition parse_pos = 0;
Formattable result;
UnicodeString parsetext("third");
form_pat.parse( parsetext, result, parse_pos );
double rd = (result.getType() == Formattable::kLong) ? result.getLong() : result.getDouble();
if (rd == 3.0) {
it_logln("parse( ..., ParsePos ) tested.");
}else{
it_errln("*** ChoiceFormat parse( ..., ParsePos )!");
}
form_pat.parse( parsetext, result, status );
rd = (result.getType() == Formattable::kLong) ? result.getLong() : result.getDouble();
if (rd == 3.0) {
it_logln("parse( ..., UErrorCode ) tested.");
}else{
it_errln("*** ChoiceFormat parse( ..., UErrorCode )!");
}
/*
UClassID classID = ChoiceFormat::getStaticClassID();
if (classID == form_pat.getDynamicClassID()) {
it_out << "getStaticClassID and getDynamicClassID tested." << endl;
}else{
it_errln("*** getStaticClassID and getDynamicClassID!");
}
*/
it_logln();
delete fileform;
delete filenumform;
delete pattform;
}
/**
* Test new closure API
*/
void TestChoiceFormat::TestClosures(void) {
// Construct open, half-open, half-open (the other way), and closed
// intervals. Do this both using arrays and using a pattern.
// 'fmt1' is created using arrays
UBool T = TRUE, F = FALSE;
// 0: ,1)
// 1: [1,2]
// 2: (2,3]
// 3: (3,4)
// 4: [4,5)
// 5: [5,
double limits[] = { 0, 1, 2, 3, 4, 5 };
UBool closures[] = { F, F, T, T, F, F };
UnicodeString fmts[] = {
",1)", "[1,2]", "(2,3]", "(3,4)", "[4,5)", "[5,"
};
ChoiceFormat fmt1(limits, closures, fmts, 6);
// 'fmt2' is created using a pattern; it should be equivalent
UErrorCode status = U_ZERO_ERROR;
const char* PAT = "0#,1)|1#[1,2]|2<(2,3]|3<(3,4)|4#[4,5)|5#[5,";
ChoiceFormat fmt2(PAT, status);
if (U_FAILURE(status)) {
errln("FAIL: ChoiceFormat constructor failed");
return;
}
// Check the patterns
UnicodeString str;
fmt1.toPattern(str);
if (str == PAT) {
logln("Ok: " + str);
} else {
errln("FAIL: " + str + ", expected " + PAT);
}
str.truncate(0);
// Check equality
if (fmt1 != fmt2) {
errln("FAIL: fmt1 != fmt2");
}
int32_t i;
int32_t count2 = 0;
const double *limits2 = fmt2.getLimits(count2);
const UBool *closures2 = fmt2.getClosures(count2);
if((count2 != 6) || !limits2 || !closures2) {
errln("FAIL: couldn't get limits or closures");
} else {
for(i=0;i<count2;i++) {
logln("#%d/%d: limit %g closed %s\n",
i, count2,
limits2[i],
closures2[i] ?"T":"F");
if(limits2[i] != limits[i]) {
errln("FAIL: limit #%d = %g, should be %g\n", i, limits2[i], limits[i]);
}
if((closures2[i]!=0) != (closures[i]!=0)) {
errln("FAIL: closure #%d = %s, should be %s\n", i, closures2[i]?"T":"F", closures[i]?"T":"F");
}
}
}
// Now test both format objects
UnicodeString exp[] = {
/*-0.5 => */ ",1)",
/* 0.0 => */ ",1)",
/* 0.5 => */ ",1)",
/* 1.0 => */ "[1,2]",
/* 1.5 => */ "[1,2]",
/* 2.0 => */ "[1,2]",
/* 2.5 => */ "(2,3]",
/* 3.0 => */ "(2,3]",
/* 3.5 => */ "(3,4)",
/* 4.0 => */ "[4,5)",
/* 4.5 => */ "[4,5)",
/* 5.0 => */ "[5,",
/* 5.5 => */ "[5,"
};
// Each format object should behave exactly the same
ChoiceFormat* FMT[] = { &fmt1, &fmt2 };
for (int32_t pass=0; pass<2; ++pass) {
int32_t j=0;
for (int32_t ix=-5; ix<=55; ix+=5) {
double x = ix / 10.0; // -0.5 to 5.5 step +0.5
FMT[pass]->format(x, str);
if (str == exp[j]) {
logln((UnicodeString)"Ok: " + x + " => " + str);
} else {
errln((UnicodeString)"FAIL: " + x + " => " + str +
", expected " + exp[j]);
}
str.truncate(0);
++j;
}
}
}
/**
* Helper for TestPatterns()
*/
void TestChoiceFormat::_testPattern(const char* pattern,
UBool isValid,
double v1, const char* str1,
double v2, const char* str2,
double v3, const char* str3) {
UErrorCode ec = U_ZERO_ERROR;
ChoiceFormat fmt(pattern, ec);
if (!isValid) {
if (U_FAILURE(ec)) {
logln((UnicodeString)"Ok: " + pattern + " failed");
} else {
logln((UnicodeString)"FAIL: " + pattern + " accepted");
}
return;
}
if (U_FAILURE(ec)) {
errln((UnicodeString)"FAIL: ChoiceFormat(" + pattern + ") failed");
return;
} else {
logln((UnicodeString)"Ok: Pattern: " + pattern);
}
UnicodeString out;
logln((UnicodeString)" toPattern: " + fmt.toPattern(out));
double v[] = {v1, v2, v3};
const char* str[] = {str1, str2, str3};
for (int32_t i=0; i<3; ++i) {
out.truncate(0);
fmt.format(v[i], out);
if (out == str[i]) {
logln((UnicodeString)"Ok: " + v[i] + " => " + out);
} else {
errln((UnicodeString)"FAIL: " + v[i] + " => " + out +
", expected " + str[i]);
}
}
}
/**
* Test applyPattern
*/
void TestChoiceFormat::TestPatterns(void) {
// Try a pattern that isolates a single value. Create
// three ranges: [-Inf,1.0) [1.0,1.0] (1.0,+Inf]
_testPattern("0.0#a|1.0#b|1.0<c", TRUE,
1.0 - 1e-9, "a",
1.0, "b",
1.0 + 1e-9, "c");
// Try an invalid pattern that isolates a single value.
// [-Inf,1.0) [1.0,1.0) [1.0,+Inf]
_testPattern("0.0#a|1.0#b|1.0#c", FALSE,
0, 0, 0, 0, 0, 0);
// Another
// [-Inf,1.0] (1.0,1.0) [1.0,+Inf]
_testPattern("0.0#a|1.0<b|1.0#c", FALSE,
0, 0, 0, 0, 0, 0);
// Another
// [-Inf,1.0] (1.0,1.0] (1.0,+Inf]
_testPattern("0.0#a|1.0<b|1.0<c", FALSE,
0, 0, 0, 0, 0, 0);
// Try a grossly invalid pattern.
// [-Inf,2.0) [2.0,1.0) [1.0,+Inf]
_testPattern("0.0#a|2.0#b|1.0#c", FALSE,
0, 0, 0, 0, 0, 0);
}
void TestChoiceFormat::TestChoiceFormatToPatternOverflow()
{
static const double limits[] = {0.1e-78, 1e13, 0.1e78};
UnicodeString monthNames[] = { "one", "two", "three" };
ChoiceFormat fmt(limits, monthNames, sizeof(limits)/sizeof(limits[0]));
UnicodeString patStr, expectedPattern1("1e-79#one|10000000000000#two|1e+77#three"),
expectedPattern2("1e-079#one|10000000000000#two|1e+077#three");
fmt.toPattern(patStr);
if (patStr != expectedPattern1 && patStr != expectedPattern2) {
errln("ChoiceFormat returned \"" + patStr + "\" instead of \"" + expectedPattern1 + " or " + expectedPattern2 + "\"");
}
}
#endif /* #if !UCONFIG_NO_FORMATTING */
| 32.447077 | 149 | 0.54175 | [
"object"
] |
c464395b44725b5bfcad4205dd22491ab75d8464 | 1,194 | cpp | C++ | uri-online-judge/2238/main.cpp | olegon/online-judges | 4ec27c8940ae492ce71aec0cc9ed944b094bce55 | [
"MIT"
] | 12 | 2017-11-30T11:10:45.000Z | 2022-01-26T23:49:19.000Z | uri-online-judge/2238/main.cpp | olegon/online-judges | 4ec27c8940ae492ce71aec0cc9ed944b094bce55 | [
"MIT"
] | null | null | null | uri-online-judge/2238/main.cpp | olegon/online-judges | 4ec27c8940ae492ce71aec0cc9ed944b094bce55 | [
"MIT"
] | 4 | 2017-11-25T03:13:32.000Z | 2019-08-16T08:08:10.000Z | /*
Divisores
https://www.urionlinejudge.com.br/judge/pt/problems/view/2238
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int main() {
int divisor, naoDivisor,
multiplo, naoMultiplo,
n = -1;
vector<int> divisores;
cin >> divisor >> naoDivisor >> multiplo >> naoMultiplo;
/*
Se (i) é um divisor de (múltiplo), então (múltiplo / i) também seu um divisor.
Só é necessário testar até a (raiz de múltiplo), pois ((múltiplo) / (raiz do múltiplo)) é igual ao próprio múltiplo. Depois desse limite, os elementos do vetor passam a se repetir.
*/
int raizDoMultiplo = sqrt(multiplo);
for (int i = 1; i <= raizDoMultiplo; i++) {
if (multiplo % i == 0) {
divisores.push_back(i);
divisores.push_back(multiplo / i);
}
}
sort(divisores.begin(), divisores.end());
for (size_t i = 0; i < divisores.size(); i++) {
if (divisores[i] % divisor == 0 && divisores[i] % naoDivisor != 0 && naoMultiplo % divisores[i] != 0) {
n = divisores[i];
break;
}
}
cout << n << endl;
return EXIT_SUCCESS;
}
| 23.411765 | 184 | 0.58794 | [
"vector"
] |
c4648a7d666adedaeaedf5acd508617265f8ed98 | 864 | cpp | C++ | acmicpc.net/source/5371.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 7 | 2019-06-26T07:03:32.000Z | 2020-11-21T16:12:51.000Z | acmicpc.net/source/5371.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | null | null | null | acmicpc.net/source/5371.cpp | tdm1223/Algorithm | 994149afffa21a81e38b822afcfc01f677d9e430 | [
"MIT"
] | 9 | 2019-02-28T03:34:54.000Z | 2020-12-18T03:02:40.000Z | // 5371. Annoying Mosquitos
// 2019.05.21
// 시뮬레이션
#include<iostream>
#include<vector>
using namespace std;
// 모기 구조체 (위치,공격여부)
struct mosquito
{
int x;
int y;
bool attack;
};
int main()
{
int t;
cin >> t;
for (int testCase = 1; testCase <= t; testCase++)
{
int cnt = 0;
int n; // 모기 수
cin >> n;
vector<mosquito> mosquitos; // 모기들의 위치
for (int i = 0; i < n; i++)
{
int x, y;
cin >> x >> y;
mosquitos.push_back({ x,y,false });
}
int m;
cin >> m; // lee가 공격하는 횟수
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y; // lee가 공격하는 좌표
for (int j = 0; j < mosquitos.size(); j++)
{
// 공격 가능하다면
if (abs(mosquitos[j].x - x) <= 50 && abs(mosquitos[j].y - y) <= 50 && !mosquitos[j].attack)
{
cnt++; // 공격한 모기 숫자 증가
mosquitos[j].attack = true;
}
}
}
cout << cnt << endl;
}
return 0;
}
| 16 | 95 | 0.512731 | [
"vector"
] |
c4664e45fe52730429e695b4ef9146130d7cd62c | 3,162 | cpp | C++ | application/sources/mesh.cpp | JuiceFV/Emscripten_OpenGL | 56b8420ca080b17ac29b7a6b05bc4cdbb2deec1e | [
"MIT"
] | 1 | 2021-04-28T17:08:47.000Z | 2021-04-28T17:08:47.000Z | application/sources/mesh.cpp | JuiceFV/Emscripten_OpenGL | 56b8420ca080b17ac29b7a6b05bc4cdbb2deec1e | [
"MIT"
] | null | null | null | application/sources/mesh.cpp | JuiceFV/Emscripten_OpenGL | 56b8420ca080b17ac29b7a6b05bc4cdbb2deec1e | [
"MIT"
] | null | null | null | #include "mesh.h"
Mesh::Mesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices,
const std::vector<Texture> &textures)
{
this->vertices = vertices;
this->indices = indices;
this->textures = textures;
// Now that we have all the required data, set the vertex buffers and its attribute pointers.
this->setupMesh();
}
// Render the mesh
void Mesh::Draw(Shader &shader)
{
// Bind appropriate textures
unsigned int diffuseNr = 1;
unsigned int specularNr = 1;
for (unsigned int i = 0; i < this->textures.size(); i++)
{
std::stringstream ss;
std::string number;
std::string name = this->textures[i].getTexType();
if (name == "texture_diffuse")
{
ss << diffuseNr++; // Transfer unsigned int to stream
}
else if (name == "texture_specular")
{
ss << specularNr++; // Transfer unsigned int to stream
}
number = ss.str();
// Now set the sampler to the correct texture unit
shader.set1i(i, (name + number).c_str());
// And finally bind the texture
this->textures[i].bind(i);
}
// Also set each mesh's shininess property to a default value (if you want you could extend this to another mesh
// property and possibly change this value)
shader.set1f(16.0f, "material.shininess");
shader.Use();
// Draw mesh
glBindVertexArray(this->VAO);
glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
// Always good practice to set everything back to defaults once configured.
for (unsigned int i = 0; i < this->textures.size(); i++) { this->textures[i].unbind(); }
}
void Mesh::setupMesh()
{
// Create buffers/arrays
glGenVertexArrays(1, &this->VAO);
glGenBuffers(1, &this->VBO);
glGenBuffers(1, &this->EBO);
glBindVertexArray(this->VAO);
// Load data into vertex buffers
glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
// A great thing about structs is that their memory layout is sequential for all its items.
// The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2
// array which again translates to 3/2 floats which translates to a byte array.
glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(Vertex), &this->vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(unsigned int), &this->indices[0],
GL_STATIC_DRAW);
// Set the vertex attribute pointers
// Vertex Positions
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)0);
// Vertex Normals
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)offsetof(Vertex, Normal));
// Vertex Texture Coords
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void *)offsetof(Vertex, TexCoords));
glBindVertexArray(0);
} | 35.931818 | 116 | 0.659393 | [
"mesh",
"render",
"vector"
] |
c466c22dee711d6b627f0465bdc54df10e860add | 1,434 | hpp | C++ | hiro/cocoa/widget/canvas.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | hiro/cocoa/widget/canvas.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | hiro/cocoa/widget/canvas.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | #if defined(Hiro_Canvas)
@interface CocoaCanvas : NSView {
@public
hiro::mCanvas* canvas;
}
-(id) initWith:(hiro::mCanvas&)canvas;
-(void) resetCursorRects;
-(NSDragOperation) draggingEntered:(id<NSDraggingInfo>)sender;
-(BOOL) performDragOperation:(id<NSDraggingInfo>)sender;
-(void) mouseButton:(NSEvent*)event down:(BOOL)isDown;
-(void) mouseEntered:(NSEvent*)event;
-(void) mouseExited:(NSEvent*)event;
-(void) mouseMove:(NSEvent*)event;
-(void) mouseDown:(NSEvent*)event;
-(void) mouseUp:(NSEvent*)event;
-(void) mouseDragged:(NSEvent*)event;
-(void) rightMouseDown:(NSEvent*)event;
-(void) rightMouseUp:(NSEvent*)event;
-(void) rightMouseDragged:(NSEvent*)event;
-(void) otherMouseDown:(NSEvent*)event;
-(void) otherMouseUp:(NSEvent*)event;
-(void) otherMouseDragged:(NSEvent*)event;
@end
namespace hiro {
struct pCanvas : pWidget {
Declare(Canvas, Widget)
auto minimumSize() const -> Size;
auto setAlignment(Alignment) -> void;
auto setColor(Color color) -> void;
auto setDroppable(bool droppable) -> void override;
auto setFocusable(bool focusable) -> void override;
auto setGeometry(Geometry geometry) -> void override;
auto setGradient(Gradient gradient) -> void;
auto setIcon(const image& icon) -> void;
auto update() -> void;
CocoaCanvas* cocoaCanvas = nullptr;
NSImage* surface = nullptr;
NSBitmapImageRep* bitmap = nullptr;
u32 surfaceWidth = 0;
u32 surfaceHeight = 0;
};
}
#endif
| 28.117647 | 62 | 0.730126 | [
"geometry"
] |
c46718799f1106e6104cb0431b3f33c8a23b7100 | 1,352 | cpp | C++ | problemsets/UVA/UVA166.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/UVA/UVA166.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/UVA/UVA166.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <string>
#include <algorithm>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <numeric>
using namespace std;
int C[6];
int S[110];
int V[] = {1,2,4,10,20,40};
int T;
int B[110][6];
int DP[110];
int main() {
S[0] = 0;
for (int i = 1; i <= 100; i++) {
S[i] = 300;
for (int j = 0; j < 6; j++) if (i-V[j]>=0)
S[i] = min(S[i], S[i-V[j]]+1);
}
while (scanf("%d %d %d %d %d %d", C, C+1, C+2, C+3, C+4, C+5)) {
if (!accumulate(C,C+6,0)) break;
int x, y;
scanf("%d.%d", &x, &y);
T = (x*100+y)/5;
DP[0] = 0;
copy(C, C+6, &B[0][0]);
for (int i = 1; i <= 100; i++) {
DP[i] = 300;
for (int j = 0; j < 6; j++) if (i-V[j] >= 0 && B[i-V[j]][j]) {
if (DP[i] > DP[i-V[j]]+1) {
copy(&B[i-V[j]][0], &B[i-V[j]][6], C);
DP[i] = DP[i-V[j]]+1;
if (i > T) DP[T] = min(DP[T], DP[i]+S[i-T]);
C[j]--;
copy(C,C+6,&B[i][0]);
}
}
}
printf("%3d\n", DP[T]);
}
return 0;
}
| 21.806452 | 74 | 0.397929 | [
"3d"
] |
c468d5259df4ffa20cd24ba782a8cd491b43165a | 11,410 | hpp | C++ | src/libefl/vector_functions_reference_impl.hpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 17 | 2019-03-12T14:52:22.000Z | 2021-11-09T01:16:23.000Z | src/libefl/vector_functions_reference_impl.hpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | null | null | null | src/libefl/vector_functions_reference_impl.hpp | s3a-spatialaudio/VISR | 55f6289bc5058d4898106f3520e1a60644ffb3ab | [
"ISC"
] | 2 | 2019-08-11T12:53:07.000Z | 2021-06-22T10:08:08.000Z | /* Copyright Institute of Sound and Vibration Research - All rights reserved */
#ifndef VISR_LIBEFL_VECTOR_FUNCTIONS_REFERENCE_IMPL_HPP_INCLUDED
#define VISR_LIBEFL_VECTOR_FUNCTIONS_REFERENCE_IMPL_HPP_INCLUDED
#include "vector_functions_reference.hpp"
#include "alignment.hpp"
#include <complex>
// avoid annoying warning about unsafe STL functions.
#ifdef _MSC_VER
#pragma warning(disable: 4996)
#endif
#include <algorithm>
#include <ciso646> // should not be necessary for c++11, but MSVC needs it somehow
#include <functional>
namespace visr
{
namespace efl
{
namespace reference
{
template <typename T>
ErrorCode vectorZero( T * const dest, std::size_t numElements, std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( dest, alignment ) ) return alignmentError;
std::fill( &dest[0], &dest[0] + numElements, static_cast<T>(0) );
return noError;
}
template <typename T>
ErrorCode vectorFill( const T value, T * const dest, std::size_t numElements, std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( dest, alignment ) ) return alignmentError;
std::fill( &dest[0], &dest[0] + numElements, value );
return noError;
}
template <typename T>
ErrorCode vectorRamp( T * const dest, std::size_t numElements, T startVal, T endVal,
bool startInclusive, bool endInclusive, std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( dest, alignment ) ) return alignmentError;
if( numElements == 0 ) return noError; // Not very sensible, but legal
if( numElements == 1 ) // Special handling for single-element ramps.
{
// Meet in the middle if either both or none of start and end points are to be included
if( startInclusive == endInclusive )
{
dest[0] = static_cast<T>(0.5f)*(startVal+endVal);
}
dest[0] = startInclusive ? startVal : endVal;
return noError;
}
std::size_t const numSteps = numElements + 1 - (startInclusive ? 1 : 0) - (endInclusive ? 1 : 0);
T const step = (endVal - startVal) / static_cast<T>(numSteps);
std::size_t calcIdx( startInclusive ? 0 : 1 );
std::generate( dest, dest + numElements, [&] { return startVal + static_cast<T>(calcIdx++) * step; } );
return noError;
}
template <typename T>
ErrorCode vectorCopy( T const * const source, T * const dest, std::size_t numElements, std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( source, alignment ) ) return alignmentError;
if( not checkAlignment( dest, alignment ) ) return alignmentError;
std::copy( &source[0], &source[0] + numElements, &dest[0] );
return noError;
}
template<typename T>
ErrorCode vectorAdd( T const * const op1,
T const * const op2,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( op1, alignment ) ) return alignmentError;
if( not checkAlignment( op2, alignment ) ) return alignmentError;
if( not checkAlignment( result, alignment ) ) return alignmentError;
std::transform( op1, op1+numElements, op2, result, [&](T const & a, T const& b){return a+b;} ); // c++11 way, using a lambda function
// std::transform( op1, op1+numElements, op2, result, std::plus<T>() ); // c++0x way, using standard function object
return noError;
}
template<typename T>
ErrorCode vectorAddInplace( T const * const op1,
T * const op2Result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if (not checkAlignment(op1, alignment)) return alignmentError;
if (not checkAlignment(op2Result, alignment)) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
op2Result[idx] += op1[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorAddConstant( T constantValue,
T const * const op,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if (not checkAlignment(op, alignment)) return alignmentError;
if (not checkAlignment(result, alignment)) return alignmentError;
std::transform(op, op + numElements, result, [=](T const & x){return x + constantValue; });
return noError;
}
template<typename T>
ErrorCode vectorAddConstantInplace( T constantValue,
T * const opResult,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( opResult, alignment ) ) return alignmentError;
std::for_each( opResult, opResult + numElements,
[=](T const & x){return x + constantValue;} );
return noError;
}
template<typename T>
ErrorCode vectorSubtract( T const * const subtrahend,
T const * const minuend,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( subtrahend, alignment ) ) return alignmentError;
if( not checkAlignment( minuend, alignment ) ) return alignmentError;
if( not checkAlignment( result, alignment ) ) return alignmentError;
std::transform( subtrahend, subtrahend + numElements, minuend, result, [=]( T x, T y ) { return x + y; } );
return noError;
}
template<typename T>
ErrorCode vectorSubtractInplace( T const * const minuend,
T * const subtrahendResult,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( minuend, alignment ) ) return alignmentError;
if( not checkAlignment( subtrahendResult, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
subtrahendResult[idx] -= minuend[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorSubtractConstant( T constantMinuend,
T const * const subtrahend,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( subtrahend, alignment ) ) return alignmentError;
if( not checkAlignment( result, alignment ) ) return alignmentError;
std::transform( subtrahend, subtrahend + numElements, result, [=]( T x ) { return x - constantMinuend; } );
return noError;
}
template<typename T>
ErrorCode vectorSubConstantInplace( T constantMinuend,
T * const subtrahendResult,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( subtrahendResult, alignment ) ) return alignmentError;
std::for_each( subtrahendResult, subtrahendResult + numElements, [=]( T& x ) { x -= constantMinuend; } );
return noError;
}
template<typename T>
ErrorCode vectorMultiply( T const * const factor1,
T const * const factor2,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( factor1, alignment ) ) return alignmentError;
if( not checkAlignment( factor2, alignment ) ) return alignmentError;
if( not checkAlignment( result, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
result[idx] = factor1[idx] * factor2[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorMultiplyInplace( T const * const factor1,
T * const factor2Result,
std::size_t numElements,
std::size_t alignment /* = 0 */ )
{
if( not checkAlignment( factor1, alignment ) ) return alignmentError;
if( not checkAlignment( factor2Result, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
factor2Result[idx] *= factor1[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorMultiplyConstant( T constantValue,
T const * const factor,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( factor, alignment ) ) return alignmentError;
if( not checkAlignment( result, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
result[idx] = constantValue * factor[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorMultiplyConstantInplace( T constantValue,
T * const factorResult,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( factorResult, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
factorResult[idx] *= constantValue;
}
return noError;
}
template<typename T>
ErrorCode vectorMultiplyAdd( T const * const factor1,
T const * const factor2,
T const * const addend,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( factor1, alignment ) ) return alignmentError;
if( not checkAlignment( factor2, alignment ) ) return alignmentError;
if( not checkAlignment( addend, alignment ) ) return alignmentError;
if( not checkAlignment( result, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
result[idx] = addend[idx] + factor1[idx] * factor2[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorMultiplyAddInplace( T const * const factor1,
T const * const factor2,
T * const accumulator,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( factor1, alignment ) ) return alignmentError;
if( not checkAlignment( factor2, alignment ) ) return alignmentError;
if( not checkAlignment( accumulator, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
accumulator[idx] += factor1[idx] * factor2[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorMultiplyConstantAdd( T constFactor,
T const * const factor,
T const * const addend,
T * const result,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( factor, alignment ) ) return alignmentError;
if( not checkAlignment( addend, alignment ) ) return alignmentError;
if( not checkAlignment( result, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
result[idx] = addend[idx] + constFactor * factor[idx];
}
return noError;
}
template<typename T>
ErrorCode vectorMultiplyConstantAddInplace( T constFactor,
T const * const factor,
T * const accumulator,
std::size_t numElements,
std::size_t alignment /*= 0*/ )
{
if( not checkAlignment( factor, alignment ) ) return alignmentError;
if( not checkAlignment( accumulator, alignment ) ) return alignmentError;
for( std::size_t idx( 0 ); idx < numElements; ++idx )
{
accumulator[idx] += constFactor * factor[idx];
}
return noError;
}
} // namespace reference
} // namespace efl
} // namespace visr
#endif // #ifndef VISR_LIBEFL_VECTOR_FUNCTIONS_REFERENCE_IMPL_HPP_INCLUDED
| 35.107692 | 135 | 0.64163 | [
"object",
"transform"
] |
c4695857a917a4feb7a8cadba6b9d4eec9ddcb2b | 45,274 | cpp | C++ | proj.cpp | jarreed0/bullet-hell | 2cb126fae139328754e662967fbf121d75373ece | [
"MIT"
] | 1 | 2022-02-10T19:58:05.000Z | 2022-02-10T19:58:05.000Z | proj.cpp | jarreed0/bullet-hell | 2cb126fae139328754e662967fbf121d75373ece | [
"MIT"
] | null | null | null | proj.cpp | jarreed0/bullet-hell | 2cb126fae139328754e662967fbf121d75373ece | [
"MIT"
] | null | null | null | //import
#include "include.h"
//def
const char * TITLE = "Day One";
bool running;
int WIDTH = 1800;
int HEIGHT = 900;
int flags = SDL_WINDOW_FULLSCREEN; //not used yet
SDL_Renderer* renderer;
SDL_Texture* screen;
SDL_Window* window;
TTF_Font *font;
SDL_Color font_color;
int font_size;
SDL_DisplayMode DM;
int seed;
#define PI 3.14159265359
#define PLAYER_ID 0
#define ENEMY_ID 1
#define TOP 1
#define WALL 2
#define FLOOR 3
#define TREE 4
#define GATE 5
#define SNOW 6
int frameCount, timerFPS, lastFrame, fps, lastTime;
int setFPS = 60;
bool shake, shaking;
SDL_Rect screensrc, screendest;
int shaketick;
const Uint8 *keystates;
Uint32 mousestate;
SDL_Event event;
SDL_Point camera;
SDL_Rect lens;
bool left, right, down, up, fire, lfire;
bool debug = 0;
bool freeroam = 0;
int ammo = 0;
int mod = 0;
int mod2 = 0;
bool changingMod = false;
int ammoCount[5] = {100,50,0,0,0};
std::string mods[6] = {"None", "Velocity", "Damage", "Burst", "Wave", "Bounce"};
std::string mods2[6] = {"None", "Velocity", "Damage", "Bounce", "Random"};
bool modsUnlocked[6] = {1,0,0,0,0,0};
bool mods2Unlocked[5] = {1,0,0,0,0};
//obj
struct obj;
struct tile {
SDL_Rect loc;
int id;
int frame;
int tick;
int flip;
};
struct obj {
int id;
SDL_Rect src, loc;
SDL_Point center;
bool flipV, flipH;
double angle;
double vel, lastVel;
bool rotateOnCenter;
int frame;
double health, maxHealth;
int img;
double tick = 0;
int extra;
bool bExtra;
bool parent;
std::vector<obj*> children;
bool collideV, collideH;
bool alive;
} player, gun, treeObj;
obj lighting;
bool dayCycle;
int dayClock;
obj enemy, enemyShadow;
std::vector<obj> enemies;
obj footTmp;
std::vector<obj> footPrints;
int footTick = 0;
obj snowTmp;
std::vector<obj> snowFall;
obj chess, shell, heart;
std::vector<obj> collectables;
obj bullet;
std::vector<obj> bullets;
SDL_Point mouse;
obj cursor;
obj UI, gunUI, modSelect, shellSelect;
SDL_Rect healthBar;
double maxHealthBar;
//map
int map_width = 150;
int map_height = 150;
int tile_size = 75;
std::vector<tile> map;
int tileImgId;
//extra
SDL_Color setColor(Uint8 r, Uint8 g, Uint8 b, Uint8 a) { return SDL_Color {r, g, b, a}; }
SDL_Color setColor(Uint8 r, Uint8 g, Uint8 b) { return setColor(r, g, b, 255); }
SDL_Color white = setColor(255, 255, 255, 255);
SDL_Color black = setColor(0, 0, 0, 255);
SDL_Color red = setColor(255, 90, 90, 255);
SDL_Color blue = setColor(18, 35, 94, 255);
SDL_Color healthColor = red;
SDL_Color wallColor = setColor(94, 120, 140);
SDL_Color floorColor = setColor(190, 216, 239);
SDL_Color bkg;
void setBkg(Uint8 r, Uint8 g, Uint8 b) {
bkg = setColor(r, g, b);
}
void setCamera(obj o) {
camera.x = o.loc.x + o.loc.w/2;
camera.y = o.loc.y + o.loc.h/2;
}
SDL_Rect initRect(int x, int y, int w, int h) {
SDL_Rect r;
r.x=x;
r.y=y;
r.w=w;
r.h=h;
return r;
}
//sound
int gunSound;
int song;
std::vector<Mix_Chunk*> sounds;
std::vector<Mix_Music*> music;
int loadMusic(const char* filename) {
Mix_Music *m = NULL;
m = Mix_LoadMUS(filename);
if(m == NULL) {
printf( "Failed to load wav! SDL_mixer Error: %s\n", Mix_GetError() );
return -1;
}
music.push_back(m);
return music.size()-1;
}
int loadSound(const char* filename) {
Mix_Chunk *s = NULL;
s = Mix_LoadWAV(filename);
if(s == NULL) {
printf( "Failed to load wav! SDL_mixer Error: %s\n", Mix_GetError() );
return -1;
}
sounds.push_back(s);
return sounds.size()-1;
}
int playSound(int s) {
Mix_Volume(-1, 22);
Mix_PlayChannel(-1, sounds[s], 0);
return 0;
}
int playMusic(int m) {
if(Mix_PlayingMusic() == 0) {
Mix_Volume(1, MIX_MAX_VOLUME);
Mix_PlayMusic(music[m], -1);
}
return 0;
}
//world gen
//flood
int floodCount = 1;
bool flood(int x, int y, int tick) {
if(map[y*map_width + x].id == FLOOR && map[y*map_width + x].tick == 0) {
map[y*map_width + x].tick = tick;
flood(x-1, y-1, tick);
flood(x+1, y-1, tick);
flood(x, y-1, tick);
flood(x-1, y+1, tick);
flood(x+1, y+1, tick);
flood(x, y+1, tick);
flood(x-1, y, tick);
flood(x+1, y, tick);
return true;
}
return false;
}
void dropChess(int x, int y) {
chess.id = 6;
chess.loc.x = x*tile_size + chess.loc.w/2;
chess.loc.y = y*tile_size + chess.loc.h/2;
collectables.push_back(chess);
}
void dropShell(int x, int y, int type) {
shell.id = type;
shell.src.x = shell.src.w * type;
shell.loc.x = x*tile_size + shell.loc.w/2;
shell.loc.y = y*tile_size + shell.loc.h/2;
shell.tick = 50;
collectables.push_back(shell);
}
void dropHeart(int x, int y, int type) {
heart.id = 7 + type;
heart.src.x = heart.src.w * type;
heart.loc.x = x*tile_size + heart.loc.w/2;
heart.loc.y = y*tile_size + heart.loc.h/2;
collectables.push_back(heart);
}
void spawnEnemy(int cx, int cy, int type, int type2, int health) {
enemy.id = type;
enemy.frame = type2;
enemy.src.x=enemy.src.w*type;
enemy.src.y=enemy.src.h*type2;
enemy.loc.x = cx;
enemy.loc.y = cy;
enemy.loc.w=enemy.loc.h=rand() % tile_size + tile_size*.5;
enemy.tick=50;
enemy.angle=0;
//enemyShadows.push_back(enemyShadow);
//enemy.child=enemyShadows.size()-1;
enemy.health=health;
enemies.push_back(enemy);
}
void spawnEnemies(int cx, int cy, int cnt) {
for(int x=cx-(cnt/2); x<cx+(cnt/2); x++) {
for(int y=cy-(cnt/2); y<cy+(cnt/2); y++) {
//if(x < lens.x/tile_size && x > (lens.x+WIDTH)/tile_size && y < lens.y/tile_size && y > (lens.y+HEIGHT)/tile_size) {
int type = rand() % 10;
if(type!=1) type=0;
if(map[y*map_width + x].id == FLOOR && rand() % 10 > 3) {spawnEnemy((x)*tile_size + (enemy.loc.w/2), (y)*tile_size + (enemy.loc.h/2), rand() % 5, type, 60+(140*type));}
//}
}
}
}
//spread, snow, tree
void spread(int x, int y, int t, int type) {
if(map[y*map_width + x].id == FLOOR and t > 0) {
if((type == TREE && (map[y*map_width + x+1].id != WALL && map[y*map_width + x+1].id != TOP) && (map[y*map_width + x+2].id != WALL && map[y*map_width + x+2].id != TOP)) || type != TREE) {
map[y*map_width + x].id = type;
map[y*map_width + x].flip = rand() % 2;
map[y*map_width + x].tick = rand() % 4;
spread(x-1,y-1,t-1, type);
spread(x+1,y-1,t-1, type);
spread(x,y-1,t-1, type);
spread(x-1,y+1,t-1, type);
spread(x+1,y+1,t-1, type);
spread(x,y+1,t-1, type);
spread(x-1,y,t-1, type);
spread(x+1,y,t-1, type);
}
}
}
//shuffle
void shuffleMap() {
map.clear();
tile tile_tmp;
tile_tmp.loc.w = tile_tmp.loc.h = tile_size;
for(int y = 0; y < map_height; y++) {
tile_tmp.loc.y = tile_size * y;
for(int x = 0; x < map_width; x++) {
int of = rand() % 100;
tile_tmp.loc.x = tile_size * x;
tile_tmp.id = TOP;
if(of > 40) tile_tmp.id = FLOOR;
map.push_back(tile_tmp);
}
}
}
//gen
void genMap() {
shuffleMap();
int oc, tc;
for(int i = 0; i < 6; i++) {
for(int y = 2; y < map_height-2; y++) {
for(int x = 2; x < map_width-2; x++) {
oc = tc = 0;
if(map[((y-1)*map_width) + (x-1)].id == FLOOR) oc++;
if(map[((y-1)*map_width) + x].id == FLOOR) oc++;
if(map[((y-1)*map_width) + (x+1)].id == FLOOR) oc++;
if(map[(y*map_width) + (x-1)].id == FLOOR) oc++;
if(map[(y*map_width) + (x+1)].id == FLOOR) oc++;
if(map[((y+1)*map_width) + (x-1)].id == FLOOR) oc++;
if(map[((y+1)*map_width) + x].id == FLOOR) oc++;
if(map[((y+1)*map_width) + (x+1)].id == FLOOR) oc++;
if(map[((y-2)*map_width) + (x-2)].id == FLOOR) tc++;
if(map[((y-2)*map_width) + (x-1)].id == FLOOR) tc++;
if(map[((y-2)*map_width) + (x)].id == FLOOR) tc++;
if(map[((y-2)*map_width) + (x+1)].id == FLOOR) tc++;
if(map[((y-2)*map_width) + (x+2)].id == FLOOR) tc++;
if(map[((y-1)*map_width) + (x-2)].id == FLOOR) tc++;
if(map[((y)*map_width) + (x-2)].id == FLOOR) tc++;
if(map[((y+1)*map_width) + (x-2)].id == FLOOR) tc++;
if(map[((y-1)*map_width) + (x+2)].id == FLOOR) tc++;
if(map[((y)*map_width) + (x+2)].id == FLOOR) tc++;
if(map[((y+1)*map_width) + (x+2)].id == FLOOR) tc++;
if(map[((y+2)*map_width) + (x-2)].id == FLOOR) tc++;
if(map[((y+2)*map_width) + (x-1)].id == FLOOR) tc++;
if(map[((y+2)*map_width) + (x)].id == FLOOR) tc++;
if(map[((y+2)*map_width) + (x+1)].id == FLOOR) tc++;
if(map[((y+2)*map_width) + (x+2)].id == FLOOR) tc++;
if(i < 1) {
if(oc>=5 || tc<=7) {
map[y*map_width + x].id=FLOOR;
} else {
map[y*map_width + x].id=TOP;
}
} else {
if(oc >= 5) {
map[y*map_width + x].id=FLOOR;
} else {
map[y*map_width + x].id=TOP;
}
}
}
}
}
for(int y = 0; y < map_height; y++) {
map[y*map_width].id = TOP;
map[y*map_width + 1].id = TOP;
map[y*map_width + map_width-2].id = TOP;
map[y*map_width + map_width-1].id = TOP;
}
for(int x = 0; x < map_width; x++) {
map[x].id = TOP;
map[map_width + x].id = TOP;
map[x + ((map_width-1)*(map_height-1))].id = TOP;
map[x + ((map_width)*(map_height-1))].id = TOP;
}
for(int y = 2; y < map_height-2; y++) {
for(int x = 2; x < map_width-2; x++) {
if(flood(x, y, floodCount)) floodCount++;
}
}
int fc=0;
int maxfc=0;
for(int i = 0; i < floodCount; i++) {
int count = 0;
for(int y = 2; y < map_height-2; y++) {
for(int x = 2; x < map_width-2; x++) {
if(map[y*map_width + x].id == FLOOR) {
if(count > maxfc) {fc=i;maxfc=count;}
count++;
}
}
}
}
for(int y = 2; y < map_height-2; y++) {
for(int x = 2; x < map_width-2; x++) {
if(map[y*map_width + x].tick != fc+1) map[y*map_width + x].id = TOP;
}
}
for(int y = 1; y < map_height-2; y++) {
for(int x = 2; x < map_width-2; x++) {
if(map[y*map_width + x].id == TOP && map[((y+1)*map_width) + x].id == FLOOR && map[((y-1)*map_width) + x].id == TOP) {
map[y*map_width + x].id = WALL;
} else if (map[y*map_width + x].id == TOP && map[((y+1)*map_width) + x].id == FLOOR && map[((y+2)*map_width) + x].id == FLOOR) {
map[((y+1)*map_width) + x].id = WALL;
}
}
}
for(int y = 1; y < map_height-2; y++) {
for(int x = 2; x < map_width-2; x++) {
int t = rand() % 2000;
if(map[y*map_width + x].id == FLOOR && t < 4) spread(x, y, rand() % 5 + 2, TREE);
t = rand() % 2000;
if(map[y*map_width + x].id == FLOOR && t < 4) spread(x, y, rand() % 5 + 2, SNOW);
}
}
player.bExtra=0;
for(int y = 2; y < map_height-2; y++) {
for(int x = 2; x < map_width-2; x++) {
if(!player.bExtra) {
if(map[y*map_width + x].id == FLOOR) {
if(map[y*map_width + x-1].id == FLOOR && map[y+1*map_width + x].id == FLOOR && map[y+1*map_width + x-1].id == FLOOR) {
if(rand() % 100 == 1) {
player.loc.x=x*tile_size;player.loc.y=y*tile_size;
player.bExtra=true;
}
}
}
}
}
}
lens.x=camera.x-(lens.w/2);
lens.y=camera.y-(lens.h/2);
for(int y = 0; y < map_height; y++) {
for(int x = 0; x < map_width; x++) {
if(map[y*map_width + x].id == FLOOR || map[y*map_width + x].id == TREE) {
if(y>0 && map[(y-1)*map_width + x].id == WALL) {
if(y>0 && x>0 && map[(y-1)*map_width + x-1].id != WALL && map[(y-1)*map_width + x-1].id != TOP) {
map[y*map_width + x].frame = 12;
} else if(y>0 && x<map_width && map[(y-1)*map_width + x+1].id != WALL && map[(y-1)*map_width + x+1].id != TOP) {
map[y*map_width + x].frame = 14;
} else {
map[y*map_width + x].frame = 13;
}
} else {
map[y*map_width + x].frame = 15;
}
if(map[(y-1)*map_width + x].frame == 21) map[y*map_width + x].frame=22;
} else if(map[y*map_width + x].id == SNOW) {
map[y*map_width + x].frame = 23;
} else if(map[y*map_width + x].id == WALL) {
if(x>0 && map[y*map_width + x-1].id == FLOOR || map[y*map_width + x-1].id == TREE) {
map[y*map_width + x].frame = 9;
} else if(x<map_width && map[y*map_width + x+1].id == FLOOR || map[y*map_width + x+1].id == TREE) {
map[y*map_width + x].frame = 11;
} else {
map[y*map_width + x].frame = 10;
}
if(map[(y-1)*map_width + x].frame == 20) map[y*map_width + x].frame=21;
} else if(map[y*map_width + x].id == TOP) {
if(y>0 && map[(y-1)*map_width + x].id != TOP) {
if(x>0 && map[y*map_width + x-1].id != TOP) {
map[y*map_width + x].frame = 0;
} else if(x<map_width && map[y*map_width + x+1].id != TOP) {
map[y*map_width + x].frame = 2;
} else {
map[y*map_width + x].frame = 1;
}
} else if(y<map_height && map[(y+1)*map_width + x].id != TOP) {
if(x>0 && map[y*map_width + x-1].id != TOP) {
map[y*map_width + x].frame = 6;
} else if(x<map_width && map[y*map_width + x+1].id != TOP) {
map[y*map_width + x].frame = 8;
} else {
map[y*map_width + x].frame = 7;
}
} else {
if(x>0 && map[y*map_width + x-1].id != TOP) {
map[y*map_width + x].frame = 3;
} else if(x<map_width && map[y*map_width + x+1].id != TOP) {
map[y*map_width + x].frame = 5;
} else {
map[y*map_width + x].frame = 4;
}
}
}
if(x>0 && y>0 and x<map_width && y<map_height && map[y*map_width + x].id == TOP) {
if(map[(y-1)*map_width + x].id != TOP && map[(y+1)*map_width + x].id != TOP && map[y*map_width + x-1].id != TOP && map[y*map_width + x+1].id != TOP) {
map[y*map_width + x].frame = 20;
} else if(map[(y-1)*map_width + x].id != TOP && map[(y+1)*map_width + x].id != TOP) {
if(map[y*map_width + x-1].id != TOP) {
map[y*map_width + x].frame = 16;
} else if(map[y*map_width + x+1].id != TOP) {
map[y*map_width + x].frame = 17;
}
} else if (map[y*map_width + x-1].id != TOP && map[y*map_width + x+1].id != TOP) {
if(map[(y-1)*map_width + x].id != TOP) {
map[y*map_width + x].frame = 19;
} else if(map[(y+1)*map_width + x].id != TOP) {
map[y*map_width + x].frame = 18;
}
}
}
}
}
}
//floor
void floorPer() {
int c = 0;
int wc = 0;
for(auto tile : map) {
if(tile.id == FLOOR) c++;
if(tile.id == WALL) wc++;
}
if(wc == 0 || ((c*100)/(map.size()+1) + 1) < 30) {
/*std::vector<int> seeds;
std::ifstream inFile;
inFile.open("res/seeds.txt");
if (inFile.is_open()) {
std::copy(std::istream_iterator<double>(inFile), std::istream_iterator<double>(), std::back_inserter(seeds));
inFile.close();
seed = seeds[rand() % seeds.size()];
srand(seed);
std::cout << "SEED: " << seed << std::endl;
genMap();
}*/
} else {
std::ofstream out;
out.open("res/seeds.txt", std::ios::app);
std::string str = std::to_string(seed) + "\n";
out << str;
}
for(int y = 0; y < map_height; y++) {
for(int x = 0; x < map_width; x++) {
if(map[y*map_width + x].id == FLOOR && rand() % 150 == 5) { dropShell(x, y, rand() % 5);
} else if(map[y*map_width + x].id == SNOW && rand() % 200 == 5) { dropChess(x, y);
} else if(map[y*map_width + x].id == FLOOR && rand() % 500 == 5) { dropHeart(x, y, rand() % 2); }
}
}
for(int y = 3; y < map_height-4; y++) {
for(int x = 3; x < map_width-4; x++) {
if(map[y*map_width + x].id == FLOOR && rand() % 500 == 5) {spawnEnemies(x, y, rand() % 9);}
}
}
}
//input
void input() {
left=right=down=up=fire=0;
int scroll = 0;
int select = -1;
keystates = SDL_GetKeyboardState(NULL);
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) running=false;
if(event.type == SDL_MOUSEWHEEL) {
if(event.wheel.y>0) scroll=1;
if(event.wheel.y<0) scroll=-1;
}
}
if(keystates[SDL_SCANCODE_ESCAPE]) running=false;
if(keystates[SDL_SCANCODE_W] || keystates[SDL_SCANCODE_UP]) up=1;
if(keystates[SDL_SCANCODE_S] || keystates[SDL_SCANCODE_DOWN]) down=1;
if(keystates[SDL_SCANCODE_A] || keystates[SDL_SCANCODE_LEFT]) left=1;
if(keystates[SDL_SCANCODE_D] || keystates[SDL_SCANCODE_RIGHT]) right=1;
//if(keystates[SDL_SCANCODE_Q]) freeroam=!freeroam;
if(keystates[SDL_SCANCODE_1]) select=0;
if(keystates[SDL_SCANCODE_2]) select=1;
if(keystates[SDL_SCANCODE_3]) select=2;
if(keystates[SDL_SCANCODE_4]) select=3;
if(keystates[SDL_SCANCODE_5]) select=4;
if(keystates[SDL_SCANCODE_6]) select=5;
if(keystates[SDL_SCANCODE_7]) select=6;
changingMod = false;
if(keystates[SDL_SCANCODE_LSHIFT]) {
if(select != -1) mod = select;
mod-=scroll;
changingMod = true;
modSelect.src.y = modSelect.src.h * 5;
} else if(keystates[SDL_SCANCODE_LCTRL]) {
if(select != -1) mod2 = select;
mod2-=scroll;
changingMod = true;
modSelect.src.y = modSelect.src.h * 6;
} else {
if(select != -1) ammo = select;
ammo-=scroll;
}
mousestate = SDL_GetMouseState(&mouse.x, &mouse.y);
if(mousestate == SDL_BUTTON_LEFT) fire=1;
//hard coded these but could use sizes but dont care atm
if(ammo>4) ammo=0;
if(ammo<0) ammo=4;
if(mod>5) mod=0;
if(mod<0) mod=5;
if(mod2>4) mod2=0;
if(mod2<0) mod2=4;
}
//update
double radToDeg(double a) {
return a * (180 / PI);
}
double degToRad(double a) {
return a * (PI / 180);
}
double pointAt(double ax, double ay, double bx, double by) {
float xDistance = bx - ax;
float yDistance = by - ay;
return atan2(yDistance, xDistance);
}
void fireBullet(int id, double sx, double sy, double a, double type, double sw, double v, double dmg, bool bnc) {
playSound(gunSound);
bullet.id = id;
bullet.frame = type;
bullet.loc.x = sx;
bullet.loc.y = sy;
bullet.angle = a;
bullet.vel = v;
bullet.src.x = bullet.src.w * type;
double r = degToRad(a);
bullet.loc.x += sw * cos(r);
bullet.loc.y += sw * sin(r);
bullet.extra = dmg;
bullet.bExtra = bnc;
bullet.tick=500;
bullets.push_back(bullet);
}
void updateBullets() {
if(fire) {
if(ammoCount[ammo] > 0) {
//std::string mods [6] = {"None", "Velocity", "Damage", "Burst", "Wave", "Bounce"};
//std::string mods2 [6] = {"None", "Velocity", "Damage", "Bounce"};
int bDmg = 6;
bool bnc = 0;
double bVel = 40;
if(modsUnlocked[mod]) {
if(mods[mod] == "Velocity") bVel+=10;
if(mods[mod] == "Damage") bDmg+=8;
if(mods[mod] == "Bounce") bnc=1;
}
if(mods2Unlocked[mod2]) {
if(mods2[mod2] == "Bounce") bnc=1;
if(mods2[mod2] == "Velocity") bVel+=10;
if(mods2[mod2] == "Damage") bDmg+=8;
if(mods2[mod2] == "Random") {
int load;
bool jammed=1;
while(jammed) {
load = rand() % 5;
if(ammoCount[load]) {
ammo = load;
jammed=0;
}
}
}
}
if(ammo == 1) bnc=1;
if(ammo == 2) bDmg+=8;
if(ammo == 3) {bDmg+=4;bVel+=4;}
if(ammo == 3) bVel+=8;
double px = gun.loc.x + gun.center.x - (bullet.loc.w/2);
double py = gun.loc.y + gun.center.y - (bullet.loc.h/2);
fireBullet(PLAYER_ID, px, py, gun.angle, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
if(mods[mod] == "Burst" && modsUnlocked[mod]) {
fireBullet(PLAYER_ID, px, py, gun.angle-4, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
fireBullet(PLAYER_ID, px, py, gun.angle-8, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
fireBullet(PLAYER_ID, px, py, gun.angle+4, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
fireBullet(PLAYER_ID, px, py, gun.angle+8, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
}
if(mods[mod] == "Wave" && modsUnlocked[mod]) {
fireBullet(PLAYER_ID, px, py, gun.angle-40, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
fireBullet(PLAYER_ID, px, py, gun.angle-80, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
fireBullet(PLAYER_ID, px, py, gun.angle+40, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
fireBullet(PLAYER_ID, px, py, gun.angle+80, ammo, gun.loc.w*.8, bVel, bDmg, bnc);
}
shaking=1;
ammoCount[ammo]--;
}
cursor.frame=1;
} else {
if(cursor.frame==2) cursor.frame=0;
if(cursor.frame==1) cursor.frame=2;
}
for(int b=0; b<bullets.size(); b++) {
double r = degToRad(bullets[b].angle);
bullets[b].loc.x += bullets[b].vel * cos(r);
bullets[b].loc.y += bullets[b].vel * sin(r);
bullets[b].tick--;
for(auto m:map) {
if(m.id == TOP && SDL_HasIntersection(&bullets[b].loc, &m.loc)) {
bullets[b].tick -= 50;
if(bullets[b].bExtra) {
bullets[b].angle+=180;
bullets[b].angle+=rand() % 40 - 20;
}
}
}
if(bullets[b].id != PLAYER_ID && SDL_HasIntersection(&player.loc, &bullets[b].loc)) {
player.health-=bullets[b].extra;
bullets[b].tick = -100;
}
if(bullets[b].tick < 0) {
bullets.erase(bullets.begin()+b);
b--;
}
}
if(fire && !lfire) {
gun.loc.y-=4;
if(gun.flipV) {
gun.loc.x+=16;
} else {
gun.loc.x-=16;
}
} else if(lfire && !fire) {
gun.loc.y-=4;
if(gun.flipV) {
gun.loc.x+=8;
} else {
gun.loc.x-=8;
}
}
lfire = fire;
}
bool inCamView(SDL_Rect loc) {
return SDL_HasIntersection(&loc, &lens);
}
//enemies
void updateEnemies() {
/*if(enemies.size() == 0) {
for(int y = 3; y < map_height-4; y++) {
for(int x = 3; x < map_width-4; x++) {
if(map[y*map_width + x].id == FLOOR && rand() % 600 == 5) {spawnEnemies(x, y, rand() % 8);}
}
}
}
if(shells.size() == 0) {
for(int y = 0; y < map_height; y++) {
for(int x = 0; x < map_width; x++) {
if(map[y*map_width + x].id == FLOOR && rand() % 150 == 5) {dropShell((x)*tile_size - (tile_size/2) + tile_size, (y)*tile_size - (tile_size/2), rand() % 5);
} else if(map[y*map_width + x].id == FLOOR && rand() % 1000 == 5) {dropChess((x)*tile_size - (tile_size/2) + tile_size, (y)*tile_size - (tile_size/2), 1);
} else if(map[y*map_width + x].id == FLOOR && rand() % 200 == 5) {dropHeart((x)*tile_size - (tile_size/2) + tile_size, (y)*tile_size - (tile_size/2), rand() % 2);}
}
}
}*/
for(int e=0; e<enemies.size(); e++) {
if(enemies[e].health<=0) {
int dropX = enemies[e].loc.x / tile_size;
int dropY = enemies[e].loc.y / tile_size;
dropShell(dropX, dropY, enemies[e].id);
if(enemies[e].frame == 1) dropChess(dropX, dropY);
if(rand() % 6 == 1) dropHeart(dropX, dropY, rand() % 2);
enemies.erase(enemies.begin()+e);
e--;
}
if(inCamView(enemies[e].loc)) {
float xDistance = round(enemies[e].loc.x + enemy.loc.w/2 - player.loc.x - (player.loc.w/2));
float yDistance = round(enemies[e].loc.y + enemy.loc.h/2 - player.loc.y - (player.loc.h/2));
float ang = (atan2(yDistance, xDistance));// * 180 / PI;
int sp = 10;
if(enemies[e].frame == 1) sp=20;
enemies[e].loc.x += sp * cos(ang * 180 / PI);
enemies[e].loc.y += sp * sin(ang * 180 / PI);
int bType = enemies[e].id;
double bnc=0;
int bDmg = 5;
int bV = 40;
if(enemies[e].frame == 1) bnc=1;
if(bType == 1) bnc=1;
if(bType == 2) bDmg+=3;
if(bType == 3) {bDmg+=3;bV+=4;}
if(bType == 3) bV+=8;
if(rand() % 30 == 1) {
//fireBullet(int id, double sx, double sy, double a, double type, double sw, double v, double dmg, bool bnc)
fireBullet(ENEMY_ID, enemies[e].loc.x + enemy.loc.w/2 + bullet.loc.w/2,
enemies[e].loc.y + enemy.loc.h/2 + bullet.loc.h/2, radToDeg(ang)+180, enemies[e].id, 0, bV, bDmg, bnc);
/*if(enemies[e].frame == 1) {
int f = rand() % 12;
if(f==0) {
fireBullet(enemies[e].loc.x + enemy.loc.w/2 + bulletTmp.loc.w/2, enemies[e].loc.y + enemy.loc.h/2 + bulletTmp.loc.h/2, bV, ang-PI-.04, 2, enemies[e].id, bDmg, bnc);
fireBullet(enemies[e].loc.x + enemy.loc.w/2 + bulletTmp.loc.w/2, enemies[e].loc.y + enemy.loc.h/2 + bulletTmp.loc.h/2, bV, ang-PI+.04, 2, enemies[e].id, bDmg, bnc);
} else if(f==1) {
fireBullet(enemies[e].loc.x + enemy.loc.w/2 + bulletTmp.loc.w/2, enemies[e].loc.y + enemy.loc.h/2 + bulletTmp.loc.h/2, bV, ang, 2, enemies[e].id, bDmg, bnc);
fireBullet(enemies[e].loc.x + enemy.loc.w/2 + bulletTmp.loc.w/2, enemies[e].loc.y + enemy.loc.h/2 + bulletTmp.loc.h/2, bV, ang-PI/2, 2, enemies[e].id, bDmg, bnc);
fireBullet(enemies[e].loc.x + enemy.loc.w/2 + bulletTmp.loc.w/2, enemies[e].loc.y + enemy.loc.h/2 + bulletTmp.loc.h/2, bV, ang+PI/2, 2, enemies[e].id, bDmg, bnc);
}
}*/
}
for(int i=0; i<bullets.size(); i++) {
enemies[e].src.x=enemies[e].src.w*enemies[e].id;
if(bullets[i].id==PLAYER_ID && bullets[i].frame!=enemies[e].id) {
if(SDL_HasIntersection(&bullets[i].loc, &enemies[e].loc)) {bullets[i].tick=0; enemies[e].health-=bullets[i].extra; enemies[e].src.x=enemies[e].src.w*5;}
}
}
}
}
}
//
void update() {
if(modsUnlocked[mod]) {gun.src.x = mod * gun.src.w;} else {gun.src.x = 0;}
gun.src.y = ammo * gun.src.h;
for(auto c = 0; c < collectables.size(); c++) {
bool del = 1;
if(SDL_HasIntersection(&player.loc, &collectables[c].loc)) {
if(collectables[c].id < 5) { //ammo
ammoCount[collectables[c].id] += collectables[c].tick;
if(ammoCount[ammo] == 0) ammo = collectables[c].id;
} else if(collectables[c].id == 6) { //chess mod 1
if(rand() % 2) {
bool unlock=1;
int cnt = 0;
bool stuck = 0;
while(unlock) {
int u = rand() % 5 + 1;
if(!modsUnlocked[u]) {modsUnlocked[u]=1; mod=u; unlock=0;}
cnt++;
if(cnt > 10) {
stuck=1;
unlock=0;
}
}
if(stuck) {
for(int i=0; i<6; i++) {
if(!modsUnlocked[i]) {modsUnlocked[i]=1; mod=i;i=1000;}
}
}
} else { //chess mod 2
bool unlock=1;
int cnt = 0;
bool stuck = 0;
while(unlock) {
int u = rand() % 4 + 1;
if(!mods2Unlocked[u]) {mods2Unlocked[u]=1; mod2=u; unlock=0;}
cnt++;
if(cnt > 10) {
stuck=1;
unlock=0;
}
}
if(stuck) {
for(int i=0; i<5; i++) {
if(!mods2Unlocked[i]) {mods2Unlocked[i]=1; mod2=i;i=1000;}
}
}
}
} else { //heart
if(player.health != player.maxHealth) {
player.health += (collectables[c].id - 6) * 50;
} else {
del=false;
}
}
if(del) {
collectables.erase(collectables.begin()+c);
c--;
}
}
}
for(int i=0; i < snowFall.size(); i++) {
snowFall[i].loc.y+=snowFall[i].vel;
snowFall[i].loc.x-=1.4;
snowFall[i].tick-=snowFall[i].vel;
if(snowFall[i].tick<0) {
snowFall.erase(snowFall.begin()+i);
i--;
}
}
if(rand() % 500 > 100) {
snowTmp.loc.x = rand() % WIDTH + lens.x;
snowTmp.loc.w = rand() % 10 + 7;
snowTmp.loc.h = snowTmp.loc.w * 1.3;
snowTmp.loc.y = 0 - snowTmp.loc.h + lens.y;
snowTmp.vel = rand() % 12 + 6;
snowTmp.tick = rand() % HEIGHT*3 + 220;
snowFall.push_back(snowTmp);
}
//setCamera(collectables[0]);
lens.x=camera.x-(lens.w/2);
lens.y=camera.y-(lens.h/2);
//playMusic(song);
bool inSnow = 0;
if(player.health > player.maxHealth) player.health=player.maxHealth;
if(player.health <=0) {player.health=0;player.alive=false;}
if(freeroam) {
if(up) camera.y-=20;
if(down) camera.y+=20;
if(left) camera.x-=20;
if(right) camera.x+=20;
} else {
healthColor = red;
player.vel = 16;
for(auto m : map) {
if(m.id == SNOW && SDL_HasIntersection(&player.loc, &m.loc)) {
player.vel = 4;
player.health-=0.05;
healthColor = blue;
inSnow=1;
}
}
if(left || right || up || down) {
footTick++;
player.collideH=player.collideV=player.bExtra=false;
if(left) player.loc.x-=player.vel;
if(right) player.loc.x+=player.vel;
double slide;
for(auto m : map) {
if(m.id == TOP && SDL_HasIntersection(&player.loc, &m.loc)) {
player.collideH = true;
slide = player.loc.x + player.loc.w - m.loc.x;
if(left) slide = m.loc.x + m.loc.w - player.loc.x;
}
if(m.id == WALL && SDL_HasIntersection(&player.loc, &m.loc)) player.bExtra=true; //wallcollision
}
if(player.collideH) {
if(left) player.loc.x+=slide;
if(right) player.loc.x-=slide;
}
if(up) player.loc.y-=player.vel;
if(down) player.loc.y+=player.vel;
slide = 0;
for(auto m : map) {
if(m.id == TOP && SDL_HasIntersection(&player.loc, &m.loc)) {
player.collideV = true;
slide = player.loc.y + player.loc.h - m.loc.y;
if(up) slide = m.loc.y + m.loc.h - player.loc.y;
}
}
if(player.collideV) {
if(up) player.loc.y+=slide+1;
if(down) player.loc.y-=slide;
}
//walking/running animation
int animCycle=3;//0//1//2//3
int animLength=6;//8//3//3//6
player.src.y=player.src.h*animCycle;
player.tick+=28;
if(inSnow)player.tick-=16;
if(player.tick>animLength*100-101) player.tick=0;
player.src.x = (round(player.tick/100)+3) * player.src.w;
if((right && player.flipH) || (left && !player.flipH)) player.src.x = (player.src.w*(animLength+3)) - ((round(player.tick/100)+3) * player.src.w);
} else {
footTick--;
//idle animation
player.tick+=3;
if(player.tick>199) player.tick=0;
player.src.x = round(player.tick/200) * player.src.w;
}
if(footTick>3) {
footTick=0;
footTmp.loc.x = player.loc.x + (player.loc.w/2) - (footTmp.loc.w/2);
footTmp.loc.y = player.loc.y + player.loc.h - footTmp.loc.h;
footTmp.angle = gun.angle;
if(footTmp.src.x==0) {
footTmp.src.x=footTmp.src.w;
} else {
footTmp.src.x=0;
}
if(!player.bExtra && !player.collideV && !player.collideH) footPrints.push_back(footTmp);
}
if(footTick<0)footTick=0;
for(int f=0; f<footPrints.size(); f++) {
footPrints[f].tick--;
if(footPrints[f].tick<200)footPrints[f].src.y=footPrints[f].src.h * 1;
if(footPrints[f].tick<100)footPrints[f].src.y=footPrints[f].src.h * 2;
if(footPrints[f].tick<40)footPrints[f].src.y=footPrints[f].src.h * 3;
if(footPrints[f].tick<0) {
footPrints.erase(footPrints.begin()+f);
f--;
}
}
//setCamera(player);
}
cursor.loc.x=mouse.x-cursor.loc.w/2;cursor.loc.y=mouse.y-cursor.loc.h/2;
player.flipH = 1;
if(mouse.x > player.loc.x - lens.x) player.flipH=0;
gun.loc = initRect(player.loc.x, player.loc.y + player.loc.h*.35, gun.loc.w, gun.loc.h);
gun.flipH = player.flipH;
if(gun.flipH) {
gun.loc.x += player.loc.w*.6;
gun.center.x = 0;
gun.flipV = 1;
} else {
gun.loc.x += player.loc.h*.3;
gun.center.x = 0;
gun.flipV = 0;
}
gun.angle = radToDeg(pointAt(gun.loc.x + gun.center.x - (bullet.loc.w/2) - lens.x, gun.loc.y + gun.center.y - (bullet.loc.h/2) - lens.y, mouse.x, mouse.y));
cursor.angle = gun.angle;
updateEnemies();
updateBullets();
if(dayCycle) {
dayClock+=4;
if(dayClock>WIDTH*2*4) {
dayCycle=!dayCycle;
}
} else {
dayClock-=4;
if(dayClock<=-WIDTH*4) {
dayCycle=!dayCycle;
}
}
lighting.loc = lens;
lighting.loc.x-=dayClock;
lighting.loc.y-=dayClock/2;
lighting.loc.w=WIDTH + (2*(dayClock));
lighting.loc.h=HEIGHT + (1*(dayClock));
if(lighting.loc.w<WIDTH) lighting.loc = lens;
setCamera(player);
}
//bullets
//enemies
//player
//snow
//world
//pickups
//render
//write
void write(std::string t, int x, int y) {
SDL_Surface *text_surface;
SDL_Texture *text_texture;
SDL_Rect wrect;
const char *text = t.c_str();
if (font == NULL) {
fprintf(stderr, "error: font not found\n");
exit(EXIT_FAILURE);
}
text_surface = TTF_RenderText_Solid(font, text, font_color);
text_texture = SDL_CreateTextureFromSurface(renderer, text_surface);
wrect.w = text_surface->w;
wrect.h = text_surface->h;
wrect.x = x;
wrect.y = y;
SDL_FreeSurface(text_surface);
SDL_RenderCopy(renderer, text_texture, NULL, &wrect);
SDL_DestroyTexture(text_texture);
}
//images
std::vector<SDL_Texture*> images;
int setImage(std::string filename) {
images.push_back(IMG_LoadTexture(renderer, filename.c_str()));
return images.size()-1;
}
//drawing
void draw(tile t) {
if(inCamView(t.loc)) {
SDL_Rect dest, src;
dest = t.loc;
dest.x-=lens.x;
dest.y-=lens.y;
src.w=src.h=20;
src.y=0;
src.x=src.w*t.frame;
if(t.flip) {
SDL_RenderCopyEx(renderer, images[tileImgId], &src, &dest, 0, NULL, SDL_FLIP_HORIZONTAL);
} else {
SDL_RenderCopyEx(renderer, images[tileImgId], &src, &dest, 0, NULL, SDL_FLIP_NONE);
}
if(debug) {
SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
SDL_RenderDrawRect(renderer, &dest);
write(std::to_string(src.x) + ", " + std::to_string(src.y), dest.x + 20, dest.y + 20);
write(std::to_string(t.id) + " - " + std::to_string(t.frame), dest.x + 20, dest.y + 40);
}
}
}
void draw(obj o) {
if(inCamView(o.loc)) {
SDL_Rect dest;
dest = o.loc;
dest.x-=lens.x;
dest.y-=lens.y;
SDL_RendererFlip flip = SDL_FLIP_NONE;
if(o.flipH) flip = SDL_FLIP_HORIZONTAL;
if(o.flipV) flip = SDL_FLIP_VERTICAL;
if(o.rotateOnCenter) {
SDL_RenderCopyEx(renderer, images[o.img], &o.src, &dest, o.angle, &o.center, flip);
} else {
SDL_RenderCopyEx(renderer, images[o.img], &o.src, &dest, o.angle, NULL, flip);
}
if(o.parent) {
for(int c=0; c<o.children.size(); c++) {
draw(*o.children[c]);
}
}
if(debug) {
SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
SDL_RenderDrawRect(renderer, &dest);
write(std::to_string(o.src.x) + ", " + std::to_string(o.src.y), dest.x + 20, dest.y + 20);
write(std::to_string(o.id) + " - " + std::to_string(o.frame), dest.x + 20, dest.y + 40);
}
}
}
void drawDebug(obj o) {
debug=1;
draw(o);
debug=0;
}
void draw(std::vector<obj> os) {
for(auto o:os) draw(o);
}
void drawDebug(std::vector<obj> os) {
for(auto o:os) drawDebug(o);
}
void drawRectUpfront(SDL_Rect r, SDL_Color c) {
SDL_SetRenderDrawColor(renderer, c.r, c.g, c.b, c.a);
SDL_RenderFillRect(renderer, &r);
}
void drawUpfront(obj o) {
SDL_RendererFlip flip = SDL_FLIP_NONE;
if(o.flipH) flip = SDL_FLIP_HORIZONTAL;
if(o.flipV) flip = SDL_FLIP_VERTICAL;
if(o.rotateOnCenter) {
SDL_RenderCopyEx(renderer, images[o.img], &o.src, &o.loc, o.angle, &o.center, flip);
} else {
SDL_RenderCopyEx(renderer, images[o.img], &o.src, &o.loc, o.angle, NULL, flip);
}
if(debug) {
SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
SDL_RenderDrawRect(renderer, &o.loc);
write(std::to_string(o.src.x) + ", " + std::to_string(o.src.y), o.loc.x + 20, o.loc.y + 20);
write(std::to_string(o.id) + " - " + std::to_string(o.frame), o.loc.x + 20, o.loc.y + 40);
}
}
void drawMap() {
for(auto m : map) {
draw(m);
}
}
void drawUI() {
healthBar.w = maxHealthBar * (player.health / player.maxHealth);
drawRectUpfront(healthBar, healthColor);
gunUI.src=gun.src;
shellSelect.src.y = shellSelect.src.h * ammo;
drawUpfront(UI);
drawUpfront(gunUI);
drawUpfront(shellSelect);
if(changingMod) drawUpfront(modSelect);
for(int a=0; a < 5; a++) {
write(std::to_string(ammoCount[a]), 220, a*23 + 35);
}
if(modsUnlocked[mod]) {write(mods[mod], 193, 6*23 + 16);} else {write("Locked", 193, 6*23 + 16);}
if(mods2Unlocked[mod2]) {write(mods2[mod2], 193, 7*23 + 20);} else {write("Locked", 193, 7*23 + 20);}
write(std::to_string(fps), 22, 5*40 + 28);
write(std::to_string(camera.x) + ", " + std::to_string(camera.y), 22, 6*40 + 16);
//SDL_RenderDrawLine(renderer, gun.loc.x + gun.center.x - (bullet.loc.w/2) - lens.x, gun.loc.y + gun.center.y - (bullet.loc.h/2) - lens.y, mouse.loc.x, mouse.loc.y);
}
std::vector<obj> buffer, organizedBuffer;
int bufLow, bufHigh;
void drawToBuffer(obj o) {
if(o.loc.y+o.loc.h > bufHigh) bufHigh=o.loc.y+o.loc.h;
if(o.loc.y+o.loc.h < bufLow || bufLow==-99) bufLow=o.loc.y+o.loc.h;
buffer.push_back(o);
}
void drawBuffer() {
for(int y=bufLow-500; y<bufHigh+500; y++) {
for(int b=0; b<buffer.size(); b++) {
if(buffer[b].loc.y+buffer[b].loc.h==y) {
organizedBuffer.push_back(buffer[b]);
if(buffer[b].parent) {
for(int c=0; c<buffer[b].children.size(); c++) {
organizedBuffer.push_back(*buffer[b].children[c]);
}
}
}
}
}
draw(organizedBuffer);
buffer.clear();
organizedBuffer.clear();
bufLow=bufHigh=-99;
}
//
void render() {
SDL_SetRenderTarget(renderer, screen);
SDL_SetRenderDrawColor(renderer, bkg.r, bkg.g, bkg.b, bkg.a);
SDL_RenderClear(renderer);
frameCount++;
timerFPS = SDL_GetTicks()-lastFrame;
if(timerFPS<(1000/setFPS)) {
SDL_Delay((1000/setFPS)-timerFPS);
}
//drawMap
drawMap();
draw(footPrints);
//drawtrees -> buffer
int treeCnt=0;
//buffer.clear();
for(auto m:map) {
int shift = 0;
if((treeCnt / map_width) % 2) shift+=tile_size/2;
if(m.id == TREE && inCamView(m.loc)) {
treeObj.loc = initRect(m.loc.x+shift,m.loc.y-(tile_size*.55),tile_size,tile_size*1.5);
treeObj.src = initRect(43*m.tick,0,43,76);
treeObj.flipH = m.flip;
drawToBuffer(treeObj);
}
treeCnt++;
}
//drawplayer -> buffer
drawToBuffer(player);
//draw(gun);
//drawenemy -> buffer
for(auto e:enemies) draw(e);
draw(bullets);
draw(collectables);
//draw(buffer);
drawBuffer();
draw(snowFall);
if(lighting.loc.w<=WIDTH*4) draw(lighting);
drawUI();
cursor.src.x = cursor.frame * cursor.src.w;
drawUpfront(cursor);
//write("hello world", WIDTH/2, HEIGHT/2);
//write(std::to_string(bullets.size()), WIDTH/2, HEIGHT/2);
SDL_SetRenderTarget(renderer, NULL);
if(shaking) {
if(shake) {
screendest.x+=3;
screendest.y+=3;
} else {
screendest.x-=3;
screendest.y-=3;
}
shake=!shake;
shaketick++;
}
if(shaketick > 3) {
shaking=0;
shaketick=0;
screendest=screensrc;
}
SDL_RenderCopy(renderer, screen, &screensrc, &screendest);
SDL_RenderPresent(renderer);
}
//draw
//init
int initAudio() {
SDL_Init(SDL_INIT_AUDIO);
if(Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0) {
printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
return -1;
}
gunSound = loadSound("res/ray.wav");
//song = loadMusic("res/cold.wav"); //https://www.youtube.com/watch?v=eQyg8MBQQog
return 0;
}
void initImages() {
tileImgId = setImage("res/tiles.png");
player.img = setImage("res/player.png");
cursor.img = setImage("res/cursor.png");
gun.img = setImage("res/raygun.png");
UI.img = setImage("res/UI.png");
shellSelect.img = setImage("res/select.png");
modSelect.img = shellSelect.img;
treeObj.img = setImage("res/tree.png");
footTmp.img = setImage("res/footprints.png");
snowTmp.img = setImage("res/snow.png");
chess.img = setImage("res/chess.png");
heart.img = setImage("res/health.png");
shell.img = setImage("res/shells.png");
bullet.img = setImage("res/bullets.png");
lighting.img = setImage("res/lighting2.png");
enemy.img = setImage("res/enemy.png");
enemyShadow.img = enemy.img;
}
void initObjs() {
player.src = initRect(0,0,7,10);
player.loc = initRect(player.loc.x, player.loc.y, tile_size-8, tile_size*1.2);
player.health=460; player.maxHealth=500;
player.vel=16;
player.alive=1;
cursor.src = initRect(0, 0, 18, 18);
cursor.loc = initRect(0, 0, tile_size, tile_size);
gun.src = initRect(0, 0, 14, 5);
gun.loc = initRect(0, 0, tile_size*1.1, (tile_size*1.1)/2);
gun.rotateOnCenter=1;
gun.center.x=0;gun.center.y=gun.loc.h*.5;
player.parent=1;
player.children.push_back(&gun);
footTmp.loc = initRect(0, 0, 50, 60);
footTmp.src = initRect(0, 0, 10, 15);
footTmp.tick = 300;
snowTmp.src = initRect(0, 0, 7, 8);
snowTmp.loc = initRect(0, 0, 17, 18);
enemy.src = initRect(0, 0, 12, 12);
enemy.loc = initRect(0, 0, player.loc.w, player.loc.w);
enemyShadow = enemy;
enemyShadow.src.x = enemyShadow.src.w * 6;
bullet.src = initRect(0, 0, 8, 6);
bullet.loc = initRect(0, 0, 40, 25);
chess.src = initRect(0,0,10,10);
chess.loc = initRect(0,0,50,50);
heart.src = initRect(0,0,10,10);
heart.loc = initRect(0,0,50,50);
shell.src = initRect(0,0,8,7);
shell.loc = initRect(0,0,30,20);
lighting.src = initRect(0, 0, 640, 360);
lighting.loc = initRect(0, 0, WIDTH, HEIGHT);
dayClock = WIDTH;
dayCycle = 1;
gunUI = gun;
gunUI.angle = -20;
gunUI.loc.x=43;gunUI.loc.y=96;
gunUI.loc.w=gun.loc.w*1.5;gunUI.loc.h=gun.loc.h*1.5;
UI.src.x=UI.src.y=0;
UI.src.w=220;UI.src.h=154;
UI.loc.x=UI.loc.y=20;
UI.loc.w=250;UI.loc.h=200;
healthBar.x=30;
healthBar.y=180;
maxHealthBar=UI.loc.w*.6;
healthBar.w=maxHealthBar;
healthBar.h=40;
int SSIMG = shellSelect.img;
shellSelect = UI;
shellSelect.img = SSIMG;
modSelect = shellSelect;
screensrc = initRect(0,0,WIDTH,HEIGHT);
screendest = screensrc;
screen = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, WIDTH, HEIGHT);
shake=shaking=0;
}
void init() {
seed = time(NULL);
srand(seed);
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
if(SDL_Init(SDL_INIT_EVERYTHING) < 0) std::cout << "Failed at SDL_Init()" << std::endl;
SDL_GetCurrentDisplayMode(0, &DM);
WIDTH=DM.w;
HEIGHT=DM.h;
window = SDL_CreateWindow(TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
TTF_Init();
font_size = 16;
font = TTF_OpenFont("res/font.ttf", font_size);
if(font == NULL) std::cout << "Failed to load font" << std::endl;
SDL_ShowCursor(SDL_DISABLE);
initAudio();
genMap();
running = 1;
setBkg(51, 73, 95);
lens.w=WIDTH;
lens.h=HEIGHT;
camera.x=WIDTH/2; camera.y=HEIGHT/2;
initImages();
initObjs();
floorPer();
font_color = white;
}
//quit
void quitSounds() {
for(int s=0; s<sounds.size(); s++) {
Mix_FreeChunk(sounds[s]);
sounds[s]=NULL;
}
for(int m=0; m<music.size(); m++) {
Mix_FreeMusic(music[m]);
music[m]=NULL;
}
Mix_Quit();
}
int quit() {
quitSounds();
TTF_CloseFont(font);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
//main
int main() {
init();
while(running) {
lastFrame=SDL_GetTicks();
if(lastFrame>=(lastTime+1000)) {
lastTime=lastFrame;
fps=frameCount;
frameCount=0;
}
input();
update();
render();
//std::cout << "Enemies: " << enemies.size() << std::endl;
//std::cout << "Bullets: " << bullets.size() << std::endl;
//std::cout << "Collectables: " << collectables.size() << std::endl;
//std::cout << "Snowfall: " << snowFall.size() << std::endl;
//std::cout << fps << std::endl << std::endl;
}
return quit();
}
| 32.315489 | 188 | 0.55343 | [
"render",
"vector"
] |
c4705de532cfa9108e7e188adb119893b12e6cfa | 15,120 | hpp | C++ | include/System/Xml/Schema/XmlSchemaException.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Xml/Schema/XmlSchemaException.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Xml/Schema/XmlSchemaException.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.SystemException
#include "System/SystemException.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Xml::Schema
namespace System::Xml::Schema {
// Forward declaring type: XmlSchemaObject
class XmlSchemaObject;
}
// Forward declaring namespace: System
namespace System {
// Skipping declaration: Exception because it is already included!
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
}
// Completed forward declares
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Forward declaring type: XmlSchemaException
class XmlSchemaException;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Xml::Schema::XmlSchemaException);
DEFINE_IL2CPP_ARG_TYPE(::System::Xml::Schema::XmlSchemaException*, "System.Xml.Schema", "XmlSchemaException");
// Type namespace: System.Xml.Schema
namespace System::Xml::Schema {
// Size: 0xB8
#pragma pack(push, 1)
// Autogenerated type: System.Xml.Schema.XmlSchemaException
// [TokenAttribute] Offset: FFFFFFFF
class XmlSchemaException : public ::System::SystemException {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private System.String res
// Size: 0x8
// Offset: 0x88
::StringW res;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private System.String[] args
// Size: 0x8
// Offset: 0x90
::ArrayW<::StringW> args;
// Field size check
static_assert(sizeof(::ArrayW<::StringW>) == 0x8);
// private System.String sourceUri
// Size: 0x8
// Offset: 0x98
::StringW sourceUri;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
// private System.Int32 lineNumber
// Size: 0x4
// Offset: 0xA0
int lineNumber;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 linePosition
// Size: 0x4
// Offset: 0xA4
int linePosition;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Xml.Schema.XmlSchemaObject sourceSchemaObject
// Size: 0x8
// Offset: 0xA8
::System::Xml::Schema::XmlSchemaObject* sourceSchemaObject;
// Field size check
static_assert(sizeof(::System::Xml::Schema::XmlSchemaObject*) == 0x8);
// private System.String message
// Size: 0x8
// Offset: 0xB0
::StringW message;
// Field size check
static_assert(sizeof(::StringW) == 0x8);
public:
// Get instance field reference: private System.String res
::StringW& dyn_res();
// Get instance field reference: private System.String[] args
::ArrayW<::StringW>& dyn_args();
// Get instance field reference: private System.String sourceUri
::StringW& dyn_sourceUri();
// Get instance field reference: private System.Int32 lineNumber
int& dyn_lineNumber();
// Get instance field reference: private System.Int32 linePosition
int& dyn_linePosition();
// Get instance field reference: private System.Xml.Schema.XmlSchemaObject sourceSchemaObject
::System::Xml::Schema::XmlSchemaObject*& dyn_sourceSchemaObject();
// Get instance field reference: private System.String message
::StringW& dyn_message();
// public System.Void .ctor(System.String message, System.Exception innerException, System.Int32 lineNumber, System.Int32 linePosition)
// Offset: 0x2011384
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor(::StringW message, ::System::Exception* innerException, int lineNumber, int linePosition) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>(message, innerException, lineNumber, linePosition)));
}
// System.Void .ctor(System.String res, System.String arg)
// Offset: 0x201153C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor(::StringW res, ::StringW arg) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>(res, arg)));
}
// System.Void .ctor(System.String res, System.String arg, System.String sourceUri, System.Int32 lineNumber, System.Int32 linePosition)
// Offset: 0x2011620
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor(::StringW res, ::StringW arg, ::StringW sourceUri, int lineNumber, int linePosition) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>(res, arg, sourceUri, lineNumber, linePosition)));
}
// System.Void .ctor(System.String res, System.String[] args, System.Exception innerException, System.String sourceUri, System.Int32 lineNumber, System.Int32 linePosition, System.Xml.Schema.XmlSchemaObject source)
// Offset: 0x20114B0
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor(::StringW res, ::ArrayW<::StringW> args, ::System::Exception* innerException, ::StringW sourceUri, int lineNumber, int linePosition, ::System::Xml::Schema::XmlSchemaObject* source) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>(res, args, innerException, sourceUri, lineNumber, linePosition, source)));
}
// static System.String CreateMessage(System.String res, System.String[] args)
// Offset: 0x2011140
static ::StringW CreateMessage(::StringW res, ::ArrayW<::StringW> args);
// public override System.String get_Message()
// Offset: 0x2011724
// Implemented from: System.Exception
// Base method: System.String Exception::get_Message()
::StringW get_Message();
// protected System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x2010E64
// Implemented from: System.SystemException
// Base method: System.Void SystemException::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Base method: System.Void Exception::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor(::System::Runtime::Serialization::SerializationInfo* info, ::System::Runtime::Serialization::StreamingContext context) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>(info, context)));
}
// public System.Void .ctor()
// Offset: 0x2011360
// Implemented from: System.SystemException
// Base method: System.Void SystemException::.ctor()
// Base method: System.Void Exception::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>()));
}
// public System.Void .ctor(System.String message)
// Offset: 0x2011374
// Implemented from: System.SystemException
// Base method: System.Void SystemException::.ctor(System.String message)
// Base method: System.Void Exception::.ctor(System.String message)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor(::StringW message) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>(message)));
}
// public System.Void .ctor(System.String message, System.Exception innerException)
// Offset: 0x20114A4
// Implemented from: System.SystemException
// Base method: System.Void SystemException::.ctor(System.String message, System.Exception innerException)
// Base method: System.Void Exception::.ctor(System.String message, System.Exception innerException)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static XmlSchemaException* New_ctor(::StringW message, ::System::Exception* innerException) {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Xml::Schema::XmlSchemaException::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<XmlSchemaException*, creationType>(message, innerException)));
}
// public override System.Void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x2011238
// Implemented from: System.Exception
// Base method: System.Void Exception::GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
void GetObjectData(::System::Runtime::Serialization::SerializationInfo* info, ::System::Runtime::Serialization::StreamingContext context);
}; // System.Xml.Schema.XmlSchemaException
#pragma pack(pop)
static check_size<sizeof(XmlSchemaException), 176 + sizeof(::StringW)> __System_Xml_Schema_XmlSchemaExceptionSizeCheck;
static_assert(sizeof(XmlSchemaException) == 0xB8);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::CreateMessage
// Il2CppName: CreateMessage
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (*)(::StringW, ::ArrayW<::StringW>)>(&System::Xml::Schema::XmlSchemaException::CreateMessage)> {
static const MethodInfo* get() {
static auto* res = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* args = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "String"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::Schema::XmlSchemaException*), "CreateMessage", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{res, args});
}
};
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::get_Message
// Il2CppName: get_Message
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (System::Xml::Schema::XmlSchemaException::*)()>(&System::Xml::Schema::XmlSchemaException::get_Message)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(System::Xml::Schema::XmlSchemaException*), "get_Message", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: System::Xml::Schema::XmlSchemaException::GetObjectData
// Il2CppName: GetObjectData
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Xml::Schema::XmlSchemaException::*)(::System::Runtime::Serialization::SerializationInfo*, ::System::Runtime::Serialization::StreamingContext)>(&System::Xml::Schema::XmlSchemaException::GetObjectData)> {
static const MethodInfo* get() {
static auto* info = &::il2cpp_utils::GetClassFromName("System.Runtime.Serialization", "SerializationInfo")->byval_arg;
static auto* context = &::il2cpp_utils::GetClassFromName("System.Runtime.Serialization", "StreamingContext")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Xml::Schema::XmlSchemaException*), "GetObjectData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{info, context});
}
};
| 57.490494 | 285 | 0.741997 | [
"object",
"vector"
] |
c4758694355135a624c4dc3731a94fcecc6ec818 | 2,357 | cc | C++ | src/q_151_200/q0153.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | 2 | 2021-09-28T18:41:03.000Z | 2021-09-28T18:42:57.000Z | src/q_151_200/q0153.cc | vNaonLu/Daily_LeetCode | 30024b561611d390931cef1b22afd6a5060cf586 | [
"MIT"
] | 16 | 2021-09-26T11:44:20.000Z | 2021-11-28T06:44:02.000Z | src/q_151_200/q0153.cc | vNaonLu/daily-leetcode | 2830c2cd413d950abe7c6d9b833c771f784443b0 | [
"MIT"
] | 1 | 2021-11-22T09:11:36.000Z | 2021-11-22T09:11:36.000Z | #include <gtest/gtest.h>
#include <iostream>
#include <vector>
using namespace std;
/**
* This file is generated by leetcode_add.py v1.0
*
* 153.
* Find Minimum in Rotated Sorted Array
*
* ––––––––––––––––––––––––––––– Description –––––––––––––––––––––––––––––
*
* Suppose an array of length ‘n’ sorted in ascending order is “rotated”
* between ‘1’ and ‘n’ times. For example, the array ‘nums =
* [0,1,2,4,5,6,7]’ might
* - ‘[4,5,6,7,0,1,2]’ if it was rotated ‘4’
* - ‘[0,1,2,4,5,6,7]’ if it was rotated ‘7’
* Notice that “rotating” an array ‘[a[0], a[1], a[2], ..., a[n-1]]’ 1
* time results in the array ‘[a[n-1], a[0], a[1], a[2], ..., a[n-2]]’
* Given the sorted rotated array ‘nums’ of “unique” elements, return
* “the minimum element of this array”
* You must write an algorithm that runs in ‘O(log n) time.’
*
* ––––––––––––––––––––––––––––– Constraints –––––––––––––––––––––––––––––
*
* • ‘n = nums.length’
* • ‘1 ≤ n ≤ 5000’
* • ‘-5000 ≤ nums[i] ≤ 5000’
* • All the integers of ‘nums’ are “unique” .
* • ‘nums’ is sorted and rotated between ‘1’ and ‘n’ times.
*
*/
struct q153 : public ::testing::Test {
// Leetcode answer here
class Solution {
public:
int findMin(vector<int>& nums) {
int beg = 0, end = nums.size() - 1;
if (nums[end] >= nums[beg])
return nums[beg];
else {
while (beg <= end) {
int mid = beg + (end - beg) / 2;
if (mid + 1 < nums.size() && nums[mid] > nums[mid + 1]) return nums[mid + 1];
if (mid - 1 >= 0 && nums[mid - 1] > nums[mid]) return nums[mid];
if (nums[mid] > nums[0])
beg = mid + 1;
else
end = mid - 1;
}
return -1;
}
}
};
class Solution *solution;
};
TEST_F(q153, sample_input01) {
solution = new Solution();
vector<int> nums = {3, 4, 5, 1, 2};
int exp = 1;
EXPECT_EQ(solution->findMin(nums), exp);
delete solution;
}
TEST_F(q153, sample_input02) {
solution = new Solution();
vector<int> nums = {4, 5, 6, 7, 0, 1, 2};
int exp = 0;
EXPECT_EQ(solution->findMin(nums), exp);
delete solution;
}
TEST_F(q153, sample_input03) {
solution = new Solution();
vector<int> nums = {11, 13, 15, 17};
int exp = 11;
EXPECT_EQ(solution->findMin(nums), exp);
delete solution;
} | 28.059524 | 87 | 0.527365 | [
"vector"
] |
c47914c677f1f77efcd4007428f167320463bb55 | 1,845 | hpp | C++ | include/parse.hpp | goens/TUD_computational_group_theory | 3f4703cae1ac049089db23eafc321e8daca2d99d | [
"MIT"
] | 2 | 2018-09-10T09:31:17.000Z | 2018-10-14T15:19:20.000Z | include/parse.hpp | goens/TUD_computational_group_theory | 3f4703cae1ac049089db23eafc321e8daca2d99d | [
"MIT"
] | 7 | 2020-06-11T07:25:08.000Z | 2020-12-19T09:07:50.000Z | include/parse.hpp | goens/TUD_computational_group_theory | 3f4703cae1ac049089db23eafc321e8daca2d99d | [
"MIT"
] | 2 | 2020-09-10T19:31:57.000Z | 2020-12-09T13:17:50.000Z | #ifndef GUARD_PARSE_H
#define GUARD_PARSE_H
#include <stdexcept>
#include <string>
#include <vector>
#include "perm.hpp"
#include "perm_set.hpp"
#include "string.hpp"
namespace mpsym
{
namespace util
{
inline internal::Perm parse_perm(unsigned degree, std::string const &str)
{
if (str == "()")
return internal::Perm(degree);
std::vector<unsigned> cycle;
std::vector<std::vector<unsigned>> cycles;
std::unordered_set<unsigned> seen;
int n_beg = -1;
for (int i = 0; i < static_cast<int>(str.size()); ++i) {
char c = str[i];
switch (c) {
case '(':
cycle.clear();
break;
case ',':
case ')':
{
unsigned n = stox<unsigned>(str.substr(n_beg, i - n_beg));
if (n >= degree)
throw std::invalid_argument("invalid permutation string");
if (!seen.insert(n).second)
throw std::invalid_argument("invalid permutation string");
cycle.push_back(n);
if (c == ')')
cycles.push_back(cycle);
n_beg = -1;
}
break;
default:
if (n_beg == -1)
n_beg = i;
}
}
return internal::Perm(degree, cycles);
}
inline internal::PermSet parse_perm_set(unsigned degree,
std::vector<std::string> const &strs)
{
internal::PermSet ret;
for (auto const &str : strs)
ret.insert(parse_perm(degree, str));
return ret;
}
inline internal::PermSet parse_perm_set(unsigned degree,
std::string const &str)
{
auto first = str.find('(');
auto last = str.rfind(')');
auto str_trimmed(str.substr(first, last - first + 1u));
auto strs(split(str_trimmed, "),"));
for (auto &str : strs)
str += ")";
return parse_perm_set(degree, strs);
}
} // namespace util
} // namespace mpsym
#endif // GUARD_PARSE_H
| 19.62766 | 77 | 0.58374 | [
"vector"
] |
c47d349d074dc180b3e0a1e6ebd7d7a751f03d94 | 10,690 | cpp | C++ | Queries/socialQueries.cpp | DnlPinguin/RangeReachSolutions | e8621b53395e2a8b45ecc46a10633aec3e1d6b84 | [
"MIT",
"Unlicense"
] | null | null | null | Queries/socialQueries.cpp | DnlPinguin/RangeReachSolutions | e8621b53395e2a8b45ecc46a10633aec3e1d6b84 | [
"MIT",
"Unlicense"
] | null | null | null | Queries/socialQueries.cpp | DnlPinguin/RangeReachSolutions | e8621b53395e2a8b45ecc46a10633aec3e1d6b84 | [
"MIT",
"Unlicense"
] | null | null | null | #include "socialQueries.h"
#include "helper.h"
bool socialFirstQuery(Graph* socialGraph, LocationMap* spatialGraph, vector<queryParameter>::iterator queryParam, socialFirstResult* statistics)
{
int node = queryParam->queryNode;
box spatialRegion = queryParam->spatialRegion;
spatialMbrRelation LocationNode;
box mbr;
vector<int> reachableNodes;
#ifdef STATISTICS
Timer clock;
clock.start();
#endif
if (socialGraph->NodeBelongsToSCC.count(node) != 0){
node = socialGraph->NodeBelongsToSCC[node];
}
vector<IntervalScheme>* Intervals = &(socialGraph->IntervalSchemeGraphMap[node]);
for (vector<IntervalScheme>::iterator iter = Intervals->begin() ; iter != Intervals->end(); iter++)
{
for (int it = iter->pre; it <= iter->post; it++)
{
reachableNodes.push_back(socialGraph->nodeHasPostorder[it]);
}
}
for (int i : reachableNodes)
#ifdef STATISTICS
int amount_of_reachable_nodes = 0;
double social_time = clock.stop();
int spatial_range_test_counter = 0;
clock.start();
#endif
for (int nodeToCheck : reachableNodes) {
#ifdef STATISTICS
amount_of_reachable_nodes++;
#endif
if (spatialGraph->existLocation(nodeToCheck))
{
LocationNode = spatialGraph->getLocation(nodeToCheck);
mbr = box(point(LocationNode.spatialData[0], LocationNode.spatialData[1]), point(LocationNode.spatialData[0], LocationNode.spatialData[1]));
if (!LocationNode.isMbr)
{
#ifdef STATISTICS
spatial_range_test_counter++;
#endif
if (boost::geometry::intersects(spatialRegion, mbr))
{
if (nodeToCheck != queryParam->queryNode) {
#ifdef STATISTICS
statistics->time_social = social_time;
statistics->time_spatial = clock.stop();
statistics->number_of_spatial_range_tests = spatial_range_test_counter;
statistics->reachable_nodes = amount_of_reachable_nodes;
#endif
return true;
}
}
}
else
{
for (int i = 4; i != LocationNode.spatialData.size(); i++)
{
#ifdef STATISTICS
spatial_range_test_counter++;
#endif
box mbr = box(point(LocationNode.spatialData[i], LocationNode.spatialData[(i + 1)]), point(LocationNode.spatialData[i], LocationNode.spatialData[(i + 1)]));
if (boost::geometry::intersects(spatialRegion, mbr))
{
if (nodeToCheck != queryParam->queryNode) {
#ifdef STATISTICS
statistics->time_social = social_time;
statistics->time_spatial = clock.stop();
statistics->number_of_spatial_range_tests = spatial_range_test_counter;
statistics->reachable_nodes = amount_of_reachable_nodes;
#endif
return true;
}
}
}
}
}
}
#ifdef STATISTICS
statistics->time_social = social_time;
statistics->time_spatial = clock.stop();
statistics->number_of_spatial_range_tests = spatial_range_test_counter;
statistics->reachable_nodes = amount_of_reachable_nodes;
#endif
return false;
}
bool socialFirstQueryWithMbr(Graph* socialGraph, LocationMap* spatialGraph, vector<queryParameter>::iterator queryParam, socialFirstResult* statistics) {
int node = queryParam->queryNode;
box spatialRegion = queryParam->spatialRegion;
if (socialGraph->NodeBelongsToSCC.count(node) != 0){
node = socialGraph->NodeBelongsToSCC[node];
}
vector<int> reachableNodes;
#ifdef STATISTICS
Timer clock;
clock.start();
#endif
vector<IntervalScheme>* Intervals = &(socialGraph->IntervalSchemeGraphMap[node]);
for (vector<IntervalScheme>::iterator iter = Intervals->begin() ; iter != Intervals->end(); iter++)
{
for (int it = iter->pre; it <= iter->post; it++)
{
reachableNodes.push_back(socialGraph->nodeHasPostorder[it]);
}
}
#ifdef STATISTICS
int amount_of_reachable_nodes = 0;
double social_time = clock.stop();
int spatial_range_test_counter = 0;
clock.start();
#endif
for (int nodeToCheck : reachableNodes)
{
#ifdef STATISTICS
amount_of_reachable_nodes++;
#endif
if (spatialGraph->existLocation(nodeToCheck))
{
spatialMbrRelation LocationNode = spatialGraph->getLocation(nodeToCheck);
tuple<bool,int> res = checkIfNodeIsInSpatialRegion(LocationNode.isMbr, LocationNode.spatialData, spatialRegion);
#ifdef STATISTICS
spatial_range_test_counter = spatial_range_test_counter + get<1>(res);
#endif
if (get<0>(res))
{
if (queryParam->queryNode != nodeToCheck) {
#ifdef STATISTICS
statistics->time_social = social_time;
statistics->time_spatial = clock.stop();
statistics->number_of_spatial_range_tests = spatial_range_test_counter;
statistics->reachable_nodes = amount_of_reachable_nodes;
#endif
return true;
}
}
}
}
#ifdef STATISTICS
statistics->time_social = social_time;
statistics->time_spatial = clock.stop();
statistics->number_of_spatial_range_tests = spatial_range_test_counter;
statistics->reachable_nodes = amount_of_reachable_nodes;
#endif
return false;
}
bool strictSocialFirstQuery(Graph* socialGraph, LocationMap* spatialGraph, vector<queryParameter>::iterator queryParam, socialFirstResult* statistics)
{
int node = queryParam->queryNode;
if (socialGraph->NodeBelongsToSCC.count(node) != 0){
node = socialGraph->NodeBelongsToSCC[node];
}
box spatialRegion = queryParam->spatialRegion;
#ifdef STATISTICS
Timer clock;
clock.start();
#endif
vector<IntervalScheme>* Intervals = &(socialGraph->IntervalSchemeGraphMap[node]);
for (vector<IntervalScheme>::iterator iter = Intervals->begin() ; iter != Intervals->end(); iter++)
{
for (int it = iter->pre; it <= iter->post; it++)
{
int reachableNode = socialGraph->nodeHasPostorder[it];
if (spatialGraph->existLocation(reachableNode))
{
spatialMbrRelation LocationNode = spatialGraph->getLocation(reachableNode);
box mbr = box(point(LocationNode.spatialData[0], LocationNode.spatialData[1]), point(LocationNode.spatialData[0], LocationNode.spatialData[1]));
if (!LocationNode.isMbr)
{
// spatial_range_test_counter++;
if (boost::geometry::intersects(spatialRegion, mbr))
{
if (reachableNode != queryParam->queryNode) {
// statistics->time_social = social_time;
// statistics->time_spatial = clock.stop();
// statistics->number_of_spatial_range_tests = spatial_range_test_counter;
// statistics->reachable_nodes = amount_of_reachable_nodes;
return true;
}
}
}
else
{
for (int i = 4; i != LocationNode.spatialData.size(); i++)
{
// spatial_range_test_counter++;
box mbr = box(point(LocationNode.spatialData[i], LocationNode.spatialData[(i + 1)]), point(LocationNode.spatialData[i], LocationNode.spatialData[(i + 1)]));
if (boost::geometry::intersects(spatialRegion, mbr))
{
if (reachableNode != queryParam->queryNode) {
// statistics->time_social = social_time;
// statistics->time_spatial = clock.stop();
// statistics->number_of_spatial_range_tests = spatial_range_test_counter;
// statistics->reachable_nodes = amount_of_reachable_nodes;
return true;
}
}
}
}
}
}
}
return false;
}
bool strictSocialFirstQueryWithMbr(Graph* socialGraph, LocationMap* spatialGraph, vector<queryParameter>::iterator queryParam, socialFirstResult* statistics)
{
int node = queryParam->queryNode;
if (socialGraph->NodeBelongsToSCC.count(node) != 0){
node = socialGraph->NodeBelongsToSCC[node];
}
box spatialRegion = queryParam->spatialRegion;
vector<IntervalScheme>* Intervals = &(socialGraph->IntervalSchemeGraphMap[node]);
for (vector<IntervalScheme>::iterator iter = Intervals->begin() ; iter != Intervals->end(); iter++)
{
for (int it = iter->pre; it <= iter->post; it++)
{
int reachableNode = socialGraph->nodeHasPostorder[it];
if (spatialGraph->existLocation(reachableNode))
{
spatialMbrRelation LocationNode = spatialGraph->getLocation(reachableNode);
tuple<bool,int> res = checkIfNodeIsInSpatialRegion(LocationNode.isMbr, LocationNode.spatialData, spatialRegion);
if (get<0>(res))
{
if (queryParam->queryNode != reachableNode)
{
// statistics->time_social = social_time;
// statistics->time_spatial = clock.stop();
// statistics->number_of_spatial_range_tests = spatial_range_test_counter;
// statistics->reachable_nodes = amount_of_reachable_nodes;
return true;
}
}
}
}
}
return false;
}
| 40.957854 | 180 | 0.557717 | [
"geometry",
"vector"
] |
c482a142e3c572eb1574ed366b2a8e75e9930b44 | 100,058 | cc | C++ | wrappers/8.1.1/vtkImagePlaneWidgetWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/8.1.1/vtkImagePlaneWidgetWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/8.1.1/vtkImagePlaneWidgetWrap.cc | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>
#include "vtkPolyDataSourceWidgetWrap.h"
#include "vtkImagePlaneWidgetWrap.h"
#include "vtkObjectBaseWrap.h"
#include "vtkAlgorithmOutputWrap.h"
#include "vtkImageDataWrap.h"
#include "vtkPolyDataWrap.h"
#include "vtkPolyDataAlgorithmWrap.h"
#include "vtkTextureWrap.h"
#include "vtkImageMapToColorsWrap.h"
#include "vtkPropertyWrap.h"
#include "vtkAbstractPropPickerWrap.h"
#include "vtkLookupTableWrap.h"
#include "vtkTextPropertyWrap.h"
#include "vtkMatrix4x4Wrap.h"
#include "vtkImageResliceWrap.h"
#include "../../plus/plus.h"
using namespace v8;
extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkImagePlaneWidgetWrap::ptpl;
VtkImagePlaneWidgetWrap::VtkImagePlaneWidgetWrap()
{ }
VtkImagePlaneWidgetWrap::VtkImagePlaneWidgetWrap(vtkSmartPointer<vtkImagePlaneWidget> _native)
{ native = _native; }
VtkImagePlaneWidgetWrap::~VtkImagePlaneWidgetWrap()
{ }
void VtkImagePlaneWidgetWrap::Init(v8::Local<v8::Object> exports)
{
Nan::SetAccessor(exports, Nan::New("vtkImagePlaneWidget").ToLocalChecked(), ConstructorGetter);
Nan::SetAccessor(exports, Nan::New("ImagePlaneWidget").ToLocalChecked(), ConstructorGetter);
}
void VtkImagePlaneWidgetWrap::ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info)
{
InitPtpl();
info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}
void VtkImagePlaneWidgetWrap::InitPtpl()
{
if (!ptpl.IsEmpty()) return;
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
VtkPolyDataSourceWidgetWrap::InitPtpl( );
tpl->Inherit(Nan::New<FunctionTemplate>(VtkPolyDataSourceWidgetWrap::ptpl));
tpl->SetClassName(Nan::New("VtkImagePlaneWidgetWrap").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "DisplayTextOff", DisplayTextOff);
Nan::SetPrototypeMethod(tpl, "displayTextOff", DisplayTextOff);
Nan::SetPrototypeMethod(tpl, "DisplayTextOn", DisplayTextOn);
Nan::SetPrototypeMethod(tpl, "displayTextOn", DisplayTextOn);
Nan::SetPrototypeMethod(tpl, "GetCenter", GetCenter);
Nan::SetPrototypeMethod(tpl, "getCenter", GetCenter);
Nan::SetPrototypeMethod(tpl, "GetColorMap", GetColorMap);
Nan::SetPrototypeMethod(tpl, "getColorMap", GetColorMap);
Nan::SetPrototypeMethod(tpl, "GetCurrentCursorPosition", GetCurrentCursorPosition);
Nan::SetPrototypeMethod(tpl, "getCurrentCursorPosition", GetCurrentCursorPosition);
Nan::SetPrototypeMethod(tpl, "GetCurrentImageValue", GetCurrentImageValue);
Nan::SetPrototypeMethod(tpl, "getCurrentImageValue", GetCurrentImageValue);
Nan::SetPrototypeMethod(tpl, "GetCursorData", GetCursorData);
Nan::SetPrototypeMethod(tpl, "getCursorData", GetCursorData);
Nan::SetPrototypeMethod(tpl, "GetCursorDataStatus", GetCursorDataStatus);
Nan::SetPrototypeMethod(tpl, "getCursorDataStatus", GetCursorDataStatus);
Nan::SetPrototypeMethod(tpl, "GetCursorProperty", GetCursorProperty);
Nan::SetPrototypeMethod(tpl, "getCursorProperty", GetCursorProperty);
Nan::SetPrototypeMethod(tpl, "GetDisplayText", GetDisplayText);
Nan::SetPrototypeMethod(tpl, "getDisplayText", GetDisplayText);
Nan::SetPrototypeMethod(tpl, "GetInteraction", GetInteraction);
Nan::SetPrototypeMethod(tpl, "getInteraction", GetInteraction);
Nan::SetPrototypeMethod(tpl, "GetLeftButtonAction", GetLeftButtonAction);
Nan::SetPrototypeMethod(tpl, "getLeftButtonAction", GetLeftButtonAction);
Nan::SetPrototypeMethod(tpl, "GetLeftButtonActionMaxValue", GetLeftButtonActionMaxValue);
Nan::SetPrototypeMethod(tpl, "getLeftButtonActionMaxValue", GetLeftButtonActionMaxValue);
Nan::SetPrototypeMethod(tpl, "GetLeftButtonActionMinValue", GetLeftButtonActionMinValue);
Nan::SetPrototypeMethod(tpl, "getLeftButtonActionMinValue", GetLeftButtonActionMinValue);
Nan::SetPrototypeMethod(tpl, "GetLeftButtonAutoModifier", GetLeftButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "getLeftButtonAutoModifier", GetLeftButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "GetLeftButtonAutoModifierMaxValue", GetLeftButtonAutoModifierMaxValue);
Nan::SetPrototypeMethod(tpl, "getLeftButtonAutoModifierMaxValue", GetLeftButtonAutoModifierMaxValue);
Nan::SetPrototypeMethod(tpl, "GetLeftButtonAutoModifierMinValue", GetLeftButtonAutoModifierMinValue);
Nan::SetPrototypeMethod(tpl, "getLeftButtonAutoModifierMinValue", GetLeftButtonAutoModifierMinValue);
Nan::SetPrototypeMethod(tpl, "GetLevel", GetLevel);
Nan::SetPrototypeMethod(tpl, "getLevel", GetLevel);
Nan::SetPrototypeMethod(tpl, "GetLookupTable", GetLookupTable);
Nan::SetPrototypeMethod(tpl, "getLookupTable", GetLookupTable);
Nan::SetPrototypeMethod(tpl, "GetMarginProperty", GetMarginProperty);
Nan::SetPrototypeMethod(tpl, "getMarginProperty", GetMarginProperty);
Nan::SetPrototypeMethod(tpl, "GetMarginSizeX", GetMarginSizeX);
Nan::SetPrototypeMethod(tpl, "getMarginSizeX", GetMarginSizeX);
Nan::SetPrototypeMethod(tpl, "GetMarginSizeXMaxValue", GetMarginSizeXMaxValue);
Nan::SetPrototypeMethod(tpl, "getMarginSizeXMaxValue", GetMarginSizeXMaxValue);
Nan::SetPrototypeMethod(tpl, "GetMarginSizeXMinValue", GetMarginSizeXMinValue);
Nan::SetPrototypeMethod(tpl, "getMarginSizeXMinValue", GetMarginSizeXMinValue);
Nan::SetPrototypeMethod(tpl, "GetMarginSizeY", GetMarginSizeY);
Nan::SetPrototypeMethod(tpl, "getMarginSizeY", GetMarginSizeY);
Nan::SetPrototypeMethod(tpl, "GetMarginSizeYMaxValue", GetMarginSizeYMaxValue);
Nan::SetPrototypeMethod(tpl, "getMarginSizeYMaxValue", GetMarginSizeYMaxValue);
Nan::SetPrototypeMethod(tpl, "GetMarginSizeYMinValue", GetMarginSizeYMinValue);
Nan::SetPrototypeMethod(tpl, "getMarginSizeYMinValue", GetMarginSizeYMinValue);
Nan::SetPrototypeMethod(tpl, "GetMiddleButtonAction", GetMiddleButtonAction);
Nan::SetPrototypeMethod(tpl, "getMiddleButtonAction", GetMiddleButtonAction);
Nan::SetPrototypeMethod(tpl, "GetMiddleButtonActionMaxValue", GetMiddleButtonActionMaxValue);
Nan::SetPrototypeMethod(tpl, "getMiddleButtonActionMaxValue", GetMiddleButtonActionMaxValue);
Nan::SetPrototypeMethod(tpl, "GetMiddleButtonActionMinValue", GetMiddleButtonActionMinValue);
Nan::SetPrototypeMethod(tpl, "getMiddleButtonActionMinValue", GetMiddleButtonActionMinValue);
Nan::SetPrototypeMethod(tpl, "GetMiddleButtonAutoModifier", GetMiddleButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "getMiddleButtonAutoModifier", GetMiddleButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "GetMiddleButtonAutoModifierMaxValue", GetMiddleButtonAutoModifierMaxValue);
Nan::SetPrototypeMethod(tpl, "getMiddleButtonAutoModifierMaxValue", GetMiddleButtonAutoModifierMaxValue);
Nan::SetPrototypeMethod(tpl, "GetMiddleButtonAutoModifierMinValue", GetMiddleButtonAutoModifierMinValue);
Nan::SetPrototypeMethod(tpl, "getMiddleButtonAutoModifierMinValue", GetMiddleButtonAutoModifierMinValue);
Nan::SetPrototypeMethod(tpl, "GetNormal", GetNormal);
Nan::SetPrototypeMethod(tpl, "getNormal", GetNormal);
Nan::SetPrototypeMethod(tpl, "GetOrigin", GetOrigin);
Nan::SetPrototypeMethod(tpl, "getOrigin", GetOrigin);
Nan::SetPrototypeMethod(tpl, "GetPlaneOrientation", GetPlaneOrientation);
Nan::SetPrototypeMethod(tpl, "getPlaneOrientation", GetPlaneOrientation);
Nan::SetPrototypeMethod(tpl, "GetPlaneProperty", GetPlaneProperty);
Nan::SetPrototypeMethod(tpl, "getPlaneProperty", GetPlaneProperty);
Nan::SetPrototypeMethod(tpl, "GetPoint1", GetPoint1);
Nan::SetPrototypeMethod(tpl, "getPoint1", GetPoint1);
Nan::SetPrototypeMethod(tpl, "GetPoint2", GetPoint2);
Nan::SetPrototypeMethod(tpl, "getPoint2", GetPoint2);
Nan::SetPrototypeMethod(tpl, "GetPolyData", GetPolyData);
Nan::SetPrototypeMethod(tpl, "getPolyData", GetPolyData);
Nan::SetPrototypeMethod(tpl, "GetPolyDataAlgorithm", GetPolyDataAlgorithm);
Nan::SetPrototypeMethod(tpl, "getPolyDataAlgorithm", GetPolyDataAlgorithm);
Nan::SetPrototypeMethod(tpl, "GetReslice", GetReslice);
Nan::SetPrototypeMethod(tpl, "getReslice", GetReslice);
Nan::SetPrototypeMethod(tpl, "GetResliceAxes", GetResliceAxes);
Nan::SetPrototypeMethod(tpl, "getResliceAxes", GetResliceAxes);
Nan::SetPrototypeMethod(tpl, "GetResliceInterpolate", GetResliceInterpolate);
Nan::SetPrototypeMethod(tpl, "getResliceInterpolate", GetResliceInterpolate);
Nan::SetPrototypeMethod(tpl, "GetResliceOutput", GetResliceOutput);
Nan::SetPrototypeMethod(tpl, "getResliceOutput", GetResliceOutput);
Nan::SetPrototypeMethod(tpl, "GetRestrictPlaneToVolume", GetRestrictPlaneToVolume);
Nan::SetPrototypeMethod(tpl, "getRestrictPlaneToVolume", GetRestrictPlaneToVolume);
Nan::SetPrototypeMethod(tpl, "GetRightButtonAction", GetRightButtonAction);
Nan::SetPrototypeMethod(tpl, "getRightButtonAction", GetRightButtonAction);
Nan::SetPrototypeMethod(tpl, "GetRightButtonActionMaxValue", GetRightButtonActionMaxValue);
Nan::SetPrototypeMethod(tpl, "getRightButtonActionMaxValue", GetRightButtonActionMaxValue);
Nan::SetPrototypeMethod(tpl, "GetRightButtonActionMinValue", GetRightButtonActionMinValue);
Nan::SetPrototypeMethod(tpl, "getRightButtonActionMinValue", GetRightButtonActionMinValue);
Nan::SetPrototypeMethod(tpl, "GetRightButtonAutoModifier", GetRightButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "getRightButtonAutoModifier", GetRightButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "GetRightButtonAutoModifierMaxValue", GetRightButtonAutoModifierMaxValue);
Nan::SetPrototypeMethod(tpl, "getRightButtonAutoModifierMaxValue", GetRightButtonAutoModifierMaxValue);
Nan::SetPrototypeMethod(tpl, "GetRightButtonAutoModifierMinValue", GetRightButtonAutoModifierMinValue);
Nan::SetPrototypeMethod(tpl, "getRightButtonAutoModifierMinValue", GetRightButtonAutoModifierMinValue);
Nan::SetPrototypeMethod(tpl, "GetSelectedPlaneProperty", GetSelectedPlaneProperty);
Nan::SetPrototypeMethod(tpl, "getSelectedPlaneProperty", GetSelectedPlaneProperty);
Nan::SetPrototypeMethod(tpl, "GetSliceIndex", GetSliceIndex);
Nan::SetPrototypeMethod(tpl, "getSliceIndex", GetSliceIndex);
Nan::SetPrototypeMethod(tpl, "GetSlicePosition", GetSlicePosition);
Nan::SetPrototypeMethod(tpl, "getSlicePosition", GetSlicePosition);
Nan::SetPrototypeMethod(tpl, "GetTextProperty", GetTextProperty);
Nan::SetPrototypeMethod(tpl, "getTextProperty", GetTextProperty);
Nan::SetPrototypeMethod(tpl, "GetTexture", GetTexture);
Nan::SetPrototypeMethod(tpl, "getTexture", GetTexture);
Nan::SetPrototypeMethod(tpl, "GetTextureInterpolate", GetTextureInterpolate);
Nan::SetPrototypeMethod(tpl, "getTextureInterpolate", GetTextureInterpolate);
Nan::SetPrototypeMethod(tpl, "GetTexturePlaneProperty", GetTexturePlaneProperty);
Nan::SetPrototypeMethod(tpl, "getTexturePlaneProperty", GetTexturePlaneProperty);
Nan::SetPrototypeMethod(tpl, "GetTextureVisibility", GetTextureVisibility);
Nan::SetPrototypeMethod(tpl, "getTextureVisibility", GetTextureVisibility);
Nan::SetPrototypeMethod(tpl, "GetUseContinuousCursor", GetUseContinuousCursor);
Nan::SetPrototypeMethod(tpl, "getUseContinuousCursor", GetUseContinuousCursor);
Nan::SetPrototypeMethod(tpl, "GetUserControlledLookupTable", GetUserControlledLookupTable);
Nan::SetPrototypeMethod(tpl, "getUserControlledLookupTable", GetUserControlledLookupTable);
Nan::SetPrototypeMethod(tpl, "GetVector1", GetVector1);
Nan::SetPrototypeMethod(tpl, "getVector1", GetVector1);
Nan::SetPrototypeMethod(tpl, "GetVector2", GetVector2);
Nan::SetPrototypeMethod(tpl, "getVector2", GetVector2);
Nan::SetPrototypeMethod(tpl, "GetWindow", GetWindow);
Nan::SetPrototypeMethod(tpl, "getWindow", GetWindow);
Nan::SetPrototypeMethod(tpl, "GetWindowLevel", GetWindowLevel);
Nan::SetPrototypeMethod(tpl, "getWindowLevel", GetWindowLevel);
Nan::SetPrototypeMethod(tpl, "InteractionOff", InteractionOff);
Nan::SetPrototypeMethod(tpl, "interactionOff", InteractionOff);
Nan::SetPrototypeMethod(tpl, "InteractionOn", InteractionOn);
Nan::SetPrototypeMethod(tpl, "interactionOn", InteractionOn);
Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);
Nan::SetPrototypeMethod(tpl, "PlaceWidget", PlaceWidget);
Nan::SetPrototypeMethod(tpl, "placeWidget", PlaceWidget);
Nan::SetPrototypeMethod(tpl, "RestrictPlaneToVolumeOff", RestrictPlaneToVolumeOff);
Nan::SetPrototypeMethod(tpl, "restrictPlaneToVolumeOff", RestrictPlaneToVolumeOff);
Nan::SetPrototypeMethod(tpl, "RestrictPlaneToVolumeOn", RestrictPlaneToVolumeOn);
Nan::SetPrototypeMethod(tpl, "restrictPlaneToVolumeOn", RestrictPlaneToVolumeOn);
Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);
Nan::SetPrototypeMethod(tpl, "SetColorMap", SetColorMap);
Nan::SetPrototypeMethod(tpl, "setColorMap", SetColorMap);
Nan::SetPrototypeMethod(tpl, "SetCursorProperty", SetCursorProperty);
Nan::SetPrototypeMethod(tpl, "setCursorProperty", SetCursorProperty);
Nan::SetPrototypeMethod(tpl, "SetDisplayText", SetDisplayText);
Nan::SetPrototypeMethod(tpl, "setDisplayText", SetDisplayText);
Nan::SetPrototypeMethod(tpl, "SetEnabled", SetEnabled);
Nan::SetPrototypeMethod(tpl, "setEnabled", SetEnabled);
Nan::SetPrototypeMethod(tpl, "SetInputConnection", SetInputConnection);
Nan::SetPrototypeMethod(tpl, "setInputConnection", SetInputConnection);
Nan::SetPrototypeMethod(tpl, "SetInteraction", SetInteraction);
Nan::SetPrototypeMethod(tpl, "setInteraction", SetInteraction);
Nan::SetPrototypeMethod(tpl, "SetLeftButtonAction", SetLeftButtonAction);
Nan::SetPrototypeMethod(tpl, "setLeftButtonAction", SetLeftButtonAction);
Nan::SetPrototypeMethod(tpl, "SetLeftButtonAutoModifier", SetLeftButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "setLeftButtonAutoModifier", SetLeftButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "SetLookupTable", SetLookupTable);
Nan::SetPrototypeMethod(tpl, "setLookupTable", SetLookupTable);
Nan::SetPrototypeMethod(tpl, "SetMarginProperty", SetMarginProperty);
Nan::SetPrototypeMethod(tpl, "setMarginProperty", SetMarginProperty);
Nan::SetPrototypeMethod(tpl, "SetMarginSizeX", SetMarginSizeX);
Nan::SetPrototypeMethod(tpl, "setMarginSizeX", SetMarginSizeX);
Nan::SetPrototypeMethod(tpl, "SetMarginSizeY", SetMarginSizeY);
Nan::SetPrototypeMethod(tpl, "setMarginSizeY", SetMarginSizeY);
Nan::SetPrototypeMethod(tpl, "SetMiddleButtonAction", SetMiddleButtonAction);
Nan::SetPrototypeMethod(tpl, "setMiddleButtonAction", SetMiddleButtonAction);
Nan::SetPrototypeMethod(tpl, "SetMiddleButtonAutoModifier", SetMiddleButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "setMiddleButtonAutoModifier", SetMiddleButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "SetOrigin", SetOrigin);
Nan::SetPrototypeMethod(tpl, "setOrigin", SetOrigin);
Nan::SetPrototypeMethod(tpl, "SetPicker", SetPicker);
Nan::SetPrototypeMethod(tpl, "setPicker", SetPicker);
Nan::SetPrototypeMethod(tpl, "SetPlaneOrientation", SetPlaneOrientation);
Nan::SetPrototypeMethod(tpl, "setPlaneOrientation", SetPlaneOrientation);
Nan::SetPrototypeMethod(tpl, "SetPlaneOrientationToXAxes", SetPlaneOrientationToXAxes);
Nan::SetPrototypeMethod(tpl, "setPlaneOrientationToXAxes", SetPlaneOrientationToXAxes);
Nan::SetPrototypeMethod(tpl, "SetPlaneOrientationToYAxes", SetPlaneOrientationToYAxes);
Nan::SetPrototypeMethod(tpl, "setPlaneOrientationToYAxes", SetPlaneOrientationToYAxes);
Nan::SetPrototypeMethod(tpl, "SetPlaneOrientationToZAxes", SetPlaneOrientationToZAxes);
Nan::SetPrototypeMethod(tpl, "setPlaneOrientationToZAxes", SetPlaneOrientationToZAxes);
Nan::SetPrototypeMethod(tpl, "SetPlaneProperty", SetPlaneProperty);
Nan::SetPrototypeMethod(tpl, "setPlaneProperty", SetPlaneProperty);
Nan::SetPrototypeMethod(tpl, "SetPoint1", SetPoint1);
Nan::SetPrototypeMethod(tpl, "setPoint1", SetPoint1);
Nan::SetPrototypeMethod(tpl, "SetPoint2", SetPoint2);
Nan::SetPrototypeMethod(tpl, "setPoint2", SetPoint2);
Nan::SetPrototypeMethod(tpl, "SetResliceInterpolate", SetResliceInterpolate);
Nan::SetPrototypeMethod(tpl, "setResliceInterpolate", SetResliceInterpolate);
Nan::SetPrototypeMethod(tpl, "SetResliceInterpolateToCubic", SetResliceInterpolateToCubic);
Nan::SetPrototypeMethod(tpl, "setResliceInterpolateToCubic", SetResliceInterpolateToCubic);
Nan::SetPrototypeMethod(tpl, "SetResliceInterpolateToLinear", SetResliceInterpolateToLinear);
Nan::SetPrototypeMethod(tpl, "setResliceInterpolateToLinear", SetResliceInterpolateToLinear);
Nan::SetPrototypeMethod(tpl, "SetResliceInterpolateToNearestNeighbour", SetResliceInterpolateToNearestNeighbour);
Nan::SetPrototypeMethod(tpl, "setResliceInterpolateToNearestNeighbour", SetResliceInterpolateToNearestNeighbour);
Nan::SetPrototypeMethod(tpl, "SetRestrictPlaneToVolume", SetRestrictPlaneToVolume);
Nan::SetPrototypeMethod(tpl, "setRestrictPlaneToVolume", SetRestrictPlaneToVolume);
Nan::SetPrototypeMethod(tpl, "SetRightButtonAction", SetRightButtonAction);
Nan::SetPrototypeMethod(tpl, "setRightButtonAction", SetRightButtonAction);
Nan::SetPrototypeMethod(tpl, "SetRightButtonAutoModifier", SetRightButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "setRightButtonAutoModifier", SetRightButtonAutoModifier);
Nan::SetPrototypeMethod(tpl, "SetSelectedPlaneProperty", SetSelectedPlaneProperty);
Nan::SetPrototypeMethod(tpl, "setSelectedPlaneProperty", SetSelectedPlaneProperty);
Nan::SetPrototypeMethod(tpl, "SetSliceIndex", SetSliceIndex);
Nan::SetPrototypeMethod(tpl, "setSliceIndex", SetSliceIndex);
Nan::SetPrototypeMethod(tpl, "SetSlicePosition", SetSlicePosition);
Nan::SetPrototypeMethod(tpl, "setSlicePosition", SetSlicePosition);
Nan::SetPrototypeMethod(tpl, "SetTextProperty", SetTextProperty);
Nan::SetPrototypeMethod(tpl, "setTextProperty", SetTextProperty);
Nan::SetPrototypeMethod(tpl, "SetTextureInterpolate", SetTextureInterpolate);
Nan::SetPrototypeMethod(tpl, "setTextureInterpolate", SetTextureInterpolate);
Nan::SetPrototypeMethod(tpl, "SetTexturePlaneProperty", SetTexturePlaneProperty);
Nan::SetPrototypeMethod(tpl, "setTexturePlaneProperty", SetTexturePlaneProperty);
Nan::SetPrototypeMethod(tpl, "SetTextureVisibility", SetTextureVisibility);
Nan::SetPrototypeMethod(tpl, "setTextureVisibility", SetTextureVisibility);
Nan::SetPrototypeMethod(tpl, "SetUseContinuousCursor", SetUseContinuousCursor);
Nan::SetPrototypeMethod(tpl, "setUseContinuousCursor", SetUseContinuousCursor);
Nan::SetPrototypeMethod(tpl, "SetUserControlledLookupTable", SetUserControlledLookupTable);
Nan::SetPrototypeMethod(tpl, "setUserControlledLookupTable", SetUserControlledLookupTable);
Nan::SetPrototypeMethod(tpl, "SetWindowLevel", SetWindowLevel);
Nan::SetPrototypeMethod(tpl, "setWindowLevel", SetWindowLevel);
Nan::SetPrototypeMethod(tpl, "TextureInterpolateOff", TextureInterpolateOff);
Nan::SetPrototypeMethod(tpl, "textureInterpolateOff", TextureInterpolateOff);
Nan::SetPrototypeMethod(tpl, "TextureInterpolateOn", TextureInterpolateOn);
Nan::SetPrototypeMethod(tpl, "textureInterpolateOn", TextureInterpolateOn);
Nan::SetPrototypeMethod(tpl, "TextureVisibilityOff", TextureVisibilityOff);
Nan::SetPrototypeMethod(tpl, "textureVisibilityOff", TextureVisibilityOff);
Nan::SetPrototypeMethod(tpl, "TextureVisibilityOn", TextureVisibilityOn);
Nan::SetPrototypeMethod(tpl, "textureVisibilityOn", TextureVisibilityOn);
Nan::SetPrototypeMethod(tpl, "UpdatePlacement", UpdatePlacement);
Nan::SetPrototypeMethod(tpl, "updatePlacement", UpdatePlacement);
Nan::SetPrototypeMethod(tpl, "UseContinuousCursorOff", UseContinuousCursorOff);
Nan::SetPrototypeMethod(tpl, "useContinuousCursorOff", UseContinuousCursorOff);
Nan::SetPrototypeMethod(tpl, "UseContinuousCursorOn", UseContinuousCursorOn);
Nan::SetPrototypeMethod(tpl, "useContinuousCursorOn", UseContinuousCursorOn);
Nan::SetPrototypeMethod(tpl, "UserControlledLookupTableOff", UserControlledLookupTableOff);
Nan::SetPrototypeMethod(tpl, "userControlledLookupTableOff", UserControlledLookupTableOff);
Nan::SetPrototypeMethod(tpl, "UserControlledLookupTableOn", UserControlledLookupTableOn);
Nan::SetPrototypeMethod(tpl, "userControlledLookupTableOn", UserControlledLookupTableOn);
#ifdef VTK_NODE_PLUS_VTKIMAGEPLANEWIDGETWRAP_INITPTPL
VTK_NODE_PLUS_VTKIMAGEPLANEWIDGETWRAP_INITPTPL
#endif
ptpl.Reset( tpl );
}
void VtkImagePlaneWidgetWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
if(!info.IsConstructCall())
{
Nan::ThrowError("Constructor not called in a construct call.");
return;
}
if(info.Length() == 0)
{
vtkSmartPointer<vtkImagePlaneWidget> native = vtkSmartPointer<vtkImagePlaneWidget>::New();
VtkImagePlaneWidgetWrap* obj = new VtkImagePlaneWidgetWrap(native);
obj->Wrap(info.This());
}
else
{
if(info[0]->ToObject() != vtkNodeJsNoWrap )
{
Nan::ThrowError("Parameter Error");
return;
}
}
info.GetReturnValue().Set(info.This());
}
void VtkImagePlaneWidgetWrap::DisplayTextOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DisplayTextOff();
}
void VtkImagePlaneWidgetWrap::DisplayTextOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->DisplayTextOn();
}
void VtkImagePlaneWidgetWrap::GetCenter(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetCenter(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetCenter(
b0
);
return;
}
double const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCenter();
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double));
Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3);
memcpy(ab->GetContents().Data(), r, 3 * sizeof(double));
info.GetReturnValue().Set(at);
}
void VtkImagePlaneWidgetWrap::GetColorMap(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkImageMapToColors * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetColorMap();
VtkImageMapToColorsWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImageMapToColorsWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImageMapToColorsWrap *w = new VtkImageMapToColorsWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetCurrentCursorPosition(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCurrentCursorPosition();
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double));
Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3);
memcpy(ab->GetContents().Data(), r, 3 * sizeof(double));
info.GetReturnValue().Set(at);
}
void VtkImagePlaneWidgetWrap::GetCurrentImageValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCurrentImageValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetCursorData(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCursorData(
(double *)(a0->Buffer()->GetContents().Data())
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[4];
if( a0->Length() < 4 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 4; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
int r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCursorData(
b0
);
info.GetReturnValue().Set(Nan::New(r));
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::GetCursorDataStatus(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCursorDataStatus();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetCursorProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetCursorProperty();
VtkPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPropertyWrap *w = new VtkPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetDisplayText(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetDisplayText();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetInteraction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetInteraction();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLeftButtonAction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLeftButtonAction();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLeftButtonActionMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLeftButtonActionMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLeftButtonActionMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLeftButtonActionMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLeftButtonAutoModifier(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLeftButtonAutoModifier();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLeftButtonAutoModifierMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLeftButtonAutoModifierMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLeftButtonAutoModifierMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLeftButtonAutoModifierMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLevel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLevel();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetLookupTable(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkLookupTable * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetLookupTable();
VtkLookupTableWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkLookupTableWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkLookupTableWrap *w = new VtkLookupTableWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetMarginProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMarginProperty();
VtkPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPropertyWrap *w = new VtkPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetMarginSizeX(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMarginSizeX();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMarginSizeXMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMarginSizeXMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMarginSizeXMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMarginSizeXMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMarginSizeY(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMarginSizeY();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMarginSizeYMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMarginSizeYMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMarginSizeYMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMarginSizeYMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMiddleButtonAction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMiddleButtonAction();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMiddleButtonActionMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMiddleButtonActionMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMiddleButtonActionMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMiddleButtonActionMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMiddleButtonAutoModifier(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMiddleButtonAutoModifier();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMiddleButtonAutoModifierMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMiddleButtonAutoModifierMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetMiddleButtonAutoModifierMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetMiddleButtonAutoModifierMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetNormal(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetNormal(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetNormal(
b0
);
return;
}
double const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetNormal();
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double));
Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3);
memcpy(ab->GetContents().Data(), r, 3 * sizeof(double));
info.GetReturnValue().Set(at);
}
void VtkImagePlaneWidgetWrap::GetOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetOrigin(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetOrigin(
b0
);
return;
}
double const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetOrigin();
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double));
Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3);
memcpy(ab->GetContents().Data(), r, 3 * sizeof(double));
info.GetReturnValue().Set(at);
}
void VtkImagePlaneWidgetWrap::GetPlaneOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetPlaneOrientation();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetPlaneProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetPlaneProperty();
VtkPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPropertyWrap *w = new VtkPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetPoint1(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetPoint1(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetPoint1(
b0
);
return;
}
double const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetPoint1();
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double));
Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3);
memcpy(ab->GetContents().Data(), r, 3 * sizeof(double));
info.GetReturnValue().Set(at);
}
void VtkImagePlaneWidgetWrap::GetPoint2(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetPoint2(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetPoint2(
b0
);
return;
}
double const * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetPoint2();
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(double));
Local<v8::Float64Array> at = v8::Float64Array::New(ab, 0, 3);
memcpy(ab->GetContents().Data(), r, 3 * sizeof(double));
info.GetReturnValue().Set(at);
}
void VtkImagePlaneWidgetWrap::GetPolyData(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPolyDataWrap::ptpl))->HasInstance(info[0]))
{
VtkPolyDataWrap *a0 = ObjectWrap::Unwrap<VtkPolyDataWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetPolyData(
(vtkPolyData *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::GetPolyDataAlgorithm(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkPolyDataAlgorithm * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetPolyDataAlgorithm();
VtkPolyDataAlgorithmWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPolyDataAlgorithmWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPolyDataAlgorithmWrap *w = new VtkPolyDataAlgorithmWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetReslice(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkImageReslice * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetReslice();
VtkImageResliceWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImageResliceWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImageResliceWrap *w = new VtkImageResliceWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetResliceAxes(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkMatrix4x4 * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetResliceAxes();
VtkMatrix4x4Wrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkMatrix4x4Wrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkMatrix4x4Wrap *w = new VtkMatrix4x4Wrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetResliceInterpolate(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetResliceInterpolate();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetResliceOutput(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkImageData * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetResliceOutput();
VtkImageDataWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImageDataWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImageDataWrap *w = new VtkImageDataWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetRestrictPlaneToVolume(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRestrictPlaneToVolume();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetRightButtonAction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRightButtonAction();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetRightButtonActionMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRightButtonActionMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetRightButtonActionMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRightButtonActionMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetRightButtonAutoModifier(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRightButtonAutoModifier();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetRightButtonAutoModifierMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRightButtonAutoModifierMaxValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetRightButtonAutoModifierMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetRightButtonAutoModifierMinValue();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetSelectedPlaneProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetSelectedPlaneProperty();
VtkPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPropertyWrap *w = new VtkPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetSliceIndex(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetSliceIndex();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetSlicePosition(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetSlicePosition();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkTextProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextProperty();
VtkTextPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkTextPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkTextPropertyWrap *w = new VtkTextPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetTexture(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkTexture * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTexture();
VtkTextureWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkTextureWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkTextureWrap *w = new VtkTextureWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetTextureInterpolate(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextureInterpolate();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetTexturePlaneProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkProperty * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTexturePlaneProperty();
VtkPropertyWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkPropertyWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkPropertyWrap *w = new VtkPropertyWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::GetTextureVisibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetTextureVisibility();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetUseContinuousCursor(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetUseContinuousCursor();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetUserControlledLookupTable(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
int r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetUserControlledLookupTable();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetVector1(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetVector1(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetVector1(
b0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::GetVector2(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetVector2(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetVector2(
b0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::GetWindow(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
double r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->GetWindow();
info.GetReturnValue().Set(Nan::New(r));
}
void VtkImagePlaneWidgetWrap::GetWindowLevel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 2 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetWindowLevel(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[2];
if( a0->Length() < 2 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 2; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->GetWindowLevel(
b0
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::InteractionOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->InteractionOff();
}
void VtkImagePlaneWidgetWrap::InteractionOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->InteractionOn();
}
void VtkImagePlaneWidgetWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
vtkImagePlaneWidget * r;
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->NewInstance();
VtkImagePlaneWidgetWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImagePlaneWidgetWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImagePlaneWidgetWrap *w = new VtkImagePlaneWidgetWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
}
void VtkImagePlaneWidgetWrap::PlaceWidget(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 6 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->PlaceWidget(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[6];
if( a0->Length() < 6 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 6; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->PlaceWidget(
b0
);
return;
}
else if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() > 3 && info[3]->IsNumber())
{
if(info.Length() > 4 && info[4]->IsNumber())
{
if(info.Length() > 5 && info[5]->IsNumber())
{
if(info.Length() != 6)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->PlaceWidget(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue(),
info[3]->NumberValue(),
info[4]->NumberValue(),
info[5]->NumberValue()
);
return;
}
}
}
}
}
}
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->PlaceWidget();
}
void VtkImagePlaneWidgetWrap::RestrictPlaneToVolumeOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->RestrictPlaneToVolumeOff();
}
void VtkImagePlaneWidgetWrap::RestrictPlaneToVolumeOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->RestrictPlaneToVolumeOn();
}
void VtkImagePlaneWidgetWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0]))
{
VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject());
vtkImagePlaneWidget * r;
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
r = native->SafeDownCast(
(vtkObjectBase *) a0->native.GetPointer()
);
VtkImagePlaneWidgetWrap::InitPtpl();
v8::Local<v8::Value> argv[1] =
{ Nan::New(vtkNodeJsNoWrap) };
v8::Local<v8::Function> cons =
Nan::New<v8::FunctionTemplate>(VtkImagePlaneWidgetWrap::ptpl)->GetFunction();
v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
VtkImagePlaneWidgetWrap *w = new VtkImagePlaneWidgetWrap();
w->native = r;
w->Wrap(wo);
info.GetReturnValue().Set(wo);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetColorMap(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkImageMapToColorsWrap::ptpl))->HasInstance(info[0]))
{
VtkImageMapToColorsWrap *a0 = ObjectWrap::Unwrap<VtkImageMapToColorsWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetColorMap(
(vtkImageMapToColors *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetCursorProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkPropertyWrap *a0 = ObjectWrap::Unwrap<VtkPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetCursorProperty(
(vtkProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetDisplayText(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetDisplayText(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetEnabled(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetEnabled(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetInputConnection(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkAlgorithmOutputWrap::ptpl))->HasInstance(info[0]))
{
VtkAlgorithmOutputWrap *a0 = ObjectWrap::Unwrap<VtkAlgorithmOutputWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetInputConnection(
(vtkAlgorithmOutput *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetInteraction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetInteraction(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetLeftButtonAction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetLeftButtonAction(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetLeftButtonAutoModifier(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetLeftButtonAutoModifier(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetLookupTable(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkLookupTableWrap::ptpl))->HasInstance(info[0]))
{
VtkLookupTableWrap *a0 = ObjectWrap::Unwrap<VtkLookupTableWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetLookupTable(
(vtkLookupTable *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetMarginProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkPropertyWrap *a0 = ObjectWrap::Unwrap<VtkPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMarginProperty(
(vtkProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetMarginSizeX(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMarginSizeX(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetMarginSizeY(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMarginSizeY(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetMiddleButtonAction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMiddleButtonAction(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetMiddleButtonAutoModifier(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetMiddleButtonAutoModifier(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOrigin(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOrigin(
b0
);
return;
}
else if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetOrigin(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetPicker(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkAbstractPropPickerWrap::ptpl))->HasInstance(info[0]))
{
VtkAbstractPropPickerWrap *a0 = ObjectWrap::Unwrap<VtkAbstractPropPickerWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPicker(
(vtkAbstractPropPicker *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetPlaneOrientation(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPlaneOrientation(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetPlaneOrientationToXAxes(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPlaneOrientationToXAxes();
}
void VtkImagePlaneWidgetWrap::SetPlaneOrientationToYAxes(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPlaneOrientationToYAxes();
}
void VtkImagePlaneWidgetWrap::SetPlaneOrientationToZAxes(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPlaneOrientationToZAxes();
}
void VtkImagePlaneWidgetWrap::SetPlaneProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkPropertyWrap *a0 = ObjectWrap::Unwrap<VtkPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPlaneProperty(
(vtkProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetPoint1(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPoint1(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPoint1(
b0
);
return;
}
else if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPoint1(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetPoint2(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
size_t i;
if(info.Length() > 0 && info[0]->IsFloat64Array())
{
v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject()));
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPoint2(
(double *)(a0->Buffer()->GetContents().Data())
);
return;
}
else if(info.Length() > 0 && info[0]->IsArray())
{
v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject()));
double b0[3];
if( a0->Length() < 3 )
{
Nan::ThrowError("Array too short.");
return;
}
for( i = 0; i < 3; i++ )
{
if( !a0->Get(i)->IsNumber() )
{
Nan::ThrowError("Array contents invalid.");
return;
}
b0[i] = a0->Get(i)->NumberValue();
}
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPoint2(
b0
);
return;
}
else if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsNumber())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetPoint2(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->NumberValue()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetResliceInterpolate(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetResliceInterpolate(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetResliceInterpolateToCubic(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetResliceInterpolateToCubic();
}
void VtkImagePlaneWidgetWrap::SetResliceInterpolateToLinear(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetResliceInterpolateToLinear();
}
void VtkImagePlaneWidgetWrap::SetResliceInterpolateToNearestNeighbour(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetResliceInterpolateToNearestNeighbour();
}
void VtkImagePlaneWidgetWrap::SetRestrictPlaneToVolume(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetRestrictPlaneToVolume(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetRightButtonAction(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetRightButtonAction(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetRightButtonAutoModifier(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetRightButtonAutoModifier(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetSelectedPlaneProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkPropertyWrap *a0 = ObjectWrap::Unwrap<VtkPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetSelectedPlaneProperty(
(vtkProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetSliceIndex(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetSliceIndex(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetSlicePosition(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetSlicePosition(
info[0]->NumberValue()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetTextProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkTextPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkTextPropertyWrap *a0 = ObjectWrap::Unwrap<VtkTextPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextProperty(
(vtkTextProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetTextureInterpolate(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextureInterpolate(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetTexturePlaneProperty(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPropertyWrap::ptpl))->HasInstance(info[0]))
{
VtkPropertyWrap *a0 = ObjectWrap::Unwrap<VtkPropertyWrap>(info[0]->ToObject());
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTexturePlaneProperty(
(vtkProperty *) a0->native.GetPointer()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetTextureVisibility(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetTextureVisibility(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetUseContinuousCursor(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetUseContinuousCursor(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetUserControlledLookupTable(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsInt32())
{
if(info.Length() != 1)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetUserControlledLookupTable(
info[0]->Int32Value()
);
return;
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::SetWindowLevel(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() > 0 && info[0]->IsNumber())
{
if(info.Length() > 1 && info[1]->IsNumber())
{
if(info.Length() > 2 && info[2]->IsInt32())
{
if(info.Length() != 3)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->SetWindowLevel(
info[0]->NumberValue(),
info[1]->NumberValue(),
info[2]->Int32Value()
);
return;
}
}
}
Nan::ThrowError("Parameter mismatch");
}
void VtkImagePlaneWidgetWrap::TextureInterpolateOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->TextureInterpolateOff();
}
void VtkImagePlaneWidgetWrap::TextureInterpolateOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->TextureInterpolateOn();
}
void VtkImagePlaneWidgetWrap::TextureVisibilityOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->TextureVisibilityOff();
}
void VtkImagePlaneWidgetWrap::TextureVisibilityOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->TextureVisibilityOn();
}
void VtkImagePlaneWidgetWrap::UpdatePlacement(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UpdatePlacement();
}
void VtkImagePlaneWidgetWrap::UseContinuousCursorOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UseContinuousCursorOff();
}
void VtkImagePlaneWidgetWrap::UseContinuousCursorOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UseContinuousCursorOn();
}
void VtkImagePlaneWidgetWrap::UserControlledLookupTableOff(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UserControlledLookupTableOff();
}
void VtkImagePlaneWidgetWrap::UserControlledLookupTableOn(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
VtkImagePlaneWidgetWrap *wrapper = ObjectWrap::Unwrap<VtkImagePlaneWidgetWrap>(info.Holder());
vtkImagePlaneWidget *native = (vtkImagePlaneWidget *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
native->UserControlledLookupTableOn();
}
| 31.957202 | 119 | 0.72335 | [
"object"
] |
c490270ed6c709c00c5373d11d00971f8366d8f6 | 125,258 | cpp | C++ | Server Lib/Game Server/GAME/game.cpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 23 | 2021-10-31T00:20:21.000Z | 2022-03-26T07:24:40.000Z | Server Lib/Game Server/GAME/game.cpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 5 | 2021-10-31T18:44:51.000Z | 2022-03-25T18:04:26.000Z | Server Lib/Game Server/GAME/game.cpp | CCasusensa/SuperSS-Dev | 6c6253b0a56bce5dad150c807a9bbf310e8ff61b | [
"MIT"
] | 18 | 2021-10-20T02:31:56.000Z | 2022-02-01T11:44:36.000Z | // Arquivo game.cpp
// Criado em 12/08/2018 as 14:50 por Acrisio
// Implementação da classe Game
#if defined(_WIN32)
#pragma pack(1)
#endif
#if defined(_WIN32)
#include <WinSock2.h>
#endif
#include "game.hpp"
#include "../../Projeto IOCP/UTIL/exception.h"
#include "../../Projeto IOCP/TYPE/stda_error.h"
#include "../../Projeto IOCP/UTIL/message_pool.h"
#include "../PACKET/packet_func_sv.h"
#include "drop_system.hpp"
#include "item_manager.h"
#include "../PANGYA_DB/cmd_update_clubset_workshop.hpp"
#include "../PANGYA_DB/cmd_update_map_statistics.hpp"
#include "../PANGYA_DB/cmd_update_item_slot.hpp"
#include "premium_system.hpp"
#include <algorithm>
#include "../Game Server/game_server.h"
#include "../UTIL/map.hpp"
#include "../../Projeto IOCP/TIMER/timer_manager.h"
#include "../../Projeto IOCP/UTIL/random_gen.hpp"
#include "../../Projeto IOCP/Smart Calculator/Smart Calculator.hpp"
#include "../../Projeto IOCP/UTIL/string_util.hpp"
#include "../UTIL/club3d.hpp"
#if defined(__linux__)
#include <numbers> // std::numbers::pi
#include <cmath>
#endif
#define CHECK_SESSION(method) if (!_session.getState()) \
throw exception("[Game::" + std::string((method)) +"][Error] player nao esta connectado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 1, 0)); \
#define REQUEST_BEGIN(method) CHECK_SESSION(std::string("request") + method); \
if (_packet == nullptr) \
throw exception("[Game::request" + std::string((method)) +"][Error] _packet is nullptr", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 6, 0)); \
// Ponteiro de session
#define INIT_PLAYER_INFO(_method, _msg, __session) auto pgi = getPlayerInfo((__session)); \
if (pgi == nullptr) \
throw exception("[Game::" + std::string((_method)) + "][Error] player[UID=" + std::to_string((__session)->m_pi.uid) + "] " + std::string((_msg)) + ", mas o game nao tem o info dele guardado. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 1, 4)); \
// Artefact of EXP
#define ART_LUMINESCENT_CORAL 0x1A0001AAu // 2%
#define ART_TROPICAL_TREE 0x1A0001ACu // 4%
#define ART_TWIN_LUNAR_MIRROR 0x1A0001AEu // 6%
#define ART_MACHINA_WRENCH 0x1A0001B0u // 8%
#define ART_SILVIA_MANUAL 0x1A0001B2u // 10%
// Artefact of Rain Rate
#define ART_SCROLL_OF_FOUR_GODS 0x1A0001C0u // 5%
#define ART_ZEPHYR_TOTEM 0x1A0001C2u // 10%
#define ART_DRAGON_ORB 0x1A0001F8u // 20%
// Artefact Frozen Flame
#define ART_FROZEN_FLAME 0x1A0001FAu // Mantém os itens Active Equipados, ou sejá não consome eles
uint32_t devil_wings[]{ 0x08016801, 0x08058801, 0x08098801, 0x080dc801, 0x08118801, 0x08160801, 0x08190801, 0x081e2801, 0x08214801, 0x08254801, 0x082d480d, 0x08314801, 0x0839c801 };
uint32_t obsidian_wings[]{ 0x0801680c, 0x0805880c, 0x0809880c, 0x080dc80c, 0x0811880c, 0x0816080c, 0x0819080c, 0x081e280c, 0x0821480c, 0x0825480c, 0x0829480c, 0x082d4806, 0x0831480a, 0x0839c80a };
uint32_t corrupt_wings[]{ 0x08016810, 0x08058810, 0x08098810, 0x080dc810, 0x08118810, 0x08160810, 0x08190810, 0x081e2810, 0x08214810, 0x08254810, 0x08294812, 0x082d4803, 0x0831480d, 0x0839c80d };
uint32_t hasegawa_chirain[]{ 0x8190809, 0x8254808 }; // Item de manter chuva
uint32_t hat_spooky_halloween[]{ 0x0801880b, 0x0805a832, 0x0809a835, 0x080d084c, 0x0811a831, 0x0815a062, 0x0818e05c, 0x081d8837, 0x08212059, 0x08252026 };
uint32_t hat_lua_sol[]{ 0x8018803, 0x805A828, 0x809A827, 0x80D083F, 0x811A823, 0x815A855, 0x818E050, 0x81D8825, 0x821204A, 0x8252015 }; // Dá 20% de Exp e Pang
uint32_t hat_birthday[]{ 0x08000885, 0x0805a81c, 0x08080832, 0x080d0836, 0x08100038, 0x0815a047, 0x0818e048, 0x081d881e, 0x0821203c, 0x08252013, 0x0829200e, 0x082d6000 };
// Motion Item da Treasure Hunter Point Também
uint32_t motion_item[]{ 0x08026800, 0x08026801, 0x08026802, 0x08064800, 0x08064801, 0x08064802, 0x08064803, 0x080A2800,
0x080A2801, 0x080A2802, 0x080E4800, 0x080E4801, 0x080E4802, 0x08122800, 0x08122801, 0x08122802,
0x0816E801, 0x0816E802, 0x0816E803, 0x0816E805, 0x816E806/*Kooh Dolph*/, 0x081A4800, 0x081A4801, 0x081EA800, 0x08228800,
0x08228801, 0x08228802, 0x08228803, 0x08268800, 0x082A6800, 0x082E4800, 0x082E4801, 0x08320800,
0x08320801, 0x08320802, 0x083A4800, 0x083A4801, 0x083A4802 };
using namespace stdA;
Game::Game(std::vector< player* >& _players, RoomInfoEx& _ri, RateValue _rv, unsigned char _channel_rookie)
: m_players(_players), m_ri(_ri), m_rv(_rv), m_channel_rookie(_channel_rookie), m_start_time{0}, m_player_info(), m_course(nullptr),
m_game_init_state(-1), m_state(false), m_player_order(), m_timer(nullptr), m_player_report_game{} {
#if defined(_WIN32)
InitializeCriticalSection(&m_cs);
InitializeCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
INIT_PTHREAD_MUTEXATTR_RECURSIVE;
INIT_PTHREAD_MUTEX_RECURSIVE(&m_cs);
INIT_PTHREAD_MUTEX_RECURSIVE(&m_cs_sync_finish_game);
DESTROY_PTHREAD_MUTEXATTR_RECURSIVE;
#endif
#if defined(_WIN32)
InterlockedExchange(&m_sync_send_init_data, 0u);
#elif defined(__linux__)
__atomic_store_n(&m_sync_send_init_data, 0u, __ATOMIC_RELAXED);
#endif
// Tirei o make player info da classe base e coloquei para a base da classe mais alta
/*for (auto& el : m_players)
makePlayerInfo(*el);*/
// Inicializar Artefact Info Of Game
initArtefact();
// Inicializar o rate chuva dos itens equipado dos players no jogo
initPlayersItemRainRate();
// Inicializa a flag persist rain next hole
initPlayersItemRainPersistNextHole();
// Map Dados Estáticos
if (!sMap::getInstance().isLoad())
sMap::getInstance().load();
auto map = sMap::getInstance().getMap(m_ri.course & 0x7F);
if (map == nullptr)
_smp::message_pool::getInstance().push(new message("[Game::Game][Error][WARNING] tentou pegar o Map dados estaticos do course[COURSE="
+ std::to_string((unsigned short)(m_ri.course & 0x7F)) + "], mas nao conseguiu encontra na classe do Server.", CL_FILE_LOG_AND_CONSOLE));
// Cria Course
m_course = new Course(m_ri, m_channel_rookie, ((map == nullptr) ? 1.f : map->star), m_rv.rain, m_rv.persist_rain);
}
Game::~Game() {
if (m_course != nullptr)
delete m_course;
clear_player_order();
clearAllPlayerInfo();
clear_time();
if (!m_player_report_game.empty())
m_player_report_game.clear();
#if defined(_WIN32)
DeleteCriticalSection(&m_cs);
DeleteCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_destroy(&m_cs);
pthread_mutex_destroy(&m_cs_sync_finish_game);
#endif
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::~Game][Log] Game destroyed on Room[Number=" + std::to_string(m_ri.numero) + "]", CL_FILE_LOG_AND_CONSOLE));
#else
_smp::message_pool::getInstance().push(new message("[Game::~Game][Log] Game destroyed on Room[Number=" + std::to_string(m_ri.numero) + "]", CL_ONLY_FILE_LOG));
#endif // _DEBUG
}
void Game::sendInitialData(player& _session) {
packet p;
try {
// Course
p.init_plain((unsigned short)0x52);
p.addUint8(m_ri.course);
p.addUint8(m_ri.tipo_show);
p.addUint8(m_ri.modo);
p.addUint8(m_ri.qntd_hole);
p.addUint32(m_ri.trofel);
p.addUint32(m_ri.time_vs);
p.addUint32(m_ri.time_30s);
// Hole Info, Hole Spinning Cube, end Seed Random Course
m_course->makePacketHoleInfo(p);
packet_func::session_send(p, &_session, 1);
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::sendInitialData][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
void Game::sendInitialDataAfter(player& _session) {
UNREFERENCED_PARAMETER(_session);
}
player* Game::findSessionByOID(uint32_t _oid) {
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
auto it = std::find_if(m_players.begin(), m_players.end(), [&](auto& el) {
return el->m_oid == _oid;
});
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return (it != m_players.end() ? *it : nullptr);
}
player* Game::findSessionByUID(uint32_t _uid) {
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
auto it = std::find_if(m_players.begin(), m_players.end(), [&](auto& el) {
return el->m_pi.uid == _uid;
});
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return (it != m_players.end() ? *it : nullptr);
}
player* Game::findSessionByNickname(std::string _nickname) {
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
auto it = std::find_if(m_players.begin(), m_players.end(), [&](auto& el) {
return (_nickname.compare(el->m_pi.nickname) == 0);
});
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return (it != m_players.end() ? *it : nullptr);
}
player* Game::findSessionByPlayerGameInfo(PlayerGameInfo* _pgi) {
if (_pgi == nullptr) {
_smp::message_pool::getInstance().push(new message("[Game::findSessionByPlayerGameInfo][Error] PlayerGameInfo* _pgi is invalid(nullptr)", CL_FILE_LOG_AND_CONSOLE));
return nullptr;
}
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
auto it = std::find_if(m_player_info.begin(), m_player_info.end(), [&](auto& _el) {
return _el.second == _pgi;
});
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return (it != m_player_info.end() ? it->first : nullptr);
}
PlayerGameInfo* Game::getPlayerInfo(player *_session) {
if (_session == nullptr)
throw exception("[Game::getPlayerInfo][Error] _session is nullptr", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 1, 0));
PlayerGameInfo *pgi = nullptr;
std::map< player*, PlayerGameInfo* >::iterator i;
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
if ((i = m_player_info.find(_session)) != m_player_info.end())
pgi = i->second;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return pgi;
}
std::vector< player* > Game::getSessions(player *_session) {
std::vector< player* > v_sessions;
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
// Se _session for diferente de nullptr retorna todas as session, menos a que foi passada no _session
for (auto& el : m_players)
if (el != nullptr && el->getState() && el->m_pi.mi.sala_numero != -1 && (_session == nullptr || _session != el))
v_sessions.push_back(el);
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return v_sessions;
}
SYSTEMTIME& Game::getTimeStart() {
return m_start_time;
}
void Game::addPlayer(player& _session) {
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
m_players.push_back(&_session);
makePlayerInfo(_session);
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
}
bool Game::deletePlayer(player* _session, int _option) {
UNREFERENCED_PARAMETER(_option);
if (_session == nullptr)
throw exception("[Game::deletePlayer][Error] tentou deletar um player, mas o seu endereco eh nullptr.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 50, 0));
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
auto it = std::find(m_players.begin(), m_players.end(), _session);
if (it != m_players.end())
m_players.erase(it);
else
_smp::message_pool::getInstance().push(new message("[Game::deletePlayer][WARNING] player ja foi excluido do game.", CL_FILE_LOG_AND_CONSOLE));
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
return false;
}
void Game::requestActiveAutoCommand(player& _session, packet *_packet) {
REQUEST_BEGIN("ActiveAutoCommand");
packet p;
try {
INIT_PLAYER_INFO("requestActiveAutoCommand", "tentou ativar Auto Command no jogo", &_session);
if (!pgi->premium_flag) { // (não é)!PREMIUM USER
auto pWi = _session.m_pi.findWarehouseItemByTypeid(AUTO_COMMAND_TYPEID);
if (pWi == nullptr)
throw exception("[Game::requestActiveAutoCommand][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou ativar o Auto Command Item[TYPEID="
+ std::to_string(AUTO_COMMAND_TYPEID) + "], mas ele nao tem o item. Hacker ou Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 1, 0x550001));
if (pWi->STDA_C_ITEM_QNTD < 1)
throw exception("[Game::requestActiveAutoCommand][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou ativar o Auto Command Item[TYPEID="
+ std::to_string(AUTO_COMMAND_TYPEID) + "], mas ele nao tem quantidade suficiente do item[QNTD=" + std::to_string(pWi->STDA_C_ITEM_QNTD) + ", QNTD_REQ=1]. Hacker ou Bug",
STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 2, 0x550002));
auto it = pgi->used_item.v_passive.find(pWi->_typeid);
if (it == pgi->used_item.v_passive.end())
throw exception("[Game::requestActiveAutoCommand][Error] player[UID = " + std::to_string(_session.m_pi.uid) + "] tentou ativar Auto Command, mas ele nao tem ele no item passive usados do server. Hacker ou Bug",
STDA_MAKE_ERROR(STDA_ERROR_TYPE::TOURNEY_BASE, 13, 0));
if ((short)it->second.count >= pWi->STDA_C_ITEM_QNTD)
throw exception("[Game::requestActiveAutoCommand][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou ativar Auto Command, mas ele ja usou todos os Auto Command. Hacker ou Bug",
STDA_MAKE_ERROR(STDA_ERROR_TYPE::TOURNEY_BASE, 14, 0));
// Add +1 ao item passive usado
it->second.count++;
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::requestActiveAutoCommand][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
// !@ Não sei o que esse pacote faz, não encontrei no meu antigo pangya
// Resposta Error
p.init_plain((unsigned short)0x22B);
p.addUint32((STDA_SOURCE_ERROR_DECODE(e.getCodeError()) == STDA_ERROR_TYPE::GAME) ? STDA_SYSTEM_ERROR_DECODE(e.getCodeError()) : 0x550001);
packet_func::session_send(p, &_session, 1);
}
}
void Game::requestActiveAssistGreen(player& _session, packet *_packet) {
REQUEST_BEGIN("ActiveAssistGreen");
packet p;
try {
uint32_t item_typeid = _packet->readUint32();
if (item_typeid == 0)
throw exception("[Game::requestActiveAssistGreen][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou ativar Assist[TYPEID="
+ std::to_string(item_typeid) + "] do Green, mas o item_typeid is invalid(zero). Hacker ou Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 1, 0x5200101));
auto pWi = _session.m_pi.findWarehouseItemByTypeid(item_typeid);
if (pWi == nullptr)
throw exception("[Game::requestActiveAssistGreen][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou ativar Assist[TYPEID="
+ std::to_string(item_typeid) + "] do Green, mas o Assist Mode do player nao esta ligado. Hacker ou Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 2, 0x5200102));
// Resposta para Active Assist Green
p.init_plain((unsigned short)0x26B);
p.addUint32(0); // OK
p.addUint32(pWi->_typeid);
p.addUint32(_session.m_pi.uid);
packet_func::session_send(p, &_session, 1);
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::requestActiveAssistGreen][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
p.init_plain((unsigned short)0x26B);
p.addUint32((STDA_SOURCE_ERROR_DECODE(e.getCodeError()) == STDA_ERROR_TYPE::GAME) ? STDA_SYSTEM_ERROR_DECODE(e.getCodeError()) : 0x5200100);
packet_func::session_send(p, &_session, 1);
}
}
void Game::requestMarkerOnCourse(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestLoadGamePercent(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestStartTurnTime(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestUnOrPause(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestExecCCGChangeWind(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestExecCCGChangeWeather(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestReplyContinue() {}
bool Game::requestUseTicketReport(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
return false;
}
void Game::requestChangeWindNextHoleRepeat(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestStartAfterEnter(job& _job) {
UNREFERENCED_PARAMETER(_job);
}
void Game::requestEndAfterEnter() {}
void Game::requestUpdateTrofel() {}
void Game::requestTeamFinishHole(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
#define FIND_ELEMENT_ARRAY_OF_ARRAY(_arr1, _arr2) (std::find_if((_arr1), LAST_ELEMENT_IN_ARRAY((_arr1)), [&](auto& _element) { \
return std::find((_arr2), LAST_ELEMENT_IN_ARRAY((_arr2)), _element) != LAST_ELEMENT_IN_ARRAY((_arr2)); \
}) != LAST_ELEMENT_IN_ARRAY((_arr1))) \
// Usa o Padrão delas
bool Game::stopTime() {
clear_time();
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::stopTime][Log] Parou o Timer[Tempo=" + std::to_string(m_ri.time_30s > 0 ? m_ri.time_30s : m_ri.time_vs)
+ (m_timer != nullptr ? ", STATE=" + std::to_string(m_timer->getState()) + "]" : "]"), CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
return true;
}
bool Game::pauseTime() {
if (m_timer != nullptr) {
m_timer->pause();
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::pauseTime][Log] pausou o Timer[Tempo=" + std::to_string(m_ri.time_30s > 0 ? m_ri.time_30s : m_ri.time_vs)
+ ", STATE=" + std::to_string(m_timer->getState()) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
return true;
}
return false;
}
bool Game::resumeTime() {
if (m_timer != nullptr) {
m_timer->start();
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::resumerTime][Log] Retomou o Timer[Tempo=" + std::to_string(m_ri.time_30s > 0 ? m_ri.time_30s : m_ri.time_vs)
+ ", STATE=" + std::to_string(m_timer->getState()) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
return true;
}
return false;
}
void Game::requestPlayerReportChatGame(player& _session, packet *_packet) {
REQUEST_BEGIN("PlayerReportChatGame");
packet p;
try {
// Verifica se o player já reportou o jogo
auto it = m_player_report_game.find(_session.m_pi.uid);
if (it != m_player_report_game.end()) {
// Player já reportou o jogo
p.init_plain((unsigned short)0x94);
p.addUint8(1u); // Player já reportou o jogo
packet_func::session_send(p, &_session, 1);
}else { // Primeira vez que o palyer report o jogo
// add ao mapa de uid de player que reportaram o jogo
m_player_report_game[_session.m_pi.uid] = _session.m_pi.uid;
// Faz Log de quem está na sala, quando pangya, o update enviar o chat log verifica o chat
// por que parece que o pangya não envia o chat, ele só cria um arquivo, acho que quem envia é o update
std::string log = "";
for (auto& el : m_players)
if (el != nullptr)
log = log + "UID: " + std::to_string(_session.m_pi.uid) + "\tID: " + el->m_pi.id + "\tNICKNAME: " + el->m_pi.nickname + "\n";
// Log
_smp::message_pool::getInstance().push(new message("[Game::requestPlayerReportChatGame][Log] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] reportou o chat do jogo na sala[NUMERO=" + std::to_string(m_ri.numero) + "] Log{" + log + "}", CL_FILE_LOG_AND_CONSOLE));
// Reposta para o cliente
p.init_plain((unsigned short)0x94);
p.addUint8(0u); // Sucesso
packet_func::session_send(p, &_session, 1);
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::requestPlayerReportChatGame][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
p.init_plain((unsigned short)0x94);
p.addUint8(1u); // 1 já foi feito report do jogo por esse player
packet_func::session_send(p, &_session, 1);
}
}
void Game::initPlayersItemRainRate() {
// Characters Equip
for (auto& s : m_players) {
if (s->getState() &&
#if defined(_WIN32)
s->m_sock != INVALID_SOCKET
#elif defined(__linux__)
s->m_sock.fd != INVALID_SOCKET
#endif
&& s->isConnected()) { // Check Player Connected
if (s->m_pi.ei.char_info == nullptr) { // Player não está com character equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] nao esta com Character equipado. kika ele do jogo. pode ser Bug.",
CL_FILE_LOG_AND_CONSOLE));
continue;// Kika aqui "deletePlayer(s);"
}
// Devil Wings
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, devil_wings)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Devil Wings no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
m_rv.rain += 10;
}
// Obsidian Wings
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, obsidian_wings)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Obsidian Wings no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
m_rv.rain += 10;
}
// Corrupt Wings
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, corrupt_wings)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Corrupt Wings no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
m_rv.rain += 15;
}
// Hasegawa Chirain
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, hasegawa_chirain)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Hasegawa Chirain Item Part no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
m_rv.rain += 10;
}
// Hat Spooky Halloween -- Esse aqui "tenho que colocar a regra para funcionar só na epoca do halloween"
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, hat_spooky_halloween)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Hat Spooky Halloween no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
m_rv.rain += 10;
}
// Card Efeito 19 rate chuva
auto it = std::find_if(s->m_pi.v_cei.begin(), s->m_pi.v_cei.end(), [](auto& _el) {
return sIff::getInstance().getItemSubGroupIdentify22(_el._typeid) == 2/*Special*/ && _el.efeito == 19;
});
if (it != s->m_pi.v_cei.end()) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Card[TYPEID="
+ std::to_string(it->_typeid) + ", EFEITO=" + std::to_string(it->efeito) + ", EFEITO_QNTD=" + std::to_string(it->efeito_qntd) + "] especial", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
if (it->efeito_qntd > 0)
m_rv.rain += it->efeito_qntd;
}
// Mascot Poltergeist -- Esse aqui "tenho que colocar a regra para funcionar só na epoca do halloween"
if (s->m_pi.ei.mascot_info != nullptr && s->m_pi.ei.mascot_info->_typeid == 0x40000029/*Poltergeist*/) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Mascot Poltergeist[TYPEID="
+ std::to_string(s->m_pi.ei.mascot_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.mascot_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
m_rv.rain += 10;
}
// Caddie Big Black Papel
if (s->m_pi.ei.cad_info != nullptr && s->m_pi.ei.cad_info->_typeid == 0x1C00000E/*Big Black Papel*/) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainRate][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Caddie Big Black Papel[TYPEID="
+ std::to_string(s->m_pi.ei.cad_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.cad_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
m_rv.rain += 10;
}
}
}
}
void Game::initPlayersItemRainPersistNextHole() {
// Characters Equip
for (auto& s : m_players) {
if (s->getState() &&
#if defined(_WIN32)
s->m_sock != INVALID_SOCKET
#elif defined(__linux__)
s->m_sock.fd != INVALID_SOCKET
#endif
&& s->isConnected()) { // Check Player Connected
if (s->m_pi.ei.char_info == nullptr) { // Player não está com character equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainPersistNextHole][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] nao esta com Character equipado. kika ele do jogo. pode ser Bug.",
CL_FILE_LOG_AND_CONSOLE));
continue;// Kika aqui "deletePlayer(s);"
}
// Devil Wings
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, devil_wings)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainPersistNextHole][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Devil Wings no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
// sai por que só precisa que 1 player tenha o item para valer para o game todo
m_rv.persist_rain = 1;
return;
}
// Obsidian Wings
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, obsidian_wings)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainPersistNextHole][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Obsidian Wings no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
// sai por que só precisa que 1 player tenha o item para valer para o game todo
m_rv.persist_rain = 1;
return;
}
// Corrupt Wings
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, corrupt_wings)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainPersistNextHole][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Corrupt Wings no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
// sai por que só precisa que 1 player tenha o item para valer para o game todo
m_rv.persist_rain = 1;
return;
}
// Hasegawa Chirain
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, hasegawa_chirain)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainPersistNextHole][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Hasegawa Chirain Item Part no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
// sai por que só precisa que 1 player tenha o item para valer para o game todo
m_rv.persist_rain = 1;
return;
}
// Hat Spooky Halloween -- Esse aqui "tenho que colocar a regra para funcionar só na epoca do halloween"
if (FIND_ELEMENT_ARRAY_OF_ARRAY(s->m_pi.ei.char_info->parts_typeid, hat_spooky_halloween)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainPersistNextHole][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Hat Spooky Halloween no Character[TYPEID="
+ std::to_string(s->m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(s->m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
// sai por que só precisa que 1 player tenha o item para valer para o game todo
m_rv.persist_rain = 1;
return;
}
// Card Efeito 31 Persist chuva para o proximo hole
auto it = std::find_if(s->m_pi.v_cei.begin(), s->m_pi.v_cei.end(), [](auto& _el) {
return sIff::getInstance().getItemSubGroupIdentify22(_el._typeid) == 2/*Special*/ && _el.efeito == 31;
});
if (it != s->m_pi.v_cei.end()) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::initPlayersItemRainPersistNextHole][Log] player[UID=" + std::to_string(s->m_pi.uid) + "] esta equipado com Card[TYPEID="
+ std::to_string(it->_typeid) + ", EFEITO=" + std::to_string(it->efeito) + ", EFEITO_QNTD=" + std::to_string(it->efeito_qntd) + "] especial", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
// sai por que só precisa que 1 player tenha o item para valer para o game todo
m_rv.persist_rain = 1;
return;
}
}
}
}
void Game::initArtefact() {
switch (m_ri.artefato) {
// Artefact of EXP
case ART_LUMINESCENT_CORAL:
m_rv.exp += 2;
break;
case ART_TROPICAL_TREE:
m_rv.exp += 4;
break;
case ART_TWIN_LUNAR_MIRROR:
m_rv.exp += 6;
break;
case ART_MACHINA_WRENCH:
m_rv.exp += 8;
break;
case ART_SILVIA_MANUAL:
m_rv.exp += 10;
break;
// End
// Artefact of Rain Rate
case ART_SCROLL_OF_FOUR_GODS:
m_rv.rain += 5;
break;
case ART_ZEPHYR_TOTEM:
m_rv.rain += 10;
break;
case ART_DRAGON_ORB:
m_rv.rain += 20;
break;
// End
}
}
PlayerGameInfo::eCARD_WIND_FLAG Game::getPlayerWindFlag(player& _session) {
if (_session.m_pi.ei.char_info == nullptr) { // Player n�o est� com character equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::getPlayerWindFlag][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] nao esta com Character equipado. kika ele do jogo. pode ser Bug.",
CL_FILE_LOG_AND_CONSOLE));
return PlayerGameInfo::eCARD_WIND_FLAG::NONE;// Kika aqui "deletePlayer(s);"
}
// 3 R, 17 SR, 13 SC, 12 N
auto it = std::find_if(_session.m_pi.v_cei.begin(), _session.m_pi.v_cei.end(), [&](auto& _el) {
return (_session.m_pi.ei.char_info->id == _el.parts_id && _session.m_pi.ei.char_info->_typeid == _el.parts_typeid)
&& sIff::getInstance().getItemSubGroupIdentify22(_el._typeid) == 1/*Caddie*/ && (_el.efeito == 3 || _el.efeito == 17 || _el.efeito == 13 || _el.efeito == 12);
});
if (it != _session.m_pi.v_cei.end()) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::getPlayerWindFlag][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com Card[TYPEID="
+ std::to_string(it->_typeid) + ", EFEITO=" + std::to_string(it->efeito) + ", EFEITO_QNTD=" + std::to_string(it->efeito_qntd) + "] Caddie", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
switch (it->efeito) {
case 3:
return PlayerGameInfo::eCARD_WIND_FLAG::RARE;
case 12:
return PlayerGameInfo::eCARD_WIND_FLAG::NORMAL;
case 13:
return PlayerGameInfo::eCARD_WIND_FLAG::SECRET;
case 17:
return PlayerGameInfo::eCARD_WIND_FLAG::SUPER_RARE;
}
}
return PlayerGameInfo::eCARD_WIND_FLAG::NONE;
}
int Game::initCardWindPlayer(PlayerGameInfo* _pgi, unsigned char _wind) {
if (_pgi == nullptr)
throw exception("[Game::initCardWindPlayer][Error] PlayerGameInfo* _pgi is invalid(nullptr). Ao tentar inicializar o card wind player no jogo. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 1, 4));
switch (_pgi->card_wind_flag) {
case PlayerGameInfo::eCARD_WIND_FLAG::NORMAL:
if (_wind == 8) // 9m Wind
return -1;
break;
case PlayerGameInfo::eCARD_WIND_FLAG::RARE:
if (_wind > 0) // All Wind
return -1;
break;
case PlayerGameInfo::eCARD_WIND_FLAG::SUPER_RARE:
if (_wind >= 5) // High(strong) Wind
return -2;
break;
case PlayerGameInfo::eCARD_WIND_FLAG::SECRET:
if (_wind >= 5) // High(strong) Wind
return -2;
else if (_wind > 0) // Low(weak) Wind, 1m não precisa diminuir
return -1;
break;
}
return 0;
}
PlayerGameInfo::stTreasureHunterInfo Game::getPlayerTreasureInfo(player& _session) {
PlayerGameInfo::stTreasureHunterInfo pti{ 0 };
if (_session.m_pi.ei.char_info == nullptr) { // Player não está com character equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::getPlayerTreasureInfo][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] nao esta com Character equipado. kika ele do jogo. pode ser Bug.",
CL_FILE_LOG_AND_CONSOLE));
return pti;// Kika aqui "deletePlayer(s);"
}
std::vector< CardEquipInfoEx* > v_cei;
// 9 N, 10 R, 14 SR por Score. 8 N, R, SR todos score
std::for_each(_session.m_pi.v_cei.begin(), _session.m_pi.v_cei.end(), [&](auto& _el) {
if ((_session.m_pi.ei.char_info->id == _el.parts_id && _session.m_pi.ei.char_info->_typeid == _el.parts_typeid)
&& sIff::getInstance().getItemSubGroupIdentify22(_el._typeid) == 1/*Caddie*/ && (_el.efeito == 8 || _el.efeito == 9 || _el.efeito == 10 || _el.efeito == 14))
v_cei.push_back(&_el);
});
if (!v_cei.empty()) {
for (auto& el : v_cei) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::getPlayerTreasureInfo][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com Card[TYPEID="
+ std::to_string(el->_typeid) + ", EFEITO=" + std::to_string(el->efeito) + ", EFEITO_QNTD=" + std::to_string(el->efeito_qntd) + "] Caddie", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
switch (el->efeito) {
case 8: // Todos Score
pti.all_score = (unsigned char)el->efeito_qntd;
break;
case 9: // Par
pti.par_score = (unsigned char)el->efeito_qntd;
break;
case 10: // Birdie
pti.birdie_score = (unsigned char)el->efeito_qntd;
break;
case 14: // Eagle
pti.eagle_score = (unsigned char)el->efeito_qntd;
break;
}
}
}
// Card Efeito 18 Aumenta o treasure point para qualquer score por 2 horas
auto it = std::find_if(_session.m_pi.v_cei.begin(), _session.m_pi.v_cei.end(), [](auto& _el) {
return sIff::getInstance().getItemSubGroupIdentify22(_el._typeid) == 2/*Special*/ && _el.efeito == 18;
});
if (it != _session.m_pi.v_cei.end()) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::getPlayerTreasureInfo][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com Card[TYPEID="
+ std::to_string(it->_typeid) + ", EFEITO=" + std::to_string(it->efeito) + ", EFEITO_QNTD=" + std::to_string(it->efeito_qntd) + "] especial", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
pti.all_score += (unsigned char)it->efeito_qntd;
}
/// Todos que dão Drop Rate da treasue hunter point, então aonde dá o drop rate já vai dá o treasure point
/// Angel Wings deixa que ela é uma excessão não tem os valores no IFF, é determinado pelo server e o ProjectG
// Passarinho gordo aumenta 30 treasure hunter point para todos scores
//if (_session.m_pi.ei.mascot_info != nullptr && _session.m_pi.ei.mascot_info->_typeid == MASCOT_FAT_BIRD)
//pti.all_score += 30; // +30 all score
// Verifica se está com asa de anjo equipada (shop ou gacha), aumenta 30 treasure hunter point para todos scores
if (_session.m_pi.ei.char_info->AngelEquiped() && _session.m_pi.ui.getQuitRate() < GOOD_PLAYER_ICON)
pti.all_score += 30; // +30 all score
return pti;
}
void Game::updatePlayerAssist(player& _session) {
INIT_PLAYER_INFO("updatePlayerAssist", "tentou atualizar assist pang no jogo", &_session);
if (pgi->assist_flag && pgi->level > 10/*Maior que 10 "great of Beginner A" Junior E ~ Inifinit Legend I*/)
pgi->data.pang = (uint64_t)(pgi->data.pang * 0.7f); // - 30% dos pangs
}
void Game::initGameTime() {
GetLocalTime(&m_start_time);
}
uint32_t Game::getRankPlace(player& _session) {
INIT_PLAYER_INFO("getRankPlace", "tentou pegar o lugar no rank do jogo", &_session);
auto it = std::find(m_player_order.begin(), m_player_order.end(), pgi);
return (it != m_player_order.end()) ? (uint32_t)(it - m_player_order.begin()) : ~0u;
}
DropItemRet Game::requestInitDrop(player& _session) {
if (!sDropSystem::getInstance().isLoad())
sDropSystem::getInstance().load();
DropItemRet dir{ 0 };
INIT_PLAYER_INFO("requestInitDrop", "tentou inicializar drop do hole no jogo", &_session);
DropSystem::stCourseInfo ci{ 0 };
auto hole = m_course->findHole(pgi->hole);
if (hole == nullptr)
throw exception("[Game::requestInitDrop][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou inicializar Drop System do hole[NUMERO="
+ std::to_string(pgi->hole) + "] no jogo, mas nao encontrou o hole no course do game. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 200, 0));
// Init Course Info Drop System
ci.artefact = m_ri.artefato;
ci.char_motion = pgi->char_motion_item;
ci.course = hole->getCourse() & 0x7F; // Course do Hole, Por que no SSC, cada hole é um course
ci.hole = pgi->hole;
ci.seq_hole = (unsigned char)m_course->findHoleSeq(pgi->hole);
ci.qntd_hole = m_ri.qntd_hole;
ci.rate_drop = pgi->used_item.rate.drop;
if (_session.m_pi.ei.char_info != nullptr && _session.m_pi.ui.getQuitRate() < GOOD_PLAYER_ICON)
ci.angel_wings = _session.m_pi.ei.char_info->AngelEquiped();
else
ci.angel_wings = 0u;
// Artefact Pang Drop
if (m_ri.qntd_hole == ci.seq_hole && m_ri.qntd_hole == 18) { // Ultimo Hole, de 18h Game
auto art_pang = sDropSystem::getInstance().drawArtefactPang(ci, (uint32_t)m_players.size());
if (art_pang._typeid != 0) { // Dropou
dir.v_drop.push_back(art_pang);
if (art_pang.qntd >= 30) { // Envia notice que o player ganhou jackpot
packet p((unsigned short)0x40);
p.addUint8(10); // JackPot
p.addString(_session.m_pi.nickname);
p.addUint16(0); // size Msg
p.addUint32(art_pang.qntd * 500);
packet_func::game_broadcast(*this, p, 1);
}
}
}
// Drop Event Course
auto course = sDropSystem::getInstance().findCourse(ci.course & 0x7F);
if (course != nullptr) { // tem Drop nesse Course
auto drop_event = sDropSystem::getInstance().drawCourse(*course, ci);
if (!drop_event.empty()) // Dropou
dir.v_drop.insert(dir.v_drop.end(), drop_event.begin(), drop_event.end());
}
// Drop Mana Artefact
auto mana_drop = sDropSystem::getInstance().drawManaArtefact(ci);
if (mana_drop._typeid != 0) // Dropou
dir.v_drop.push_back(mana_drop);
// Drop Grand Prix Ticket, não drop no Grand Prix
if (m_ri.qntd_hole == ci.seq_hole && m_ri.tipo != RoomInfo::TIPO::GRAND_PRIX) {
auto gp_ticket = sDropSystem::getInstance().drawGrandPrixTicket(ci, _session);
if (gp_ticket._typeid != 0) // Dropou
dir.v_drop.push_back(gp_ticket);
}
// SSC Ticket
auto ssc = sDropSystem::getInstance().drawSSCTicket(ci);
if (!ssc.empty()) {
dir.v_drop.insert(dir.v_drop.end(), ssc.begin(), ssc.end());
// SSC Ticket Achievement
pgi->sys_achieve.incrementCounter(0x6C400053u/*SSC Ticket*/, (int)ssc.size());
}
// Adiciona para a lista de drop's do player
if (!dir.v_drop.empty())
pgi->drop_list.v_drop.insert(pgi->drop_list.v_drop.end(), dir.v_drop.begin(), dir.v_drop.end());
return dir;
}
void Game::requestSaveDrop(player& _session) {
INIT_PLAYER_INFO("requestSaveDrop", "tentou salvar drop item no jogo", &_session);
if (!pgi->drop_list.v_drop.empty()) {
std::map< uint32_t, stItem > v_item;
std::map< uint32_t, stItem >::iterator it;
stItem item{ 0 };
for (auto& el : pgi->drop_list.v_drop) {
item.clear();
item.type = 2;
item._typeid = el._typeid;
item.qntd = (el.type == el.QNTD_MULTIPLE_500) ? el.qntd * 500 : el.qntd;
item.STDA_C_ITEM_QNTD = (short)item.qntd;
if ((it = v_item.find(item._typeid)) == v_item.end()) // Novo item
v_item.insert(std::make_pair(item._typeid, item));
else { // J� tem
it->second.qntd += item.qntd;
it->second.STDA_C_ITEM_QNTD = (short)it->second.qntd;
}
}
auto rai = item_manager::addItem(v_item, _session, 0, 0);
if (rai.fails.size() > 0 && rai.type != item_manager::RetAddItem::T_SUCCESS_PANG_AND_EXP_AND_CP_POUCH)
_smp::message_pool::getInstance().push(new message("[Game:requestSaveDrop][WARNIG] nao conseguiu adicionar os drop itens. Bug", CL_FILE_LOG_AND_CONSOLE));
packet p((unsigned short)0x216);
p.addUint32((const uint32_t)GetSystemTimeAsUnix());
p.addUint32((uint32_t)v_item.size());
for (auto& el : v_item) {
p.addUint8(el.second.type);
p.addUint32(el.second._typeid);
p.addInt32(el.second.id);
p.addUint32(el.second.flag_time);
p.addBuffer(&el.second.stat, sizeof(el.second.stat));
p.addUint32((el.second.STDA_C_ITEM_TIME > 0) ? el.second.STDA_C_ITEM_TIME : el.second.STDA_C_ITEM_QNTD);
p.addZeroByte(25);
}
packet_func::session_send(p, &_session, 1);
}
}
DropItemRet Game::requestInitCubeCoin(player& _session, packet *_packet) {
REQUEST_BEGIN("InitCubeCoin");
try {
unsigned char opt = _packet->readUint8();
unsigned char count = _packet->readUint8();
// Player que tacou e tem drops (Coin ou Cube)
if (opt == 1 && count > 0) {
DropItemRet dir;
INIT_PLAYER_INFO("initCubeCoin", "tentou terninar o hole no jogo", &_session);
auto hole = m_course->findHole(pgi->hole);
if (hole == nullptr)
throw exception("[Game::requestInitCubeCoin][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou terminar hole[NUMERO="
+ std::to_string((unsigned short)pgi->hole) + "], mas no course nao tem esse hole. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 250, 0));
uint32_t tipo = 0u;
uint32_t id = 0u;
CubeEx *pCube = nullptr;
for (auto i = 0u; i < count; ++i) {
tipo = _packet->readUint8();
id = _packet->readUint32();
pCube = hole->findCubeCoin(id);
if (pCube == nullptr)
throw exception("[Game::requestInitCubeCoin][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou terminar hole[NUMERO="
+ std::to_string((unsigned short)pgi->hole) + "], mas o cliente forneceu um cube/coin id[ID=" + std::to_string(id) + "] invalido. Hacker ou Bug",
STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 251, 0));
switch (tipo) {
case 0: // Coin
{
// Tipo 3 Coin da borda do green ganha menos pangs ganha de 1 a 50, Tipo 4 Coin no chão qualquer lugar ganha mais pang de 1 a 200
dir.v_drop.push_back({ COIN_TYPEID, (unsigned char)hole->getCourse(),
(unsigned char)hole->getNumero(),
(short)(sRandomGen::getInstance().rIbeMt19937_64_chrono() % (pCube->flag_location == 0 ? 50 : 200) + 1),
(pCube->flag_location == 0) ? DropItem::eTYPE::COIN_EDGE_GREEN : DropItem::eTYPE::COIN_GROUND });
// Achievement, coin do chão sem ser da borda do green
if (pCube->flag_location != 0)
pgi->sys_achieve.incrementCounter(0x6C400037u/*Coin do chão, sem ser da borda do green*/);
break;
}
case 1: // Cube
{
dir.v_drop.push_back({ SPINNING_CUBE_TYPEID, (unsigned char)hole->getCourse(), (unsigned char)hole->getNumero(), 1, DropItem::eTYPE::CUBE/*Cube*/ });
// Achievement, pegou cube
pgi->sys_achieve.incrementCounter(0x6C400036u/*Cube*/);
break;
} // End Case 1 "Cube"
} // End Switch
}
// Add os Cube Coin para o player list drop
pgi->drop_list.v_drop.insert(pgi->drop_list.v_drop.begin(), dir.v_drop.begin(), dir.v_drop.end());
return dir;
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::requestInitCubeCoin][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
return DropItemRet();
}
void Game::requestCalculePang(player& _session) {
INIT_PLAYER_INFO("requestCalculePang", "tentou calcular o pang do player no jogo", &_session);
// Course Rate of Pang
auto course = sIff::getInstance().findCourse((m_ri.course & 0x7F) | 0x28000000u);
// Rate do course, tem uns que é 10% a+ tem outros que é 30% a mais que o pangya JP deixou
float course_rate = (course != nullptr && course->rate_pang >= 1.f) ? course->rate_pang : 1.f;
float pang_rate = 0.f;
pang_rate = TRANSF_SERVER_RATE_VALUE(pgi->used_item.rate.pang) * TRANSF_SERVER_RATE_VALUE(m_rv.pang + (m_ri.modo == RoomInfo::MODO::M_SHUFFLE ? 10/*+10% Suffle mode*/ : 0)) * course_rate;
pgi->data.bonus_pang = (uint64_t)(((pgi->data.pang * pang_rate) - pgi->data.pang) + (pgi->data.bonus_pang * pang_rate));
}
void Game::requestSaveInfo(player& _session, int option) {
INIT_PLAYER_INFO("requestSaveInfo", "tentou salvar o info dele no jogo", &_session);
try {
// Aqui dados do jogo ele passa o holein no lugar do mad_conduta <-> holein, agora quando ele passa o info user é invertido(Normal)
// Inverte para salvar direito no banco de dados
auto tmp_holein = pgi->ui.hole_in;
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::requestSaveInfo][Log] Player[UID=" + std::to_string(_session.m_pi.uid) + "] UserInfo[" + pgi->ui.toString() + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
pgi->ui.hole_in = pgi->ui.mad_conduta;
pgi->ui.mad_conduta = tmp_holein;
if (option == 0) { // Terminou VS
// Verifica se o Angel Event está ativo de tira 1 quit do player que concluí o jogo
if (m_ri.angel_event) {
pgi->ui.quitado = -1;
_smp::message_pool::getInstance().push(new message("[Game::requestSaveInfo][Log][AngelEvent] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] vai reduzir o quit em " + std::to_string(pgi->ui.quitado * -1) + " unidade(s).", CL_FILE_LOG_AND_CONSOLE));
}
pgi->ui.exp = 0;
pgi->ui.combo = 1;
pgi->ui.jogado = 1;
pgi->ui.media_score = pgi->data.score;
// Os valores que eu não colocava
pgi->ui.jogados_disconnect = 1; // Esse aqui é o contador de jogos que o player começou é o mesmo do jogado, só que esse aqui usa para o disconnect
auto diff = getLocalTimeDiff(m_start_time);
if (diff > 0)
diff /= STDA_10_MICRO_PER_SEC; // NanoSeconds To Seconds
pgi->ui.tempo = (uint32_t)diff;
}else if (option == 1) { // Quitou ou tomou DC
// Quitou ou saiu não ganha pangs
pgi->data.pang = 0u;
pgi->data.bonus_pang = 0u;
pgi->ui.exp = 0;
pgi->ui.combo = DECREASE_COMBO_VALUE * -1;
pgi->ui.jogado = 1;
// Verifica se tomou DC ou Quitou, ai soma o membro certo
if (!_session.m_connection_timeout)
pgi->ui.quitado = 1;
else
pgi->ui.disconnect = 1;
// Os valores que eu não colocava
pgi->ui.jogados_disconnect = 1; // Esse aqui é o contador de jogos que o player começou é o mesmo do jogado, só que esse aqui usa para o disconnect
pgi->ui.media_score = pgi->data.score;
auto diff = getLocalTimeDiff(m_start_time);
if (diff > 0)
diff /= STDA_10_MICRO_PER_SEC; // NanoSeconds To Seconds
pgi->ui.tempo = (uint32_t)diff;
}else if (option == 2) { // Não terminou o hole 1, alguem saiu ai volta para sala sem contar o combo, só conta o jogo que começou
pgi->data.pang = 0u;
pgi->data.bonus_pang = 0u;
pgi->ui.exp = 0;
pgi->ui.jogado = 1;
// Os valores que eu não colocava
pgi->ui.jogados_disconnect = 1; // Esse aqui é o contador de jogos que o player começou é o mesmo do jogado, só que esse aqui usa para o disconnect
auto diff = getLocalTimeDiff(m_start_time);
if (diff > 0)
diff /= STDA_10_MICRO_PER_SEC; // NanoSeconds To Seconds
pgi->ui.tempo = (uint32_t)diff;
}else if (option == 4) { // SSC
pgi->ui.clear();
// Verifica se o Angel Event está ativo de tira 1 quit do player que concluí o jogo
if (m_ri.angel_event) {
pgi->ui.quitado = -1;
_smp::message_pool::getInstance().push(new message("[Game::requestSaveInfo][Log][AngelEvent] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] vai reduzir o quit em " + std::to_string(pgi->ui.quitado * -1) + " unidade(s).", CL_FILE_LOG_AND_CONSOLE));
}
pgi->ui.exp = 0;
pgi->ui.combo = 1;
pgi->ui.jogado = 1;
pgi->ui.media_score = 0;
// Os valores que eu não colocava
pgi->ui.jogados_disconnect = 1; // Esse aqui é o contador de jogos que o player começou é o mesmo do jogado, só que esse aqui usa para o disconnect
auto diff = getLocalTimeDiff(m_start_time);
if (diff > 0)
diff /= STDA_10_MICRO_PER_SEC;
pgi->ui.tempo = (uint32_t)diff;
}else if (option == 5/*Não conta quit*/) {
// Quitou ou saiu não ganha pangs
pgi->data.pang = 0u;
pgi->data.bonus_pang = 0u;
pgi->ui.exp = 0;
pgi->ui.jogado = 1;
pgi->ui.media_score = pgi->data.score;
// Os valores que eu não colocava
pgi->ui.jogados_disconnect = 1; // Esse aqui é o contador de jogos que o player começou é o mesmo do jogado, só que esse aqui usa para o disconnect
auto diff = getLocalTimeDiff(m_start_time);
if (diff > 0)
diff /= STDA_10_MICRO_PER_SEC; // NanoSeconds To Seconds
pgi->ui.tempo = (uint32_t)diff;
}
// Achievement Records
records_player_achievement(_session);
// Pode tirar pangs
int64_t total_pang = pgi->data.pang + pgi->data.bonus_pang;
// UPDATE ON SERVER AND DB
_session.m_pi.addUserInfo(pgi->ui, total_pang); // add User Info
if (total_pang > 0)
_session.m_pi.addPang(total_pang); // add Pang
else if (total_pang < 0)
_session.m_pi.consomePang(total_pang * -1); // consome Pangs
// Game Combo
if (_session.m_pi.ui.combo > 0)
pgi->sys_achieve.incrementCounter(0x6C40004Bu/*Game Combo*/, _session.m_pi.ui.combo);
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::requestSaveInfo][Error] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
void Game::requestUpdateItemUsedGame(player& _session) {
INIT_PLAYER_INFO("requestUpdateItemUsedGame", "tentou atualizar itens usado no jogo", &_session);
auto& ui = pgi->used_item;
// Club Mastery // ((m_ri.course & 0x7f) == RoomInfo::TIPO::SPECIAL_SHUFFLE_COURSE ? 1.5f : 1.f), SSSC sobrecarrega essa função para colocar os valores dele
ui.club.count += (uint32_t)(1.f * 10.f * ui.club.rate * TRANSF_SERVER_RATE_VALUE(m_rv.clubset) * TRANSF_SERVER_RATE_VALUE(ui.rate.club));
// Passive Item exceto Time Booster e Auto Command, que soma o contador por uso, o cliente passa o pacote, dizendo que usou o item
for (auto& el : ui.v_passive) {
// Verica se é o ultimo hole, terminou o jogo, ai tira soma 1 ao count do pirulito que consome por jogo
if (CHECK_PASSIVE_ITEM(el.second._typeid) && el.second._typeid != TIME_BOOSTER_TYPEID/*Time Booster*/ && el.second._typeid != AUTO_COMMAND_TYPEID) {
// Item de Exp Boost que só consome 1 Por Jogo, só soma no requestFinishItemUsedGame
if (std::find(passive_item_exp_1perGame, LAST_ELEMENT_IN_ARRAY(passive_item_exp_1perGame), el.second._typeid) == LAST_ELEMENT_IN_ARRAY(passive_item_exp_1perGame))
el.second.count++;
}else if (sIff::getInstance().getItemGroupIdentify(el.second._typeid) == iff::BALL /*Ball*/
|| sIff::getInstance().getItemGroupIdentify(el.second._typeid) == iff::AUX_PART) /*AuxPart(Anel)*/
el.second.count++;
}
}
void Game::requestFinishItemUsedGame(player& _session) {
std::vector< stItemEx > v_item;
stItemEx item{ 0 };
INIT_PLAYER_INFO("requestFinishItemUsedGame", "tentou finalizar itens usado no jogo", &_session);
// Player já finializou os itens usados, verifica para não finalizar dua vezes os itens do player
if (pgi->finish_item_used) {
_smp::message_pool::getInstance().push(new message("[Game::requestFinishItemUsedGame][WARNING] Player[UID=" + std::to_string(_session.m_pi.uid) + "] ja finalizou os itens. Bug", CL_FILE_LOG_AND_CONSOLE));
return;
}
auto& ui = pgi->used_item;
uint32_t tmp_counter_typeid = 0u;
// Add +1 ao itens que consome 1 só por jogo
// Item de Exp Boost que só consome 1 Por Jogo
std::for_each(ui.v_passive.begin(), ui.v_passive.end(), [&](auto& _el) {
if (std::find(passive_item_exp_1perGame, LAST_ELEMENT_IN_ARRAY(passive_item_exp_1perGame), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_exp_1perGame))
_el.second.count++;
});
// Verifica se é premium 2 e se ele tem o auto caliper para poder somar no Achievement
if (_session.m_pi.m_cap.stBit.premium_user && sPremiumSystem::getInstance().isPremium2(_session.m_pi.pt._typeid)) {
auto it_ac = ui.v_passive.find(AUTO_CALIPER_TYPEID);
if (it_ac == ui.v_passive.end()) {
uint32_t qntd = m_course->findHoleSeq(pgi->hole);
if (qntd == (unsigned short)~0u)
qntd = m_ri.qntd_hole;
// Adiciona Auto Caliper para ser contado no Achievement
auto it_p_ac = ui.v_passive.insert({
AUTO_CALIPER_TYPEID,
{ AUTO_CALIPER_TYPEID , qntd }
});
if (!it_p_ac.second && it_p_ac.first == ui.v_passive.end())
// Log
_smp::message_pool::getInstance().push(new message("[Game::requestFinishItemUsedGame][Error][WARNING] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] nao conseguiu adicionar o Auto Caliper passive item para adicionar no contador do Achievement, por que ele eh premium user 2", CL_FILE_LOG_AND_CONSOLE));
}
}
// Passive Item
for (auto& el : ui.v_passive) {
if (el.second.count > 0u) {
// Item Aqui tem o Achievemente de passive item
if (sIff::getInstance().getItemGroupIdentify(el.second._typeid) == iff::ITEM && !sIff::getInstance().IsItemEquipable(el.second._typeid)/*Nega == Passive Item*/) {
pgi->sys_achieve.incrementCounter(0x6C400075u/*Passive Item*/, el.second.count);
if ((tmp_counter_typeid = SysAchievement::getPassiveItemCounterTypeId(el.second._typeid)) > 0)
pgi->sys_achieve.incrementCounter(tmp_counter_typeid, el.second.count);
}
// Só atualiza o Auto Caliper se não for Premium 2
if (!_session.m_pi.m_cap.stBit.premium_user || !sPremiumSystem::getInstance().isPremium2(_session.m_pi.pt._typeid) || el.second._typeid != AUTO_CALIPER_TYPEID/*Auto Caliper*/) {
// Tira todos itens passivo, antes estava Item e AuxPart, não ia Ball por que eu fiz errado, só preciso verifica se é item e passivo para somar o achievement
// Para tirar os itens, tem que tirar(atualizar) todos.
auto pWi = _session.m_pi.findWarehouseItemByTypeid(el.second._typeid);
if (pWi != nullptr) {
// Init Item
item.clear();
item.type = 2;
item._typeid = el.second._typeid;
item.id = pWi->id;
item.qntd = el.second.count;
item.STDA_C_ITEM_QNTD = (short)item.qntd * -1;
// Add On Vector
v_item.push_back(item);
}else
_smp::message_pool::getInstance().push(new message("[Game::requestFinishItemUsedGame][WARNING] player[UID=" + std::to_string(_session.m_pi.uid)
+ "] tentou atualizar item[TYPEID=" + std::to_string(el.second._typeid) + "] que ele nao possui. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE));
}
}
}
// Active Item
for (auto& el : ui.v_active) {
if (el.second.count > 0u) {
// Aqui tem achievement de Item Active
if (sIff::getInstance().getItemGroupIdentify(el.second._typeid) == iff::ITEM && sIff::getInstance().IsItemEquipable(el.second._typeid)) {
pgi->sys_achieve.incrementCounter(0x6C40004Fu/*Active Item*/, el.second.count);
if ((tmp_counter_typeid = SysAchievement::getActiveItemCounterTypeId(el.second._typeid)) > 0)
pgi->sys_achieve.incrementCounter(tmp_counter_typeid, el.second.count);
}
// Só tira os itens Active se a sala não estiver com o artefact Frozen Flame,
// se ele estiver com artefact Frozen Flame ele mantém os Itens Active, não consome e nem desequipa do inventório do player
if (m_ri.artefato != ART_FROZEN_FLAME) {
// Limpa o Item Slot do player, dos itens que foram usados(Ativados) no jogo
if (el.second.count <= el.second.v_slot.size()) {
for (auto i = 0u; i < el.second.count; ++i)
_session.m_pi.ue.item_slot[el.second.v_slot[i]] = 0;
}
auto pWi = _session.m_pi.findWarehouseItemByTypeid(el.second._typeid);
if (pWi != nullptr) {
// Init Item
item.clear();
item.type = 2;
item._typeid = el.second._typeid;
item.id = pWi->id;
item.qntd = el.second.count;
item.STDA_C_ITEM_QNTD = (short)item.qntd * -1;
// Add On Vector
v_item.push_back(item);
}else
_smp::message_pool::getInstance().push(new message("[Game::requestFinishItemUsedGame][WARNING] player[UID=" + std::to_string(_session.m_pi.uid)
+ "] tentou atualizar item[TYPEID=" + std::to_string(el.second._typeid) + "] que ele nao possui. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE));
}
}
}
// Update Item Equiped Slot ON DB
snmdb::NormalManagerDB::getInstance().add(25, new CmdUpdateItemSlot(_session.m_pi.uid, (uint32_t*)_session.m_pi.ue.item_slot), Game::SQLDBResponse, this);
// Se for o Master da sala e ele estiver com artefato tira o mana dele
// Antes tirava assim que começava o jogo, mas aí o cliente atualizava a sala tirando o artefact aí no final não tinha como ver se o frozen flame estava equipado
// e as outras pessoas que estão na lobby não sabe qual artefect que está na sala, por que o master mesmo mando o pacote pra tirar da sala quando o server tira o mana dele no init game
if (m_ri.artefato != 0 && m_ri.master == _session.m_pi.uid) {
// Tira Artefact Mana do master da sala
auto pWi = _session.m_pi.findWarehouseItemByTypeid(m_ri.artefato + 1);
if (pWi != nullptr) {
item.clear();
item.type = 2;
item.id = pWi->id;
item._typeid = pWi->_typeid;
item.qntd = (pWi->STDA_C_ITEM_QNTD <= 0) ? 1 : pWi->STDA_C_ITEM_QNTD;
item.STDA_C_ITEM_QNTD = (short)item.qntd * -1;
// Add on Vector Update Itens
v_item.push_back(item);
}else
_smp::message_pool::getInstance().push(new message("[Game::requestFinishItemUsedGame][WARNING] Master[UID=" + std::to_string(_session.m_pi.uid) + "] do jogo nao tem Mana do Artefect[TYPEID="
+ std::to_string(m_ri.artefato) + ", MANA=" + std::to_string(m_ri.artefato + 1) + "] e criou e comecou um jogo com artefact sem mana. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE));
}
// Update Item ON Server AND DB
if (!v_item.empty()) {
if (item_manager::removeItem(v_item, _session) <= 0)
_smp::message_pool::getInstance().push(new message("[Game::requestFinishItemUsedGame][WARNING] player[UID=" + std::to_string(_session.m_pi.uid)
+ "] nao conseguiu deletar os item do player. Bug", CL_FILE_LOG_AND_CONSOLE));
}
// Club Mastery
if (ui.club.count > 0u && ui.club._typeid > 0u) {
auto pClub = _session.m_pi.findWarehouseItemByTypeid(ui.club._typeid);
if (pClub != nullptr) {
pClub->clubset_workshop.mastery += ui.club.count;
item.clear();
item.type = 0xCC;
item.id = pClub->id;
item._typeid = pClub->_typeid;
#if defined(_WIN32)
memcpy_s(item.clubset_workshop.c, sizeof(item.clubset_workshop.c), pClub->clubset_workshop.c, sizeof(item.clubset_workshop.c));
#elif defined(__linux__)
memcpy(item.clubset_workshop.c, pClub->clubset_workshop.c, sizeof(item.clubset_workshop.c));
#endif
item.clubset_workshop.level = (char)pClub->clubset_workshop.level;
item.clubset_workshop.mastery = pClub->clubset_workshop.mastery;
item.clubset_workshop.rank = pClub->clubset_workshop.rank;
item.clubset_workshop.recovery = pClub->clubset_workshop.recovery_pts;
snmdb::NormalManagerDB::getInstance().add(12, new CmdUpdateClubSetWorkshop(_session.m_pi.uid, *pClub, CmdUpdateClubSetWorkshop::F_TRANSFER_MASTERY_PTS/*Usa o transfere que é o mesmo que o add*/), Game::SQLDBResponse, this);
// Add Begin Vector
v_item.insert(v_item.begin(), item);
}else
_smp::message_pool::getInstance().push(new message("[Game::requestFinishItemUsedGame][WARNING] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou salvar mastery do ClubSet[TYPEID="
+ std::to_string(ui.club._typeid) + "] que ele nao tem. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE));
}
// Flag de que o palyer já finalizou os itens usados no jogo, para não finalizar duas vezes
pgi->finish_item_used = 1u;
// Atualiza ON Jogo
if (!v_item.empty()) {
packet p((unsigned short)0x216);
p.addUint32((const uint32_t)GetSystemTimeAsUnix());
p.addUint32((uint32_t)v_item.size());
for (auto& el : v_item) {
p.addUint8(el.type);
p.addUint32(el._typeid);
p.addInt32(el.id);
p.addUint32(el.flag_time);
p.addBuffer(&el.stat, sizeof(el.stat));
p.addUint32((el.STDA_C_ITEM_TIME > 0) ? el.STDA_C_ITEM_TIME : el.STDA_C_ITEM_QNTD);
p.addZeroByte(25); // 10 PCL[C0~C4] 2 Bytes cada, 15 bytes desconhecido
if (el.type == 0xCC)
p.addBuffer(&el.clubset_workshop, sizeof(el.clubset_workshop));
}
packet_func::session_send(p, &_session, 1);
}
}
void Game::requestFinishHole(player& _session, int option) {
INIT_PLAYER_INFO("requestFinishHole", "tentou finalizar o dados do hole do player no jogo", &_session);
auto hole = m_course->findHole(pgi->hole);
if (hole == nullptr)
throw exception("[Game::finishHole][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou finalizar hole[NUMERO="
+ std::to_string((unsigned short)pgi->hole) + "] no jogo, mas o numero do hole is invalid. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 20, 0));
char score_hole = 0;
uint32_t tacada_hole = 0u;
// Finish Hole Dados
if (option == 0) {
pgi->data.total_tacada_num += pgi->data.tacada_num;
// Score do hole
score_hole = (char)(pgi->data.tacada_num - hole->getPar().par);
// Tacadas do hole
tacada_hole = pgi->data.tacada_num;
pgi->data.score += score_hole;
// Achievement Score
auto tmp_counter_typeid = SysAchievement::getScoreCounterTypeId(tacada_hole, hole->getPar().par);
if (tmp_counter_typeid > 0)
pgi->sys_achieve.incrementCounter(tmp_counter_typeid);
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::requestFinishHole][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] terminou o hole[COURSE="
+ std::to_string(hole->getCourse()) + ", NUMERO=" + std::to_string(hole->getNumero()) + ", PAR="
+ std::to_string(hole->getPar().par) + ", SHOT=" + std::to_string(tacada_hole) + ", SCORE=" + std::to_string(score_hole) + ", TOTAL_SHOT="
+ std::to_string(pgi->data.total_tacada_num) + ", TOTAL_SCORE=" + std::to_string(pgi->data.score) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
// Zera dados
pgi->data.time_out = 0u;
// Giveup Flag
pgi->data.giveup = 0u;
// Zera as penalidades do hole
pgi->data.penalidade = 0u;
}else if (option == 1) { // Não acabou o hole então faz os calculos para o jogo todo
auto pair = m_course->findRange(pgi->hole);
for (auto it = pair.first; it != pair.second && it->first <= m_ri.qntd_hole/*9h ou 18h ele verifica*/; ++it) {
pgi->data.total_tacada_num += it->second.getPar().total_shot;
pgi->data.score += it->second.getPar().range_score[1]; // Max Score
}
// Zera dados
pgi->data.time_out = 0u;
pgi->data.tacada_num = 0u;
// Giveup Flag
pgi->data.giveup = 0u;
// Zera as penalidades do hole do player
pgi->data.penalidade = 0u;
}
// Aqui tem que atualiza o PGI direitinho com outros dados
pgi->progress.hole = (short)m_course->findHoleSeq(pgi->hole);
// Dados Game Progress do Player
if (option == 0) {
if (pgi->progress.hole > 0) {
if (pgi->shot_sync.state_shot.display.stDisplay.acerto_hole)
pgi->progress.finish_hole[pgi->progress.hole - 1] = 1; // Terminou o hole
pgi->progress.par_hole[pgi->progress.hole - 1] = hole->getPar().par;
pgi->progress.score[pgi->progress.hole - 1] = score_hole;
pgi->progress.tacada[pgi->progress.hole - 1] = tacada_hole;
}
}else {
auto pair = m_course->findRange(pgi->hole);
for (auto it = pair.first; it != pair.second && it->first <= m_ri.qntd_hole/*9h ou 18h ele verifica*/; ++it) {
pgi->progress.finish_hole[it->first - 1] = 0; // não terminou
pgi->progress.par_hole[it->first - 1] = it->second.getPar().par;
pgi->progress.score[it->first - 1] = it->second.getPar().range_score[1]; // Max Score
pgi->progress.tacada[it->first - 1] = it->second.getPar().total_shot;
}
}
}
void Game::requestSaveRecordCourse(player& _session, int game, int option) {
INIT_PLAYER_INFO("requestSaveRecordCourse", "tentou salvar record do course do player no jogo", &_session);
if (_session.m_pi.ei.char_info == nullptr) { // Player não está com character equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::requestSaveRecordCourse][Log] player[UID=" + std::to_string(_session.m_pi.uid)
+ "] nao esta com Character equipado. kika ele do jogo. pode ser Bug.", CL_FILE_LOG_AND_CONSOLE));
return;// Kika aqui "deletePlayer(s);"
}
MapStatistics *pMs = nullptr;
if (pgi->assist_flag) { // Assist
if (game == 52/*Grand Prix*/) {
pMs = &_session.m_pi.a_msa_grand_prix[(m_ri.course & 0x7F)];
}else if (m_ri.natural.stBit.natural/* & 1*/) { // Natural
pMs = &_session.m_pi.a_msa_natural[(m_ri.course & 0x7F)];
game = 51; // Natural
}else { // Normal
pMs = &_session.m_pi.a_msa_normal[(m_ri.course & 0x7F)];
}
}else { // Sem Assist
if (game == 52/*Grand Prix*/) {
pMs = &_session.m_pi.a_ms_grand_prix[(m_ri.course & 0x7F)];
}else if (m_ri.natural.stBit.natural/* & 1*/) { // Natural
pMs = &_session.m_pi.a_ms_natural[(m_ri.course & 0x7F)];
game = 51; // Natural
}else { // Normal
pMs = &_session.m_pi.a_ms_normal[(m_ri.course & 0x7F)];
}
}
bool make_record = false;
// UPDATE ON SERVER
if (option == 1) { // 18h pode contar record
// Fez Record
if (pMs->best_score == 127 || pgi->data.score < (int)pMs->best_score || pgi->data.pang > (uint64_t)pMs->best_pang) {
// Update Best Score Record
if (pgi->data.score < pMs->best_score)
pMs->best_score = (char)pgi->data.score;
// Update Best Pang Record
if (pgi->data.pang > (uint64_t)pMs->best_pang)
pMs->best_pang = pgi->data.pang;
// Update Character Record
pMs->character_typeid = _session.m_pi.ei.char_info->_typeid;
make_record = true;
}
}
// Salva os dados normais
pMs->tacada += pgi->ui.tacada;
pMs->putt += pgi->ui.putt;
pMs->hole += pgi->ui.hole;
pMs->fairway += pgi->ui.fairway;
pMs->hole_in += pgi->ui.hole_in;
pMs->putt_in += pgi->ui.putt_in;
pMs->total_score += pgi->data.score;
pMs->event_score = 0u;
MapStatisticsEx ms{ *pMs };
//memcpy_s(&ms, sizeof(MapStatistics), pMs, sizeof(MapStatistics));
ms.tipo = game;
//ms.course = pMs->course;
// UPDATE ON DB
snmdb::NormalManagerDB::getInstance().add(5, new CmdUpdateMapStatistics(_session.m_pi.uid, ms, pgi->assist_flag), Game::SQLDBResponse, this);
// UPDATE ON GAME, se ele fez record, e add 1000 para ele
if (make_record) {
// Log
_smp::message_pool::getInstance().push(new message("[Game::requestSaveRecordCourse][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] fez record no Map[COURSE="
+ std::to_string((unsigned short)(m_ri.course & 0x7F)) +" (" + std::to_string((unsigned short)pMs->course) + "), SCORE=" + std::to_string((short)pMs->best_score) + ", PANG="
+ std::to_string(pMs->best_pang) + ", CHARACTER=" + std::to_string(pMs->character_typeid) + "]", CL_FILE_LOG_AND_CONSOLE));
// Add 1000 pang por ele ter quebrado o record dele
_session.m_pi.addPang(1000);
// Resposta para make record
packet p((unsigned short)0xB9);
p.addInt8(m_ri.course & 0x7F);
packet_func::session_send(p, &_session, 1);
}
}
void Game::requestInitItemUsedGame(player& _session, PlayerGameInfo& _pgi) {
//INIT_PLAYER_INFO("requestInitItemUsedGame", "tentou inicializar itens usado no jogo", &_session);
// Characters Equip
if (_session.getState() &&
#if defined(_WIN32)
_session.m_sock != INVALID_SOCKET
#elif defined(__linux__)
_session.m_sock.fd != INVALID_SOCKET
#endif
&& _session.isConnected()) { // Check Player Connected
if (_session.m_pi.ei.char_info == nullptr) { // Player não está com character equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::requestInitItemUsedGame][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] nao esta com Character equipado. kika ele do jogo. pode ser Bug.",
CL_FILE_LOG_AND_CONSOLE));
return;// Kika aqui "deletePlayer(s);"
}
if (_session.m_pi.ei.comet == nullptr) { // Player não está com Comet(Ball) equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::requestInitItemUsedGame][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] nao esta com Ball equipado. kika ele do jogo. pode ser Bug.",
CL_FILE_LOG_AND_CONSOLE));
return;// Kika aqui "deletePlayer(s);"
}
auto& ui = _pgi.used_item;
// Zera os Itens usados
ui.clear();
/// ********** Itens Usado **********
// Passive Item Equipado
std::for_each(_session.m_pi.mp_wi.begin(), _session.m_pi.mp_wi.end(), [&](auto& _el) {
if (std::find(passive_item, LAST_ELEMENT_IN_ARRAY(passive_item), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item))
ui.v_passive.insert(std::make_pair((uint32_t)_el.second._typeid, UsedItem::Passive{ (uint32_t)_el.second._typeid, 0u }));
});
// Ball Equiped
if (_session.m_pi.ei.comet->_typeid != DEFAULT_COMET_TYPEID && (!_session.m_pi.m_cap.stBit.premium_user || _session.m_pi.ei.comet->_typeid != sPremiumSystem::getInstance().getPremiumBallByTicket(_session.m_pi.pt._typeid)))
ui.v_passive.insert(std::make_pair((uint32_t)_session.m_pi.ei.comet->_typeid, UsedItem::Passive{ (uint32_t)_session.m_pi.ei.comet->_typeid, 0u }));
// AuxParts
for (auto i = 0u; i < (sizeof(_session.m_pi.ei.char_info->auxparts) / sizeof(_session.m_pi.ei.char_info->auxparts[0])); ++i)
if (_session.m_pi.ei.char_info->auxparts[i] >= 0x70000000 && _session.m_pi.ei.char_info->auxparts[i] < 0x70010000)
ui.v_passive.insert(std::make_pair((uint32_t)_session.m_pi.ei.char_info->auxparts[i], UsedItem::Passive{ (uint32_t)_session.m_pi.ei.char_info->auxparts[i], 0u }));
// Item Active Slot
auto it = ui.v_active.end();
for (auto i = 0u; i < (sizeof(_session.m_pi.ue.item_slot) / sizeof(_session.m_pi.ue.item_slot[0])); ++i) {
// Diferente de 0 item está equipado
if (_session.m_pi.ue.item_slot[i] != 0) {
if ((it = ui.v_active.find(_session.m_pi.ue.item_slot[i])) == ui.v_active.end()) // Não tem add o novo
ui.v_active.insert(std::make_pair((uint32_t)_session.m_pi.ue.item_slot[i], UsedItem::Active{ (uint32_t)_session.m_pi.ue.item_slot[i], 0u, std::vector< unsigned char >{(unsigned char)i} }));
else // Já tem add só o slot
it->second.v_slot.push_back((unsigned char)i); // Slot
}
}
// ClubSet For ClubMastery
ui.club._typeid = _session.m_pi.ei.csi._typeid;
ui.club.count = 0u;
ui.club.rate = 1.f;
auto club = sIff::getInstance().findClubSet(ui.club._typeid);
if (club != nullptr)
ui.club.rate = club->work_shop.rate;
else
_smp::message_pool::getInstance().push(new message("[Game::requestIniItemUsedGame][WARNING] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com um ClubSet[TYPEID="
+ std::to_string(_session.m_pi.ei.csi._typeid) + ", ID=" + std::to_string(_session.m_pi.ei.csi.id) + "] que nao tem no IFF_STRUCT do Server. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE));
/// ********** Itens Usado **********
/// ********** Itens Exp/Pang Rate **********
// Item Buff
auto time_limit_item = sIff::getInstance().getTimeLimitItem();
std::for_each(_session.m_pi.v_ib.begin(), _session.m_pi.v_ib.end(), [&](auto& _el) {
auto it = time_limit_item.end();
if ((it = std::find_if(time_limit_item.begin(), time_limit_item.end(), [&](auto& _el2) {
return _el2.second._typeid == _el._typeid;
})) != time_limit_item.end()) {
switch (it->second.type) {
case ItemBuff::eTYPE::YAM_AND_GOLD:
ui.rate.exp += it->second.percent;
break;
case ItemBuff::eTYPE::RAINBOW:
case ItemBuff::eTYPE::RED:
ui.rate.exp += (it->second.percent > 0) ? it->second.percent : 100;
ui.rate.pang += (it->second.percent > 0) ? it->second.percent : 100;
break;
case ItemBuff::eTYPE::GREEN:
ui.rate.exp += (it->second.percent > 0) ? it->second.percent : 100;
break;
case ItemBuff::eTYPE::YELLOW:
ui.rate.pang += (it->second.percent > 0) ? it->second.percent : 100;
break;
}
}
});
// Card Equipado, Special, NPC, e Caddie
std::for_each(_session.m_pi.v_cei.begin(), _session.m_pi.v_cei.end(), [&](auto& _el) {
if (_el.parts_id == _session.m_pi.ei.char_info->id && _el.parts_typeid == _session.m_pi.ei.char_info->_typeid
&& sIff::getInstance().getItemSubGroupIdentify22(_el._typeid) == 5/*NPC*/) {
if (_el.efeito == 2/*Exp*/)
ui.rate.exp += _el.efeito_qntd;
else if (_el.efeito == 1/*Pang*/)
ui.rate.pang += _el.efeito_qntd;
}else if (_el.parts_id == 0 && _el.parts_typeid == 0 && sIff::getInstance().getItemSubGroupIdentify22(_el._typeid) == 2/*Special*/) {
if (_el.efeito == 3/*Exp*/)
ui.rate.exp += _el.efeito_qntd;
else if (_el.efeito == 2/*Pang*/)
ui.rate.pang += _el.efeito_qntd;
else if (_el.efeito == 34/*Club Mastery*/)
ui.rate.club += _el.efeito_qntd;
}
});
// Item Passive Boost Exp, Pang and Club Mastery
// Pang
std::for_each(ui.v_passive.begin(), ui.v_passive.end(), [&](auto& _el) {
// Pang Boost X2
if (std::find(passive_item_pang_x2, LAST_ELEMENT_IN_ARRAY(passive_item_pang_x2), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_pang_x2)) {
ui.rate.pang += 200; // 200%
// Flag Boost Item
_pgi.boost_item_flag.flag.pang = 1;
}
// Pang Boost X4
if (std::find(passive_item_pang_x4, LAST_ELEMENT_IN_ARRAY(passive_item_pang_x4), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_pang_x4)) {
ui.rate.pang += 400; // 400%
// Flag Boost Item
_pgi.boost_item_flag.flag.pang_nitro = 1;
}
// Pang Boost X1.5
if (std::find(passive_item_pang_x1_5, LAST_ELEMENT_IN_ARRAY(passive_item_pang_x1_5), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_pang_x1_5)) {
ui.rate.pang += 50; // 150%
// Flag Boost Item
_pgi.boost_item_flag.flag.pang = 1;
}
// Pang Boost X1.4
if (std::find(passive_item_pang_x1_4, LAST_ELEMENT_IN_ARRAY(passive_item_pang_x1_4), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_pang_x1_4)) {
ui.rate.pang += 40; // 140%
// Flag Boost Item
_pgi.boost_item_flag.flag.pang = 1;
}
// Pang Boost X1.2
if (std::find(passive_item_pang_x1_2, LAST_ELEMENT_IN_ARRAY(passive_item_pang_x1_2), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_pang_x1_2)) {
ui.rate.pang += 20; // 120%
// Flag Boost Item
_pgi.boost_item_flag.flag.pang = 1;
}
});
// Exp
std::for_each(ui.v_passive.begin(), ui.v_passive.end(), [&](auto& _el) {
if (std::find(passive_item_exp, LAST_ELEMENT_IN_ARRAY(passive_item_exp), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_exp))
ui.rate.exp += 200; // 200%
});
// Club Mastery Boost
std::for_each(ui.v_passive.begin(), ui.v_passive.end(), [&](auto& _el) {
if (std::find(passive_item_club_boost, LAST_ELEMENT_IN_ARRAY(passive_item_club_boost), _el.second._typeid) != LAST_ELEMENT_IN_ARRAY(passive_item_club_boost))
ui.rate.club += 200; // Por Hora só tem 1 item
});
// Character Parts Equipado
if (FIND_ELEMENT_ARRAY_OF_ARRAY(_session.m_pi.ei.char_info->parts_typeid, hat_birthday)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::requestInitItemUsedGame][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com Hat Birthday no Character[TYPEID="
+ std::to_string(_session.m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(_session.m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
ui.rate.exp += 20; // 20% Hat Birthday
}
// Hat Lua e sol que na epoca do evento dava +20% Exp e Pang, voud colocar para ele dá direto aqui
if (FIND_ELEMENT_ARRAY_OF_ARRAY(_session.m_pi.ei.char_info->parts_typeid, hat_lua_sol)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::requestInitItemUsedGame][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com Hat Lua e Sol no Character[TYPEID="
+ std::to_string(_session.m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(_session.m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
ui.rate.exp += 20; // 20% Hat Lua e Sol
ui.rate.pang += 20; // 20% Hat Lua e Sol
}
// Verifica se está com o anel que da +1.1% de Club Mastery
if (std::find(_session.m_pi.ei.char_info->auxparts, LAST_ELEMENT_IN_ARRAY(_session.m_pi.ei.char_info->auxparts), KURAFAITO_RING_CLUBMASTERY) != LAST_ELEMENT_IN_ARRAY(_session.m_pi.ei.char_info->auxparts)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::requestInitItemUsedGame][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com Anel (Kurafaito) que da Club Mastery +1.1% no Character[TYPEID="
+ std::to_string(_session.m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(_session.m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
ui.rate.club += 10; // Kurafaito Ring da + 10% no Club Mastery
}
// Character AuxParts Equipado
// Aux parts tem seus próprios valores de rate no iff
std::for_each(_session.m_pi.ei.char_info->auxparts, LAST_ELEMENT_IN_ARRAY(_session.m_pi.ei.char_info->auxparts), [&](auto& _el) {
if (_el != 0 && sIff::getInstance().getItemGroupIdentify(_el) == iff::AUX_PART) {
auto auxpart = sIff::getInstance().findAuxPart(_el);
if (auxpart != nullptr) {
// Pang
if (auxpart->efeito.pang_rate > 100)
ui.rate.pang += (auxpart->efeito.pang_rate - 100);
else if (auxpart->efeito.pang_rate > 0)
ui.rate.pang += auxpart->efeito.pang_rate;
// Exp
if (auxpart->efeito.exp_rate > 100)
ui.rate.exp += (auxpart->efeito.exp_rate - 100);
else if (auxpart->efeito.exp_rate > 0)
ui.rate.exp += auxpart->efeito.exp_rate;
// Drop item, aqui ele add os 120% e no Drop System ele trata isso direito
// Todos itens que dá drop rate da treasure hunter point
if (auxpart->efeito.drop_rate > 100) {
if (auxpart->efeito.drop_rate > 100)
ui.rate.drop += (auxpart->efeito.drop_rate - 100);
else if (auxpart->efeito.drop_rate > 0)
ui.rate.drop += auxpart->efeito.drop_rate;
// Passaro gordo que usa isso aqui, mas pode adicionar mais mascot que dé drop rate e treasure hunter point
_pgi.thi.all_score += 15; // Add +15 ao all score
}
}
}
});
// Mascot Equipado Rate Exp And Pang, Drop item e Treasure Hunter rate
if (_session.m_pi.ei.mascot_info != nullptr) {
auto mascot = sIff::getInstance().findMascot(_session.m_pi.ei.mascot_info->_typeid);
if (mascot != nullptr) {
// Pang
if (mascot->efeito.pang_rate > 100)
ui.rate.pang += (mascot->efeito.pang_rate - 100);
else if (mascot->efeito.pang_rate > 0)
ui.rate.pang += mascot->efeito.pang_rate;
// Exp
if (mascot->efeito.exp_rate > 100)
ui.rate.exp += (mascot->efeito.exp_rate - 100);
else if (mascot->efeito.exp_rate > 0)
ui.rate.exp += mascot->efeito.exp_rate;
// Drop item, aqui ele add os 120% e no Drop System ele trata isso direito
// Todos itens que dá drop rate da treasure hunter point
if (mascot->efeito.drop_rate > 100) {
if (mascot->efeito.drop_rate > 100)
ui.rate.drop += (mascot->efeito.drop_rate - 100);
else if (mascot->efeito.drop_rate > 0)
ui.rate.drop += mascot->efeito.drop_rate;
// Passaro gordo que usa isso aqui, mas pode adicionar mais mascot que dé drop rate e treasure hunter point
_pgi.thi.all_score += 15; // Add +15 ao all score
}
}else
_smp::message_pool::getInstance().push(new message("[Game::requestInitItemUsedGame][WARNING] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com um mascot[TYPEID="
+ std::to_string(_session.m_pi.ei.mascot_info->_typeid) + ", ID=" + std::to_string(_session.m_pi.ei.mascot_info->id) + "] que nao tem no IFF_STRUCT do Server. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE));
}
/// ********** Premium User +10% EXP and PANG *********************
if (_pgi.premium_flag) {
auto rate_premium = sPremiumSystem::getInstance().getExpPangRateByTicket(_session.m_pi.pt._typeid);
ui.rate.exp += rate_premium;
ui.rate.pang += rate_premium;
}
/// ********** Itens Exp/Pang Rate **********
}
}
void Game::requestSendTreasureHunterItem(player& _session) {
INIT_PLAYER_INFO("requestSendTreasureHunterItem", "tentou enviar os itens ganho no Treasure Hunter do jogo", &_session);
std::vector< stItem > v_item;
stItem item{ 0 };
BuyItem bi{ 0 };
if (!pgi->thi.v_item.empty()) {
for (auto& el : pgi->thi.v_item) {
bi.clear();
item.clear();
bi.id = -1;
bi._typeid = el._typeid;
bi.qntd = el.qntd;
item_manager::initItemFromBuyItem(_session.m_pi, item, bi, false, 0, 0, 1/*Não verifica o Level*/);
if (item._typeid == 0) {
_smp::message_pool::getInstance().push(new message("[Game::requestSendTreasureHunterItem][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou inicializar item[TYPEID="
+ std::to_string(bi._typeid) + "], mas nao consgeuiu. Bug", CL_FILE_LOG_AND_CONSOLE));
continue;
}
v_item.push_back(item);
}
// Add Item, se tiver Item
if (!v_item.empty()) {
auto rai = item_manager::addItem(v_item, _session, 0, 0);
if (rai.fails.size() > 0 && rai.type != item_manager::RetAddItem::T_SUCCESS_PANG_AND_EXP_AND_CP_POUCH)
_smp::message_pool::getInstance().push(new message("[Game::requestSendTreasureHunterItem][Error] player[UID=" + std::to_string(_session.m_pi.uid)
+ "] nao conseguiu adicionar os itens que ele ganhou no Treasure Hunter. Bug", CL_FILE_LOG_AND_CONSOLE));
}
}
// UPDATE ON GAME
packet p((unsigned short)0x134);
p.addUint8((unsigned char)v_item.size());
for (auto& el : v_item) {
p.addUint32(_session.m_pi.uid);
p.addUint32(el._typeid);
p.addInt32(el.id);
p.addUint32(el.qntd);
p.addUint8(0); // Opt Acho, mas nunca vi diferente de 0
p.addUint16((unsigned short)(el.stat.qntd_dep / 0x8000));
p.addUint16((unsigned short)(el.stat.qntd_dep % 0x8000));
}
packet_func::session_send(p, &_session, 1);
}
unsigned char Game::checkCharMotionItem(player& _session) {
// Characters Equip
if (_session.getState() &&
#if defined(_WIN32)
_session.m_sock != INVALID_SOCKET
#elif defined(__linux__)
_session.m_sock.fd != INVALID_SOCKET
#endif
&& _session.isConnected()) { // Check Player Connected
if (_session.m_pi.ei.char_info == nullptr) { // Player não está com character equipado, kika dele do jogo
_smp::message_pool::getInstance().push(new message("[Game::checkCharMotionItem][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] nao esta com Character equipado. kika ele do jogo. pode ser Bug.",
CL_FILE_LOG_AND_CONSOLE));
// Kika aqui "deletePlayer(s);"
return 0;
}
// Motion Item
if (FIND_ELEMENT_ARRAY_OF_ARRAY(_session.m_pi.ei.char_info->parts_typeid, motion_item)) {
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::checkCharMotionItem][Log] player[UID=" + std::to_string(_session.m_pi.uid) + "] esta equipado com Motion Item no Character[TYPEID="
+ std::to_string(_session.m_pi.ei.char_info->_typeid) + ", ID=" + std::to_string(_session.m_pi.ei.char_info->id) + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
return 1u;
}
}
return 0u;
}
void Game::sendUpdateInfoAndMapStatistics(player& _session, int _option) {
packet p((unsigned short)0x45);
p.addBuffer(&_session.m_pi.ui, sizeof(UserInfo));
p.addBuffer(&_session.m_pi.ti_current_season, sizeof(TrofelInfo));
// Ainda tenho que ajeitar esses Map Statistics no Pacote Principal, No Banco de dados e no player_info class
if (_option == -1) {
// -1 12 Bytes, os 2 tipos de dados do Map Statistics
p.addInt64(-1);
p.addInt32(-1);
}else {
// Normal essa season
if (_session.m_pi.a_ms_normal[m_ri.course & 0x7F].course != (m_ri.course & 0x7F))
p.addInt8(-1); // Não tem
else {
p.addInt8((char)m_ri.course & 0x7F);
p.addBuffer(&_session.m_pi.a_ms_normal[m_ri.course & 0x7F], sizeof(MapStatistics));
}
// Normal rest season
// tem que fazer o map statistics soma de todas season
//p.addInt8((char)m_ri.course & 0x7F);
//p.addBuffer(&_session.m_pi.aa_ms_normal_todas_season[0][m_ri.course & 0x7F], sizeof(MapStatistics));
p.addInt8(-1); // Não tem
// Natural essa season
if (_session.m_pi.a_ms_natural[m_ri.course & 0x7F].course != (m_ri.course & 0x7F))
p.addInt8(-1); // N�o tem
else {
p.addInt8((char)m_ri.course & 0x7F);
p.addBuffer(&_session.m_pi.a_ms_natural[m_ri.course & 0x7F], sizeof(MapStatistics));
}
// Natural rest season
// tem que fazer o map statistics soma de todas season
//p.addInt8((char)m_ri.course & 0x7F);
//p.addBuffer(&_session.m_pi.aa_ms_normal_todas_season[0][m_ri.course & 0x7F], sizeof(MapStatistics));
p.addInt8(-1); // Não tem
// Normal Assist essa season
if (_session.m_pi.a_msa_normal[m_ri.course & 0x7F].course != (m_ri.course & 0x7F))
p.addInt8(-1); // Não tem
else {
p.addInt8((char)m_ri.course & 0x7F);
p.addBuffer(&_session.m_pi.a_msa_normal[m_ri.course & 0x7F], sizeof(MapStatistics));
}
// Normal Assist rest season
// tem que fazer o map statistics soma de todas season
//p.addInt8((char)m_ri.course & 0x7F);
//p.addBuffer(&_session.m_pi.aa_ms_normal_todas_season[0][m_ri.course & 0x7F], sizeof(MapStatistics));
p.addInt8(-1); // Não tem
// Natural Assist essa season
if (_session.m_pi.a_msa_natural[m_ri.course & 0x7F].course != (m_ri.course & 0x7F))
p.addInt8(-1); // Não tem
else {
p.addInt8((char)m_ri.course & 0x7F);
p.addBuffer(&_session.m_pi.a_msa_natural[m_ri.course & 0x7F], sizeof(MapStatistics));
}
// Natural Assist rest season
// tem que fazer o map statistics soma de todas season
//p.addInt8((char)m_ri.course & 0x7F);
//p.addBuffer(&_session.m_pi.aa_ms_normal_todas_season[0][m_ri.course & 0x7F], sizeof(MapStatistics));
p.addInt8(-1); // Não tem
// Grand Prix essa season
if (_session.m_pi.a_ms_grand_prix[m_ri.course & 0x7F].course != (m_ri.course & 0x7F))
p.addInt8(-1); // Não tem
else {
p.addInt8((char)m_ri.course & 0x7F);
p.addBuffer(&_session.m_pi.a_ms_grand_prix[m_ri.course & 0x7F], sizeof(MapStatistics));
}
// Grand Prix rest season
// tem que fazer o map statistics soma de todas season
//p.addInt8((char)m_ri.course & 0x7F);
//p.addBuffer(&_session.m_pi.aa_ms_normal_todas_season[0][m_ri.course & 0x7F], sizeof(MapStatistics));
p.addInt8(-1); // Não tem
// Grand Prix Assist essa season
if (_session.m_pi.a_msa_grand_prix[m_ri.course & 0x7F].course != (m_ri.course & 0x7F))
p.addInt8(-1); // Não tem
else {
p.addInt8((char)m_ri.course & 0x7F);
p.addBuffer(&_session.m_pi.a_msa_grand_prix[m_ri.course & 0x7F], sizeof(MapStatistics));
}
// Grand Prix Assist rest season
// tem que fazer o map statistics soma de todas season
//p.addInt8((char)m_ri.course & 0x7F);
//p.addBuffer(&_session.m_pi.aa_ms_normal_todas_season[0][m_ri.course & 0x7F], sizeof(MapStatistics));
p.addInt8(-1); // Não tem
}
packet_func::session_send(p, &_session, 1);
}
void Game::sendFinishMessage(player& _session) {
INIT_PLAYER_INFO("sendFinishMessage", "tentou enviar message no chat que o player terminou o jogo", &_session);
packet p((unsigned short)0x40);
p.addUint8(16); // Msg que terminou o game
p.addString(_session.m_pi.nickname);
p.addUint16(0); // Size Msg
p.addInt32(pgi->data.score);
p.addUint64(pgi->data.pang);
p.addUint8(pgi->assist_flag);
packet_func::game_broadcast(*this, p, 1);
}
void Game::requestCalculeRankPlace() {
if (!m_player_order.empty())
m_player_order.clear();
for (auto& el : m_player_info)
if (el.second->flag != PlayerGameInfo::eFLAG_GAME::QUIT) // menos os que quitaram
m_player_order.push_back(el.second);
std::sort(m_player_order.begin(), m_player_order.end(), Game::sort_player_rank);
}
void Game::setGameFlag(PlayerGameInfo* _pgi, PlayerGameInfo::eFLAG_GAME _fg) {
if (_pgi == nullptr) {
_smp::message_pool::getInstance().push(new message("[Game::setGameFlag][Error] PlayerGameInfo* _pgi is invalid(nullptr).", CL_FILE_LOG_AND_CONSOLE));
return;
}
#if defined(_WIN32)
EnterCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs_sync_finish_game);
#endif
_pgi->flag = _fg;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs_sync_finish_game);
#endif
}
void Game::setFinishGameFlag(PlayerGameInfo* _pgi, unsigned char _finish_game) {
if (_pgi == nullptr) {
_smp::message_pool::getInstance().push(new message("[Game::setFinishGameFlag][Error] PlayerGameInfo* _pgi is invlaid(nullptr).", CL_FILE_LOG_AND_CONSOLE));
return;
}
#if defined(_WIN32)
EnterCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs_sync_finish_game);
#endif
_pgi->finish_game = _finish_game;
#if defined(_WIN32)
LeaveCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs_sync_finish_game);
#endif
}
bool Game::AllCompleteGameAndClear() {
uint32_t count = 0u;
bool ret = false;
#if defined(_WIN32)
EnterCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs_sync_finish_game);
#endif
// Da error Aqui
for (auto& el : m_players) {
try {
INIT_PLAYER_INFO("PlayersCompleteGameAndClear", "tentou verificar se o player terminou o jogo", el);
if (pgi->flag != PlayerGameInfo::eFLAG_GAME::PLAYING)
count++;
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::AllCompleteGameAndClear][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
ret = (count == m_players.size());
#if defined(_WIN32)
LeaveCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs_sync_finish_game);
#endif
return ret;
}
bool Game::PlayersCompleteGameAndClear() {
uint32_t count = 0u;
bool ret = false;
#if defined(_WIN32)
EnterCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs_sync_finish_game);
#endif
// Da error Aqui
for (auto& el : m_players) {
try {
INIT_PLAYER_INFO("PlayersCompleteGameAndClear", "tentou verificar se o player terminou o jogo", el);
if (pgi->finish_game)
count++;
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[GamePlayersCompleteGameAndClear][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
ret = (count == m_players.size());
#if defined(_WIN32)
LeaveCriticalSection(&m_cs_sync_finish_game);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs_sync_finish_game);
#endif
return ret;
}
bool Game::checkEndGame(player& _session) {
INIT_PLAYER_INFO("checkEndGame", "tentou verificar se eh o final do jogo", &_session);
return (m_course->findHoleSeq(pgi->hole) == m_ri.qntd_hole);
}
uint32_t Game::getCountPlayersGame() {
size_t count = 0u;
count = std::count_if(m_player_info.begin(), m_player_info.end(), [](auto& _el) {
return _el.second->flag != PlayerGameInfo::eFLAG_GAME::QUIT;
});
return (uint32_t)count;
}
unsigned char Game::requestPlace(player& _session) {
if (!_session.getState())
throw exception("[Game::requestPlace][Error] player nao esta connectado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::TOURNEY_BASE, 1, 0));
// Valor padrão
unsigned short hole = 0u;
INIT_PLAYER_INFO("requestPlace", "tentou pegar o lugar[Hole] do player no jogo", &_session);
if (pgi->hole > -1) {
hole = m_course->findHoleSeq(pgi->hole);
if (hole == (unsigned short)~0/*Error*/) {
// Valor padrão
hole = 0u;
_smp::message_pool::getInstance().push(new message("[Game::requestPlace][Error] player[UID=" + std::to_string(_session.m_pi.uid) + "] tentou pegar a sequencia do hole[NUMERO="
+ std::to_string(pgi->hole) + "], mas ele nao encontrou no course do game na sala[NUMERO=" + std::to_string(m_ri.numero) + "]", CL_FILE_LOG_AND_CONSOLE));
}
}else if (pgi->init_first_hole) // Só cria mensagem de log se o player já inicializou o primeiro hole do jogo e tem um valor inválido no pgi->hole (não é uma sequência de hole válida)
_smp::message_pool::getInstance().push(new message("[Game::requesPlace][Error] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] tentou pegar o hole[NUMERO=" + std::to_string(pgi->hole) + "] em que o player esta na sala[NUMERO=" + std::to_string(m_ri.numero)
+ "], mas ele esta carregando o course ou tem algum error.", CL_FILE_LOG_AND_CONSOLE));
return (unsigned char)hole;
}
bool Game::isGamingBefore(uint32_t _uid) {
if (_uid == 0u)
throw exception("[Game::isGamingBefore][Error] _uid is invalid(zero)", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 1000, 0));
return std::find_if(m_player_info.begin(), m_player_info.end(), [&](auto& _el) {
return _el.second->uid == _uid;
}) != m_player_info.end();
}
void Game::requestSendTimeGame(player& _session) {
UNREFERENCED_PARAMETER(_session);
}
void Game::requestUpdateEnterAfterStartedInfo(player& _session, EnterAfterStartInfo& _easi) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_easi);
}
void Game::requestStartFirstHoleGrandZodiac(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestReplyInitialValueGrandZodiac(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
void Game::requestReadSyncShotData(player& _session, packet *_packet, ShotSyncData& _ssd) {
REQUEST_BEGIN("readSyncShotData");
try {
// Decrypt Packet Dados, que esse o cliente encripta com a chave segura da sala
//DECRYPT16((_packet->getBuffer() + 2), (_packet->getSize() - 2), m_ri.key);
_packet->readBuffer(&_ssd, sizeof(_ssd));
// Decrypt Packet Dados, que esse o cliente encripta com a chave segura da sala
DECRYPT16((unsigned char*)&_ssd, sizeof(_ssd), m_ri.key);
if (_ssd.pang > 40000u)
_smp::message_pool::getInstance().push(new message("[Game::requestReadSyncShotDate][WARNING] player[UID=" + std::to_string(_session.m_pi.uid)
+ "] pode esta usando hack, PANG[" + std::to_string(_ssd.pang) + "] maior que 40k. Hacker ou Bug.", CL_FILE_LOG_AND_CONSOLE));
if (_ssd.bonus_pang > 10000u)
_smp::message_pool::getInstance().push(new message("[Game::requestReadSyncShotDate][WARNING] player[UID=" + std::to_string(_session.m_pi.uid)
+ "] pode esta usando hack, BONUS PANG[" + std::to_string(_ssd.bonus_pang) + "] maior que 10k. Hacker ou Bug.", CL_FILE_LOG_AND_CONSOLE));
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("size data: " + std::to_string(sizeof(_ssd)) + "\n\r" + hex_util::BufferToHexString((unsigned char*)&_ssd, sizeof(_ssd)), CL_FILE_LOG_AND_CONSOLE));
// Log Shot Sync Data
_smp::message_pool::getInstance().push(new message("Log Shot Sync Data:\n\r" + _ssd.toString(), CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::requestReadSyncShotData][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
bool Game::execSmartCalculatorCmd(player& _session, std::string& _msg, eTYPE_CALCULATOR_CMD _type) {
CHECK_SESSION("execSmartCalculatorCmd");
bool ret = false;
try {
if (_type == eTYPE_CALCULATOR_CMD::SMART_CALCULATOR) {
auto ctx = sSmartCalculator::getInstance().getPlayerCtx(_session.m_pi.uid, _type);
if (ctx == nullptr)
ctx = sSmartCalculator::getInstance().makePlayerCtx(_session.m_pi.uid, _type);
auto pp = ctx->getSmartPlayer();
auto gsv = getGameShotValueToSmartCalculator(_session, pp->m_club_index, pp->m_power_shot_index);
pp->setGameShotValue(gsv);
sSmartCalculator::getInstance().checkCommand(_session.m_pi.uid, _msg, _type);
}else {
// Stadium Calculator
auto ctx = sSmartCalculator::getInstance().getPlayerCtx(_session.m_pi.uid, _type);
if (ctx == nullptr)
ctx = sSmartCalculator::getInstance().makePlayerCtx(_session.m_pi.uid, _type);
sSmartCalculator::getInstance().checkCommand(_session.m_pi.uid, _msg, _type);
}
// OK
ret = true;
// Log
#ifdef _DEBUG
_smp::message_pool::getInstance().push(new message("[Game::execSmartCalculatorCmd][Log] Player[UID="
+ std::to_string(_session.m_pi.uid) + "] mandou o comando(" + _msg + ") para o " + std::string(_type == eTYPE_CALCULATOR_CMD::SMART_CALCULATOR ? "Smart Calculator" : "Stadium Calculator"), CL_FILE_LOG_AND_CONSOLE));
#else
_smp::message_pool::getInstance().push(new message("[Game::execSmartCalculatorCmd][Log] Player[UID="
+ std::to_string(_session.m_pi.uid) + "] mandou o comando(" + _msg + ") para o " + std::string(_type == eTYPE_CALCULATOR_CMD::SMART_CALCULATOR ? "Smart Calculator" : "Stadium Calculator"), CL_ONLY_FILE_LOG));
#endif // _DEBUG
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::execSmartCalculatorCmd][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
ret = false;
}
return ret;
}
stGameShotValue Game::getGameShotValueToSmartCalculator(player& _session, unsigned char _club_index, unsigned char _power_shot_index) {
CHECK_SESSION("getGameShotValueToSmartCalculator");
stGameShotValue gsv{ 0u };
try {
INIT_PLAYER_INFO("getGameShotValueToSmartCalculator", "tentou executar Smart Calculator Command", &_session);
auto hole = m_course->findHole(pgi->hole);
if (hole == nullptr)
throw exception("[Game::getGameShotValueToSmartCalculator][Error] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] tentou executar Smart Calculator command na sala[NUMERO=" + std::to_string(m_ri.numero)
+ "], mas nao encontrou o Hole[NUMERO=" + std::to_string((short)pgi->hole)
+ "] no Course.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 10000, 0));
auto wind_flag = initCardWindPlayer(pgi, hole->getWind().wind);
auto wind = hole->getWind().wind + 1 + wind_flag;
auto distance = hole->getPinLocation().diffXZ(pgi->location) * 0.3125f;
auto ground = 1u;
auto power_range = 230.f;
auto slope_break = 1.f;
auto power = _session.m_pi.getSlotPower();
auto angTo_rad = -std::atan2(hole->getPinLocation().x - pgi->location.x, hole->getPinLocation().z - pgi->location.z);
auto angTo = angTo_rad * 180 /
#if defined(_WIN32)
std::_Pi;
#elif defined(__linux__)
std::numbers::pi;
#endif
auto angEarcuff = pgi->earcuff_wind_angle_shot * 180 /
#if defined(_WIN32)
std::_Pi;
#elif defined(__linux__)
std::numbers::pi;
#endif
auto ang = 0.l;
if (pgi->effect_flag_shot.stFlag.EARCUFF_DIRECTION_WIND) {
long double rad_earcuff_hole = pgi->earcuff_wind_angle_shot + -angTo_rad;
if (rad_earcuff_hole < 0.f)
rad_earcuff_hole = (2 *
#if defined(_WIN32)
std::_Pi
#elif defined(__linux__)
std::numbers::pi
#endif
) + rad_earcuff_hole;
ang = rad_earcuff_hole * 180 /
#if defined(_WIN32)
std::_Pi;
#elif defined(__linux__)
std::numbers::pi;
#endif
}else
ang = fmodl((pgi->degree / 255.f) * 360.f + -angTo, 360.f);
bool pwr_by_condition_actived = pgi->effect_flag_shot.stFlag.SWITCH_TWO_EFFECT;
if (pwr_by_condition_actived && _session.m_pi.ei.char_info != nullptr
&& _session.m_pi.ei.char_info->isAuxPartEquiped(0x70210001u) && pgi->item_active_used_shot != 0u
&& pgi->item_active_used_shot == POWER_MILK_TYPEID)
pwr_by_condition_actived = false; // Usou Milk, encheu 1 ps perde a condição para ativar o efeito
auto power_extra = _session.m_pi.getExtraPower(pwr_by_condition_actived);
if (pgi->effect_flag_shot.stFlag.DECREASE_1M_OF_WIND && wind > 1)
wind--;
if (pgi->effect_flag_shot.stFlag.WIND_1M_RANDOM)
wind = 1;
if (pgi->effect_flag_shot.stFlag.SAFETY_CLIENT_RANDOM || pgi->effect_flag_shot.stFlag.SAFETY_RANDOM) {
ground = 100;
slope_break = 0.f;
}
if (pgi->effect_flag_shot.stFlag.GROUND_100_PERCENT_RONDOM)
ground = 100;
if (pgi->item_active_used_shot != 0u) {
if (isSilentWindItem(pgi->item_active_used_shot))
wind = 1;
if (isSafetyItem(pgi->item_active_used_shot)) {
ground = 100;
slope_break = 0.f;
}
}
#ifdef _DEBUG
// Log
_smp::message_pool::getInstance().push(new message("[Game::getGameShotValueToSmartCalculator][Log] Wind=" + std::to_string(wind)
+ ", Distance=" + std::to_string(distance) + ", Power=" + std::to_string(power) + ", Power_Extra="
+ std::to_string(power_extra.getTotal(0)) + ", ANGLE[ANG_TO_RAD=" + std::to_string(angTo_rad)
+ ", ANG_TO=" + std::to_string(angTo) + ", ANG=" + std::to_string(ang) + ", DEGREE=" + std::to_string((pgi->degree / 255.f) * 360.f)
+ ", ANG_EARCUFF=" + (pgi->effect_flag_shot.stFlag.EARCUFF_DIRECTION_WIND ? std::to_string(angEarcuff) : "NONE") + "]", CL_FILE_LOG_AND_CONSOLE));
#endif // _DEBUG
if (_club_index < sAllClubInfo3D::getInstance().m_clubs.size()) {
Club3D club(sAllClubInfo3D::getInstance().m_clubs[_club_index], calculeTypeDistance((float)distance));
power_range = (float)club.getRange(power_extra, (float)power, ePOWER_SHOT_FACTORY(_power_shot_index));
}
gsv.gm = (_session.m_pi.m_cap.stBit.gm_normal || _session.m_pi.m_cap.stBit.game_master) ? true : false;
gsv.safety = (slope_break == 0.f) ? true : false;
gsv.ground = (ground == 100u) ? true : false;
gsv.rain = (hole->getWeather() == 2 && !pgi->effect_flag_shot.stFlag.NO_RAIN_EFFECT) ? true : false;
gsv.power_slot = (unsigned char)power;
gsv.auxpart_pwr = (char)power_extra.getPowerDrive().m_auxpart;
gsv.mascot_pwr = (char)power_extra.getPowerDrive().m_mascot;
gsv.card_pwr = (char)power_extra.getPowerDrive().m_card;
gsv.ps_card_pwr = (char)power_extra.getPowerShot().m_card;
gsv.distance = (float)distance;
gsv.wind = (float)wind;
gsv.degree = (float)ang;
gsv.mira_rad = angTo_rad;
gsv.power_range = power_range;
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::getGameShotValueToSmartCalculator][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
return gsv;
}
void Game::clear_time() {
// Garantir que qualquer exception derrube o server
try {
if (m_timer != nullptr)
sgs::gs::getInstance().unMakeTime(m_timer);
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::clear_time][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
m_timer = nullptr;
}
void Game::clear_player_order() {
if (!m_player_order.empty()) {
m_player_order.clear();
m_players.shrink_to_fit();
}
}
void Game::initAchievement(player& _session) {
INIT_PLAYER_INFO("initAchievement", "tentou inicializar o achievemento do player no jogo", &_session);
try {
// Initialize Achievement Player
pgi->sys_achieve.incrementCounter(0x6C400002u/*Normal Game*/);
if (m_ri.natural.stBit.short_game/* & 2 /*Short Game*/)
pgi->sys_achieve.incrementCounter(0x6C4000BBu/*Short Game*/);
if (m_ri.master == _session.m_pi.uid) {
pgi->sys_achieve.incrementCounter(0x6C400098u/*Master da Sala*/);
if (m_ri.artefato > 0)
pgi->sys_achieve.incrementCounter(0x6C400099u/*Master da Sala com Artefact*/);
}
if (_session.m_pi.ei.char_info != nullptr) {
auto ctc = SysAchievement::getCharacterCounterTypeId(_session.m_pi.ei.char_info->_typeid);
if (ctc > 0u)
pgi->sys_achieve.incrementCounter(ctc/*Character Counter Typeid*/);
}
if (_session.m_pi.ei.cad_info != nullptr) {
auto ctc = SysAchievement::getCaddieCounterTypeId(_session.m_pi.ei.cad_info->_typeid);
if (ctc > 0u)
pgi->sys_achieve.incrementCounter(ctc/*Caddie Counter Typeid*/);
}
if (_session.m_pi.ei.mascot_info != nullptr) {
auto ctm = SysAchievement::getMascotCounterTypeId(_session.m_pi.ei.mascot_info->_typeid);
if (ctm > 0u)
pgi->sys_achieve.incrementCounter(ctm/*Mascot Counter Typeid*/);
}
auto ct = SysAchievement::getCourseCounterTypeId(m_ri.course & 0x7F);
if (ct > 0u)
pgi->sys_achieve.incrementCounter(ct/*Course Counter Item*/);
ct = SysAchievement::getQntdHoleCounterTypeId(m_ri.qntd_hole);
if (ct > 0u)
pgi->sys_achieve.incrementCounter(ct/*Qntd Hole Counter Item*/);
// Fim do inicializa o Achievement
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::initAchievement][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::SYS_ACHIEVEMENT)
throw; // relança exception
}
}
void Game::records_player_achievement(player& _session) {
CHECK_SESSION("records_players_achievement");
INIT_PLAYER_INFO("records_player_achievement", "tentou atualizar os achievement de records do player no jogo", &_session);
try {
if (pgi->ui.ob > 0)
pgi->sys_achieve.incrementCounter(0x6C40004Cu/*OB*/, pgi->ui.ob);
if (pgi->ui.bunker > 0)
pgi->sys_achieve.incrementCounter(0x6C40004Eu/*Bunker*/, pgi->ui.bunker);
if (pgi->ui.tacada > 0 || pgi->ui.putt > 0)
pgi->sys_achieve.incrementCounter(0x6C400055u/*Shots*/, pgi->ui.tacada + pgi->ui.putt);
if (pgi->ui.hole > 0)
pgi->sys_achieve.incrementCounter(0x6C400005u/*Holes*/, pgi->ui.hole);
if (pgi->ui.total_distancia > 0)
pgi->sys_achieve.incrementCounter(0x6C400056u/*Yards*/, pgi->ui.total_distancia);
// Bug o valor é 0 por que (int)0.9f é 0 ele trunca não arredondo, e tem que truncar mesmo
// Para fixa esse bug é só fazer >= 1.f sempre vai ser (int) >= 1(truncado)
if (pgi->ui.best_drive >= 1.f)
pgi->sys_achieve.incrementCounter(0x6C400057u/*Best Drive*/, (int)pgi->ui.best_drive);
if (pgi->ui.best_chip_in >= 1.f)
pgi->sys_achieve.incrementCounter(0x6C400058u/*Best Chip-in*/, (int)pgi->ui.best_chip_in);
if (pgi->ui.best_long_putt >= 1.f)
pgi->sys_achieve.incrementCounter(0x6C400077u/*Best Long-putt*/, (int)pgi->ui.best_long_putt);
if (pgi->ui.acerto_pangya > 0)
pgi->sys_achieve.incrementCounter(0x6C40000Bu/*Acerto PangYa*/, pgi->ui.acerto_pangya);
if (pgi->data.pang > 0)
pgi->sys_achieve.incrementCounter(0x6C40000Du/*Pangs Ganho em 1 jogo*/, (int)pgi->data.pang);
if (pgi->data.score != 0)
pgi->sys_achieve.incrementCounter(0x6C40000Cu/*Score*/, pgi->data.score);
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::records_player_achievement][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::SYS_ACHIEVEMENT)
throw; // relança exception
}
}
void Game::update_sync_shot_achievement(player& _session, Location& _last_location) {
CHECK_SESSION("update_sync_shot_achievement");
INIT_PLAYER_INFO("update_sync_shot_achievement", "tentou atualizar o achievement de Desafios no jogo", &_session);
try {
// Só conta se o player acertou o hole
if (pgi->shot_sync.state_shot.display.stDisplay.acerto_hole) {
// Long-putt
if (pgi->shot_sync.state_shot.display.stDisplay.long_putt && pgi->shot_sync.state_shot.shot.stShot.club_putt) {
auto diff = pgi->location.diffXZ(_last_location) * MEDIDA_PARA_YARDS;
if (diff >= 30.f)
pgi->sys_achieve.incrementCounter(0x6C400035u/*Long Putt 30y+*/);
if (diff >= 25.f)
pgi->sys_achieve.incrementCounter(0x6C400034u/*Long Putt 25y+*/);
if (diff >= 20.f)
pgi->sys_achieve.incrementCounter(0x6C400033u/*Long Putt 20y+*/);
if (diff >= 17.f)
pgi->sys_achieve.incrementCounter(0x6C400032u/*Long Putt 17y+*/);
}
// Fez o hole de Beam Impact
if (pgi->shot_sync.state_shot.display.stDisplay.beam_impact)
pgi->sys_achieve.incrementCounter(0x6C40006Fu/*Beam Impact*/);
// Fez o hole com
if (pgi->shot_sync.state_shot.shot.stShot.spin_front)
pgi->sys_achieve.incrementCounter(0x6C400064u/*Spin Front*/);
if (pgi->shot_sync.state_shot.shot.stShot.spin_back)
pgi->sys_achieve.incrementCounter(0x6C400065u/*Spin Back*/);
if (pgi->shot_sync.state_shot.shot.stShot.curve_left || pgi->shot_sync.state_shot.shot.stShot.curve_right)
pgi->sys_achieve.incrementCounter(0x6C400066u/*Curve*/);
if (pgi->shot_sync.state_shot.shot.stShot.tomahawk)
pgi->sys_achieve.incrementCounter(0x6C400067u/*Tomahawk*/);
if (pgi->shot_sync.state_shot.shot.stShot.spike)
pgi->sys_achieve.incrementCounter(0x6C400068u/*Spike*/);
if (pgi->shot_sync.state_shot.shot.stShot.cobra)
pgi->sys_achieve.incrementCounter(0x6C40006Eu/*Cobra*/);
// Fez sem usar power shot
if (pgi->shot_sync.state_shot.display.stDisplay.chip_in_without_special_shot && !pgi->shot_sync.state_shot.display.stDisplay.special_shot/*Nega*/)
pgi->sys_achieve.incrementCounter(0x6C40005Bu/*Fez sem usar power shot*/);
// o pacote12 passa primeiro depois que o server response ele passa esse pacote1B, então esse valor sempre vai está certo
// Fez Errando pangya
if (pgi->shot_data.acerto_pangya_flag & 2/*Errou pangya*/ && !pgi->shot_sync.state_shot.shot.stShot.club_putt/*Nega*/)
pgi->sys_achieve.incrementCounter(0x6C400059u/*Fez errando pangya*/);
}
// Tacada Power Shot ou Double Power Shot
if (pgi->shot_sync.state_shot.shot.stShot.power_shot)
pgi->sys_achieve.incrementCounter(0x6C400051u/*Power Shot*/);
if (pgi->shot_sync.state_shot.shot.stShot.double_power_shot)
pgi->sys_achieve.incrementCounter(0x6C400052u/*Double Power Shot*/);
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::update_sync_shot_achievement][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::SYS_ACHIEVEMENT)
throw; // relança exception
}
}
void Game::rain_hole_consecutivos_count(player& _session) {
auto& chr = m_course->getConsecutivesHolesRain();
INIT_PLAYER_INFO("rain_hole_consecutivos_count", "tentou atualizar o achievement count de chuva em holes consecutivos do player no jogo", &_session);
try {
uint32_t count = 0u;
auto seq = m_course->findHoleSeq(pgi->hole);
if (chr.isValid()) {
// 2 Holes consecutivos
if ((count = chr._2_count.getCountHolesRainBySeq(seq)) > 0u)
pgi->sys_achieve.incrementCounter(0x6C40009Bu/*2 Holes consecutivos*/, count);
if ((count = chr._3_count.getCountHolesRainBySeq(seq)) > 0u)
pgi->sys_achieve.incrementCounter(0x6C40009Cu/*3 Holes consecutivos*/, count);
if ((count = chr._4_pluss_count.getCountHolesRainBySeq(seq)) > 0u)
pgi->sys_achieve.incrementCounter(0x6C40009Du/*4 ou mais Holes consecutivos*/, count);
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::rain_hole_consecutivos_count][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::SYS_ACHIEVEMENT)
throw; // relança exception
}
}
void Game::score_consecutivos_count(player& _session) {
int32_t score = -2, last_score = -2;
uint32_t count = 0u;
INIT_PLAYER_INFO("rain_score_consecutivos", "tentou atualizar o achievement contador de score consecutivos do player no jogo", &_session);
try {
for (auto i = 0u; i < m_ri.qntd_hole; ++i) {
score = SysAchievement::getScoreNum(pgi->progress.tacada[i], pgi->progress.par_hole[i]);
// Change Score, Soma o Count do Score
if ((score != last_score || i == (m_ri.qntd_hole - 1)/*Ultimo hole*/) && last_score != -2/*Primeiro Hole*/) {
// 1 == 2, 2 ou mais Holes com o mesmo score
if (count >= 1u && last_score >= 0/*Scores que tem no achievement*/) {
switch (last_score) {
case 0: // HIO
pgi->sys_achieve.incrementCounter(0x6C400063u/*HIO*/);
break;
case 1: // Alba
pgi->sys_achieve.incrementCounter(0x6C400062u/*Alba*/);
break;
case 2: // Eagle
pgi->sys_achieve.incrementCounter(0x6C400061u/*Eagle*/);
break;
case 3: // Birdie
pgi->sys_achieve.incrementCounter(0x6C40005Du/*Birdie*/);
break;
case 4: // Par
pgi->sys_achieve.incrementCounter(0x6C40005Eu/*Par*/);
break;
case 5: // Bogey
pgi->sys_achieve.incrementCounter(0x6C40005Fu/*Bogey*/);
break;
case 6: // Double Bogey
pgi->sys_achieve.incrementCounter(0x6C400060u/*Double Bogey*/);
break;
}
}
// Reseta o count
count = 0u;
}else if (score == last_score)
count++;
// Update Last Score
last_score = score;
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::score_consecutivos_count][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::SYS_ACHIEVEMENT)
throw; // relança exception
}
}
void Game::rain_count(player& _session) {
try {
// Recovery, Chuva, Neve/*Tempo Ruim*/
if (m_course->countHolesRain() > 0) {
uint32_t count = 0u;
INIT_PLAYER_INFO("rain_count_players", "tentou atualizar o achievement contador de chuva do player no jogo", &_session);
// Pega pela quantidade de holes jogados
auto seq = m_course->findHoleSeq(pgi->hole);
if ((count = m_course->countHolesRainBySeq(seq)) > 0u)
pgi->sys_achieve.incrementCounter(0x6C40009Au/*Chuva*/, count);
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::rain_count][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::SYS_ACHIEVEMENT)
throw; // relança exception
}
}
void Game::setEffectActiveInShot(player& _session, uint64_t _effect) {
CHECK_SESSION("setEffectActiveInShot");
try {
INIT_PLAYER_INFO("setEffectActiveInShot", "tentou setar o efeito ativado na tacada", &_session);
pgi->effect_flag_shot.ullFlag |= _effect;
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::setEffectActiveInShot][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
void Game::clearDataEndShot(PlayerGameInfo* _pgi) {
if (_pgi == nullptr)
throw exception("[Game::clearDataEndShot][Error] PlayerGameInfo *_pgi is invalid(nullptr). Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::GAME, 100, 0));
try {
_pgi->effect_flag_shot.clear();
_pgi->item_active_used_shot = 0u;
_pgi->earcuff_wind_angle_shot = 0.f;
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::clearDataEndShot][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
void Game::checkEffectItemAndSet(player & _session, uint32_t _typeid) {
CHECK_SESSION("checkEffectitemAndSet");
try {
auto ability = sIff::getInstance().findAbility(_typeid);
if (ability != nullptr) {
for (auto i = 0u; i < (sizeof(ability->efeito.type) / sizeof(ability->efeito.type[0])); ++i) {
if (ability->efeito.type[i] == 0u)
continue;
if (ability->efeito.type[i] == (uint32_t)IFF::Ability::eEFFECT_TYPE::COMBINE_ITEM_EFFECT) {
// find item setEffectTable
auto effectTable = sIff::getInstance().findSetEffectTable((uint32_t)ability->efeito.rate[i]);
if (effectTable != nullptr) {
for (auto j = 0u; j < (sizeof(effectTable->effect.effect) / sizeof(effectTable->effect.effect[0])); ++j) {
if (effectTable->effect.effect[j] == 0u || effectTable->effect.effect[j] < 4u)
continue;
switch (effectTable->effect.effect[j]) {
case IFF::SetEffectTable::eEFFECT::PIXEL:
setEffectActiveInShot(_session, enumToBitValue<IFF::Ability::eEFFECT_TYPE, uint64_t>(IFF::Ability::eEFFECT_TYPE::PIXEL_2));
break;
case IFF::SetEffectTable::eEFFECT::ONE_ALL_STATS:
setEffectActiveInShot(_session, enumToBitValue<IFF::Ability::eEFFECT_TYPE, uint64_t>(IFF::Ability::eEFFECT_TYPE::ONE_IN_ALL_STATS));
break;
case IFF::SetEffectTable::eEFFECT::WIND_DECREASE:
setEffectActiveInShot(_session, enumToBitValue<IFF::Ability::eEFFECT_TYPE, uint64_t>(IFF::Ability::eEFFECT_TYPE::DECREASE_1M_OF_WIND));
break;
case IFF::SetEffectTable::eEFFECT::PATINHA:
setEffectActiveInShot(_session, enumToBitValue<IFF::Ability::eEFFECT_TYPE, uint64_t>(IFF::Ability::eEFFECT_TYPE::PAWS_NOT_ACCUMULATE));
break;
}
}
}
}else
setEffectActiveInShot(_session, enumToBitValue<IFF::Ability::eEFFECT_TYPE, uint64_t>(IFF::Ability::eEFFECT_TYPE(ability->efeito.type[i])));
}
}
}catch (exception& e) {
_smp::message_pool::getInstance().push(new message("[Game::checkEffectitemAndSet][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
}
}
void Game::SQLDBResponse(uint32_t _msg_id, pangya_db& _pangya_db, void* _arg) {
if (_arg == nullptr) {
_smp::message_pool::getInstance().push(new message("[Game::SQLDBResponse][WARNING] _arg is nullptr com msg_id = " + std::to_string(_msg_id), CL_FILE_LOG_AND_CONSOLE));
return;
}
// Por Hora só sai, depois faço outro tipo de tratamento se precisar
if (_pangya_db.getException().getCodeError() != 0) {
_smp::message_pool::getInstance().push(new message("[Game::SQLDBResponse][Error] " + _pangya_db.getException().getFullMessageError(), CL_FILE_LOG_AND_CONSOLE));
return;
}
auto *game = reinterpret_cast< Game* >(_arg);
switch (_msg_id) {
case 12: // Update ClubSet Workshop
{
auto cmd_ucw = reinterpret_cast< CmdUpdateClubSetWorkshop* >(&_pangya_db);
_smp::message_pool::getInstance().push(new message("[Game::SQLDBResponse][Log] player[UID=" + std::to_string(cmd_ucw->getUID()) + "] Atualizou ClubSet[TYPEID=" + std::to_string(cmd_ucw->getInfo()._typeid) + ", ID="
+ std::to_string(cmd_ucw->getInfo().id) + "] Workshop[C0=" + std::to_string(cmd_ucw->getInfo().clubset_workshop.c[0]) + ", C1=" + std::to_string(cmd_ucw->getInfo().clubset_workshop.c[1]) + ", C2="
+ std::to_string(cmd_ucw->getInfo().clubset_workshop.c[2]) + ", C3=" + std::to_string(cmd_ucw->getInfo().clubset_workshop.c[3]) + ", C4=" + std::to_string(cmd_ucw->getInfo().clubset_workshop.c[4])
+ ", Level=" + std::to_string(cmd_ucw->getInfo().clubset_workshop.level) + ", Mastery=" + std::to_string(cmd_ucw->getInfo().clubset_workshop.mastery) + ", Rank="
+ std::to_string(cmd_ucw->getInfo().clubset_workshop.rank) + ", Recovery=" + std::to_string(cmd_ucw->getInfo().clubset_workshop.recovery_pts) + "] Flag=" + std::to_string(cmd_ucw->getFlag()) + "", CL_FILE_LOG_AND_CONSOLE));
break;
}
case 1: // Insert Ticket Report Dados
{
break;
}
case 0:
default: // 25 é update item equipado slot
break;
}
}
bool Game::sort_player_rank(PlayerGameInfo* _pgi1, PlayerGameInfo* _pgi2) {
if (_pgi1->data.score == _pgi2->data.score)
return _pgi1->data.pang > _pgi2->data.pang;
return _pgi1->data.score < _pgi2->data.score;
}
void Game::makePlayerInfo(player& _session) {
PlayerGameInfo *pgi = makePlayerInfoObject(_session);
// Bloqueia o OID para ninguém pegar ele até o torneio acabar
sgs::gs::getInstance().blockOID(_session.m_oid);
// Update Place player
_session.m_pi.place = 0u; // Jogando
pgi->uid = _session.m_pi.uid;
pgi->oid = _session.m_oid;
pgi->level = (unsigned char)_session.m_pi.mi.level;
// Entrou no Jogo depois de ele ter começado
if (m_state)
pgi->enter_after_started = 1u;
// Typeid do Mascot Equipado
if (_session.m_pi.ei.mascot_info != nullptr)
pgi->mascot_typeid = _session.m_pi.ei.mascot_info->_typeid;
// Premium User
if (_session.m_pi.m_cap.stBit.premium_user/* & (1 << 14)/*Premium User*/)
pgi->premium_flag = 1u;
// Card Wind Flag
pgi->card_wind_flag = getPlayerWindFlag(_session);
// Treasure Hunter Points Card Player Initialize Data
// Não pode ser chamado depois do Init Item Used Game, por que ele vai add os pontos dos itens que dá Drop rate e treasure hunter point
pgi->thi = getPlayerTreasureInfo(_session);
// Flag Assist
auto pWi = _session.m_pi.findWarehouseItemByTypeid(ASSIST_ITEM_TYPEID);
if (pWi != nullptr)
pgi->assist_flag = 1u;
// Verifica se o player está com o motion item equipado
pgi->char_motion_item = checkCharMotionItem(_session);
// Motion Item da Treasure Hunter Point também
if (pgi->char_motion_item)
pgi->thi.all_score += 20; // +20 all score
pgi->data.clear();
pgi->location.clear();
auto it = m_player_info.insert(std::make_pair(&_session, pgi));
// Check insert pair in map of game player info
if (!it.second) {
if (it.first != m_player_info.end() && it.first->first != nullptr && it.first->first == (&_session)) {
if (it.first->second->uid != _session.m_pi.uid) {
// Add novo PlayerGameInfo para a (session*), que tem um novo player conectado na session.
// Isso pode acontecer quando um player entrou no jogo saiu com ticket ou tomou dc e desconectou do server,
// e outro player pegou essa session e tentou entrar no mesmo jogo que o player estava
try {
// pega o antigo PlayerGameInfo para usar no Log
auto pgi_ant = m_player_info.at(&_session);
// Novo PlayerGameInfo
m_player_info.at(&_session) = pgi;
// Log de que trocou o PlayerGameInfo da session
_smp::message_pool::getInstance().push(new message("[Game::makePlayerInfo][WARNING][Log] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] esta trocando o PlayerGameInfo[UID=" + std::to_string(pgi_ant->uid) + "] do player anterior que estava conectado com essa session, pelo o PlayerGameInfo[UID="
+ std::to_string(pgi->uid) + "] do player atual da session.", CL_FILE_LOG_AND_CONSOLE));
// Libera a memória do antigo player info
delete pgi_ant;
}catch (std::out_of_range& e) {
UNREFERENCED_PARAMETER(e);
_smp::message_pool::getInstance().push(new message("[Game::makePlayerInfo][Error][WARNING] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "], nao conseguiu atualizar o PlayerGameInfo da session para o novo PlayerGameInfo do player atual da session. Bug", CL_FILE_LOG_AND_CONSOLE));
}
}else
_smp::message_pool::getInstance().push(new message("[Game::makePlayerInfo][Log] Player[UID=" + std::to_string(_session.m_pi.uid)
+ "] nao conseguiu adicionar o PlayerGameInfo da session, por que ja tem o mesmo PlayerGameInfo no map.", CL_FILE_LOG_AND_CONSOLE));
}else
_smp::message_pool::getInstance().push(new message("[Game::makePlayerInfo][Error] nao conseguiu inserir o pair de PlayerInfo do player[UID="
+ std::to_string(_session.m_pi.uid) + "] no map de player info do game. Bug", CL_FILE_LOG_AND_CONSOLE));
}
// Init Item Used Game
requestInitItemUsedGame(_session, *it.first->second);
}
void Game::clearAllPlayerInfo() {
#if defined(_WIN32)
EnterCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_lock(&m_cs);
#endif
for (auto& el : m_player_info) {
if (el.second != nullptr) {
sgs::gs::getInstance().unblockOID(el.second->oid); // Desbloqueia o OID
// Libera a memória
delete el.second;
}
}
m_player_info.clear();
#if defined(_WIN32)
LeaveCriticalSection(&m_cs);
#elif defined(__linux__)
pthread_mutex_unlock(&m_cs);
#endif
}
void Game::initAllPlayerInfo() {
for (auto& el : m_players)
makePlayerInfo(*el);
}
// Make Object Player Info Polimofirsmo
PlayerGameInfo* Game::makePlayerInfoObject(player& _session) {
UNREFERENCED_PARAMETER(_session);
return new PlayerGameInfo{ 0 };
}
void Game::requestInitShotSended(player& _session, packet *_packet) {
UNREFERENCED_PARAMETER(_session);
UNREFERENCED_PARAMETER(_packet);
}
| 35.942037 | 247 | 0.702765 | [
"object",
"vector"
] |
c490bc21af2f66c87cc81f8da850d3714a1e2e8b | 8,267 | hpp | C++ | src/helpers.hpp | MaBunny/My_IRCbot | 82fc1e27843628b5cae9e5f6e66de456acb140d5 | [
"Apache-2.0"
] | 1 | 2019-04-29T15:01:57.000Z | 2019-04-29T15:01:57.000Z | src/helpers.hpp | OtakuSenpai/My_IRCbot | 82fc1e27843628b5cae9e5f6e66de456acb140d5 | [
"Apache-2.0"
] | 7 | 2016-07-01T06:41:23.000Z | 2016-10-31T13:35:20.000Z | src/helpers.hpp | MaBunny/My_IRCbot | 82fc1e27843628b5cae9e5f6e66de456acb140d5 | [
"Apache-2.0"
] | null | null | null | #ifndef HELPERS_HPP_INCLUDED
#define HELPERS_HPP_INCLUDED
#include <string>
#include <algorithm>
#include "settings_exception.hpp"
class Settings
{
private:
std::string server;
std::string channel;
unsigned int port;
std::string nick;
Settings_Exception *SE;
//Compare two strings
inline bool Compare_To(std::string param1,std::string param2)
{
std::transform(param1.begin(),param1.end(),param1.begin(),
std::ptr_fun<int,int>(std::toupper));
std::transform(param2.begin(),param2.end(),param2.begin(),
std::ptr_fun<int,int>(std::toupper));
if( param1.compare(param2) == 0 )
return true;
else if( param1.compare(param2) != 0 )
return false;
}
//Compare two unsigned shorts
inline bool Compare_To(unsigned int param1,unsigned int param2)
{
if( param1 == param2 )
return true;
else if ( param1 != param2 )
return false;
}
//Clear the contents of the variables
inline void Clear()
{
server.clear();
channel.clear();
nick.clear();
port = 0;
logger.GetLogs(static_cast<std::string>("In Settings class: Cleared the data members."));
logger.Log(0);
}
public:
Settings() { SE = new Settings_Exception; }
Settings (Settings &a) : server(a.server), channel(a.channel),
port(a.port), nick(a.nick)
{
try
{
SE = new Settings_Exception(a.server,a.port);
}
catch(Settings_Exception &S)
{
std::cout<<"Oops....found an error!!!\n";
std::cout<<S.what()<<std::endl;
}
std::string Msg;
Msg = static_cast<std::string>("In Settings class: Created a Settings object with server = ") + a.server + static_cast<std::string>(",Channel = ") + a.channel + static_cast<std::string>(",Port = ") + std::to_string(a.port) + static_cast<std::string>(",Nick = ") + a.nick + static_cast<std::string>(".");
logger.GetLogs(Msg);
Msg = static_cast<std::string>("In Settings class: Created an Settings_Exception object with Server= ") + a.server + static_cast<std::string>("\n and Port = ") + std::to_string(a.port) + static_cast<std::string>(".");
logger.GetLogs(Msg);
logger.Log(0);
}
Settings& operator=(const Settings& lvalue)
{
try
{
server.assign(lvalue.server);
channel.assign(lvalue.channel);
nick.assign(lvalue.nick);
port = lvalue.port;
return *this;
}
catch(std::exception& e)
{
std::cout<<"Oops...caught an error !!!"<<std::endl
<<e.what()<<std::endl;
}
return *this;
}
Settings(std::string &Serv,std::string &Chan,unsigned int &Port,
std::string &Nick): server(Serv),channel(Chan),port(Port),nick(Nick)
{
try
{
SE = new Settings_Exception(Serv,Port);
}
catch(Settings_Exception &S)
{
std::cout<<"Oops....found an error!!!\n";
std::cout<<S.what()<<std::endl;
}
std::string Msg;
Msg = static_cast<std::string>("In Settings class: Created a Settings object with server = ") + Serv + static_cast<std::string>(",Channel = ") + Chan + static_cast<std::string>(",Port = ") +std::to_string(Port) + static_cast<std::string>(",Nick = ") +Nick+ static_cast<std::string>(".");
logger.GetLogs(Msg);
Msg = static_cast<std::string>("In Settings class: Created an Settings_Exception object with Server= ") + Serv + static_cast<std::string>("\n and Port = ") + std::to_string(Port) + static_cast<std::string>(".");
logger.GetLogs(Msg);
logger.Log(0);
}
~Settings() { delete SE; }
std::string RetServer() { return this->server; }
std::string RetChannel() { return this->channel; }
unsigned short RetPort() { return this->port; }
std::string RetNick() { return this->nick; }
void GetServer(std::string &Serv)
{
server = Serv;
try { SE->GetServ(server); }
catch(Settings_Exception &S)
{
std::cout<<"Oops....found an error!!!\n";
std::cout<<S.what()<<std::endl;
}
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Server = ") + Serv +static_cast<std::string>("."));
logger.Log(0);
}
void GetChannel(std::string &Chan)
{
channel = Chan;
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Channel = ") + Chan +static_cast<std::string>("."));
logger.Log(0);
}
void GetPort(unsigned int &Port)
{
port = Port;
try { SE->GetPort(port); }
catch(Settings_Exception &S)
{
std::cout<<"Oops....found an error!!!\n";
std::cout<<S.what()<<std::endl;
}
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Port = ") + std::to_string(Port) +static_cast<std::string>("."));
logger.Log(0);
}
void GetNick(std::string &Nick)
{
nick = Nick;
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Nick = ") + Nick +static_cast<std::string>("."));
logger.Log(0);
}
//Get the data
inline void GetData(std::string &serv,std::string &chan,
unsigned int &p,std::string &n)
{
server = serv; channel = chan; port = p; nick = n;
try
{
SE->GetServ(server); SE->GetPort(port);
}
catch(Settings_Exception &S)
{
std::cout<<"Oops....found an error!!!\n";
std::cout<<S.what()<<std::endl;
}
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Server = ") + serv +static_cast<std::string>("."));
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Channel = ") + chan +static_cast<std::string>("."));
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Port = ") + std::to_string(p) +static_cast<std::string>("."));
logger.GetLogs(static_cast<std::string>("In Settings class: Used get function to store Nick = ") + n +static_cast<std::string>("."));
}
inline void PutData(std::string &serv,std::string &chan,
unsigned int &p,std::string &n)
{
serv = server; chan = channel; p = port; n = nick;
logger.GetLogs(static_cast<std::string>("In Settings class: Used put function to return Server = ") + server + static_cast<std::string>(",Channel = ") + channel + static_cast<std::string>(",Port = ") + std::to_string(port) + static_cast<std::string>(",Nick = ") + nick + static_cast<std::string>("."));
logger.Log(0);
}
};
class Metadata
{
private:
unsigned int count = 0;
friend class Config;
void Cear()
{
count = 0;
}
void GetCount(unsigned int &Count)
{
count = Count;
logger.GetLogs(static_cast<std::string>("In Metadata class: Inputed the number of Counts as: ") + std::to_string(count));
logger.Log(0);
}
void UpCount()
{
count++;
logger.GetLogs(static_cast<std::string>("In Metadata class: Updated Count by one. "));
logger.Log(0);
}
public:
Metadata() { count=0; }
Metadata(Metadata &a) : count(a.count) {}
~Metadata() {}
unsigned int RetCount() { return count; }
bool Compare_To(unsigned int ¶m1,unsigned int ¶m2)
{
if(param1 == param2)
return true;
else if(param1 != param2)
return false;
return false;
}
};
#endif // HELPERS_HPP_INCLUDED
| 35.943478 | 316 | 0.548325 | [
"object",
"transform"
] |
c49761cfe2db8df93430ea3f2be9e001e0bc34a9 | 1,825 | hpp | C++ | lib/graph/cycle_detection.hpp | hareku/cpp-algorithm | 455339645d5797f0e6b211694345e1a221fc131c | [
"Apache-2.0"
] | null | null | null | lib/graph/cycle_detection.hpp | hareku/cpp-algorithm | 455339645d5797f0e6b211694345e1a221fc131c | [
"Apache-2.0"
] | null | null | null | lib/graph/cycle_detection.hpp | hareku/cpp-algorithm | 455339645d5797f0e6b211694345e1a221fc131c | [
"Apache-2.0"
] | null | null | null | #ifndef LIB_GRAPH_CYCLE_DETECTION_HPP
#define LIB_GRAPH_CYCLE_DETECTION_HPP 1
#include <bits/stdc++.h>
namespace lib::graph {
struct cycle_detection_graph {
public:
cycle_detection_graph() : _n(0) {}
cycle_detection_graph(int n) : _n(n), g(n) {}
void add_edge(int from, int to) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
g[from].push_back(_edge{to});
}
std::vector<int> detect() {
std::vector<int> his;
std::vector<bool> seen(_n, false);
std::vector<bool> seen_children(_n, false);
int start;
auto dfs = [&](auto self, int cur) {
seen[cur] = true;
his.push_back(cur);
for(auto& e : g[cur]) {
if(seen_children[e.to]) continue;
if(seen[e.to] && !seen_children[e.to]) {
start = e.to;
return true;
}
bool detected = self(self, e.to);
if(detected) {
return true;
}
}
his.pop_back();
seen_children[cur] = true;
return false;
};
auto make_cycle = [&]() {
std::vector<int> cycle;
int i = 0;
while(his[i] != start) ++i;
for(; i < int(his.size()); ++i) {
cycle.push_back(his[i]);
}
return cycle;
};
for(int i = 0; i < _n; ++i) {
if(seen[i]) continue;
if(dfs(dfs, i)) {
return make_cycle();
}
}
return {};
}
private:
int _n;
struct _edge {
int to;
};
std::vector<std::vector<_edge>> g;
};
} // namespace lib::graph
#endif // LIB_GRAPH_CYCLE_DETECTION_HPP
| 23.101266 | 56 | 0.456438 | [
"vector"
] |
c497e3030a2c5bdf83eef0645ab480e5f46d7e6b | 6,813 | cpp | C++ | core/performance_test/peakflops/01_cpp_simple.cpp | suchyta1/Cabana | 126d67ce76645b90042197174fcc4cf494e6a56d | [
"Unlicense"
] | null | null | null | core/performance_test/peakflops/01_cpp_simple.cpp | suchyta1/Cabana | 126d67ce76645b90042197174fcc4cf494e6a56d | [
"Unlicense"
] | null | null | null | core/performance_test/peakflops/01_cpp_simple.cpp | suchyta1/Cabana | 126d67ce76645b90042197174fcc4cf494e6a56d | [
"Unlicense"
] | null | null | null | #include "common.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gtest/gtest.h>
/*
For skylake
Model name: Intel(R) Xeon(R) Gold 6152 CPU @ 2.10GHz
gcc version 7.2.0
g++ -O3 -march=native peakflops.cpp -DVECLENTH=16
640000000.000000 flops
6482486 clocks
98.727556 flops/clock
For knl
Model name: Intel(R) Xeon Phi(TM) CPU 7250 @ 1.40GHz
g++ version 8.1.0
g++ -O3 -march=native peakflops.cpp -DVECLENTH=16
640000000.000000 flops
10900834 clocks
58.711104 flops/clock
For haswell/broadwell
Model name: Intel(R) Xeon(R) CPU E5-2660 v3 @ 2.60GHz
gcc 7.3.0/intel 17.0.6/clang 5.0.1
$ g++ -O3 -march=native peakflops.cpp -fopt-info-vec
$ ./a.out
160000000000.000000 flops
4200302774 clocks
38.092492 flops/clock
x_[0] = 2.161056
x_[1] = 11.734885
x_[2] = 4.641315
x_[3] = 160.230576
x_[4] = 1.043288
x_[5] = 6.865434
x_[6] = 14.501436
x_[7] = 1.216459
$ icpc -O3 -march=core-avx2 -fma peakflops.cpp
[gchen@cn151 openmp]$ ./a.out
160000000000.000000 flops
4200379130 clocks
38.091800 flops/clock
x_[0] = 2.161056
x_[1] = 11.734885
x_[2] = 4.641316
x_[3] = 160.230591
x_[4] = 1.043288
x_[5] = 6.865434
x_[6] = 14.501434
x_[7] = 1.216459
$ clang++ -O3 peakflops.cpp -mavx2 -mfma -ffp-contract=fast
$ ./a.out
160000000000.000000 flops
4200978198 clocks
38.086368 flops/clock
x_[0] = 2.161056
x_[1] = 11.734885
x_[2] = 4.641315
x_[3] = 160.230576
x_[4] = 1.043288
x_[5] = 6.865434
x_[6] = 14.501436
x_[7] = 1.216459
-------------------
For Sandy/Ivy Bridge you need to unroll by >=3:
Only FP Add has dependency on the previous iteration of the loop
FP Add can issue every cycle
FP Add takes three cycles to complete
Thus unrolling by 3/1 = 3 completely hides the latency (theoretically)
FP Mul and FP Load do not have a dependency on the previous iteration and you
can rely on the OoO core to issue them in the near-optimal order. These
instructions could affect the unroll factor only if they lowered the throughput
of FP Add (not the case here, FP Load + FP Add + FP Mul can issue every cycle).
For Haswell you need to unroll by 10 (as we do below, using x0..x9):
Only FMA has dependency on the previous iteration of the loop
FMA can double-issue every cycle (i.e. on average independent instructions take
0.5 cycles) FMA has latency of 5 Thus unrolling by 5/0.5 = 10 completely hides
FMA latency The two FP Load microoperations do not have a dependency on the
previous iteration, and can co-issue with 2x FMA, so they don't affect the
unroll factor.
*/
struct data
{
float vec[CABANA_PERFORMANCE_VECLENGTH];
};
struct data *
axpy_10( struct data *__restrict__ a, struct data *__restrict__ x0,
struct data *__restrict__ x1, struct data *__restrict__ x2,
struct data *__restrict__ x3, struct data *__restrict__ x4,
struct data *__restrict__ x5, struct data *__restrict__ x6,
struct data *__restrict__ x7, struct data *__restrict__ x8,
struct data *__restrict__ x9, struct data *__restrict__ c, long n )
{
long i;
int j;
asm volatile( "# ax+c loop begin" );
for ( i = 0; i < n; i++ )
{
#pragma omp simd
for ( j = 0; j < CABANA_PERFORMANCE_VECLENGTH; j++ )
{
x0->vec[j] = a->vec[j] * x0->vec[j] + c->vec[j];
x1->vec[j] = a->vec[j] * x1->vec[j] + c->vec[j];
x2->vec[j] = a->vec[j] * x2->vec[j] + c->vec[j];
x3->vec[j] = a->vec[j] * x3->vec[j] + c->vec[j];
x4->vec[j] = a->vec[j] * x4->vec[j] + c->vec[j];
x5->vec[j] = a->vec[j] * x5->vec[j] + c->vec[j];
x6->vec[j] = a->vec[j] * x6->vec[j] + c->vec[j];
x7->vec[j] = a->vec[j] * x7->vec[j] + c->vec[j];
x8->vec[j] = a->vec[j] * x8->vec[j] + c->vec[j];
x9->vec[j] = a->vec[j] * x9->vec[j] + c->vec[j];
}
}
asm volatile( "# ax+c loop end" );
for ( j = 0; j < CABANA_PERFORMANCE_VECLENGTH; j++ )
{
x0->vec[j] = x0->vec[j] + x1->vec[j] + x2->vec[j] + x3->vec[j] +
x4->vec[j] + x5->vec[j] + x6->vec[j] + x7->vec[j] +
x8->vec[j] + x9->vec[j] + (float)n;
}
return x0;
}
TEST( cpp, simple )
{
#ifndef CABANA_PERFORMANCE_ITERATIONS
#define CABANA_PERFORMANCE_ITERATIONS 2e6
#endif
#ifndef CABANA_PERFORMANCE_SEED
#define CABANA_PERFORMANCE_SEED 76843802738543
#endif
long n = static_cast<long>( CABANA_PERFORMANCE_ITERATIONS );
long seed = CABANA_PERFORMANCE_SEED;
data *a_ = new data();
data *x_ = new data();
data *x1_ = new data();
data *x2_ = new data();
data *x3_ = new data();
data *x4_ = new data();
data *x5_ = new data();
data *x6_ = new data();
data *x7_ = new data();
data *x8_ = new data();
data *x9_ = new data();
data *c_ = new data();
long i;
unsigned short rg[3] = {static_cast<unsigned short>( seed >> 16 ),
static_cast<unsigned short>( seed >> 8 ),
static_cast<unsigned short>( seed )};
for ( i = 0; i < CABANA_PERFORMANCE_VECLENGTH; i++ )
{
a_->vec[i] = erand48( rg );
x_->vec[i] = erand48( rg );
c_->vec[i] = erand48( rg );
x1_->vec[i] = erand48( rg );
x2_->vec[i] = erand48( rg );
x3_->vec[i] = erand48( rg );
x4_->vec[i] = erand48( rg );
x5_->vec[i] = erand48( rg );
x6_->vec[i] = erand48( rg );
x7_->vec[i] = erand48( rg );
x8_->vec[i] = erand48( rg );
x9_->vec[i] = erand48( rg );
}
unsigned long long c0 = rdtscp();
x_ = axpy_10( a_, x_, x1_, x2_, x3_, x4_, x5_, x6_, x7_, x8_, x9_, c_, n );
unsigned long long c1 = rdtscp();
unsigned long long dc = c1 - c0;
double flops = 10 * 2 * CABANA_PERFORMANCE_VECLENGTH * (double)n;
printf( "Outer loop n=%lu\n", n );
printf( "Inner loop VECLENTH=%d\n", CABANA_PERFORMANCE_VECLENGTH );
printf( "%f flops\n", flops );
printf( "%llu clocks\n", dc );
double flops_clock = flops / dc;
printf( "%f flops/clock\n", flops_clock );
for ( i = 0; i < CABANA_PERFORMANCE_VECLENGTH; i++ )
{
printf( "x_[%ld] = %f\n", i, x_->vec[i] );
}
delete a_;
delete x_;
delete c_;
delete x1_;
delete x2_;
delete x3_;
delete x4_;
delete x5_;
delete x6_;
delete x7_;
delete x8_;
delete x9_;
bool acceptable_fraction = false;
double expected_flops_clock = CABANA_PERFORMANCE_EXPECTED_FLOPS;
printf( "Expected %f \n", expected_flops_clock );
printf( "(with margin %f )\n",
expected_flops_clock * CABANA_PERFORMANCE_ERROR_MARGIN );
if ( flops_clock > expected_flops_clock * CABANA_PERFORMANCE_ERROR_MARGIN )
{
acceptable_fraction = true;
}
EXPECT_TRUE( acceptable_fraction );
}
| 29.493506 | 79 | 0.607368 | [
"model"
] |
7bd4a99acb0b8746284b22d4d6928a373aea9359 | 3,362 | cpp | C++ | proto/pkg_ptr.cpp | stdbio/FastBinaryEncoding | 260bae4b5c61934ef2a99ec1f51c84ea0d9c9e62 | [
"MIT"
] | null | null | null | proto/pkg_ptr.cpp | stdbio/FastBinaryEncoding | 260bae4b5c61934ef2a99ec1f51c84ea0d9c9e62 | [
"MIT"
] | 2 | 2021-12-22T09:56:18.000Z | 2022-01-10T13:35:09.000Z | proto/pkg_ptr.cpp | stdbio/FastBinaryEncoding | 260bae4b5c61934ef2a99ec1f51c84ea0d9c9e62 | [
"MIT"
] | null | null | null | // Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: pkg.fbe
// Version: 1.7.0.0
#include "pkg_ptr.h"
namespace pkg {
Info::Info()
: info()
, sex()
, flag()
, extra()
{}
Info::Info(const std::string& arg_info, ::osa::Sex&& arg_sex, ::osa::MyFLags&& arg_flag, ::osa::Extra&& arg_extra)
: info(arg_info)
, sex(std::move(arg_sex))
, flag(std::move(arg_flag))
, extra(std::move(arg_extra))
{}
Info::Info(Info&& other) noexcept
: info(std::move(other.info))
, sex(std::move(other.sex))
, flag(std::move(other.flag))
, extra(std::move(other.extra))
{}
Info::~Info()
{
}
bool Info::operator==([[maybe_unused]] const Info& other) const noexcept
{
return (
true
);
}
bool Info::operator<([[maybe_unused]] const Info& other) const noexcept
{
return false;
}
Info& Info::operator=(Info&& other) noexcept
{
if (this != &other)
{
info = std::move(other.info);
sex = std::move(other.sex);
flag = std::move(other.flag);
extra = std::move(other.extra);
}
return *this;
}
void Info::swap(Info& other) noexcept
{
using std::swap;
swap(info, other.info);
swap(sex, other.sex);
swap(flag, other.flag);
swap(extra, other.extra);
}
std::ostream& operator<<(std::ostream& stream, const Info& value)
{
stream << "Info(";
stream << "info="; stream << "\"" << value.info << "\"";
stream << ",sex="; stream << value.sex;
stream << ",flag="; stream << value.flag;
stream << ",extra="; stream << value.extra;
stream << ")";
return stream;
}
Detail::Detail()
: extrav()
, extram()
{}
Detail::Detail(std::vector<::osa::Extra> arg_extrav, std::map<int32_t, ::osa::Extra> arg_extram)
: extrav(std::move(arg_extrav))
, extram(std::move(arg_extram))
{}
Detail::Detail(Detail&& other) noexcept
: extrav(std::move(other.extrav))
, extram(std::move(other.extram))
{}
Detail::~Detail()
{
}
bool Detail::operator==([[maybe_unused]] const Detail& other) const noexcept
{
return (
true
);
}
bool Detail::operator<([[maybe_unused]] const Detail& other) const noexcept
{
return false;
}
Detail& Detail::operator=(Detail&& other) noexcept
{
if (this != &other)
{
extrav = std::move(other.extrav);
extram = std::move(other.extram);
}
return *this;
}
void Detail::swap(Detail& other) noexcept
{
using std::swap;
swap(extrav, other.extrav);
swap(extram, other.extram);
}
std::ostream& operator<<(std::ostream& stream, const Detail& value)
{
stream << "Detail(";
{
bool first = true;
stream << "extrav=[" << value.extrav.size() << "][";
for (const auto& it : value.extrav)
{
stream << std::string(first ? "" : ",") << it;
first = false;
}
stream << "]";
}
{
bool first = true;
stream << ",extram=[" << value.extram.size()<< "]<{";
for (const auto& it : value.extram)
{
stream << std::string(first ? "" : ",") << it.first;
stream << "->";
stream << it.second;
first = false;
}
stream << "}>";
}
stream << ")";
return stream;
}
} // namespace pkg
| 21.414013 | 114 | 0.558299 | [
"vector"
] |
7bda4fec74899b86015872d654a3b24d0a386ead | 603 | cpp | C++ | project/OFEC_sc2/instance/problem/continuous/multi_objective/ZDT/ZDT6.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/problem/continuous/multi_objective/ZDT/ZDT6.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/problem/continuous/multi_objective/ZDT/ZDT6.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | #include "ZDT6.h"
namespace OFEC {
ZDT6::ZDT6(param_map & v) : ZDT6(v.at("problem name"), v.at("number of variables")) { //param_numDim = 10 is suggested
}
ZDT6::ZDT6(const std::string & name, size_t size_var) : problem(name, size_var, 2), ZDT(name, size_var) {
}
EvalTag ZDT6::evaluateObjective(Real *x, std::vector<Real> &obj) {
Real g = 0;
for (size_t n = 1; n<m_num_vars; n++)
g = g + x[n];
g = pow(g / (m_num_vars - 1), 0.25);
g = 1 + 9 * g;
obj[0] = 1 - exp(-4 * x[0])*pow(sin(6 * OFEC_PI*x[0]), 6);
obj[1] = g*(1 - pow(obj[0] / g, 2));
return EvalTag::Normal;
}
}
| 27.409091 | 120 | 0.577114 | [
"vector"
] |
7be17d16d0274ed1f2cd03bc17da9e4b6063c144 | 9,167 | cpp | C++ | bxt.cpp | Eddio0141/bxt-frame-bulk-calculator | d900e480fc842020426ad142a611cb644ea4aa7c | [
"MIT"
] | null | null | null | bxt.cpp | Eddio0141/bxt-frame-bulk-calculator | d900e480fc842020426ad142a611cb644ea4aa7c | [
"MIT"
] | null | null | null | bxt.cpp | Eddio0141/bxt-frame-bulk-calculator | d900e480fc842020426ad142a611cb644ea4aa7c | [
"MIT"
] | null | null | null | #include "bxt.h"
namespace bxt {
namespace commands {
namespace headerSection {
// only accept version 1 format
const std::string version{ "version 1" };
const std::string seed{ "seed %m %m" };
const std::string demo{ "demo" };
const std::string frameTime{ "frametime0ms %N" };
const std::string hlstrafeVersion{ "hlstrafe_version %m" };
}
namespace specialSection {
const std::string frames{ "frames" };
const std::string strafing{ "strafing %a" };
const std::string targetYaw{ "target_yaw %a" };
const std::string lgagstminspeed{ "lgagstminspeed %N" };
const std::string reset{ "reset %m" };
const std::string seed{ "seed %m" };
const std::string changeYaw{ "change yaw to %N over %N s" };
const std::string changePitch{ "change pitch to %N over %N s" };
const std::string changeTargetYaw{ "change target_yaw to %N over %N s" };
const std::string save{ "save %a" };
const std::string buttons{ "buttons %n %n %n %n" };
}
}
namespace frameBulk {
const char Separator{ '|' };
const char NoEntry{ '-' };
struct Section {
std::string content;
bool allowCaps;
};
std::vector<std::vector<Section>> FrameBulkContent = {
// auto section
{
{ "s", false },
{ "%n", false },
{ "%n", false },
{ "l", true },
{ "j", false },
{ "d", true },
{ "b", false },
{ "c", true },
{ "g", false },
{ "w", false },
},
// manual movement input
{
{ "f", false },
{ "l", false },
{ "r", false },
{ "b", false },
{ "u", false },
{ "d", false }
},
// manual control
{
{ "j", false },
{ "d", false },
{ "u", false },
{ "1", false },
{ "2", false },
{ "r", false }
}
};
namespace miscPatterns {
const std::string FrameTime{ "%N" };
const std::string Yaw{ "%N" };
const std::string Pitch{ "%N" };
const std::string Frames{ "%m" };
}
}
const std::vector<const std::string*> validCommands = {
&commands::headerSection::version,
&commands::headerSection::seed,
&commands::headerSection::demo,
&commands::headerSection::frameTime,
&commands::headerSection::hlstrafeVersion,
&commands::specialSection::frames,
&commands::specialSection::strafing,
&commands::specialSection::targetYaw,
&commands::specialSection::lgagstminspeed,
&commands::specialSection::reset,
&commands::specialSection::seed,
&commands::specialSection::changeYaw,
&commands::specialSection::changePitch,
&commands::specialSection::save,
&commands::specialSection::buttons
};
bool IsItAFrameBulk(std::string input) {
// check seperator occurances
std::vector<uint64_t> seperatorOccurances{ };
uint64_t pos{ input.find(frameBulk::Separator, 0) };
while (pos != std::string::npos) {
seperatorOccurances.push_back(pos);
pos = input.find(frameBulk::Separator, pos + 1);
}
if (seperatorOccurances.size() < 6) {
return false;
}
// go through sections (excluding frame time, yaw, pitch, number of frames, and commands)
uint64_t inputProcIndex{ 0 };
for (uint64_t seperationIndex = 0; seperationIndex < 3; seperationIndex++)
{
for (uint64_t i = 0; i < frameBulk::FrameBulkContent.at(seperationIndex).size(); i++)
{
frameBulk::Section* currentSection = &frameBulk::FrameBulkContent.at(seperationIndex).at(i);
char inputProcessing{ input.at(inputProcIndex) };
inputProcIndex++;
if (currentSection->allowCaps) {
inputProcessing = std::tolower(inputProcessing);
}
if ((!patternFinder::DoesItMatch(std::string{ inputProcessing }, currentSection->content)) && (inputProcessing != frameBulk::NoEntry)) {
return false;
}
}
if (input.at(inputProcIndex) != frameBulk::Separator) {
return false;
}
inputProcIndex++;
}
// hacky checks from here ew
// frame time
if (!patternFinder::DoesItMatch(input.substr(inputProcIndex, seperatorOccurances.at(3) - inputProcIndex),
frameBulk::miscPatterns::FrameTime)) {
return false;
}
inputProcIndex = seperatorOccurances.at(3);
if (input.at(inputProcIndex) != frameBulk::Separator) {
return false;
}
inputProcIndex++;
// yaw
if ((!patternFinder::DoesItMatch(input.substr(inputProcIndex, seperatorOccurances.at(4) - inputProcIndex),
frameBulk::miscPatterns::Yaw)) && (input.substr(inputProcIndex, seperatorOccurances.at(4) - inputProcIndex).at(0) != frameBulk::NoEntry)) {
// check for seperate thing
if (input.at(2) != '4' && !patternFinder::DoesItMatch(input.substr(inputProcIndex, seperatorOccurances.at(4) - inputProcIndex), "%N %N")) {
return false;
}
}
inputProcIndex = seperatorOccurances.at(4);
if (input.at(inputProcIndex) != frameBulk::Separator) {
return false;
}
inputProcIndex++;
// pitch
if ((!patternFinder::DoesItMatch(input.substr(inputProcIndex, seperatorOccurances.at(5) - inputProcIndex),
frameBulk::miscPatterns::Pitch)) && (input.substr(inputProcIndex, seperatorOccurances.at(5) - inputProcIndex).at(0) != frameBulk::NoEntry)) {
return false;
}
inputProcIndex = seperatorOccurances.at(5);
if (input.at(inputProcIndex) != frameBulk::Separator) {
return false;
}
inputProcIndex++;
// frames
if (seperatorOccurances.size() == 7) {
// includes commands
if (!patternFinder::DoesItMatch(input.substr(inputProcIndex, seperatorOccurances.at(6) - inputProcIndex),
frameBulk::miscPatterns::Frames)) {
return false;
}
inputProcIndex = seperatorOccurances.at(6);
if (input.at(inputProcIndex) != frameBulk::Separator) {
return false;
}
// check if value is at least 1
if (std::stoi(input.substr(seperatorOccurances.at(5) + 1, seperatorOccurances.at(6) - seperatorOccurances.at(5) + 1)) < 1) {
return false;
}
}
else {
// no commands
if (!patternFinder::DoesItMatch(input.substr(inputProcIndex, input.size() - inputProcIndex),
frameBulk::miscPatterns::Frames)) {
return false;
}
// check if value is at least 1
if (std::stoi(input.substr(inputProcIndex, input.size() - inputProcIndex)) < 1) {
return false;
}
}
return true;
}
bool CheckIfValidLine(std::string input) {
if (input.size() < 1) {
return true;
}
// remove empty characters
while (input.at(0) == ' ') {
input.erase(0, 1);
}
// is it empty
if (input == "") {
return true;
}
// is it a comment
if (patternFinder::DoesItMatch(input, "//%a")) {
return true;
}
// search in commands
for (const std::string* command : validCommands)
{
if (patternFinder::DoesItMatch(input, *command)) {
return true;
}
}
// search if frame bulk
return IsItAFrameBulk(input);
}
long double ReturnFrameBulkTimeInSeconds(std::string input) {
// remove empty characters
if (input.size() < 1) {
return 0;
}
while (input.at(0) == ' ') {
input.erase(0, 1);
}
// check if frame bulk
if (!IsItAFrameBulk(input)) {
return 0;
}
// checking seperator occurances
std::vector<uint64_t> seperatorOccurances{ };
uint64_t pos{ input.find(frameBulk::Separator, 0) };
while (pos != std::string::npos) {
seperatorOccurances.push_back(pos);
pos = input.find(frameBulk::Separator, pos + 1);
}
long double frameTime{ std::stod(input.substr(seperatorOccurances.at(2) + 1, seperatorOccurances.at(3) - seperatorOccurances.at(2))) };
long double frames;
if (seperatorOccurances.size() == 7) {
// with command
frames = std::stod(input.substr(seperatorOccurances.at(5) + 1, seperatorOccurances.at(6) - seperatorOccurances.at(5)));
}
else {
// without command
frames = std::stod(input.substr(seperatorOccurances.at(5) + 1, input.size() - seperatorOccurances.at(5)));
}
return frameTime * frames;
}
std::pair<long double, uint64_t> ReturnFrameBulkFrameRateAndNumOfFrames(std::string input) {
// remove empty characters
if (input.size() < 1) {
return { };
}
while (input.at(0) == ' ') {
input.erase(0, 1);
}
// check if its a frame bulk
if (!IsItAFrameBulk(input)) {
return { };
}
// check seperator occurances
std::vector<uint64_t> seperatorOccurances{ };
uint64_t pos{ input.find(frameBulk::Separator, 0) };
while (pos != std::string::npos) {
seperatorOccurances.push_back(pos);
pos = input.find(frameBulk::Separator, pos + 1);
}
long double frameTime{ std::stod(input.substr(seperatorOccurances.at(2) + 1, seperatorOccurances.at(3) - seperatorOccurances.at(2))) };
long double frames;
if (seperatorOccurances.size() == 7) {
// with command
frames = std::stod(input.substr(seperatorOccurances.at(5) + 1, seperatorOccurances.at(6) - seperatorOccurances.at(5)));
}
else {
// without command
frames = std::stod(input.substr(seperatorOccurances.at(5) + 1, input.size() - seperatorOccurances.at(5)));
}
return { frameTime, frames };
}
} | 28.736677 | 145 | 0.628014 | [
"vector"
] |
7bf073b4b1a17271b1765e569e260949f289a5b1 | 6,193 | cpp | C++ | cmds/screencap/screencap.cpp | Keneral/aframeworksbase | e1212ca12f63686efee5c32582b2878c9ae71ead | [
"Unlicense"
] | null | null | null | cmds/screencap/screencap.cpp | Keneral/aframeworksbase | e1212ca12f63686efee5c32582b2878c9ae71ead | [
"Unlicense"
] | null | null | null | cmds/screencap/screencap.cpp | Keneral/aframeworksbase | e1212ca12f63686efee5c32582b2878c9ae71ead | [
"Unlicense"
] | null | null | null | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <binder/ProcessState.h>
#include <gui/SurfaceComposerClient.h>
#include <gui/ISurfaceComposer.h>
#include <ui/DisplayInfo.h>
#include <ui/PixelFormat.h>
// TODO: Fix Skia.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#include <SkImageEncoder.h>
#include <SkData.h>
#pragma GCC diagnostic pop
using namespace android;
static uint32_t DEFAULT_DISPLAY_ID = ISurfaceComposer::eDisplayIdMain;
static void usage(const char* pname)
{
fprintf(stderr,
"usage: %s [-hp] [-d display-id] [FILENAME]\n"
" -h: this message\n"
" -p: save the file as a png.\n"
" -d: specify the display id to capture, default %d.\n"
"If FILENAME ends with .png it will be saved as a png.\n"
"If FILENAME is not given, the results will be printed to stdout.\n",
pname, DEFAULT_DISPLAY_ID
);
}
static SkColorType flinger2skia(PixelFormat f)
{
switch (f) {
case PIXEL_FORMAT_RGB_565:
return kRGB_565_SkColorType;
default:
return kN32_SkColorType;
}
}
static status_t notifyMediaScanner(const char* fileName) {
String8 cmd("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file://");
String8 fileUrl("\"");
fileUrl.append(fileName);
fileUrl.append("\"");
cmd.append(fileName);
cmd.append(" > /dev/null");
int result = system(cmd.string());
if (result < 0) {
fprintf(stderr, "Unable to broadcast intent for media scanner.\n");
return UNKNOWN_ERROR;
}
return NO_ERROR;
}
int main(int argc, char** argv)
{
ProcessState::self()->startThreadPool();
const char* pname = argv[0];
bool png = false;
int32_t displayId = DEFAULT_DISPLAY_ID;
int c;
while ((c = getopt(argc, argv, "phd:")) != -1) {
switch (c) {
case 'p':
png = true;
break;
case 'd':
displayId = atoi(optarg);
break;
case '?':
case 'h':
usage(pname);
return 1;
}
}
argc -= optind;
argv += optind;
int fd = -1;
const char* fn = NULL;
if (argc == 0) {
fd = dup(STDOUT_FILENO);
} else if (argc == 1) {
fn = argv[0];
fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (fd == -1) {
fprintf(stderr, "Error opening file: %s (%s)\n", fn, strerror(errno));
return 1;
}
const int len = strlen(fn);
if (len >= 4 && 0 == strcmp(fn+len-4, ".png")) {
png = true;
}
}
if (fd == -1) {
usage(pname);
return 1;
}
void const* mapbase = MAP_FAILED;
ssize_t mapsize = -1;
void const* base = NULL;
uint32_t w, s, h, f;
size_t size = 0;
// Maps orientations from DisplayInfo to ISurfaceComposer
static const uint32_t ORIENTATION_MAP[] = {
ISurfaceComposer::eRotateNone, // 0 == DISPLAY_ORIENTATION_0
ISurfaceComposer::eRotate270, // 1 == DISPLAY_ORIENTATION_90
ISurfaceComposer::eRotate180, // 2 == DISPLAY_ORIENTATION_180
ISurfaceComposer::eRotate90, // 3 == DISPLAY_ORIENTATION_270
};
ScreenshotClient screenshot;
sp<IBinder> display = SurfaceComposerClient::getBuiltInDisplay(displayId);
if (display == NULL) {
fprintf(stderr, "Unable to get handle for display %d\n", displayId);
return 1;
}
Vector<DisplayInfo> configs;
SurfaceComposerClient::getDisplayConfigs(display, &configs);
int activeConfig = SurfaceComposerClient::getActiveConfig(display);
if (static_cast<size_t>(activeConfig) >= configs.size()) {
fprintf(stderr, "Active config %d not inside configs (size %zu)\n",
activeConfig, configs.size());
return 1;
}
uint8_t displayOrientation = configs[activeConfig].orientation;
uint32_t captureOrientation = ORIENTATION_MAP[displayOrientation];
status_t result = screenshot.update(display, Rect(), 0, 0, 0, -1U,
false, captureOrientation);
if (result == NO_ERROR) {
base = screenshot.getPixels();
w = screenshot.getWidth();
h = screenshot.getHeight();
s = screenshot.getStride();
f = screenshot.getFormat();
size = screenshot.getSize();
}
if (base != NULL) {
if (png) {
const SkImageInfo info = SkImageInfo::Make(w, h, flinger2skia(f),
kPremul_SkAlphaType);
SkAutoTUnref<SkData> data(SkImageEncoder::EncodeData(info, base, s*bytesPerPixel(f),
SkImageEncoder::kPNG_Type, SkImageEncoder::kDefaultQuality));
if (data.get()) {
write(fd, data->data(), data->size());
}
if (fn != NULL) {
notifyMediaScanner(fn);
}
} else {
write(fd, &w, 4);
write(fd, &h, 4);
write(fd, &f, 4);
size_t Bpp = bytesPerPixel(f);
for (size_t y=0 ; y<h ; y++) {
write(fd, base, w*Bpp);
base = (void *)((char *)base + s*Bpp);
}
}
}
close(fd);
if (mapbase != MAP_FAILED) {
munmap((void *)mapbase, mapsize);
}
return 0;
}
| 30.209756 | 96 | 0.584854 | [
"vector"
] |
7bf186ae2d3b5d5c29e6069a57ab9d620cddd0c7 | 29,196 | cpp | C++ | tests/integration/olp-cpp-sdk-dataservice-write/StreamLayerClientTest.cpp | forslund/here-data-sdk-cpp | 6226950ef2543281e027b2a458fcff0c71e2f0b2 | [
"Apache-2.0"
] | 21 | 2019-07-03T07:26:52.000Z | 2019-09-04T08:35:07.000Z | tests/integration/olp-cpp-sdk-dataservice-write/StreamLayerClientTest.cpp | forslund/here-data-sdk-cpp | 6226950ef2543281e027b2a458fcff0c71e2f0b2 | [
"Apache-2.0"
] | 639 | 2019-09-13T17:14:24.000Z | 2020-05-13T11:49:14.000Z | tests/integration/olp-cpp-sdk-dataservice-write/StreamLayerClientTest.cpp | forslund/here-data-sdk-cpp | 6226950ef2543281e027b2a458fcff0c71e2f0b2 | [
"Apache-2.0"
] | 21 | 2020-05-14T15:32:28.000Z | 2022-03-15T13:52:33.000Z | /*
* Copyright (C) 2019-2020 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#include <gmock/gmock.h>
#include <matchers/NetworkUrlMatchers.h>
#include <mocks/NetworkMock.h>
#include <olp/core/client/ApiError.h>
#include <olp/core/client/HRN.h>
#include <olp/core/client/HttpResponse.h>
#include <olp/core/client/OlpClient.h>
#include <olp/core/client/OlpClientSettings.h>
#include <olp/core/client/OlpClientSettingsFactory.h>
#include <olp/core/http/HttpStatusCode.h>
#include <olp/dataservice/write/StreamLayerClient.h>
#include <olp/dataservice/write/model/PublishDataRequest.h>
#include <olp/dataservice/write/model/PublishSdiiRequest.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "HttpResponses.h"
namespace {
namespace write = olp::dataservice::write;
namespace model = olp::dataservice::write::model;
namespace http = olp::http;
using testing::_;
const std::string kBillingTag = "OlpCppSdkTest";
constexpr int64_t kTwentyMib = 20971520; // 20 MiB
// Binary SDII Message List protobuf data. See the OLP SDII data specification
// and schema documents to learn about the format. This char array was created
// using the `xxd -i` unix command on the encoded data file. The data was
// encoded using the `protoc` command line tool which is part of a standard
// protobuf system installation.
constexpr unsigned char kSDIITestData[] = {
0x0a, 0x67, 0x0a, 0x34, 0x0a, 0x05, 0x33, 0x2e, 0x33, 0x2e, 0x32, 0x12,
0x05, 0x53, 0x49, 0x4d, 0x50, 0x4c, 0x4a, 0x24, 0x31, 0x36, 0x38, 0x64,
0x38, 0x33, 0x61, 0x65, 0x2d, 0x31, 0x39, 0x63, 0x66, 0x2d, 0x34, 0x62,
0x38, 0x61, 0x2d, 0x39, 0x30, 0x37, 0x36, 0x2d, 0x66, 0x30, 0x37, 0x38,
0x35, 0x31, 0x61, 0x35, 0x61, 0x35, 0x31, 0x30, 0x12, 0x2f, 0x0a, 0x2d,
0x08, 0xb4, 0xda, 0xbd, 0x92, 0xd0, 0x2c, 0x10, 0x01, 0x21, 0xa6, 0x7b,
0x42, 0x1b, 0x25, 0xec, 0x27, 0x40, 0x29, 0x68, 0xf2, 0x83, 0xa9, 0x1c,
0x14, 0x48, 0x40, 0x31, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x69, 0xf8, 0xc0,
0x49, 0xe5, 0x35, 0x94, 0xd7, 0x50, 0x5e, 0x32, 0x40};
constexpr unsigned int kSDIITestDataLength = 105;
void PublishDataSuccessAssertions(
const olp::client::ApiResponse<model::ResponseOkSingle,
olp::client::ApiError>& result) {
EXPECT_TRUE(result.IsSuccessful());
EXPECT_FALSE(result.GetResult().GetTraceID().empty());
}
void PublishSdiiSuccessAssertions(
const olp::client::ApiResponse<model::ResponseOk, olp::client::ApiError>&
result) {
EXPECT_TRUE(result.IsSuccessful());
EXPECT_FALSE(result.GetResult().GetTraceID().GetParentID().empty());
ASSERT_FALSE(result.GetResult().GetTraceID().GetGeneratedIDs().empty());
EXPECT_FALSE(result.GetResult().GetTraceID().GetGeneratedIDs().at(0).empty());
}
template <typename T>
void PublishCancelledAssertions(
const olp::client::ApiResponse<T, olp::client::ApiError>& result) {
EXPECT_FALSE(result.IsSuccessful());
EXPECT_EQ(static_cast<int>(olp::http::ErrorCode::CANCELLED_ERROR),
result.GetError().GetHttpStatusCode());
EXPECT_EQ(olp::client::ErrorCode::Cancelled,
result.GetError().GetErrorCode());
EXPECT_EQ("Cancelled", result.GetError().GetMessage());
}
template <typename T>
void PublishFailureAssertions(
const olp::client::ApiResponse<T, olp::client::ApiError>& result) {
EXPECT_FALSE(result.IsSuccessful());
EXPECT_NE(result.GetError().GetHttpStatusCode(), http::HttpStatusCode::OK);
// EXPECT_FALSE(result.GetError().GetMessage().empty());
}
class StreamLayerClientTest : public ::testing::Test {
protected:
StreamLayerClientTest() {
sdii_data_ = std::make_shared<std::vector<unsigned char>>(
kSDIITestData, kSDIITestData + kSDIITestDataLength);
}
~StreamLayerClientTest() = default;
void SetUp() override {
ASSERT_NO_FATAL_FAILURE(client_ = CreateStreamLayerClient());
data_ = GenerateData();
}
void TearDown() override {
testing::Mock::VerifyAndClearExpectations(network_.get());
data_.reset();
client_.reset();
}
std::string GetTestCatalog() {
return "hrn:here:data::olp-here-test:olp-cpp-sdk-ingestion-test-catalog";
}
std::string GetTestLayer() {
return "olp-cpp-sdk-ingestion-test-stream-layer";
}
std::string GetTestLayer2() {
return "olp-cpp-sdk-ingestion-test-stream-layer-2";
}
std::string GetTestLayerSdii() {
return "olp-cpp-sdk-ingestion-test-stream-layer-sdii";
}
void QueueMultipleEvents(int num_events) {
for (int i = 0; i < num_events; i++) {
data_->push_back(' ');
data_->push_back(i);
auto error = client_->Queue(
model::PublishDataRequest().WithData(data_).WithLayerId(
GetTestLayer()));
ASSERT_FALSE(error) << error.get();
}
}
virtual std::shared_ptr<write::StreamLayerClient> CreateStreamLayerClient() {
olp::client::OlpClientSettings client_settings;
network_ = std::make_shared<NetworkMock>();
client_settings.network_request_handler = network_;
client_settings.task_scheduler =
olp::client::OlpClientSettingsFactory::CreateDefaultTaskScheduler();
SetUpCommonNetworkMockCalls(*network_);
return std::make_shared<write::StreamLayerClient>(
olp::client::HRN{GetTestCatalog()}, write::StreamLayerClientSettings{},
client_settings);
}
void SetUpCommonNetworkMockCalls(NetworkMock& network) {
// Catch unexpected calls and fail immediatley
ON_CALL(network, Send(_, _, _, _, _))
.WillByDefault(testing::DoAll(
ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(-1), ""),
[](olp::http::NetworkRequest /*request*/,
olp::http::Network::Payload /*payload*/,
olp::http::Network::Callback /*callback*/,
olp::http::Network::HeaderCallback /*header_callback*/,
olp::http::Network::DataCallback /*data_callback*/) {
auto fail_helper = []() { FAIL(); };
fail_helper();
return olp::http::SendOutcome(5);
}));
ON_CALL(network, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_LOOKUP_INGEST));
ON_CALL(network, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_LOOKUP_CONFIG));
ON_CALL(network, Send(IsGetRequest(URL_LOOKUP_PUBLISH_V2), _, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_LOOKUP_PUBLISH_V2));
ON_CALL(network, Send(IsGetRequest(URL_LOOKUP_BLOB), _, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_LOOKUP_BLOB));
ON_CALL(network,
Send(testing::AnyOf(IsGetRequest(URL_GET_CATALOG),
IsGetRequest(URL_GET_CATALOG_BILLING_TAG)),
_, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_GET_CATALOG));
ON_CALL(network,
Send(testing::AnyOf(IsPostRequest(URL_INGEST_DATA),
IsPostRequest(URL_INGEST_DATA_BILLING_TAG)),
_, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_INGEST_DATA));
ON_CALL(network, Send(IsPostRequest(URL_INGEST_DATA_LAYER_2), _, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_INGEST_DATA_LAYER_2));
ON_CALL(network, Send(IsPostRequest(URL_INIT_PUBLICATION), _, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_INIT_PUBLICATION));
ON_CALL(network, Send(IsPutRequestPrefix(URL_PUT_BLOB_PREFIX), _, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
""));
ON_CALL(network, Send(testing::AnyOf(IsPostRequest(URL_UPLOAD_PARTITIONS),
IsPutRequest(URL_SUBMIT_PUBLICATION)),
_, _, _, _))
.WillByDefault(
ReturnHttpResponse(olp::http::NetworkResponse().WithStatus(
http::HttpStatusCode::NO_CONTENT),
""));
ON_CALL(network,
Send(testing::AnyOf(IsPostRequest(URL_INGEST_SDII),
IsPostRequest(URL_INGEST_SDII_BILLING_TAG)),
_, _, _, _))
.WillByDefault(ReturnHttpResponse(
olp::http::NetworkResponse().WithStatus(http::HttpStatusCode::OK),
HTTP_RESPONSE_INGEST_SDII));
}
private:
std::shared_ptr<std::vector<unsigned char>> GenerateData() {
std::string test_suite_name(testing::UnitTest::GetInstance()
->current_test_info()
->test_suite_name());
std::string test_name(
testing::UnitTest::GetInstance()->current_test_info()->name());
std::string data_string(test_suite_name + " " + test_name + " Payload");
return std::make_shared<std::vector<unsigned char>>(data_string.begin(),
data_string.end());
}
protected:
std::shared_ptr<NetworkMock> network_;
std::shared_ptr<write::StreamLayerClient> client_;
std::shared_ptr<std::vector<unsigned char>> data_;
std::shared_ptr<std::vector<unsigned char>> sdii_data_;
};
using testing::_;
TEST_F(StreamLayerClientTest, PublishData) {
{
testing::InSequence dummy;
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_GET_CATALOG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsPostRequest(URL_INGEST_DATA), _, _, _, _))
.Times(1);
}
auto response =
client_
->PublishData(model::PublishDataRequest().WithData(data_).WithLayerId(
GetTestLayer()))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishDataSuccessAssertions(response));
}
TEST_F(StreamLayerClientTest, PublishDataGreaterThanTwentyMib) {
{
testing::InSequence dummy;
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_GET_CATALOG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsGetRequest(URL_LOOKUP_PUBLISH_V2), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_BLOB), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsPostRequest(URL_INIT_PUBLICATION), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsPutRequestPrefix(URL_PUT_BLOB_PREFIX), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsPostRequest(URL_UPLOAD_PARTITIONS), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsPutRequest(URL_SUBMIT_PUBLICATION), _, _, _, _))
.Times(1);
}
auto large_data =
std::make_shared<std::vector<unsigned char>>(kTwentyMib + 1, 'z');
auto response = client_
->PublishData(model::PublishDataRequest()
.WithData(large_data)
.WithLayerId(GetTestLayer()))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishDataSuccessAssertions(response));
}
TEST_F(StreamLayerClientTest, PublishDataCancel) {
using PromisePtr = std::shared_ptr<std::promise<void>>;
auto pause_for_cancel = std::make_shared<std::promise<void>>();
auto setup_network_expectations_on_cancel =
[](std::shared_ptr<NetworkMock> network)
-> std::pair<PromisePtr, PromisePtr> {
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
std::tie(request_id, send_mock, cancel_mock) = GenerateNetworkMockActions(
wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK, HTTP_RESPONSE_LOOKUP_INGEST});
{
EXPECT_CALL(*network, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network, Send(IsGetRequest(URL_GET_CATALOG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1)
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network, Cancel(request_id))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
}
return {wait_for_cancel, pause_for_cancel};
};
auto publish_request =
model::PublishDataRequest().WithData(data_).WithLayerId(GetTestLayer());
{
SCOPED_TRACE("Cancel PublishData via cancellation token");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishData(publish_request);
wait_for_cancel->get_future().get();
cancel_future.GetCancellationToken().Cancel();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
{
SCOPED_TRACE("Cancel PublishData via CancelPendingRequests");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishData(publish_request);
wait_for_cancel->get_future().get();
client->CancelPendingRequests();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
{
SCOPED_TRACE("Cancel PublishData on client being destroyed");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishData(publish_request);
wait_for_cancel->get_future().get();
client.reset();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
}
TEST_F(StreamLayerClientTest, PublishDataGreaterThanTwentyMibCancel) {
using PromisePtr = std::shared_ptr<std::promise<void>>;
auto pause_for_cancel = std::make_shared<std::promise<void>>();
auto setup_network_expectations_on_cancel =
[](std::shared_ptr<NetworkMock> network)
-> std::pair<PromisePtr, PromisePtr> {
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
std::tie(request_id, send_mock, cancel_mock) = GenerateNetworkMockActions(
wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK, HTTP_RESPONSE_LOOKUP_CONFIG});
{
testing::InSequence dummy;
EXPECT_CALL(*network, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1)
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network, Cancel(request_id))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
}
return {wait_for_cancel, pause_for_cancel};
};
auto large_data =
std::make_shared<std::vector<unsigned char>>(kTwentyMib + 1, 'z');
auto publish_request = model::PublishDataRequest()
.WithData(large_data)
.WithLayerId(GetTestLayer());
{
SCOPED_TRACE(
"Cancel PublishDataGreaterThanTwentyMib via cancellation token");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishData(publish_request);
wait_for_cancel->get_future().get();
cancel_future.GetCancellationToken().Cancel();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
{
SCOPED_TRACE(
"Cancel PublishDataGreaterThanTwentyMib via CancelPendingRequests");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishData(publish_request);
wait_for_cancel->get_future().get();
client->CancelPendingRequests();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
{
SCOPED_TRACE("Cancel PublishDataGreaterThanTwentyMib on client destroy");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishData(publish_request);
wait_for_cancel->get_future().get();
client.reset();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
}
TEST_F(StreamLayerClientTest, PublishDataCancelLongDelay) {
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
std::tie(request_id, send_mock, cancel_mock) = GenerateNetworkMockActions(
wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK, HTTP_RESPONSE_GET_CATALOG});
{
testing::InSequence dummy;
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_GET_CATALOG), _, _, _, _))
.Times(1)
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network_, Cancel(request_id))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
}
auto promise = client_->PublishData(
model::PublishDataRequest().WithData(data_).WithLayerId(GetTestLayer()));
wait_for_cancel->get_future().get();
promise.GetCancellationToken().Cancel();
pause_for_cancel->set_value();
auto response = promise.GetFuture().get();
ASSERT_NO_FATAL_FAILURE(PublishFailureAssertions(response));
}
TEST_F(StreamLayerClientTest, BillingTag) {
{
testing::InSequence dummy;
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsGetRequest(URL_GET_CATALOG_BILLING_TAG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsPostRequest(URL_INGEST_DATA_BILLING_TAG), _, _, _, _))
.Times(1);
}
auto response = client_
->PublishData(model::PublishDataRequest()
.WithData(data_)
.WithLayerId(GetTestLayer())
.WithBillingTag(kBillingTag))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishDataSuccessAssertions(response));
}
TEST_F(StreamLayerClientTest, ConcurrentPublishSameIngestApi) {
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_GET_CATALOG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsPostRequest(URL_INGEST_DATA), _, _, _, _))
.Times(5);
auto publish_data = [&]() {
auto response =
client_
->PublishData(
model::PublishDataRequest().WithData(data_).WithLayerId(
GetTestLayer()))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishDataSuccessAssertions(response));
};
auto async1 = std::async(std::launch::async, publish_data);
auto async2 = std::async(std::launch::async, publish_data);
auto async3 = std::async(std::launch::async, publish_data);
auto async4 = std::async(std::launch::async, publish_data);
auto async5 = std::async(std::launch::async, publish_data);
async1.get();
async2.get();
async3.get();
async4.get();
async5.get();
}
TEST_F(StreamLayerClientTest, SequentialPublishDifferentLayer) {
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_CONFIG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_GET_CATALOG), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsPostRequest(URL_INGEST_DATA), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsPostRequest(URL_INGEST_DATA_LAYER_2), _, _, _, _))
.Times(1);
auto response =
client_
->PublishData(model::PublishDataRequest().WithData(data_).WithLayerId(
GetTestLayer()))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishDataSuccessAssertions(response));
response =
client_
->PublishData(model::PublishDataRequest().WithData(data_).WithLayerId(
GetTestLayer2()))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishDataSuccessAssertions(response));
}
TEST_F(StreamLayerClientTest, PublishSdii) {
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsPostRequest(URL_INGEST_SDII), _, _, _, _))
.Times(1);
auto response = client_
->PublishSdii(model::PublishSdiiRequest()
.WithSdiiMessageList(sdii_data_)
.WithLayerId(GetTestLayerSdii()))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishSdiiSuccessAssertions(response));
}
TEST_F(StreamLayerClientTest, PublishSDIIBillingTag) {
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_,
Send(IsPostRequest(URL_INGEST_SDII_BILLING_TAG), _, _, _, _))
.Times(1);
auto response = client_
->PublishSdii(model::PublishSdiiRequest()
.WithSdiiMessageList(sdii_data_)
.WithLayerId(GetTestLayerSdii())
.WithBillingTag(kBillingTag))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishSdiiSuccessAssertions(response));
}
TEST_F(StreamLayerClientTest, PublishSdiiCancel) {
using PromisePtr = std::shared_ptr<std::promise<void>>;
auto pause_for_cancel = std::make_shared<std::promise<void>>();
auto setup_network_expectations_on_cancel =
[](std::shared_ptr<NetworkMock> network)
-> std::pair<PromisePtr, PromisePtr> {
auto wait_for_cancel = std::make_shared<std::promise<void>>();
auto pause_for_cancel = std::make_shared<std::promise<void>>();
olp::http::RequestId request_id;
NetworkCallback send_mock;
CancelCallback cancel_mock;
std::tie(request_id, send_mock, cancel_mock) = GenerateNetworkMockActions(
wait_for_cancel, pause_for_cancel,
{olp::http::HttpStatusCode::OK, HTTP_RESPONSE_LOOKUP_INGEST});
EXPECT_CALL(*network, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1)
.WillOnce(testing::Invoke(std::move(send_mock)));
EXPECT_CALL(*network, Cancel(request_id))
.WillOnce(testing::Invoke(std::move(cancel_mock)));
return {wait_for_cancel, pause_for_cancel};
};
auto publish_request = model::PublishSdiiRequest()
.WithSdiiMessageList(sdii_data_)
.WithLayerId(GetTestLayerSdii());
{
SCOPED_TRACE("Cancel PublishSdii via cancellation token");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishSdii(publish_request);
wait_for_cancel->get_future().get();
cancel_future.GetCancellationToken().Cancel();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_EQ(response.GetError().GetErrorCode(),
olp::client::ErrorCode::Cancelled);
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
{
SCOPED_TRACE("Cancel PublishSdii via cancellation token");
auto client = CreateStreamLayerClient();
auto network_promises = setup_network_expectations_on_cancel(network_);
auto wait_for_cancel = network_promises.first;
auto pause_for_cancel = network_promises.second;
auto cancel_future = client->PublishSdii(publish_request);
wait_for_cancel->get_future().get();
client->CancelPendingRequests();
pause_for_cancel->set_value();
auto response = cancel_future.GetFuture().get();
EXPECT_NO_FATAL_FAILURE(PublishCancelledAssertions(response));
testing::Mock::VerifyAndClearExpectations(network_.get());
}
}
TEST_F(StreamLayerClientTest, SDIIConcurrentPublishSameIngestApi) {
EXPECT_CALL(*network_, Send(IsGetRequest(URL_LOOKUP_INGEST), _, _, _, _))
.Times(1);
EXPECT_CALL(*network_, Send(IsPostRequest(URL_INGEST_SDII), _, _, _, _))
.Times(6);
auto publish_data = [&]() {
auto response = client_
->PublishSdii(model::PublishSdiiRequest()
.WithSdiiMessageList(sdii_data_)
.WithLayerId(GetTestLayerSdii()))
.GetFuture()
.get();
ASSERT_NO_FATAL_FAILURE(PublishSdiiSuccessAssertions(response));
};
// Trigger one call prior to get cache filled else we face
// flakiness due to missing expects
publish_data();
auto async1 = std::async(std::launch::async, publish_data);
auto async2 = std::async(std::launch::async, publish_data);
auto async3 = std::async(std::launch::async, publish_data);
auto async4 = std::async(std::launch::async, publish_data);
auto async5 = std::async(std::launch::async, publish_data);
async1.get();
async2.get();
async3.get();
async4.get();
async5.get();
}
} // namespace
| 37.192357 | 80 | 0.67016 | [
"vector",
"model"
] |
7bff6268fa0847c1896a398df5af33efdf377d6e | 22,309 | cpp | C++ | src/MacMessage.cpp | gocarlos/COSE-C | 30ece3d9adf3ed56b6bcf9ae66558d62a9895560 | [
"BSD-3-Clause"
] | null | null | null | src/MacMessage.cpp | gocarlos/COSE-C | 30ece3d9adf3ed56b6bcf9ae66558d62a9895560 | [
"BSD-3-Clause"
] | null | null | null | src/MacMessage.cpp | gocarlos/COSE-C | 30ece3d9adf3ed56b6bcf9ae66558d62a9895560 | [
"BSD-3-Clause"
] | null | null | null | /** \file MacMessage.c
* Contains implementation of the functions related to HCOSE_MAC handle objects.
*/
#include <stdlib.h>
#ifndef __MBED__
#include <memory.h>
#endif
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "cose/cose.h"
#include "cose_int.h"
#include "cose/cose_configure.h"
#include "cose_crypto.h"
#if INCLUDE_MAC
COSE *MacRoot = NULL;
/*! \private
* @brief Test if a HCOSE_MAC handle is valid
*
* Internal function to test if a MAC message handle is valid.
* This will start returning invalid results and cause the code to
* crash if handles are not released before the memory that underlies them
* is deallocated. This is an issue of a block allocator is used since
* in that case it is common to allocate memory but never to de-allocate it
* and just do that in a single big block.
*
* @param h handle to be validated
* @returns result of check
*/
bool IsValidMacHandle(HCOSE_MAC h)
{
COSE_MacMessage *p = (COSE_MacMessage *)h;
return _COSE_IsInList(MacRoot, (COSE *)p);
}
HCOSE_MAC COSE_Mac_Init(COSE_INIT_FLAGS flags,
CBOR_CONTEXT_COMMA cose_errback *perr)
{
COSE_MacMessage *pobj = NULL;
CHECK_CONDITION(flags == COSE_INIT_FLAGS_NONE, COSE_ERR_INVALID_PARAMETER);
pobj = (COSE_MacMessage *)COSE_CALLOC(1, sizeof(COSE_MacMessage), context);
CHECK_CONDITION(pobj != NULL, COSE_ERR_OUT_OF_MEMORY);
if (!_COSE_Init(flags, &pobj->m_message, COSE_mac_object,
CBOR_CONTEXT_PARAM_COMMA perr)) {
goto errorReturn;
}
_COSE_InsertInList(&MacRoot, &pobj->m_message);
return (HCOSE_MAC)pobj;
errorReturn:
if (pobj != NULL) {
_COSE_Mac_Release(pobj);
COSE_FREE(pobj, context);
}
return NULL;
}
HCOSE_MAC _COSE_Mac_Init_From_Object(cn_cbor *cbor,
COSE_MacMessage *pIn,
CBOR_CONTEXT_COMMA cose_errback *perr)
{
COSE_MacMessage *pobj = pIn;
cn_cbor *pRecipients = NULL;
// cn_cbor * tmp;
cose_errback error = {COSE_ERR_NONE};
if (perr == NULL) {
perr = &error;
}
if (pobj == NULL) {
pobj =
(COSE_MacMessage *)COSE_CALLOC(1, sizeof(COSE_MacMessage), context);
}
if (pobj == NULL) {
perr->err = COSE_ERR_OUT_OF_MEMORY;
errorReturn:
if (pobj != NULL) {
_COSE_Mac_Release(pobj);
if (pIn == NULL) {
COSE_FREE(pobj, context);
}
}
return NULL;
}
if (!_COSE_Init_From_Object(
&pobj->m_message, cbor, CBOR_CONTEXT_PARAM_COMMA perr)) {
goto errorReturn;
}
pRecipients = _COSE_arrayget_int(&pobj->m_message, INDEX_MAC_RECIPIENTS);
if (pRecipients != NULL) {
CHECK_CONDITION(
pRecipients->type == CN_CBOR_ARRAY, COSE_ERR_INVALID_PARAMETER);
pRecipients = pRecipients->first_child;
while (pRecipients != NULL) {
COSE_RecipientInfo *pInfo = _COSE_Recipient_Init_From_Object(
pRecipients, CBOR_CONTEXT_PARAM_COMMA perr);
if (pInfo == NULL) {
goto errorReturn;
}
pInfo->m_recipientNext = pobj->m_recipientFirst;
pobj->m_recipientFirst = pInfo;
pRecipients = pRecipients->next;
}
}
_COSE_InsertInList(&MacRoot, &pobj->m_message);
return (HCOSE_MAC)pobj;
}
bool COSE_Mac_Free(HCOSE_MAC h)
{
#ifdef USE_CBOR_CONTEXT
cn_cbor_context *context;
#endif
COSE_MacMessage *p = (COSE_MacMessage *)h;
if (!IsValidMacHandle(h)) {
return false;
}
if (p->m_message.m_refCount > 1) {
p->m_message.m_refCount--;
return true;
}
_COSE_RemoveFromList(&MacRoot, &p->m_message);
#ifdef USE_CBOR_CONTEXT
context = &((COSE_MacMessage *)h)->m_message.m_allocContext;
#endif
_COSE_Mac_Release((COSE_MacMessage *)h);
COSE_FREE((COSE_MacMessage *)h, context);
return true;
}
bool _COSE_Mac_Release(COSE_MacMessage *p)
{
COSE_RecipientInfo *pRecipient;
COSE_RecipientInfo *pRecipient2;
for (pRecipient = p->m_recipientFirst; pRecipient != NULL;
pRecipient = pRecipient2) {
pRecipient2 = pRecipient->m_recipientNext;
COSE_Recipient_Free((HCOSE_RECIPIENT)pRecipient);
}
_COSE_Release(&p->m_message);
return true;
}
bool COSE_Mac_SetContent(HCOSE_MAC cose,
const byte *rgbContent,
size_t cbContent,
cose_errback *perr)
{
COSE_MacMessage *p = (COSE_MacMessage *)cose;
#ifdef USE_CBOR_CONTEXT
cn_cbor_context *context = &p->m_message.m_allocContext;
#endif
cn_cbor *ptmp = NULL;
cn_cbor_errback cbor_error;
CHECK_CONDITION(IsValidMacHandle(cose), COSE_ERR_INVALID_PARAMETER);
ptmp = cn_cbor_data_create(
rgbContent, (int)cbContent, CBOR_CONTEXT_PARAM_COMMA & cbor_error);
CHECK_CONDITION_CBOR(ptmp != NULL, cbor_error);
CHECK_CONDITION_CBOR(_COSE_array_replace(&p->m_message, ptmp, INDEX_BODY,
CBOR_CONTEXT_PARAM_COMMA & cbor_error),
cbor_error);
ptmp = NULL;
return true;
errorReturn:
if (ptmp != NULL) {
CN_CBOR_FREE(ptmp, context);
}
return false;
}
/*!
* @brief Set the application external data for authentication
*
* MAC data objects support the authentication of external application
* supplied data. This function is provided to supply that data to the library.
*
* The external data is not copied, nor will be it freed when the handle is
* released.
*
* @param hcose Handle for the COSE MAC data object
* @param pbEternalData point to the external data
* @param cbExternalData size of the external data
* @param perr location to return errors
* @return result of the operation.
*/
bool COSE_Mac_SetExternal(HCOSE_MAC hcose,
const byte *pbExternalData,
size_t cbExternalData,
cose_errback *perr)
{
if (!IsValidMacHandle(hcose)) {
if (perr != NULL) {
perr->err = COSE_ERR_INVALID_PARAMETER;
}
return false;
}
return _COSE_SetExternal(&((COSE_MacMessage *)hcose)->m_message,
pbExternalData, cbExternalData, perr);
}
cn_cbor *COSE_Mac_map_get_int(HCOSE_MAC h,
int key,
int flags,
cose_errback *perror)
{
if (!IsValidMacHandle(h)) {
if (perror != NULL) {
perror->err = COSE_ERR_INVALID_PARAMETER;
}
return NULL;
}
return _COSE_map_get_int(
&((COSE_MacMessage *)h)->m_message, key, flags, perror);
}
bool COSE_Mac_map_put_int(HCOSE_MAC h,
int key,
cn_cbor *value,
int flags,
cose_errback *perror)
{
if (!IsValidMacHandle(h) || (value == NULL)) {
if (perror != NULL) {
perror->err = COSE_ERR_INVALID_PARAMETER;
}
return false;
}
return _COSE_map_put(
&((COSE_MacMessage *)h)->m_message, key, value, flags, perror);
}
#endif
#if INCLUDE_MAC || INCLUDE_MAC0
bool _COSE_Mac_Build_AAD(COSE *pCose,
const char *szContext,
byte **ppbAuthData,
size_t *pcbAuthData,
CBOR_CONTEXT_COMMA cose_errback *perr)
{
cn_cbor *pAuthData = NULL;
bool fRet = false;
cn_cbor_errback cbor_error;
cn_cbor *ptmp = NULL;
cn_cbor *pcn;
size_t cbAuthData;
byte *pbAuthData = NULL;
// Build authenticated data
// Protected headers
// external data
// body
pAuthData = cn_cbor_array_create(CBOR_CONTEXT_PARAM_COMMA NULL);
CHECK_CONDITION(pAuthData != NULL, COSE_ERR_OUT_OF_MEMORY);
// Add the context string
ptmp =
cn_cbor_string_create(szContext, CBOR_CONTEXT_PARAM_COMMA & cbor_error);
CHECK_CONDITION_CBOR(ptmp != NULL, cbor_error);
CHECK_CONDITION_CBOR(
cn_cbor_array_append(pAuthData, ptmp, &cbor_error), cbor_error);
ptmp = NULL;
// Add the protected attributes
pcn = _COSE_arrayget_int(pCose, INDEX_PROTECTED);
CHECK_CONDITION((pcn != NULL) && (pcn->type == CN_CBOR_BYTES),
COSE_ERR_INVALID_PARAMETER);
if ((pcn->length == 1) && (pcn->v.bytes[0] == 0xa0)) {
ptmp = cn_cbor_data_create(NULL, 0, CBOR_CONTEXT_PARAM_COMMA NULL);
}
else {
ptmp = cn_cbor_data_create(
pcn->v.bytes, (int)pcn->length, CBOR_CONTEXT_PARAM_COMMA NULL);
}
CHECK_CONDITION(ptmp != NULL, COSE_ERR_CBOR);
CHECK_CONDITION(cn_cbor_array_append(pAuthData, ptmp, NULL), COSE_ERR_CBOR);
ptmp = NULL;
// Add the external bytes
ptmp = cn_cbor_data_create(pCose->m_pbExternal, (int)pCose->m_cbExternal,
CBOR_CONTEXT_PARAM_COMMA & cbor_error);
CHECK_CONDITION_CBOR(ptmp != NULL, cbor_error);
CHECK_CONDITION_CBOR(
cn_cbor_array_append(pAuthData, ptmp, &cbor_error), cbor_error);
ptmp = NULL;
// Add the content
pcn = _COSE_arrayget_int(pCose, INDEX_BODY);
ptmp = cn_cbor_data_create(
pcn->v.bytes, (int)pcn->length, CBOR_CONTEXT_PARAM_COMMA & cbor_error);
CHECK_CONDITION_CBOR(ptmp != NULL, cbor_error);
CHECK_CONDITION_CBOR(
cn_cbor_array_append(pAuthData, ptmp, &cbor_error), cbor_error);
ptmp = NULL;
// Turn it into bytes
cbAuthData = cn_cbor_encode_size(pAuthData);
CHECK_CONDITION(cbAuthData > 0, COSE_ERR_CBOR);
pbAuthData = (byte *)COSE_CALLOC(cbAuthData, 1, context);
CHECK_CONDITION(pbAuthData != NULL, COSE_ERR_OUT_OF_MEMORY);
CHECK_CONDITION(cn_cbor_encoder_write(pbAuthData, 0, cbAuthData,
pAuthData) == (ssize_t)cbAuthData,
COSE_ERR_CBOR);
*ppbAuthData = pbAuthData;
*pcbAuthData = cbAuthData;
pbAuthData = NULL;
fRet = true;
errorReturn:
if (pbAuthData != NULL) {
COSE_FREE(pbAuthData, context);
}
if (pAuthData != NULL) {
CN_CBOR_FREE(pAuthData, context);
}
if (ptmp != NULL) {
CN_CBOR_FREE(ptmp, context);
}
return fRet;
}
#endif
#if INCLUDE_MAC
bool COSE_Mac_encrypt(HCOSE_MAC h, cose_errback *perr)
{
COSE_MacMessage *pcose = (COSE_MacMessage *)h;
CHECK_CONDITION(IsValidMacHandle(h), COSE_ERR_INVALID_HANDLE);
CHECK_CONDITION(
pcose->m_recipientFirst != NULL, COSE_ERR_INVALID_PARAMETER);
return _COSE_Mac_compute(pcose, NULL, 0, "MAC", perr);
errorReturn:
return false;
}
#endif
#if INCLUDE_MAC || INCLUDE_MAC0
bool _COSE_Mac_compute(COSE_MacMessage *pcose,
const byte *pbKeyIn,
size_t cbKeyIn,
const char *szContext,
cose_errback *perr)
{
int alg;
int t;
COSE_RecipientInfo *pri;
const cn_cbor *cn_Alg = NULL;
byte *pbAuthData = NULL;
size_t cbitKey;
#ifdef USE_CBOR_CONTEXT
cn_cbor_context *context = &pcose->m_message.m_allocContext;
#endif
bool fRet = false;
size_t cbAuthData = 0;
const byte *pbKey = NULL;
byte *pbKeyNew = NULL;
size_t cbKey = 0;
if (false) {
errorReturn:
if (pbKeyNew != NULL) {
memset(pbKeyNew, 0, cbKey);
COSE_FREE(pbKeyNew, context);
}
if (pbAuthData != NULL) {
COSE_FREE(pbAuthData, context);
}
return fRet;
}
cn_Alg = _COSE_map_get_int(
&pcose->m_message, COSE_Header_Algorithm, COSE_BOTH, perr);
if (cn_Alg == NULL) {
goto errorReturn;
}
CHECK_CONDITION(cn_Alg->type != CN_CBOR_TEXT, COSE_ERR_UNKNOWN_ALGORITHM);
CHECK_CONDITION(
((cn_Alg->type == CN_CBOR_UINT || cn_Alg->type == CN_CBOR_INT)),
COSE_ERR_INVALID_PARAMETER);
alg = (int)cn_Alg->v.uint;
// Get the key size
switch (alg) {
#ifdef USE_AES_CBC_MAC_128_64
case COSE_Algorithm_CBC_MAC_128_64:
cbitKey = 128;
break;
#endif
#ifdef USE_AES_CBC_MAC_128_128
case COSE_Algorithm_CBC_MAC_128_128:
cbitKey = 128;
break;
#endif
#ifdef USE_AES_CBC_MAC_256_64
case COSE_Algorithm_CBC_MAC_256_64:
cbitKey = 256;
break;
#endif
#ifdef USE_AES_CBC_MAC_256_128
case COSE_Algorithm_CBC_MAC_256_128:
cbitKey = 256;
break;
#endif
#ifdef USE_HMAC_256_64
case COSE_Algorithm_HMAC_256_64:
cbitKey = 256;
break;
#endif
#ifdef USE_HMAC_256_256
case COSE_Algorithm_HMAC_256_256:
cbitKey = 256;
break;
#endif
#ifdef USE_HMAC_384_384
case COSE_Algorithm_HMAC_384_384:
cbitKey = 384;
break;
#endif
#ifdef USE_HMAC_512_512
case COSE_Algorithm_HMAC_512_512:
cbitKey = 512;
break;
#endif
default:
FAIL_CONDITION(COSE_ERR_UNKNOWN_ALGORITHM);
}
// If we are doing direct encryption - then recipient generates the key
if (pbKeyIn != NULL) {
CHECK_CONDITION(cbKeyIn == cbitKey / 8, COSE_ERR_INVALID_PARAMETER);
pbKey = pbKeyIn;
cbKey = cbKeyIn;
}
else {
t = 0;
for (pri = pcose->m_recipientFirst; pri != NULL;
pri = pri->m_recipientNext) {
if (pri->m_encrypt.m_message.m_flags & 1) {
CHECK_CONDITION(pbKey == NULL, COSE_ERR_INVALID_PARAMETER);
t |= 1;
pbKeyNew =
_COSE_RecipientInfo_generateKey(pri, alg, cbitKey, perr);
cbKey = cbitKey / 8;
CHECK_CONDITION(pbKeyNew != NULL, COSE_ERR_OUT_OF_MEMORY);
pbKey = pbKeyNew;
}
else {
t |= 2;
}
}
CHECK_CONDITION(t != 3, COSE_ERR_INVALID_PARAMETER);
if (t == 2) {
pbKeyNew = (byte *)COSE_CALLOC(cbitKey / 8, 1, context);
CHECK_CONDITION(pbKeyNew != NULL, COSE_ERR_OUT_OF_MEMORY);
pbKey = pbKeyNew;
cbKey = cbitKey / 8;
rand_bytes(pbKeyNew, cbKey);
}
}
// Build protected headers
const cn_cbor *cbProtected =
_COSE_encode_protected(&pcose->m_message, perr);
if (cbProtected == NULL) {
goto errorReturn;
}
// Build authenticated data
if (!_COSE_Mac_Build_AAD(&pcose->m_message, szContext, &pbAuthData,
&cbAuthData, CBOR_CONTEXT_PARAM_COMMA perr)) {
goto errorReturn;
}
switch (alg) {
#ifdef USE_AES_CBC_MAC_128_64
case COSE_Algorithm_CBC_MAC_128_64:
if (!AES_CBC_MAC_Create(
pcose, 64, pbKey, cbKey, pbAuthData, cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_AES_CBC_MAC_256_64
case COSE_Algorithm_CBC_MAC_256_64:
if (!AES_CBC_MAC_Create(
pcose, 64, pbKey, cbKey, pbAuthData, cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_AES_CBC_MAC_128_128
case COSE_Algorithm_CBC_MAC_128_128:
if (!AES_CBC_MAC_Create(
pcose, 128, pbKey, cbKey, pbAuthData, cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_AES_CBC_MAC_256_128
case COSE_Algorithm_CBC_MAC_256_128:
if (!AES_CBC_MAC_Create(
pcose, 128, pbKey, cbKey, pbAuthData, cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_HMAC_256_64
case COSE_Algorithm_HMAC_256_64:
if (!HMAC_Create(pcose, 256, 64, pbKey, cbKey, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_HMAC_256_256
case COSE_Algorithm_HMAC_256_256:
if (!HMAC_Create(pcose, 256, 256, pbKey, cbKey, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_HMAC_384_384
case COSE_Algorithm_HMAC_384_384:
if (!HMAC_Create(pcose, 384, 384, pbKey, cbKey, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_HMAC_512_512
case COSE_Algorithm_HMAC_512_512:
if (!HMAC_Create(pcose, 512, 512, pbKey, cbKey, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
default:
FAIL_CONDITION(COSE_ERR_INVALID_PARAMETER);
}
for (pri = pcose->m_recipientFirst; pri != NULL;
pri = pri->m_recipientNext) {
if (!_COSE_Recipient_encrypt(pri, pbKey, cbKey, perr)) {
goto errorReturn;
}
}
#if INCLUDE_COUNTERSIGNATURE
if (pcose->m_message.m_counterSigners != NULL) {
if (!_COSE_CounterSign_Sign(
&pcose->m_message, CBOR_CONTEXT_PARAM_COMMA perr)) {
goto errorReturn;
}
}
#endif
// Figure out the clean up
fRet = true;
goto errorReturn;
}
#endif
#if INCLUDE_MAC
bool COSE_Mac_validate(HCOSE_MAC h, HCOSE_RECIPIENT hRecip, cose_errback *perr)
{
cose_errback error;
if (perr == NULL) {
perr = &error;
}
COSE_MacMessage *pcose = (COSE_MacMessage *)h;
COSE_RecipientInfo *pRecip = (COSE_RecipientInfo *)hRecip;
CHECK_CONDITION(IsValidMacHandle(h) && IsValidRecipientHandle(hRecip),
COSE_ERR_INVALID_PARAMETER);
return _COSE_Mac_validate(pcose, pRecip, NULL, 0, "MAC", perr);
errorReturn:
return false;
}
#endif
#if INCLUDE_MAC || INCLUDE_MAC0
bool _COSE_Mac_validate(COSE_MacMessage *pcose,
COSE_RecipientInfo *pRecip,
const byte *pbKeyIn,
size_t cbKeyIn,
const char *szContext,
cose_errback *perr)
{
byte *pbAuthData = NULL;
size_t cbitKey = 0;
bool fRet = false;
int alg;
const cn_cbor *cn = NULL;
byte *pbKeyNew = NULL;
const byte *pbKey = NULL;
#ifdef USE_CBOR_CONTEXT
cn_cbor_context *context = &pcose->m_message.m_allocContext;
#endif
size_t cbAuthData;
CHECK_CONDITION(
!((pRecip != NULL) && (pbKeyIn != NULL)), COSE_ERR_INTERNAL);
cn = _COSE_map_get_int(
&pcose->m_message, COSE_Header_Algorithm, COSE_BOTH, perr);
if (cn == NULL) {
goto errorReturn;
}
if (cn->type == CN_CBOR_TEXT) {
FAIL_CONDITION(COSE_ERR_UNKNOWN_ALGORITHM);
}
else {
CHECK_CONDITION((cn->type == CN_CBOR_UINT || cn->type == CN_CBOR_INT),
COSE_ERR_INVALID_PARAMETER);
alg = (int)cn->v.uint;
switch (alg) {
#ifdef USE_AES_CBC_MAC_128_64
case COSE_Algorithm_CBC_MAC_128_64:
cbitKey = 128;
break;
#endif
#ifdef USE_AES_CBC_MAC_128_128
case COSE_Algorithm_CBC_MAC_128_128:
cbitKey = 128;
break;
#endif
#ifdef USE_AES_CBC_MAC_256_64
case COSE_Algorithm_CBC_MAC_256_64:
cbitKey = 256;
break;
#endif
#ifdef USE_AES_CBC_MAC_256_128
case COSE_Algorithm_CBC_MAC_256_128:
cbitKey = 256;
break;
#endif
#ifdef USE_HMAC_256_64
case COSE_Algorithm_HMAC_256_64:
cbitKey = 256;
break;
#endif
#ifdef USE_HMAC_256_256
case COSE_Algorithm_HMAC_256_256:
cbitKey = 256;
break;
#endif
#ifdef USE_HMAC_384_384
case COSE_Algorithm_HMAC_384_384:
cbitKey = 384;
break;
#endif
#ifdef USE_HMAC_512_512
case COSE_Algorithm_HMAC_512_512:
cbitKey = 512;
break;
#endif
default:
FAIL_CONDITION(COSE_ERR_UNKNOWN_ALGORITHM);
break;
}
}
// Allocate the key if we have not already done so
if (pbKeyIn != NULL) {
CHECK_CONDITION(cbitKey / 8 == cbKeyIn, COSE_ERR_INVALID_PARAMETER);
pbKey = pbKeyIn;
}
else {
if (pbKeyNew == NULL) {
pbKeyNew = static_cast<byte*>(COSE_CALLOC(cbitKey / 8, 1, context));
CHECK_CONDITION(pbKeyNew != NULL, COSE_ERR_OUT_OF_MEMORY);
pbKey = pbKeyNew;
}
// If there is a recipient - ask it for the key
if (pRecip != NULL) {
COSE_RecipientInfo *pRecipX;
for (pRecipX = pcose->m_recipientFirst; pRecipX != NULL;
pRecipX = pRecipX->m_recipientNext) {
if (pRecip == pRecipX) {
if (!_COSE_Recipient_decrypt(
pRecipX, pRecip, alg, cbitKey, pbKeyNew, perr)) {
goto errorReturn;
}
break;
}
else if (pRecipX->m_encrypt.m_recipientFirst != NULL) {
if (_COSE_Recipient_decrypt(
pRecipX, pRecip, alg, cbitKey, pbKeyNew, perr)) {
break;
}
}
}
CHECK_CONDITION(pRecipX != NULL, COSE_ERR_NO_RECIPIENT_FOUND);
}
else {
for (pRecip = pcose->m_recipientFirst; pRecip != NULL;
pRecip = pRecip->m_recipientNext) {
if (_COSE_Recipient_decrypt(
pRecip, NULL, alg, cbitKey, pbKeyNew, perr)) {
break;
}
}
CHECK_CONDITION(pRecip != NULL, COSE_ERR_NO_RECIPIENT_FOUND);
}
}
// Build authenticated data
if (!_COSE_Mac_Build_AAD(&pcose->m_message, szContext, &pbAuthData,
&cbAuthData, CBOR_CONTEXT_PARAM_COMMA perr)) {
goto errorReturn;
}
switch (alg) {
#ifdef USE_HMAC_256_256
case COSE_Algorithm_HMAC_256_256:
if (!HMAC_Validate(pcose, 256, 256, pbKey, cbitKey / 8, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_HMAC_256_64
case COSE_Algorithm_HMAC_256_64:
if (!HMAC_Validate(pcose, 256, 64, pbKey, cbitKey / 8, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_HMAC_384_384
case COSE_Algorithm_HMAC_384_384:
if (!HMAC_Validate(pcose, 384, 384, pbKey, cbitKey / 8, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_HMAC_512_512
case COSE_Algorithm_HMAC_512_512:
if (!HMAC_Validate(pcose, 512, 512, pbKey, cbitKey / 8, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_AES_CBC_MAC_128_64
case COSE_Algorithm_CBC_MAC_128_64:
if (!AES_CBC_MAC_Validate(pcose, 64, pbKey, cbitKey / 8, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_AES_CBC_MAC_256_64
case COSE_Algorithm_CBC_MAC_256_64:
if (!AES_CBC_MAC_Validate(pcose, 64, pbKey, cbitKey / 8, pbAuthData,
cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_AES_CBC_MAC_128_128
case COSE_Algorithm_CBC_MAC_128_128:
if (!AES_CBC_MAC_Validate(pcose, 128, pbKey, cbitKey / 8,
pbAuthData, cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
#ifdef USE_AES_CBC_MAC_256_128
case COSE_Algorithm_CBC_MAC_256_128:
if (!AES_CBC_MAC_Validate(pcose, 128, pbKey, cbitKey / 8,
pbAuthData, cbAuthData, perr)) {
goto errorReturn;
}
break;
#endif
default:
FAIL_CONDITION(COSE_ERR_UNKNOWN_ALGORITHM);
break;
}
fRet = true;
errorReturn:
if (pbKeyNew != NULL) {
memset(pbKeyNew, 0xff, cbitKey / 8);
COSE_FREE(pbKeyNew, context);
}
if (pbAuthData != NULL) {
COSE_FREE(pbAuthData, context);
}
return fRet;
}
#endif
#if INCLUDE_MAC
bool COSE_Mac_AddRecipient(HCOSE_MAC hMac,
HCOSE_RECIPIENT hRecip,
cose_errback *perr)
{
COSE_RecipientInfo *pRecip;
COSE_MacMessage *pMac;
cn_cbor *pRecipients = NULL;
cn_cbor *pRecipientsT = NULL;
#ifdef USE_CBOR_CONTEXT
cn_cbor_context *context = NULL;
#endif
cn_cbor_errback cbor_error;
CHECK_CONDITION(IsValidMacHandle(hMac), COSE_ERR_INVALID_PARAMETER);
CHECK_CONDITION(IsValidRecipientHandle(hRecip), COSE_ERR_INVALID_PARAMETER);
pMac = (COSE_MacMessage *)hMac;
pRecip = (COSE_RecipientInfo *)hRecip;
pRecip->m_recipientNext = pMac->m_recipientFirst;
pMac->m_recipientFirst = pRecip;
#ifdef USE_CBOR_CONTEXT
context = &pMac->m_message.m_allocContext;
#endif // USE_CBOR_CONTEXT
pRecipients = _COSE_arrayget_int(&pMac->m_message, INDEX_MAC_RECIPIENTS);
if (pRecipients == NULL) {
pRecipientsT =
cn_cbor_array_create(CBOR_CONTEXT_PARAM_COMMA & cbor_error);
CHECK_CONDITION_CBOR(pRecipientsT != NULL, cbor_error);
CHECK_CONDITION_CBOR(
_COSE_array_replace(&pMac->m_message, pRecipientsT,
INDEX_MAC_RECIPIENTS, CBOR_CONTEXT_PARAM_COMMA & cbor_error),
cbor_error);
pRecipients = pRecipientsT;
pRecipientsT = NULL;
}
CHECK_CONDITION_CBOR(cn_cbor_array_append(pRecipients,
pRecip->m_encrypt.m_message.m_cbor, &cbor_error),
cbor_error);
pRecip->m_encrypt.m_message.m_refCount++;
return true;
errorReturn:
if (pRecipientsT == NULL) {
CN_CBOR_FREE(pRecipientsT, context);
}
return false;
}
HCOSE_RECIPIENT COSE_Mac_GetRecipient(HCOSE_MAC cose,
int iRecipient,
cose_errback *perr)
{
int i;
COSE_RecipientInfo *p;
CHECK_CONDITION(IsValidMacHandle(cose), COSE_ERR_INVALID_PARAMETER);
p = ((COSE_MacMessage *)cose)->m_recipientFirst;
for (i = 0; i < iRecipient; i++) {
CHECK_CONDITION(p != NULL, COSE_ERR_NO_RECIPIENT_FOUND);
p = p->m_recipientNext;
}
if (p != NULL) {
p->m_encrypt.m_message.m_refCount++;
}
return (HCOSE_RECIPIENT)p;
errorReturn:
return NULL;
}
#endif
| 22.857582 | 80 | 0.722309 | [
"object"
] |
d00a76fe2c4b50d871cf4fc9bd71fa6d7b28d416 | 5,412 | cpp | C++ | third_party/geogram/src/lib/geogram/mesh/mesh_halfedges.cpp | ringmesh/RINGMesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 74 | 2017-10-26T15:40:23.000Z | 2022-03-22T09:27:39.000Z | third_party/geogram/src/lib/geogram/mesh/mesh_halfedges.cpp | ringmesh/ringmesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 45 | 2017-10-26T15:54:01.000Z | 2021-01-27T10:16:34.000Z | third_party/geogram/src/lib/geogram/mesh/mesh_halfedges.cpp | ringmesh/ringmesh | 82a0a0fb0a119492c6747265de6ec24006c4741f | [
"BSD-3-Clause"
] | 17 | 2018-03-27T11:31:24.000Z | 2022-03-06T18:41:52.000Z | /*
* Copyright (c) 2012-2014, Bruno Levy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ALICE Project-Team nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy
*
* Bruno.Levy@inria.fr
* http://www.loria.fr/~levy
*
* ALICE Project
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
*/
#include <geogram/mesh/mesh_halfedges.h>
namespace GEO {
bool MeshHalfedges::move_to_next_around_vertex(Halfedge& H) const {
geo_debug_assert(halfedge_is_valid(H));
index_t v = mesh_.facet_corners.vertex(H.corner);
index_t f = mesh_.facet_corners.adjacent_facet(H.corner);
if(f == NO_FACET) {
return false;
}
if(
facet_region_.is_bound() &&
facet_region_[H.facet] != facet_region_[f]
) {
return false;
}
for(
index_t c = mesh_.facets.corners_begin(f);
c < mesh_.facets.corners_end(f); c++
) {
index_t pc = mesh_.facets.prev_corner_around_facet(f, c);
if(
mesh_.facet_corners.vertex(c) == v &&
mesh_.facet_corners.adjacent_facet(pc) == H.facet
) {
H.corner = c;
H.facet = f;
return true;
}
}
geo_assert_not_reached;
}
bool MeshHalfedges::move_to_prev_around_vertex(Halfedge& H) const {
geo_debug_assert(halfedge_is_valid(H));
index_t v = mesh_.facet_corners.vertex(H.corner);
index_t pc = mesh_.facets.prev_corner_around_facet(H.facet, H.corner);
index_t f = mesh_.facet_corners.adjacent_facet(pc);
if(f == NO_FACET) {
return false;
}
if(
facet_region_.is_bound() &&
facet_region_[H.facet] != facet_region_[f]
) {
return false;
}
for(
index_t c = mesh_.facets.corners_begin(f);
c < mesh_.facets.corners_end(f); c++
) {
if(
mesh_.facet_corners.vertex(c) == v &&
mesh_.facet_corners.adjacent_facet(c) == H.facet
) {
H.corner = c;
H.facet = f;
return true;
}
}
geo_assert_not_reached;
}
void MeshHalfedges::move_to_next_around_border(Halfedge& H) const {
geo_debug_assert(halfedge_is_valid(H));
geo_debug_assert(halfedge_is_border(H));
move_to_next_around_facet(H);
index_t count = 0;
while(move_to_next_around_vertex(H)) {
++count;
geo_assert(count < 10000);
}
}
void MeshHalfedges::move_to_prev_around_border(Halfedge& H) const {
geo_debug_assert(halfedge_is_valid(H));
geo_debug_assert(halfedge_is_border(H));
index_t count = 0;
while(move_to_prev_around_vertex(H)) {
++count;
geo_assert(count < 10000);
}
move_to_prev_around_facet(H);
}
void MeshHalfedges::move_to_opposite(Halfedge& H) const {
geo_debug_assert(halfedge_is_valid(H));
index_t v = mesh_.facet_corners.vertex(
mesh_.facets.next_corner_around_facet(H.facet, H.corner)
);
index_t f = mesh_.facet_corners.adjacent_facet(H.corner);
geo_assert(f != NO_FACET);
for(
index_t c = mesh_.facets.corners_begin(f);
c != mesh_.facets.corners_end(f); ++c
) {
if(mesh_.facet_corners.vertex(c) == v) {
H.facet = f;
H.corner = c;
return;
}
}
geo_assert_not_reached;
}
}
| 35.372549 | 79 | 0.614375 | [
"mesh"
] |
d00e51e11573d856110bacc972b9117911b57282 | 12,234 | cpp | C++ | source/src/ChebyshevApproximation.cpp | TatianaOvsiannikova/ostap | a005a78b4e2860ac8f4b618e94b4b563b2eddcf1 | [
"BSD-3-Clause"
] | 14 | 2017-03-24T12:38:08.000Z | 2022-02-21T05:00:57.000Z | source/src/ChebyshevApproximation.cpp | TatianaOvsiannikova/ostap | a005a78b4e2860ac8f4b618e94b4b563b2eddcf1 | [
"BSD-3-Clause"
] | 10 | 2019-03-08T18:48:42.000Z | 2022-03-22T11:59:48.000Z | source/src/ChebyshevApproximation.cpp | TatianaOvsiannikova/ostap | a005a78b4e2860ac8f4b618e94b4b563b2eddcf1 | [
"BSD-3-Clause"
] | 11 | 2017-03-23T15:29:58.000Z | 2022-02-21T05:03:57.000Z | // ============================================================================
// Include files
// ============================================================================
// STD&STL
// ============================================================================
#include <algorithm>
// ============================================================================
// GSL
// ============================================================================
#include "gsl/gsl_math.h"
#include "gsl/gsl_chebyshev.h"
// ============================================================================
// ROOT
// ============================================================================
#include "Math/GSLFunctionAdapter.h"
// ============================================================================
// Ostap
// ============================================================================
#include "Ostap/ChebyshevApproximation.h"
#include "Ostap/PyCallable.h"
#include "Ostap/Polynomials.h"
// ============================================================================
// Local
// ============================================================================
#include "Exception.h"
// ============================================================================
/** @file
* Implementation file for class Ostap::Math::ChebyshevApproximation
* @date 2019-09-25
* @author Vanya Belyaev Ivan.Belyaev@itep.ru
*/
// ============================================================================
namespace
{
// ==========================================================================
const char s_ERROR [] = "Invalid gsl_cheb_series object!" ;
const char s_METHOD1 [] = "Ostap::Math::ChebyshevApproximation::evaluate" ;
const char s_METHOD2 [] = "Ostap::Math::ChebyshevApproximation::derivative" ;
const char s_METHOD3 [] = "Ostap::Math::ChebyshevApproximation::integral" ;
const char s_METHOD4 [] = "Ostap::Math::ChebyshevApproximation::operator+" ;
const char s_METHOD5 [] = "Ostap::Math::ChebyshevApproximation::operator*" ;
const char s_METHOD6 [] = "Ostap::Math::ChebyshevApproximation::polynomial" ;
const Ostap::StatusCode s_SC = Ostap::StatusCode::FAILURE ;
// ==========================================================================
}
// ============================================================================
/* constructor from the function, low/high-limits and the approximation order
* @param func the function
* @param a the low-limit
* @param b the high-limit
* @param N the approximation order
*/
// ============================================================================
Ostap::Math::ChebyshevApproximation::ChebyshevApproximation
( std::function<double(double)> func ,
const double a ,
const double b ,
const unsigned short N )
: m_a ( std::min ( a , b ) )
, m_b ( std::max ( a , b ) )
, m_N ( N )
, m_chebyshev ( nullptr )
{
//
ROOT::Math::GSLFunctionAdapter< std::function<double(double)> > adapter ;
const void* p = &func ;
//
gsl_function F ;
F.function = &adapter.F ;
F.params = const_cast<void*> (p) ;
//
gsl_cheb_series* ns = gsl_cheb_alloc ( m_N ) ;
gsl_cheb_init ( ns , &F , m_a , m_b ) ;
//
m_chebyshev = (char*) ns ;
}
// ============================================================================
/* constructor from the function, low/high-limits and the approximation order
* @param func the function
* @param a the low-limit
* @param b the high-limit
* @param N the approximation order
*/
// ============================================================================
Ostap::Math::ChebyshevApproximation::ChebyshevApproximation
( const Ostap::Functions::PyCallable& func ,
const double a ,
const double b ,
const unsigned short N )
: ChebyshevApproximation ( std::function<double(double)> ( std::cref ( func ) ) , a , b , N )
{}
// ============================================================================
// ============================================================================
// default (protected) constructor
// ============================================================================
Ostap::Math::ChebyshevApproximation::ChebyshevApproximation()
: m_a ( 0 )
, m_b ( 1 )
, m_N ( 0 )
, m_chebyshev ( nullptr )
{}
// ============================================================================
// copy constructor
// ============================================================================
Ostap::Math::ChebyshevApproximation::ChebyshevApproximation
( const Ostap::Math::ChebyshevApproximation& right )
: m_a ( right.m_a )
, m_b ( right.m_b )
, m_N ( right.m_N )
, m_chebyshev ( nullptr )
{
gsl_cheb_series* ns = gsl_cheb_alloc ( m_N ) ;
gsl_cheb_series* os = (gsl_cheb_series*) right.m_chebyshev ;
//
ns -> a = os -> a ;
ns -> b = os -> b ;
ns -> order = os -> order ;
ns -> order_sp = os -> order_sp ;
//
// copy the coefficients and the function values
//
std::copy ( os -> c , os-> c + ( m_N + 1 ) , ns -> c ) ;
std::copy ( os -> f , os-> f + ( m_N + 1 ) , ns -> f ) ;
//
m_chebyshev = (char*) ns ;
}
// ============================================================================
// move constructor
// ============================================================================
Ostap::Math::ChebyshevApproximation::ChebyshevApproximation
( Ostap::Math::ChebyshevApproximation&& right )
: m_a ( right.m_a )
, m_b ( right.m_b )
, m_N ( right.m_N )
, m_chebyshev ( right.m_chebyshev )
{
right.m_chebyshev = nullptr ;
}
// ============================================================================
// destructor
// ============================================================================
Ostap::Math::ChebyshevApproximation::~ChebyshevApproximation()
{
if ( m_chebyshev )
{
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
gsl_cheb_free ( cs ) ;
m_chebyshev = nullptr ;
}
}
// ============================================================================
// the main method: evaluate the approximation sum
// ============================================================================
double Ostap::Math::ChebyshevApproximation::evaluate
( const double x ) const
{
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD1 , s_SC ) ;
//
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
return x < m_a ? 0.0 : x > m_b ? 0.0 : gsl_cheb_eval ( cs , x ) ;
}
// ============================================================================
/* the main method: evaluate the approximation sum,
* using at most <code>n</code> terms
*/
// ============================================================================
double Ostap::Math::ChebyshevApproximation::evaluate
( const double x ,
const unsigned short n ) const
{
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD1 , s_SC ) ;
//
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
return x < m_a ? 0.0 : x > m_b ? 0.0 : gsl_cheb_eval_n ( cs , n , x ) ;
}
// ============================================================================
/* the main method: evaluate the approximation sum
* @return the approximation with the error estimate
*/
// ============================================================================
Ostap::Math::ValueWithError
Ostap::Math::ChebyshevApproximation::eval_err
( const double x ) const
{
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD1 , s_SC ) ;
//
if ( x < m_a || x > m_b ) { return 0 ; }
//
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
//
double result = 0 ;
double error = 0 ;
//
gsl_cheb_eval_err ( cs , x , &result , &error ) ;
//
return Ostap::Math::ValueWithError ( result , error * error ) ;
}
// ============================================================================
/* the main method: evaluate the approximation sum
* using at most <code>n</code> terms
* @retutn the approximation with the error estimate
*/
// ============================================================================
Ostap::Math::ValueWithError
Ostap::Math::ChebyshevApproximation::eval_err
( const double x ,
const unsigned short n ) const
{
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD1 , s_SC ) ;
//
if ( x < m_a || x > m_b ) { return 0 ; }
//
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
//
double result = 0 ;
double error = 0 ;
//
gsl_cheb_eval_n_err ( cs , n , x , &result , &error ) ;
//
return Ostap::Math::ValueWithError ( result , error * error ) ;
}
// ============================================================================
// get a derivative
// ============================================================================
Ostap::Math::ChebyshevApproximation
Ostap::Math::ChebyshevApproximation::derivative () const
{
//
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD2 , s_SC ) ;
//
gsl_cheb_series* ds = gsl_cheb_alloc ( m_N ) ;
const gsl_cheb_series* cs = (const gsl_cheb_series*) m_chebyshev ;
//
gsl_cheb_calc_deriv ( ds , cs ) ;
//
ChebyshevApproximation deriv ;
deriv.m_a = m_a ;
deriv.m_b = m_b ;
deriv.m_N = m_N ;
deriv.m_chebyshev = (char*) ds ;
//
return deriv ;
}
// ============================================================================
// get an integral: \f$ F(x) \equiv \int_a^{z} f(t) \deriv t + C \f$
// ============================================================================
Ostap::Math::ChebyshevApproximation
Ostap::Math::ChebyshevApproximation::integral
( const double C ) const
{
//
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD3 , s_SC ) ;
//
gsl_cheb_series* ds = gsl_cheb_alloc ( m_N ) ;
const gsl_cheb_series* cs = (const gsl_cheb_series*) m_chebyshev ;
//
gsl_cheb_calc_integ ( ds , cs ) ;
//
ds->c[0] += 2*C ;
//
ChebyshevApproximation integ ;
integ.m_a = m_a ;
integ.m_b = m_b ;
integ.m_N = m_N ;
integ.m_chebyshev = (char*) ds ;
//
return integ ;
}
// ============================================================================
// shift by a constant
// ============================================================================
Ostap::Math::ChebyshevApproximation&
Ostap::Math::ChebyshevApproximation::operator+= ( const double a )
{
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD4 , s_SC ) ;
//
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
//
cs -> c[0] += 2 * a ;
//
return *this ;
}
// ============================================================================
// scale by a constant
// ============================================================================
Ostap::Math::ChebyshevApproximation&
Ostap::Math::ChebyshevApproximation::operator*= ( const double a )
{
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD5 , s_SC ) ;
//
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
std::transform ( cs->c ,
cs->c + cs->order + 1 ,
cs->c ,
[a]( double v ) -> double { return v * a ; } );
//
return *this ;
}
// ============================================================================
// convert it to pure chebyshev sum
// ============================================================================
Ostap::Math::ChebyshevSum
Ostap::Math::ChebyshevApproximation::polynomial() const
{
Ostap::Assert ( m_chebyshev , s_ERROR , s_METHOD6 , s_SC ) ;
gsl_cheb_series* cs = (gsl_cheb_series*) m_chebyshev ;
Ostap::Math::ChebyshevSum cp { cs->c , cs->c + cs->order + 1 , cs->a , cs->b } ;
cp.setPar ( 0 , 0.5 * cp.par(0) ) ;
return cp ;
}
// ============================================================================
// ============================================================================
// The END
// ============================================================================
| 38.11215 | 96 | 0.418506 | [
"object",
"transform"
] |
d0125b98e5bcc0a3b2a5acd638443c9b964edb18 | 53,168 | cpp | C++ | lib/Cloud9/Worker/JobManager.cpp | dslab-epfl/state-merging | abe500674ab3013f266836315e9c4ef18d0fb55c | [
"BSD-3-Clause"
] | null | null | null | lib/Cloud9/Worker/JobManager.cpp | dslab-epfl/state-merging | abe500674ab3013f266836315e9c4ef18d0fb55c | [
"BSD-3-Clause"
] | null | null | null | lib/Cloud9/Worker/JobManager.cpp | dslab-epfl/state-merging | abe500674ab3013f266836315e9c4ef18d0fb55c | [
"BSD-3-Clause"
] | null | null | null | /*
* Cloud9 Parallel Symbolic Execution Engine
*
* Copyright (c) 2011, Dependable Systems Laboratory, EPFL
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Dependable Systems Laboratory, EPFL nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE DEPENDABLE SYSTEMS LABORATORY, EPFL BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* All contributors are listed in CLOUD9-AUTHORS file.
*
*/
/*
* Implementation invariants, between two consecutive job executions, when the
* job lock is set:
* - Every time in the tree, there is a full frontier of symbolic states.
*
* - A job can be either on the frontier, or ahead of it (case in which
* replaying needs to be done). XXX: Perform a more clever way of replay.
*
* - An exported job will leave the frontier intact.
*
* - A job import cannot happen in such a way that a job lies within the limits
* of the frontier.
*
*/
#include "cloud9/worker/JobManager.h"
#include "cloud9/worker/TreeObjects.h"
#include "cloud9/worker/WorkerCommon.h"
#include "cloud9/worker/KleeCommon.h"
#include "cloud9/worker/CoreStrategies.h"
#include "cloud9/worker/ComplexStrategies.h"
#include "cloud9/worker/OracleStrategy.h"
#include "cloud9/worker/FIStrategy.h"
#include "cloud9/worker/PartitioningStrategy.h"
#include "cloud9/worker/LazyMergingStrategy.h"
#include "cloud9/Logger.h"
#include "cloud9/Common.h"
#include "cloud9/ExecutionTree.h"
#include "cloud9/instrum/InstrumentationManager.h"
#include "cloud9/instrum/LocalFileWriter.h"
#include "cloud9/instrum/Timing.h"
#include "llvm/Function.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#if (LLVM_VERSION_MAJOR == 2 && LLVM_VERSION_MINOR < 9)
#include "llvm/System/TimeValue.h"
#else
#include "llvm/Support/TimeValue.h"
#endif
#if (LLVM_VERSION_MAJOR == 2 && LLVM_VERSION_MINOR < 9)
#include "llvm/System/Path.h"
#else
#include "llvm/Support/Path.h"
#endif
#include "llvm/Support/CommandLine.h"
#if !(LLVM_VERSION_MAJOR == 2 && LLVM_VERSION_MINOR < 7)
#include "llvm/Support/raw_os_ostream.h"
#endif
#include "klee/Interpreter.h"
#include "klee/Statistics.h"
#include "klee/ExecutionState.h"
#include "klee/Internal/Module/KInstruction.h"
#include "klee/Internal/Module/InstructionInfoTable.h"
#include "klee/Internal/Module/KModule.h"
#include "klee/Internal/System/Time.h"
#include "klee/Internal/ADT/RNG.h"
#include "klee/util/ExprPPrinter.h"
#include "klee/KleeHandler.h"
#include "klee/Init.h"
#include "klee/Constants.h"
#include "../../Core/Common.h"
#include <boost/io/ios_state.hpp>
#include <boost/crc.hpp>
#include <boost/bind.hpp>
#include <stack>
#include <map>
#include <set>
#include <fstream>
#include <iostream>
#include <iomanip>
using llvm::sys::TimeValue;
using cloud9::instrum::Timer;
using namespace llvm;
namespace klee {
namespace stats {
extern Statistic locallyCoveredInstructions;
extern Statistic globallyCoveredInstructions;
extern Statistic locallyUncoveredInstructions;
extern Statistic globallyUncoveredInstructions;
}
}
namespace {
/* Job Selection Settings *****************************************************/
cl::opt<bool> StratRandom("c9-job-random", cl::desc("Use random job selection"));
cl::opt<bool> StratRandomPath("c9-job-random-path" , cl::desc("Use random path job selection"));
cl::opt<bool> StratCovOpt("c9-job-cov-opt", cl::desc("Use coverage optimized job selection"));
cl::opt<bool> StratOracle("c9-job-oracle", cl::desc("Use the almighty oracle"));
cl::opt<bool> StratFaultInj("c9-job-fault-inj", cl::desc("Use fault injection"));
/* Other Settings *************************************************************/
cl::opt<unsigned> MakeConcreteSymbolic("make-concrete-symbolic", cl::desc(
"Rate at which to make concrete reads symbolic (0=off)"), cl::init(0));
cl::opt<bool> OptimizeModule("optimize", cl::desc("Optimize before execution"));
cl::opt<bool> CheckDivZero("check-div-zero", cl::desc(
"Inject checks for division-by-zero"), cl::init(true));
cl::list<unsigned int> CodeBreakpoints("c9-code-bp", cl::desc(
"Breakpoints in the LLVM assembly file"));
cl::opt<bool> BreakOnReplayBroken("c9-bp-on-replaybr", cl::desc(
"Break on last valid position if a broken replay occurrs."));
cl::opt<bool>
DumpStateTraces("c9-dump-traces",
cl::desc("Dump state traces when a breakpoint or any other relevant event happens during execution"),
cl::init(false));
cl::opt<bool>
DumpInstrTraces("c9-dump-instr",
cl::desc("Dump instruction traces for each finished state. Designed to be used for concrete executions."),
cl::init(false));
cl::opt<bool>
DebugJobReconstruction("debug-job-reconstruction",
cl::desc("Dump job reconstruction debug information"),
cl::init(false));
cl::opt<std::string>
OraclePath("c9-oracle-path", cl::desc("The file used by the oracle strategy to get the path."));
cl::opt<double>
JobQuanta("c9-job-quanta", cl::desc("The maximum quantum of time for a job"),
cl::init(1.0));
cl::opt<bool>
InjectFaults("c9-fault-inj", cl::desc("Fork at fault injection points"),
cl::init(false));
cl::opt<bool>
ZombieNodes("zombie-nodes", cl::desc("Preserve the structure of the paths that finished."),
cl::init(false));
cl::opt<unsigned> FlowSizeLimit("flow-size-limit", cl::init(10));
}
using namespace klee;
namespace cloud9 {
namespace worker {
/*******************************************************************************
* HELPER FUNCTIONS FOR THE JOB MANAGER
******************************************************************************/
StateSelectionStrategy *JobManager::createCoverageOptimizedStrat(StateSelectionStrategy *base) {
std::vector<StateSelectionStrategy*> strategies;
strategies.push_back(new WeightedRandomStrategy(
WeightedRandomStrategy::CoveringNew,
tree,
symbEngine));
strategies.push_back(base);
return new TimeMultiplexedStrategy(strategies);
}
bool JobManager::isJob(WorkerTree::Node *node) {
return (**node).getJob() != NULL;
}
bool JobManager::isExportableJob(WorkerTree::Node *node) {
ExecutionJob *job = (**node).getJob();
if (!job)
return false;
if (job == currentJob)
return false;
return true;
}
bool JobManager::isValidJob(WorkerTree::Node *node) {
assert(node->layerExists(WORKER_LAYER_JOBS));
while (node != NULL) {
if (node->layerExists(WORKER_LAYER_STATES)) {
if ((**node).getSymbolicState() != NULL)
return true;
else
return false;
} else {
node = node->getParent();
}
}
return false;
}
void JobManager::serializeInstructionTrace(std::ostream &s,
WorkerTree::Node *node) {
std::vector<int> path;
tree->buildPath(WORKER_LAYER_STATES, node, tree->getRoot(), path);
const WorkerTree::Node *crtNode = tree->getRoot();
unsigned int count = 0;
bool enabled = false;
for (unsigned int i = 0; i <= path.size(); i++) {
const ExecutionTrace &trace = (**crtNode).getTrace();
for (ExecutionTrace::const_iterator it = trace.getEntries().begin();
it != trace.getEntries().end(); it++) {
if (InstructionTraceEntry *instEntry = dyn_cast<InstructionTraceEntry>(*it)) {
if (enabled) {
unsigned int opcode = instEntry->getInstruction()->inst->getOpcode();
s.write((char*)&opcode, sizeof(unsigned int));
}
count++;
} else if (BreakpointEntry *brkEntry = dyn_cast<BreakpointEntry>(*it)) {
if (!enabled && brkEntry->getID() == KLEE_BRK_START_TRACING) {
CLOUD9_DEBUG("Starting to serialize. Skipped " << count << " instructions.");
enabled = true;
}
}
}
if (i < path.size()) {
crtNode = crtNode->getChild(WORKER_LAYER_STATES, path[i]);
assert(crtNode);
}
}
CLOUD9_DEBUG("Serialized " << count << " instructions.");
}
void JobManager::parseInstructionTrace(std::istream &s,
std::vector<unsigned int> &dest) {
dest.clear();
while (!s.eof()) {
unsigned int instID;
s.read((char*)&instID, sizeof(unsigned int));
if (!s.fail()) {
dest.push_back(instID);
}
}
CLOUD9_DEBUG("Parsed " << dest.size() << " instructions.");
}
void JobManager::serializeExecutionTrace(std::ostream &os,
WorkerTree::Node *node) { // XXX very slow - read the .ll file and use it instead
std::vector<int> path;
tree->buildPath(WORKER_LAYER_STATES, node, tree->getRoot(), path);
WorkerTree::Node *crtNode = tree->getRoot();
const llvm::BasicBlock *crtBasicBlock = NULL;
const llvm::Function *crtFunction = NULL;
llvm::raw_os_ostream raw_os(os);
for (unsigned int i = 0; i <= path.size(); i++) {
const ExecutionTrace &trace = (**crtNode).getTrace();
// Output each instruction in the node
for (ExecutionTrace::const_iterator it = trace.getEntries().begin(); it
!= trace.getEntries().end(); it++) {
if (InstructionTraceEntry *instEntry = dyn_cast<InstructionTraceEntry>(*it)) {
klee::KInstruction *ki = instEntry->getInstruction();
bool newBB = false;
bool newFn = false;
if (ki->inst->getParent() != crtBasicBlock) {
crtBasicBlock = ki->inst->getParent();
newBB = true;
}
if (crtBasicBlock != NULL && crtBasicBlock->getParent() != crtFunction) {
crtFunction = crtBasicBlock->getParent();
newFn = true;
}
if (newFn) {
os << std::endl;
os << " Function '"
<< ((crtFunction != NULL) ? crtFunction->getNameStr() : "")
<< "':" << std::endl;
}
if (newBB) {
os << "----------- "
<< ((crtBasicBlock != NULL) ? crtBasicBlock->getNameStr() : "")
<< " ----" << std::endl;
}
boost::io::ios_all_saver saver(os);
os << std::setw(9) << ki->info->assemblyLine << ": ";
saver.restore();
ki->inst->print(raw_os, NULL);
os << std::endl;
} else if (DebugLogEntry *logEntry = dyn_cast<DebugLogEntry>(*it)) {
os << logEntry->getMessage() << std::endl;
}
}
if (i < path.size()) {
crtNode = crtNode->getChild(WORKER_LAYER_STATES, path[i]);
}
}
}
void JobManager::serializeExecutionTrace(std::ostream &os, SymbolicState *state) {
WorkerTree::Node *node = state->getNode().get();
serializeExecutionTrace(os, node);
}
void JobManager::processTestCase(SymbolicState *state) {
std::vector<EventEntry*> eventEntries;
// First, collect the event entries
std::vector<int> path;
tree->buildPath(WORKER_LAYER_STATES, state->getNode().get(), tree->getRoot(), path);
const WorkerTree::Node *crtNode = tree->getRoot();
for (unsigned int i = 0; i <= path.size(); i++) {
const ExecutionTrace &trace = (**crtNode).getTrace();
for (ExecutionTrace::const_iterator it = trace.getEntries().begin();
it != trace.getEntries().end(); it++) {
if (EventEntry *eventEntry = dyn_cast<EventEntry>(*it)) {
eventEntries.push_back(eventEntry);
}
}
if (i < path.size()) {
crtNode = crtNode->getChild(WORKER_LAYER_STATES, path[i]);
assert(crtNode);
}
}
if (eventEntries.size() == 0)
return;
std::ostream *f = kleeHandler->openTestFile("events");
if (f) {
for (std::vector<EventEntry*>::iterator it = eventEntries.begin();
it != eventEntries.end(); it++) {
EventEntry *event = *it;
*f << "Event: " << event->getType() << " Value: " << event->getValue() << std::endl;
event->getStackTrace().dump(*f);
*f << std::endl;
}
delete f;
}
}
/*******************************************************************************
* JOB MANAGER METHODS
******************************************************************************/
/* Initialization Methods *****************************************************/
JobManager::JobManager(llvm::Module *module, std::string mainFnName, int argc,
char **argv, char **envp) :
terminationRequest(false), jobCount(0), currentJob(NULL), currentState(NULL),
replaying(false), batching(true), traceCounter(0) {
tree = new WorkerTree();
llvm::Function *mainFn = module->getFunction(mainFnName);
collectTraces = DumpStateTraces || DumpInstrTraces;
initialize(module, mainFn, argc, argv, envp);
}
void JobManager::initialize(llvm::Module *module, llvm::Function *_mainFn,
int argc, char **argv, char **envp) {
mainFn = _mainFn;
assert(mainFn);
klee::Interpreter::InterpreterOptions iOpts;
iOpts.MakeConcreteSymbolic = MakeConcreteSymbolic;
llvm::sys::Path libraryPath(getKleeLibraryPath());
klee::Interpreter::ModuleOptions mOpts(libraryPath.c_str(),
/*Optimize=*/OptimizeModule,
/*CheckDivZero=*/CheckDivZero);
kleeHandler = new klee::KleeHandler(argc, argv);
interpreter = klee::Interpreter::create(iOpts, kleeHandler);
kleeHandler->setInterpreter(interpreter);
symbEngine = dyn_cast<SymbolicEngine> (interpreter);
interpreter->setModule(module, mOpts);
kleeModule = symbEngine->getModule();
klee::externalsAndGlobalsCheck(kleeModule->module);
symbEngine->registerStateEventHandler(this);
theStatisticManager->trackChanges(stats::locallyCoveredInstructions);
initStrategy();
initStatistics();
initBreakpoints();
initRootState(mainFn, argc, argv, envp);
}
void JobManager::initRootState(llvm::Function *f, int argc, char **argv,
char **envp) {
klee::ExecutionState *kState = symbEngine->createRootState(f);
SymbolicState *state = new SymbolicState(kState, NULL);
state->rebindToNode(tree->getRoot());
symbEngine->initRootState(kState, argc, argv, envp);
}
StateSelectionStrategy *JobManager::createBaseStrategy() {
// Step 1: Compose the basic strategy
StateSelectionStrategy *stateStrat = NULL;
if (StratRandomPath) {
stateStrat = new RandomPathStrategy(tree);
} else {
stateStrat = new RandomStrategy();
}
// Step 2: Check to see if want the coverage-optimized strategy
if (StratCovOpt) {
stateStrat = createCoverageOptimizedStrat(stateStrat);
}
return stateStrat;
}
void JobManager::initStrategy() {
if (StratOracle)
batching = false;
if (StratOracle) {
selStrategy = createOracleStrategy();
CLOUD9_INFO("Using the oracle");
return;
}
StateSelectionStrategy *stateStrat = NULL;
stateStrat = createBaseStrategy();
CLOUD9_INFO("Using the regular strategy stack");
selStrategy = new RandomJobFromStateStrategy(tree, stateStrat, this);
}
OracleStrategy *JobManager::createOracleStrategy() {
std::vector<unsigned int> goalPath;
std::ifstream ifs(OraclePath.c_str());
assert(!ifs.fail());
parseInstructionTrace(ifs, goalPath);
OracleStrategy *result = new OracleStrategy(tree, goalPath, this);
return result;
}
void JobManager::initStatistics() {
// Configure the root as a statistics node
WorkerTree::NodePin rootPin = tree->getRoot()->pin(WORKER_LAYER_STATISTICS);
stats.insert(rootPin);
statChanged = true;
refineStats = false;
}
void JobManager::initBreakpoints() {
// Register code breakpoints
for (unsigned int i = 0; i < CodeBreakpoints.size(); i++) {
setCodeBreakpoint(CodeBreakpoints[i]);
}
}
/* Finalization Methods *******************************************************/
JobManager::~JobManager() {
if (symbEngine != NULL) {
delete symbEngine;
}
cloud9::instrum::theInstrManager.stop();
}
void JobManager::finalize() {
dumpSymbolicTree(NULL, WorkerNodeDecorator(NULL));
symbEngine->deregisterStateEventHandler(this);
symbEngine->destroyStates();
CLOUD9_INFO("Finalized job execution.");
}
/* Misc. Methods **************************************************************/
unsigned JobManager::getModuleCRC() const {
std::string moduleContents;
llvm::raw_string_ostream os(moduleContents);
kleeModule->module->print(os, NULL);
os.flush();
boost::crc_ccitt_type crc;
crc.process_bytes(moduleContents.c_str(), moduleContents.size());
return crc.checksum();
}
/* Job Manipulation Methods ***************************************************/
void JobManager::processJobs(bool standAlone, unsigned int timeOut) {
if (timeOut > 0) {
CLOUD9_INFO("Processing jobs with a timeout of " << timeOut << " seconds.");
}
if (standAlone) {
// We need to import the root job
std::vector<long> replayInstrs;
std::map<unsigned, JobReconstruction*> reconstructions;
ExecutionPathSetPin pathSet = ExecutionPathSet::getRootSet();
JobReconstruction::getDefaultReconstruction(pathSet, reconstructions);
importJobs(ExecutionPathSet::getRootSet(), reconstructions);
}
processLoop(true, !standAlone, timeOut);
}
void JobManager::replayJobs(ExecutionPathSetPin paths, unsigned int timeOut) {
// First, we need to import the jobs in the manager
std::map<unsigned, JobReconstruction*> reconstructions;
JobReconstruction::getDefaultReconstruction(paths, reconstructions);
importJobs(paths, reconstructions);
// Then we execute them, but only them (non blocking, don't allow growth),
// until the queue is exhausted
processLoop(false, false, timeOut);
}
void JobManager::processLoop(bool allowGrowth, bool blocking,
unsigned int timeOut) {
ExecutionJob *job = NULL;
boost::unique_lock<boost::mutex> lock(jobsMutex);
TimeValue deadline = TimeValue::now() + TimeValue(timeOut, 0);
while (!terminationRequest) {
TimeValue now = TimeValue::now();
bool canBatch = false;
uint32_t batchDest = 0;
if (timeOut > 0 && now > deadline) {
CLOUD9_INFO("Timeout reached. Suspending execution.");
break;
}
if (blocking) {
if (timeOut > 0) {
TimeValue remaining = deadline - now;
job = selectNextJob(lock, remaining.seconds(), canBatch, batchDest);
} else {
job = selectNextJob(lock, 0, canBatch, batchDest);
}
} else {
job = selectNextJob(canBatch, batchDest);
}
if (blocking && timeOut == 0 && !terminationRequest) {
assert(job != NULL);
} else {
if (job == NULL)
break;
}
executeJobsBatch(lock, job, allowGrowth, canBatch, batchDest);
if (refineStats) {
refineStatistics();
refineStats = false;
}
}
if (terminationRequest)
CLOUD9_INFO("Termination was requested.");
}
ExecutionJob* JobManager::selectNextJob(boost::unique_lock<boost::mutex> &lock,
unsigned int timeOut, bool &canBatch, uint32_t &batchDest) {
ExecutionJob *job = selectNextJob(canBatch, batchDest);
assert(job != NULL || jobCount == 0);
while (job == NULL && !terminationRequest) {
CLOUD9_INFO("No jobs in the queue, waiting for...");
cloud9::instrum::theInstrManager.recordEvent(
cloud9::instrum::JobExecutionState, "idle");
bool result = true;
if (timeOut > 0)
result = jobsAvailabe.timed_wait(lock,
boost::posix_time::seconds(timeOut));
else
jobsAvailabe.wait(lock);
if (!result) {
CLOUD9_INFO("Timeout while waiting for new jobs. Aborting.");
return NULL;
} else
CLOUD9_INFO("More jobs available. Resuming exploration...");
job = selectNextJob(canBatch, batchDest);
if (job != NULL)
cloud9::instrum::theInstrManager.recordEvent(
cloud9::instrum::JobExecutionState, "working");
}
return job;
}
ExecutionJob* JobManager::selectNextJob(bool &canBatch, uint32_t &batchDest) {
ExecutionJob *job = selStrategy->onNextJobSelectionEx(canBatch, batchDest);
if (!StratOracle)
assert(job != NULL || jobCount == 0);
return job;
}
void JobManager::submitJob(ExecutionJob* job, bool activateStates) {
WorkerTree::Node *node = job->getNode().get();
assert((**node).symState || job->reconstruct);
fireAddJob(job);
if (activateStates) {
// Check for the state on the supporting branch
while (node) {
SymbolicState *state = (**node).getSymbolicState();
if (state) {
if (!state->_active) {
cloud9::instrum::theInstrManager.decStatistic(
cloud9::instrum::TotalWastedInstructions,
state->_instrSinceFork);
}
fireActivateState(state);
break;
}
node = node->getParent();
}
}
jobCount++;
}
void JobManager::finalizeJob(ExecutionJob *job, bool deactivateStates, bool invalid) {
WorkerTree::Node *node = job->getNode().get();
if (deactivateStates) {
while (node) {
if (node->getCount(WORKER_LAYER_JOBS) > 1)
break; // We reached a junction
SymbolicState *state = (**node).getSymbolicState();
if (state) {
fireDeactivateState(state);
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalWastedInstructions,
state->_instrSinceFork);
break;
}
node = node->getParent();
}
}
if (currentJob == job) {
currentJob = NULL;
}
fireRemovingJob(job);
delete job;
jobCount--;
if (invalid) {
cloud9::instrum::theInstrManager.incStatistic(cloud9::instrum::TotalDroppedJobs);
}
}
void JobManager::selectJobs(WorkerTree::Node *root,
std::vector<ExecutionJob*> &jobSet, int maxCount) {
std::vector<WorkerTree::Node*> nodes;
tree->getLeaves(WORKER_LAYER_JOBS, root, boost::bind(
&JobManager::isExportableJob, this, _1), maxCount, nodes);
for (std::vector<WorkerTree::Node*>::iterator it = nodes.begin(); it
!= nodes.end(); it++) {
WorkerTree::Node* node = *it;
jobSet.push_back((**node).getJob());
}
}
unsigned int JobManager::countJobs(WorkerTree::Node *root) {
return tree->countLeaves(WORKER_LAYER_JOBS, root, &isJob);
}
void JobManager::importJobs(ExecutionPathSetPin paths,
std::map<unsigned,JobReconstruction*> &reconstruct) {
boost::unique_lock<boost::mutex> lock(jobsMutex);
std::vector<WorkerTree::Node*> nodes;
std::map<unsigned, WorkerTree::Node*> decodeMap;
std::vector<ExecutionJob*> jobs;
tree->getNodes(WORKER_LAYER_SKELETON, paths, nodes, &decodeMap);
CLOUD9_DEBUG("Importing " << reconstruct.size() << " jobs");
unsigned droppedCount = 0;
for (std::map<unsigned,JobReconstruction*>::iterator it = reconstruct.begin();
it != reconstruct.end(); it++) {
WorkerTree::Node *crtNode = decodeMap[it->first];
assert(crtNode->getCount(WORKER_LAYER_JOBS) == 0
&& "Job duplication detected");
assert((!crtNode->layerExists(WORKER_LAYER_STATES) || crtNode->getCount(WORKER_LAYER_STATES) == 0)
&& "Job before the state frontier");
it->second->decode(tree, decodeMap);
// The exploration job object gets a pin on the node, thus
// ensuring it will be released automatically after it's no
// longer needed
ExecutionJob *job = new ExecutionJob(tree->getNode(WORKER_LAYER_JOBS, crtNode));
job->reconstruct = it->second;
if (!isValidJob(crtNode)) {
droppedCount++;
delete job;
} else {
jobs.push_back(job);
}
}
if (droppedCount > 0) {
CLOUD9_DEBUG("BUG! " << droppedCount << " jobs dropped before being imported.");
}
submitJobs(jobs.begin(), jobs.end(), true);
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalImportedJobs, jobs.size());
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalTreePaths, jobs.size());
}
ExecutionPathSetPin JobManager::exportJobs(ExecutionPathSetPin seeds,
std::vector<int> &counts,
std::map<unsigned,JobReconstruction*> &reconstruct) {
boost::unique_lock<boost::mutex> lock(jobsMutex);
std::vector<WorkerTree::Node*> roots;
std::vector<ExecutionJob*> jobs;
std::map<WorkerTree::Node*, JobReconstruction*> nodeReconMap;
std::map<WorkerTree::Node*, unsigned> encodeMap;
std::set<WorkerTree::Node*> nodeSet;
// First, collect the set of jobs we'll be working with
tree->getNodes(WORKER_LAYER_JOBS, seeds, roots, (std::map<unsigned,WorkerTree::Node*>*)NULL);
for (unsigned int i = 0; i < seeds->count(); i++) {
selectJobs(roots[i], jobs, (counts.size() > 0) ? counts[i] : 0);
}
for (std::vector<ExecutionJob*>::iterator it = jobs.begin(); it != jobs.end(); it++) {
ExecutionJob *job = *it;
WorkerTree::Node *node = job->getNode().get();
JobReconstruction *reconJob = getJobReconstruction(job);
nodeReconMap[node] = reconJob;
reconJob->appendNodes(nodeSet);
}
// Do this before de-registering the jobs, in order to keep the nodes pinned
ExecutionPathSetPin paths = tree->buildPathSet(nodeSet.begin(),
nodeSet.end(), &encodeMap);
for (std::map<WorkerTree::Node*, JobReconstruction*>::iterator it = nodeReconMap.begin();
it != nodeReconMap.end(); it++) {
reconstruct[encodeMap[it->first]] = it->second;
it->second->encode(encodeMap);
}
CLOUD9_DEBUG("Exporting " << jobs.size() << " jobs");
// De-register the jobs with the worker
for (std::vector<ExecutionJob*>::iterator it = jobs.begin(); it != jobs.end(); it++) {
// Cancel each job
ExecutionJob *job = *it;
assert(currentJob != job);
finalizeJob(job, true, false);
}
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalExportedJobs, paths->count());
cloud9::instrum::theInstrManager.decStatistic(
cloud9::instrum::TotalTreePaths, paths->count());
return paths;
}
/* Strategy Handler Triggers *************************************************/
void JobManager::fireActivateState(SymbolicState *state) {
if (!state->_active) {
state->_active = true;
selStrategy->onStateActivated(state);
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::CurrentActiveStateCount);
}
}
void JobManager::fireDeactivateState(SymbolicState *state) {
if (state->_active) {
state->_active = false;
selStrategy->onStateDeactivated(state);
cloud9::instrum::theInstrManager.decStatistic(
cloud9::instrum::CurrentActiveStateCount);
}
}
void JobManager::fireUpdateState(SymbolicState *state, WorkerTree::Node *oldNode) {
if (state->_active) {
selStrategy->onStateUpdated(state, oldNode);
}
}
void JobManager::fireStepState(SymbolicState *state) {
if (state->_active) {
selStrategy->onStateStepped(state);
}
}
void JobManager::fireAddJob(ExecutionJob *job) {
selStrategy->onJobAdded(job);
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::CurrentJobCount);
}
void JobManager::fireRemovingJob(ExecutionJob *job) {
selStrategy->onRemovingJob(job);
cloud9::instrum::theInstrManager.decStatistic(
cloud9::instrum::CurrentJobCount);
}
/* Job Execution Methods ******************************************************/
void JobManager::executeJobsBatch(boost::unique_lock<boost::mutex> &lock,
ExecutionJob *origJob, bool spawnNew, bool canBatch, uint32_t batchDest) {
Timer timer;
timer.start();
WorkerTree::NodePin nodePin = origJob->getNode();
if (origJob->reconstruct) {
// Replay job
executeJob(lock, origJob, canBatch, batchDest);
return;
}
double startTime = klee::util::getUserTime();
double currentTime = startTime;
do {
executeJob(lock, (**nodePin).getJob(), canBatch, batchDest);
if ((**nodePin).getJob() == NULL) {
WorkerTree::Node *newNode = tree->selectRandomLeaf(WORKER_LAYER_JOBS, nodePin.get(), theRNG);
if ((**newNode).getJob() == NULL)
break;
nodePin = (**newNode).getJob()->getNode();
}
currentTime = klee::util::getUserTime();
if (!batching) {
SymbolicState *state = (**nodePin).getSymbolicState();
if (state && !(**state).pc()->isBBHead)
continue;
}
} while (batching && currentTime - startTime < JobQuanta);
timer.stop();
cloud9::instrum::theInstrManager.recordEvent(
cloud9::instrum::InstructionBatch, timer);
//CLOUD9_DEBUG("Batched " << count << " jobs");
}
void JobManager::executeJob(boost::unique_lock<boost::mutex> &lock,
ExecutionJob *job, bool canBatch, uint32_t batchDest) {
WorkerTree::NodePin nodePin = job->getNode(); // Keep the node around until we finish with it
currentJob = job;
if (job->reconstruct) {
JobReconstruction *reconstruct = job->reconstruct;
job->reconstruct = NULL;
cloud9::instrum::theInstrManager.recordEvent(
cloud9::instrum::JobExecutionState, "startReplay");
runJobReconstruction(lock, reconstruct);
// Release all the associated pins
delete reconstruct;
cloud9::instrum::theInstrManager.recordEvent(
cloud9::instrum::JobExecutionState, "endReplay");
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalReplayedJobs);
}
if (currentJob) {
if (!(**job->getNode().get()).getSymbolicState()) {
CLOUD9_DEBUG("BUG! Could not replay the state to the job position.");
if (job->getNode()->layerExists(WORKER_LAYER_STATES)) {
dumpSymbolicTree(NULL, WorkerNodeDecorator(nodePin.get()));
}
finalizeJob(job, false, true);
} else {
stepInNode(lock, nodePin.get(), 1/*canBatch ? -1 : 1*/, batchDest);
}
}
currentJob = NULL;
}
void JobManager::cleanInvalidJobs(WorkerTree::Node *rootNode) {
std::vector<WorkerTree::Node*> jobNodes;
if (!rootNode->layerExists(WORKER_LAYER_JOBS))
return;
tree->getLeaves(WORKER_LAYER_JOBS, rootNode, jobNodes);
CLOUD9_DEBUG("BUG! Cleaning " << jobNodes.size() << " broken jobs.");
for (std::vector<WorkerTree::Node*>::iterator it = jobNodes.begin();
it != jobNodes.end(); it++) {
WorkerTree::Node *node = *it;
assert(!node->layerExists(WORKER_LAYER_STATES));
ExecutionJob *job = (**node).job;
if (job != NULL)
finalizeJob(job, false, true);
}
}
void JobManager::getReconstructionTasks(WorkerTree::Node *node,
unsigned long offset, JobReconstruction *job,
std::set<std::pair<WorkerTree::Node*, unsigned long> > &reconstructed) {
// XXX Refactor this into something nicer
WorkerTree::Node *crtNode = node;
std::vector<WorkerTree::Node*> path;
while (crtNode != NULL) {
path.push_back(crtNode);
crtNode = crtNode->getParent();
}
for (std::vector<WorkerTree::Node*>::reverse_iterator it = path.rbegin();
it != path.rend(); it++) {
crtNode = *it;
if ((**crtNode).getMergePoints().size() > 0) {
// We'll have first to reconstruct the merged states
WorkerNodeInfo::merge_points_t &mp = (**crtNode).getMergePoints();
for (WorkerNodeInfo::merge_points_t::iterator it = mp.begin();
it != mp.end(); it++) {
std::pair<WorkerTree::Node*, unsigned long> dest, src;
dest = std::make_pair(crtNode, it->first.first);
src = std::make_pair(it->second.get(), it->first.second);
if (reconstructed.count(src) == 0) {
getReconstructionTasks(src.first, src.second, job, reconstructed);
}
if (reconstructed.count(dest) == 0) {
job->tasks.push_back(ReconstructionTask(tree, false, dest.second, dest.first, NULL));
if (DebugJobReconstruction)
CLOUD9_DEBUG("Creating reconstruction job for replay at " << *dest.first << ":" << dest.second);
reconstructed.insert(dest);
job->tasks.push_back(ReconstructionTask(tree, true, 0, dest.first, src.first));
if (DebugJobReconstruction)
CLOUD9_DEBUG("Creating reconstruction job for merging between " << *dest.first << " and " << *src.first);
}
}
}
}
job->tasks.push_back(ReconstructionTask(tree, false, offset, node, NULL));
reconstructed.insert(std::make_pair(node, offset));
if (DebugJobReconstruction)
CLOUD9_DEBUG("Creating reconstruction job for replay at " << *node << ":" << offset);
}
JobReconstruction *JobManager::getJobReconstruction(ExecutionJob *job) {
if (job->reconstruct) // The job is not yet reconstructed
return new JobReconstruction(*job->reconstruct);
WorkerTree::Node *node = job->getNode().get();
if (DebugJobReconstruction)
CLOUD9_DEBUG("Getting job reconstruction for " << *node << ":" << (**node).getSymbolicState()->_instrSinceFork);
assert((**node).getSymbolicState() != NULL);
JobReconstruction *reconstruct = new JobReconstruction();
std::set<std::pair<WorkerTree::Node*, unsigned long> > reconstructed;
getReconstructionTasks(node, (**node).getSymbolicState()->_instrSinceFork,
reconstruct, reconstructed);
return reconstruct;
}
void JobManager::runJobReconstruction(boost::unique_lock<boost::mutex> &lock,
JobReconstruction* job) {
if (DebugJobReconstruction)
CLOUD9_DEBUG("Running job reconstruction " << job);
for (std::list<ReconstructionTask>::iterator it = job->tasks.begin();
it != job->tasks.end(); it++) {
if (it->isMerge) {
if (DebugJobReconstruction)
CLOUD9_DEBUG("Reconstructing a merge between " << (*it->node1.get()) << " and " << (*it->node2.get()));
// Attempt state merging
SymbolicState *dest = (**it->node1).getSymbolicState();
SymbolicState *src = (**it->node2).getSymbolicState();
if (dest != NULL && src != NULL) {
if (!mergeStates(dest, src)) {
if (DebugJobReconstruction)
CLOUD9_DEBUG("BUG! Cannot merge states during reconstruction. Losing the source state.");
}
}
} else {
// Try to replay to this point
if (DebugJobReconstruction)
CLOUD9_DEBUG("Reconstructing a state at " << (*it->node1.get()) << ":" << it->offset);
WorkerTree::Node *brokenNode = NULL;
replayPath(lock, it->node1.get(), it->offset, brokenNode);
if (brokenNode != NULL) {
if (DebugJobReconstruction)
CLOUD9_DEBUG("BUG! Broken path replay during reconstruction");
cleanInvalidJobs(brokenNode);
}
}
}
}
void JobManager::requestStateDestroy(SymbolicState *state) {
pendingDeletions.insert(state);
}
void JobManager::processPendingDeletions() {
if (pendingDeletions.empty())
return;
std::set<SymbolicState*> workingSet;
workingSet.swap(pendingDeletions);
for (std::set<SymbolicState*>::iterator it = workingSet.begin();
it != workingSet.end(); it++) {
symbEngine->destroyState(&(**(*it)));
}
}
long JobManager::stepInNode(boost::unique_lock<boost::mutex> &lock,
WorkerTree::Node *node, long count, uint32_t batchDest) {
assert((**node).symState != NULL);
// Keep the node alive until we finish with it
WorkerTree::NodePin nodePin = node->pin(WORKER_LAYER_STATES);
long totalExec = 0;
while ((**node).symState != NULL) {
SymbolicState *state = (**node).symState;
currentState = state;
if (!codeBreaks.empty()) {
if (codeBreaks.find((**state).pc()->info->assemblyLine)
!= codeBreaks.end()) {
// We hit a breakpoint
fireBreakpointHit(node);
}
}
//if (replaying)
// fprintf(stderr, "%d ", state->getKleeState()->pc()->info->assemblyLine);
if (state->collectProgress) {
state->_instrProgress.push_back((**state).pc());
}
// Execute the instruction
state->_instrSinceFork++;
lock.unlock();
processPendingDeletions();
if (currentState) {
symbEngine->stepInState(&(**state));
}
lock.lock();
if (currentState) {
totalExec++;
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalProcInstructions);
if (replaying)
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalReplayInstructions);
}
if (count == 1) {
break;
} else if (count > 1) {
count--;
} else {
if (currentState && (**currentState).getMergeIndex() == batchDest) {
CLOUD9_DEBUG("Found batching destination!");
break;
}
}
}
currentState = NULL;
return totalExec;
}
void JobManager::replayPath(boost::unique_lock<boost::mutex> &lock,
WorkerTree::Node *pathEnd, unsigned long offset,
WorkerTree::Node *&brokenEnd) {
Timer timer;
timer.start();
std::vector<int> path;
WorkerTree::Node *crtNode = pathEnd;
brokenEnd = NULL;
//CLOUD9_DEBUG("Replaying path: " << *crtNode);
// Find the state to pick from
while (crtNode != NULL && (**crtNode).symState == NULL) {
assert(crtNode->layerExists(WORKER_LAYER_SKELETON));
path.push_back(crtNode->getIndex());
crtNode = crtNode->getParent();
}
if (crtNode == NULL) {
if (DebugJobReconstruction)
CLOUD9_DEBUG("Could not find a starting state to replay from.");
return;
}
std::reverse(path.begin(), path.end());
//CLOUD9_DEBUG("Started path replay at position: " << *crtNode);
replaying = true;
// Perform the replay work
for (unsigned int i = 0; i < path.size(); i++) {
if (!crtNode->layerExists(WORKER_LAYER_STATES)) {
if (crtNode->getParent() && crtNode->getParent()->layerExists(WORKER_LAYER_STATES) &&
crtNode->getParent()->getChild(WORKER_LAYER_STATES, 1-crtNode->getIndex())) {
CLOUD9_DEBUG("Replay broken because of different branch taken");
WorkerTree::Node *node = crtNode->getParent()->getChild(WORKER_LAYER_STATES, 1-crtNode->getIndex());
if ((**node).getSymbolicState()) {
(**(**node).getSymbolicState()).getStackTrace().dump(std::cout);
}
}
// We have a broken replay
break;
}
if ((**crtNode).symState != NULL) {
stepInNode(lock, crtNode, -1, 0);
}
if (crtNode->layerExists(WORKER_LAYER_JOBS)) {
if (crtNode->getChild(WORKER_LAYER_JOBS, 1-path[i]) &&
!crtNode->getChild(WORKER_LAYER_STATES, 1-path[i])) {
// Broken replays...
cleanInvalidJobs(crtNode->getChild(WORKER_LAYER_JOBS, 1-path[i]));
}
}
crtNode = crtNode->getChild(WORKER_LAYER_SKELETON, path[i]);
assert(crtNode != NULL);
}
// Now advance the state to the desired offset
if ((**crtNode).symState != NULL) {
long count = offset - (**crtNode).symState->_instrSinceFork;
if (count > 0) {
long result = stepInNode(lock, crtNode, count, 0);
if (result != count) {
CLOUD9_DEBUG("BUG! Could not set the state at the desired offset");
}
}
}
replaying = false;
if (!crtNode->layerExists(WORKER_LAYER_STATES)) {
assert((**crtNode).symState == NULL);
CLOUD9_ERROR("Replay broken, NULL state at the end of the path.");
brokenEnd = crtNode;
if (BreakOnReplayBroken) {
fireBreakpointHit(crtNode->getParent());
}
}
timer.stop();
cloud9::instrum::theInstrManager.recordEvent(cloud9::instrum::ReplayBatch, timer);
}
bool JobManager::mergeStates(SymbolicState* dest, SymbolicState *src) {
// Perform the actual merging
klee::ExecutionState *mState = symbEngine->merge(**dest, **src);
if (!mState) {
CLOUD9_DEBUG("States could not be merged...");
return false;
}
// Record the event...
WorkerTree::Node *destNode = dest->getNode().get();
// Pin the skeleton layer on source
WorkerTree::NodePin srcNodePin = tree->getNode(WORKER_LAYER_SKELETON,
src->getNode().get())->pin(WORKER_LAYER_SKELETON);
(**destNode).getMergePoints().push_back(std::make_pair(std::make_pair(dest->_instrSinceFork,
src->_instrSinceFork), srcNodePin));
// Update the destination state container
if (&(**dest) != mState) {
(**dest).setCloud9State(NULL);
dest->replaceKleeState(mState);
mState->setCloud9State(dest);
}
// Now terminate the source state. Issue this from the executor - this will
// propagate all way through the entire infrastructure
requestStateDestroy(src);
CLOUD9_DEBUG("State merged");
return true;
}
/* Symbolic Engine Callbacks **************************************************/
bool JobManager::onStateBranching(klee::ExecutionState *state, klee::ForkTag forkTag) {
switch (forkTag.forkClass) {
case KLEE_FORK_FAULTINJ:
return StratFaultInj;
default:
return false;
}
}
void JobManager::onStateBranched(klee::ExecutionState *kState,
klee::ExecutionState *parent, int index, klee::ForkTag forkTag) {
boost::unique_lock<boost::mutex> lock(jobsMutex);
assert(parent);
assert(kState);
//if (kState)
// CLOUD9_DEBUG("State branched: " << parent->getCloud9State()->getNode());
WorkerTree::NodePin pNode = parent->getCloud9State()->getNode();
updateTreeOnBranch(kState, parent, index, forkTag);
SymbolicState *state = kState->getCloud9State();
if (parent->getCloud9State()->collectProgress) {
state->collectProgress = true;
state->_instrProgress = parent->getCloud9State()->_instrProgress; // XXX This is totally inefficient
state->_instrPos = parent->getCloud9State()->_instrPos;
}
//CLOUD9_DEBUG("State forked at level " << state->getNode()->getLevel());
SymbolicState *pState = parent->getCloud9State();
if (pState->getNode()->layerExists(WORKER_LAYER_JOBS) || !replaying) {
fireUpdateState(pState, pNode.get());
} else {
fireUpdateState(pState, pNode.get());
fireDeactivateState(pState);
}
if (state->getNode()->layerExists(WORKER_LAYER_JOBS) || !replaying) {
fireActivateState(state);
}
// Reset the number of instructions since forking
state->_instrSinceFork = 0;
pState->_instrSinceFork = 0;
}
void JobManager::onStateDestroy(klee::ExecutionState *kState, bool silenced) {
boost::unique_lock<boost::mutex> lock(jobsMutex);
assert(kState);
if (replaying && DebugJobReconstruction) {
CLOUD9_DEBUG("State destroyed during replay");
kState->getStackTrace().dump(std::cout);
}
//CLOUD9_DEBUG("State destroyed");
SymbolicState *state = kState->getCloud9State();
pendingDeletions.erase(state);
if (currentState == state) {
currentState = NULL;
}
if (!silenced) {
processTestCase(state);
}
if (DumpInstrTraces) {
dumpInstructionTrace(state->getNode().get());
}
fireDeactivateState(state);
updateTreeOnDestroy(kState);
}
void JobManager::onOutOfResources(klee::ExecutionState *destroyedState) {
// TODO: Implement a job migration mechanism
CLOUD9_INFO("Executor ran out of resources. Dropping state.");
}
void JobManager::onEvent(klee::ExecutionState *kState,
unsigned int type, long int value) {
WorkerTree::Node *node = kState->getCloud9State()->getNode().get();
switch (type) {
case KLEE_EVENT_BREAKPOINT:
if (collectTraces) {
(**node).trace.appendEntry(new BreakpointEntry(value));
}
if (StratOracle) {
if (value == KLEE_BRK_START_TRACING) {
kState->getCloud9State()->collectProgress = true; // Enable progress collection in the manager
}
}
break;
default:
(**node).trace.appendEntry(new EventEntry(kState->getStackTrace(), type, value));
break;
}
}
void JobManager::onControlFlowEvent(klee::ExecutionState *kState,
ControlFlowEvent event) {
boost::unique_lock<boost::mutex> lock(jobsMutex);
SymbolicState *state = kState->getCloud9State();
if (!state) {
return;
}
WorkerTree::Node *node = state->getNode().get();
switch(event) {
case STEP:
// XXX Hack - do this only for basic block starts
if (kState->pc()->isBBHead)
fireStepState(state);
break;
default:
break;
}
// Add the instruction to the node trace
if (collectTraces) {
switch (event) {
case STEP:
(**node).trace.appendEntry(new InstructionTraceEntry(kState->pc()));
break;
case BRANCH_FALSE:
case BRANCH_TRUE:
//(**node).trace.appendEntry(new ConstraintLogEntry(state));
(**node).trace.appendEntry(new ControlFlowEntry(true, false, false));
break;
case CALL:
break;
case RETURN:
break;
}
}
}
void JobManager::onDebugInfo(klee::ExecutionState *kState,
const std::string &message) {
WorkerTree::Node *node = kState->getCloud9State()->getNode().get();
if (collectTraces) {
(**node).trace.appendEntry(new DebugLogEntry(message));
}
}
void JobManager::fireBreakpointHit(WorkerTree::Node *node) {
SymbolicState *state = (**node).symState;
CLOUD9_INFO("Breakpoint hit!");
CLOUD9_DEBUG("State at position: " << *node);
if (state) {
CLOUD9_DEBUG("State stack trace: " << *state);
klee::ExprPPrinter::printConstraints(std::cerr, (**state).constraints());
dumpStateTrace(node);
}
// Also signal a breakpoint, for stopping GDB
cloud9::breakSignal();
}
void JobManager::updateTreeOnBranch(klee::ExecutionState *kState,
klee::ExecutionState *parent, int index, klee::ForkTag forkTag) {
WorkerTree::NodePin pNodePin = parent->getCloud9State()->getNode();
(**pNodePin).forkTag = forkTag;
WorkerTree::Node *newNode, *oldNode;
// Obtain the new node pointers
oldNode = tree->getNode(WORKER_LAYER_STATES, pNodePin.get(), 1 - index);
parent->getCloud9State()->rebindToNode(oldNode);
newNode = tree->getNode(WORKER_LAYER_STATES, pNodePin.get(), index);
SymbolicState *state = new SymbolicState(kState, parent->getCloud9State());
state->rebindToNode(newNode);
if (!replaying) {
ExecutionJob *job = (**pNodePin).getJob();
if (job != NULL) {
oldNode = tree->getNode(WORKER_LAYER_JOBS, oldNode);
job->rebindToNode(oldNode);
newNode = tree->getNode(WORKER_LAYER_JOBS, newNode);
ExecutionJob *newJob = new ExecutionJob(newNode);
submitJob(newJob, false);
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalTreePaths);
} else {
CLOUD9_DEBUG("Job-less state terminated. Probably it was exported while the state was executing.");
}
}
}
void JobManager::updateTreeOnDestroy(klee::ExecutionState *kState) {
SymbolicState *state = kState->getCloud9State();
WorkerTree::Node *node = state->getNode().get();
if (ZombieNodes) {
// Pin the state on the skeleton layer
WorkerTree::NodePin zombiePin =
tree->getNode(WORKER_LAYER_SKELETON, node)->pin(WORKER_LAYER_SKELETON);
zombieNodes.insert(zombiePin);
}
if (node->layerExists(WORKER_LAYER_JOBS)) {
std::vector<WorkerTree::Node*> jobNodes;
tree->getLeaves(WORKER_LAYER_JOBS, node, jobNodes);
for (std::vector<WorkerTree::Node*>::iterator it = jobNodes.begin(); it != jobNodes.end(); it++) {
ExecutionJob *job = (**(*it)).getJob();
if (job != NULL) {
finalizeJob(job, false, false);
cloud9::instrum::theInstrManager.incStatistic(
cloud9::instrum::TotalProcJobs);
}
}
}
state->rebindToNode(NULL);
kState->setCloud9State(NULL);
delete state;
}
/* Statistics Management ******************************************************/
void JobManager::refineStatistics() {
std::set<WorkerTree::NodePin> newStats;
for (std::set<WorkerTree::NodePin>::iterator it = stats.begin(); it
!= stats.end(); it++) {
const WorkerTree::NodePin &nodePin = *it;
if (!nodePin->layerExists(WORKER_LAYER_JOBS)) {
// Statistic node invalidated
continue;
}
if (nodePin->getCount(WORKER_LAYER_JOBS) > 0) {
// Move along the path
WorkerTree::Node *left = nodePin->getChild(WORKER_LAYER_JOBS, 0);
WorkerTree::Node *right = nodePin->getChild(WORKER_LAYER_JOBS, 1);
if (left) {
WorkerTree::NodePin leftPin = tree->getNode(WORKER_LAYER_STATISTICS,
left)->pin(WORKER_LAYER_STATISTICS);
newStats.insert(leftPin);
}
if (right) {
WorkerTree::NodePin rightPin = tree->getNode(WORKER_LAYER_STATISTICS,
right)->pin(WORKER_LAYER_STATISTICS);
newStats.insert(rightPin);
}
} else {
newStats.insert(nodePin);
}
}
stats = newStats;
statChanged = true;
}
void JobManager::cleanupStatistics() {
for (std::set<WorkerTree::NodePin>::iterator it = stats.begin(); it
!= stats.end();) {
std::set<WorkerTree::NodePin>::iterator oldIt = it++;
WorkerTree::NodePin nodePin = *oldIt;
if (!nodePin->layerExists(WORKER_LAYER_JOBS)) {
stats.erase(oldIt);
statChanged = true;
}
}
if (stats.empty()) {
// Add back the root state in the statistics
WorkerTree::NodePin rootPin = tree->getRoot()->pin(WORKER_LAYER_STATISTICS);
stats.insert(rootPin);
statChanged = true;
}
}
#if 0
void JobManager::getStatisticsData(std::vector<int> &data,
ExecutionPathSetPin &paths, bool onlyChanged) {
boost::unique_lock<boost::mutex> lock(jobsMutex);
cleanupStatistics();
if (statChanged || !onlyChanged) {
std::vector<WorkerTree::Node*> newStats;
for (std::set<WorkerTree::NodePin>::iterator it = stats.begin(); it
!= stats.end(); it++) {
newStats.push_back((*it).get());
}
paths = tree->buildPathSet(newStats.begin(), newStats.end());
statChanged = false;
//CLOUD9_DEBUG("Sent node set: " << getASCIINodeSet(newStats.begin(), newStats.end()));
}
data.clear();
for (std::set<WorkerTree::NodePin>::iterator it = stats.begin(); it
!= stats.end(); it++) {
const WorkerTree::NodePin &crtNodePin = *it;
unsigned int jobCount = countJobs(crtNodePin.get());
data.push_back(jobCount);
}
//CLOUD9_DEBUG("Sent data set: " << getASCIIDataSet(data.begin(), data.end()));
}
#else
void JobManager::getStatisticsData(std::vector<int> &data,
ExecutionPathSetPin &paths, bool onlyChanged) {
boost::unique_lock<boost::mutex> lock(jobsMutex);
paths = ExecutionPathSet::getRootSet();
data.clear();
data.push_back(jobCount);
}
#endif
/* Coverage Management ********************************************************/
void JobManager::getUpdatedLocalCoverage(cov_update_t &data) {
theStatisticManager->collectChanges(stats::locallyCoveredInstructions, data);
theStatisticManager->resetChanges(stats::locallyCoveredInstructions);
}
void JobManager::setUpdatedGlobalCoverage(const cov_update_t &data) {
for (cov_update_t::const_iterator it = data.begin(); it != data.end(); it++) {
assert(it->second != 0 && "code uncovered after update");
uint32_t index = it->first;
if (!theStatisticManager->getIndexedValue(
stats::globallyCoveredInstructions, index)) {
theStatisticManager->incrementIndexedValue(
stats::globallyCoveredInstructions, index, 1);
theStatisticManager->incrementIndexedValue(
stats::globallyUncoveredInstructions, index, (uint64_t) -1);
assert(!theStatisticManager->getIndexedValue(stats::globallyUncoveredInstructions, index));
}
}
}
uint32_t JobManager::getCoverageIDCount() const {
return symbEngine->getModule()->infos->getMaxID();
}
/* Debugging Support **********************************************************/
void JobManager::setPathBreakpoint(ExecutionPathPin path) {
assert(0 && "Not yet implemented"); // TODO: Implement this as soon as the
// tree data structures are refactored
}
void JobManager::setCodeBreakpoint(int assemblyLine) {
CLOUD9_INFO("Code breakpoint at assembly line " << assemblyLine);
codeBreaks.insert(assemblyLine);
}
void JobManager::dumpStateTrace(WorkerTree::Node *node) {
if (!collectTraces) {
// We have nothing collected, why bother?
return;
}
// Get a file to dump the path into
char fileName[256];
snprintf(fileName, 256, "pathDump%05d.txt", traceCounter);
traceCounter++;
CLOUD9_INFO("Dumping state trace in file '" << fileName << "'");
std::ostream *os = kleeHandler->openOutputFile(fileName);
assert(os != NULL);
(*os) << (*node) << std::endl;
SymbolicState *state = (**node).symState;
assert(state != NULL);
serializeExecutionTrace(*os, state);
delete os;
}
void JobManager::dumpInstructionTrace(WorkerTree::Node *node) {
if (!collectTraces)
return;
char fileName[256];
snprintf(fileName, 256, "instrDump%05d.txt", traceCounter);
traceCounter++;
CLOUD9_INFO("Dumping instruction trace in file " << fileName);
std::ostream *os = kleeHandler->openOutputFile(fileName);
assert(os != NULL);
serializeInstructionTrace(*os, node);
delete os;
}
}
}
| 29.686209 | 117 | 0.660792 | [
"object",
"vector"
] |
d013f775700f21b8d7891bc28b65e61d44e3d9b2 | 386 | cpp | C++ | lang/C++/horners-rule-for-polynomial-evaluation-1.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 5 | 2021-01-29T20:08:05.000Z | 2022-03-22T06:16:05.000Z | lang/C++/horners-rule-for-polynomial-evaluation-1.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/horners-rule-for-polynomial-evaluation-1.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2021-04-13T04:19:31.000Z | 2021-04-13T04:19:31.000Z | #include <iostream>
#include <vector>
using namespace std;
double horner(vector<double> v, double x)
{
double s = 0;
for( vector<double>::const_reverse_iterator i = v.rbegin(); i != v.rend(); i++ )
s = s*x + *i;
return s;
}
int main()
{
double c[] = { -19, 7, -4, 6 };
vector<double> v(c, c + sizeof(c)/sizeof(double));
cout << horner(v, 3.0) << endl;
return 0;
}
| 17.545455 | 82 | 0.582902 | [
"vector"
] |
d017ffcd49ce71a33460a41415ae5e668f284cf0 | 1,032 | hpp | C++ | Library/Source/EnergyManager/Benchmarking/Workloads/Workload.hpp | NB4444/BachelorProjectEnergyManager | d1fd93dcc83af6d6acd36b7efda364ac2aab90eb | [
"MIT"
] | null | null | null | Library/Source/EnergyManager/Benchmarking/Workloads/Workload.hpp | NB4444/BachelorProjectEnergyManager | d1fd93dcc83af6d6acd36b7efda364ac2aab90eb | [
"MIT"
] | null | null | null | Library/Source/EnergyManager/Benchmarking/Workloads/Workload.hpp | NB4444/BachelorProjectEnergyManager | d1fd93dcc83af6d6acd36b7efda364ac2aab90eb | [
"MIT"
] | null | null | null | #pragma once
#include "EnergyManager/Benchmarking/Operations/Operation.hpp"
#include "EnergyManager/Hardware/GPU.hpp"
#include "EnergyManager/Utility/Runnable.hpp"
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace EnergyManager {
namespace Benchmarking {
namespace Workloads {
/**
* A workload of Operations that use dummy data to simulate a real workload.
*/
class Workload : public Utility::Runnable {
/**
* The Operations to perform.
*/
std::vector<std::shared_ptr<Operations::Operation>> operations_;
protected:
void onRun() final;
public:
/**
* Creates a new Workload.
* @param operations The Operations to perform.
*/
explicit Workload(std::vector<std::shared_ptr<Operations::Operation>> operations = {});
/**
* Adds an Operation to the Workload.
* @param operation The Operation to add.
*/
void addOperation(const std::shared_ptr<Operations::Operation>& operation);
};
}
}
} | 24 | 91 | 0.679264 | [
"vector"
] |
d01ae8a45113b0a823dd2d47e80249e5ca6931a8 | 2,331 | cc | C++ | src/tir/transforms/convert_for_loops_serial.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 4,640 | 2017-08-17T19:22:15.000Z | 2019-11-04T15:29:46.000Z | src/tir/transforms/convert_for_loops_serial.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 3,022 | 2020-11-24T14:02:31.000Z | 2022-03-31T23:55:31.000Z | src/tir/transforms/convert_for_loops_serial.cc | XiaoSong9905/tvm | 48940f697e15d5b50fa1f032003e6c700ae1e423 | [
"Apache-2.0"
] | 1,352 | 2017-08-17T19:30:38.000Z | 2019-11-04T16:09:29.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* \file tir/transforms/convert_for_loops_serial.cc
* \brief Convert all for loops to serial for lesser memory consumption
*/
#include <tvm/arith/analyzer.h>
#include <tvm/runtime/device_api.h>
#include <tvm/tir/function.h>
#include <tvm/tir/stmt_functor.h>
#include <tvm/tir/transform.h>
namespace tvm {
namespace tir {
class ForLoopSerialConverter : public StmtExprMutator {
public:
ForLoopSerialConverter() = default;
Stmt operator()(const PrimFunc& func);
private:
Stmt VisitStmt_(const ForNode* op) override;
};
Stmt ForLoopSerialConverter::VisitStmt_(const ForNode* op) {
if (op->kind == ForKind::kParallel) {
return For(op->loop_var, op->min, op->extent, ForKind::kSerial, op->body, op->thread_binding,
op->annotations, op->span);
}
return StmtExprMutator::VisitStmt_(op);
}
Stmt ForLoopSerialConverter::operator()(const PrimFunc& func) {
return this->VisitStmt(func->body);
}
PrimFunc ConvertForLoopsToSerial(PrimFunc func) {
PrimFuncNode* fptr = func.CopyOnWrite();
fptr->body = ForLoopSerialConverter()(func);
return func;
}
namespace transform {
Pass ConvertForLoopsToSerial() {
auto pass_func = [=](PrimFunc f, IRModule m, PassContext ctx) {
return ConvertForLoopsToSerial(std::move(f));
};
return CreatePrimFuncPass(pass_func, 0, "tir.ConvertForLoopsToSerial", {});
}
TVM_REGISTER_GLOBAL("tir.transform.ConvertForLoopsToSerial")
.set_body_typed(ConvertForLoopsToSerial);
} // namespace transform
} // namespace tir
} // namespace tvm
| 30.671053 | 97 | 0.737452 | [
"transform"
] |
d01ba09371de6eb7829957f33a46fa0c2c1d83b4 | 7,107 | hpp | C++ | include/Dice/einsum/internal/RawSubscript.hpp | lennartaustenfeld/hypertrie | 4a656a806f7fe66db1f5f123e1fcc78037dbc24c | [
"BSD-2-Clause"
] | 11 | 2020-03-02T05:02:20.000Z | 2020-12-20T09:52:58.000Z | include/Dice/einsum/internal/RawSubscript.hpp | lennartaustenfeld/hypertrie | 4a656a806f7fe66db1f5f123e1fcc78037dbc24c | [
"BSD-2-Clause"
] | 49 | 2020-01-29T16:41:04.000Z | 2021-09-03T09:40:25.000Z | include/Dice/einsum/internal/RawSubscript.hpp | lennartaustenfeld/hypertrie | 4a656a806f7fe66db1f5f123e1fcc78037dbc24c | [
"BSD-2-Clause"
] | 4 | 2020-03-24T11:14:31.000Z | 2021-02-02T13:59:38.000Z | #ifndef HYPERTRIE_RAWSUBSCRIPT_HPP
#define HYPERTRIE_RAWSUBSCRIPT_HPP
#include <vector>
#include <tuple>
#include <Dice/hash/DiceHash.hpp>
#include <tsl/hopscotch_set.h>
#include <tsl/hopscotch_map.h>
#include <itertools.hpp>
namespace einsum::internal {
/**
* A Einstein summation subscript label.
*/
using Label = char;
/**
* The subscript of an operand in Einstein summation. This consists of a sequence of labels.
*/
using OperandSc = std::vector<Label>;
/**
* The subscript of the result in Einstein summation. This consists of a sequence of labels.
*/
using ResultSc = OperandSc;
/**
* The subscripts of all operands in Einstein summation.
*/
using OperandsSc = std::vector<OperandSc>;
/**
* The position of an operand in Einstein summation. Starting at 0.
*/
using OperandPos = uint8_t;
/**
* The position of an Label in the subscript of an operand or of the result Einstein summation. Starting at 0.
*/
using LabelPos = uint8_t;
/**
* The positions of a single label in the subscript of a single operand.
*/
using LabelPossInOperand = std::vector<LabelPos>;
/**
* For a single label, this stores for each operand the positions of the label in the Einstein summation subscript
* of that operand.
*/
using LabelPossInOperands = std::vector<LabelPossInOperand>;
/**
* The RawSubscript represents the subscripts to the operands and result in Einstein summation.
* This class handles the actual storage, while Subscript provides a higher-level interface to the Subscript.
*/
class RawSubscript {
public:
/**
* The labels for each operand.
*/
mutable OperandsSc operands{};
/**
* The labels for the result.
*/
mutable ResultSc result{};
/**
* A hash of the Subscript.
*/
mutable std::size_t hash{};
public:
/**
* Generates a empty subscript. This subscript '<>-><>' has no operands and evaluates to the scalar 0.
*/
RawSubscript() = default;
RawSubscript(RawSubscript &) = default;
RawSubscript(const RawSubscript &) = default;
RawSubscript(RawSubscript &&) = default;
RawSubscript &operator=(const RawSubscript &) = default;
RawSubscript &operator=(RawSubscript &&) = default;
/**
* Constructs a RawSubscript.
* @param operands the labels of the operands
* @param result the labels of the result
*/
RawSubscript(const OperandsSc &operands, const ResultSc &result) :
operands(operands), result(result),
hash(Dice::hash::dice_hash(std::make_tuple(operands, result))) {}
/**
* Constructs a RawSubscript.
* @param operands the labels of the operands
* @param result the labels of the result
*/
/**
* Constructs a RawSubscript.
* @tparam PAIR_t works at least with std::pair and std::tuple
* @param raw_subscript the labels of the operands and the labels of the result in a container that supports std::get
*/
template<template<typename, typename> typename PAIR_t>
RawSubscript(const PAIR_t<OperandsSc, ResultSc> &raw_subscript) :
RawSubscript(std::get<0>(raw_subscript), std::get<1>(raw_subscript)) {}
/**
* @return number of operands
*/
[[nodiscard]] auto operandsCount() const noexcept {
return operands.size();
}
/**
* @param operand_pos the position of a specific operand
* @return number of labels at the specific operand
*/
[[nodiscard]] auto labelCount(OperandPos operand_pos) const {
return operands[operand_pos].size();
}
/**
* @return number of labels used in the result
*/
[[nodiscard]] auto resultLabelCount() const noexcept {
return result.size();
}
/**
* @return set of labels used in the operands
*/
[[nodiscard]] auto getOperandsLabelSet() const noexcept {
tsl::hopscotch_set<Label> operand_labels{};
for (const auto &operand : operands)
for (auto label : operand)
operand_labels.insert(label);
return operand_labels;
}
/**
* @return set of labels used in the result
*/
[[nodiscard]] auto getResultLabelSet() const noexcept {
tsl::hopscotch_set<Label> result_labels{};
for (auto label : result)
result_labels.insert(label);
return result_labels;
}
/**
* @param label the label to look for
* @return the positions of the given label in the operands' subscripts
*/
[[nodiscard]] auto getLabelPossInOperands(Label label) const noexcept {
LabelPossInOperands label_poss_in_operands{};
label_poss_in_operands.resize(operands.size());
for (auto i : iter::range(operands.size())) {
auto &label_poss_in_operand = label_poss_in_operands[i];
const auto &operand = operands[i];
for (const auto &[label_pos, current_label] : iter::enumerate(operand))
if (current_label == label)
label_poss_in_operand.push_back(label_pos);
}
return label_poss_in_operands;
}
/**
* @return a map from label to its position in the result. Only labels, that are in the result, are mapped.
*/
[[nodiscard]] auto getLabelPossInResult() const noexcept {
tsl::hopscotch_map<Label, LabelPos> label_poss_in_result{};
for (auto[pos, label]: iter::enumerate(result))
label_poss_in_result.insert({label, pos});
return label_poss_in_result;
}
/**
* Create a new RawSubscript without the given label.
* @param label the label to remove
* @return a new RawSubscript equal to this but without the given label.
*/
[[nodiscard]] auto removeLabel(Label label) const noexcept {
assert(getOperandsLabelSet().count(label));
OperandsSc next_operands{};
for (const auto &operand: operands) {
OperandSc new_operand{};
for (auto current_label: operand)
if (current_label != label)
new_operand.push_back(current_label);
if (not new_operand.empty()) {
next_operands.push_back(std::move(new_operand));
}
}
return RawSubscript(next_operands, result);
}
/**
* Check if another Subscript is different. It is also different if the labels are ordered alike but other
* labels are used.
* @param other another RawSubscript
* @return true if they are different, else false.
*/
[[nodiscard]] bool operator!=(const RawSubscript &other) const noexcept {
// check the number of operands
if (this->operands.size() != other.operands.size())
return true;
// check the number of labels in the result
if (this->result.size() != other.result.size())
return true;
// for each operand ...
for (const auto &[op1, op2] : iter::zip(this->operands, other.operands)) {
// check the number of labels
if (std::size(op1) != std::size(op2))
return true;
// check each label
for (const auto &[label1, label2] : iter::zip(op1, op2))
if (label1 != label2)
return true;
}
// check each label of the result
for (const auto &[label1, label2] : iter::zip(this->result, other.result))
if (label1 != label2)
return true;
return false;
};
};
}
template<>
struct std::hash<einsum::internal::RawSubscript> {
size_t operator()(const einsum::internal::RawSubscript &s) const { return s.hash; }
};
#endif //HYPERTRIE_RAWSUBSCRIPT_HPP
| 29.736402 | 119 | 0.68735 | [
"vector"
] |
d01dfda416faf05c1c82effce96685429a829ecf | 961 | hpp | C++ | TGEngine/Stdbase.hpp | ThePixly/TGEngine | aff5d5f42c3094dcc37253f4a3f5e09db560a4eb | [
"Apache-2.0"
] | null | null | null | TGEngine/Stdbase.hpp | ThePixly/TGEngine | aff5d5f42c3094dcc37253f4a3f5e09db560a4eb | [
"Apache-2.0"
] | null | null | null | TGEngine/Stdbase.hpp | ThePixly/TGEngine | aff5d5f42c3094dcc37253f4a3f5e09db560a4eb | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <stdio.h>
#include <iostream>
#include <cstddef>
#ifdef _WIN32
#define VK_USE_PLATFORM_WIN32_KHR
#endif
#undef VK_NO_PROTOTYPES
#include <vulkan/vulkan.hpp>
#include <vector>
#include <string>
#include "util/Annotations.hpp"
#include <thread>
#include "io/Properties.hpp"
#include "util/Math.hpp"
#include <glm/glm.hpp>
#include "util/TGVertex.hpp"
#include "Error.hpp"
extern prop::Properties* properties;
extern uint32_t image_count;
SINCE(0, 0, 4)
#define TGE_VERSION VK_MAKE_VERSION(0, 0, 4)
SINCE(0, 0, 1)
#define HANDEL(result)\
if (result != VK_SUCCESS) {\
TGERROR(result)\
}
SINCE(0, 0, 1)
#define HANDEL_RECREATE(result)\
if(result == VK_ERROR_OUT_OF_DATE_KHR){\
if(window_list[0]->minimized){\
return;\
}\
recreateSwapchain(ibuffer, vbuffer);\
} else {\
HANDEL(result)\
}
SINCE(0, 0, 1)
USAGE_DEBUG
#ifdef DEBUG
#define OUT_LV_DEBUG(out) std::cout << "DEBUG: " << out << std::endl;
#else
#define OUT_LV_DEBUG(out)
#endif
| 18.480769 | 69 | 0.727367 | [
"vector"
] |
d020fc7e091a926d0abb2ac9e55e6ecb8476fad2 | 6,005 | cpp | C++ | tests/test_sql.cpp | Samsung/ckm | a61e9ce01fa45323b381e6456d07117516d2e55d | [
"Apache-2.0"
] | 10 | 2015-06-02T09:16:16.000Z | 2022-03-18T11:30:21.000Z | tests/test_sql.cpp | Samsung/ckm | a61e9ce01fa45323b381e6456d07117516d2e55d | [
"Apache-2.0"
] | null | null | null | tests/test_sql.cpp | Samsung/ckm | a61e9ce01fa45323b381e6456d07117516d2e55d | [
"Apache-2.0"
] | 6 | 2017-01-28T04:21:33.000Z | 2022-02-07T03:25:43.000Z | /*
* Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
*
* Contact: Kyungwook Tak <k.tak@samsung.com>
*
* 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
*
* @file test_sql.cpp
* @author Zofia Abramowska (z.abramowska@samsung.com)
* @version
* @brief
*/
#include <dpl/db/sql_connection.h>
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <sstream>
#include <assert.h>
#include <sqlcipher.h>
#include <ckm/ckm-type.h>
#include <errno.h>
#include <test_common.h>
#pragma GCC diagnostic push
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
const char *encrypt_me = "/tmp/encryptme.db";
const char *encrypt_me_not = "/tmp/encryptmenot.db";
const char *create_table = "CREATE TABLE t1(a,b);";
const char *insert_table = "INSERT INTO t1(a,b) VALUES ("
" 'one for the money',"
" 'two for the show');";
const char *select_table = "SELECT * FROM t1";
CKM::RawBuffer raw_password = createDefaultPass();
BOOST_AUTO_TEST_SUITE(SQL_TEST)
BOOST_AUTO_TEST_CASE(sqlTestConversion){
BOOST_REQUIRE_MESSAGE(raw_password.size() == RAW_PASS_SIZE,
"Password should have 32 characters, got: " << raw_password.size());
std::string pass_check = rawToHexString(raw_password);
BOOST_REQUIRE_MESSAGE(pass_check.length() == HEX_PASS_SIZE,
"Hex string should have 64 characters, got: " << pass_check.length());
BOOST_CHECK(pass_check == pattern);
}
BOOST_AUTO_TEST_CASE(sqlTestSetKeyTooShort) {
using namespace CKM::DB;
BOOST_CHECK(unlink(encrypt_me_not) == 0 || errno == ENOENT);
SqlConnection connection(encrypt_me_not,
SqlConnection::Flag::CRW);
CKM::RawBuffer wrong_key(RAW_PASS_SIZE - 1, 1);
BOOST_REQUIRE_THROW(connection.SetKey(wrong_key),
SqlConnection::Exception::InvalidArguments);
}
BOOST_AUTO_TEST_CASE(sqlTestSetKeyTooLong) {
using namespace CKM::DB;
BOOST_CHECK(unlink(encrypt_me_not) == 0 || errno == ENOENT);
SqlConnection connection(encrypt_me_not,
SqlConnection::Flag::CRW);
CKM::RawBuffer wrong_key(RAW_PASS_SIZE + 1, 1);
BOOST_REQUIRE_THROW(connection.SetKey(wrong_key),
SqlConnection::Exception::InvalidArguments);
}
BOOST_AUTO_TEST_CASE(sqlTestConnectionUnencrypted) {
using namespace CKM::DB;
BOOST_CHECK(unlink(encrypt_me_not) == 0 || errno == ENOENT);
{
SqlConnection encrypting_you_not(encrypt_me_not,
SqlConnection::Flag::CRW);
BOOST_REQUIRE_NO_THROW(encrypting_you_not.ExecCommand(create_table));
BOOST_REQUIRE_NO_THROW(encrypting_you_not.ExecCommand(insert_table));
}
{
SqlConnection encrypting_you_not(encrypt_me_not,
SqlConnection::Flag::RW);
SqlConnection::DataCommandUniquePtr selectCommand;
BOOST_REQUIRE_NO_THROW(selectCommand = encrypting_you_not.
PrepareDataCommand(select_table));
BOOST_REQUIRE_NO_THROW(selectCommand->Step());
std::string value;
BOOST_REQUIRE_NO_THROW(value = selectCommand->GetColumnString(0));
BOOST_REQUIRE(value == "one for the money");
}
}
BOOST_AUTO_TEST_CASE(sqlTestConnectionEncrypted) {
using namespace CKM::DB;
BOOST_CHECK(unlink(encrypt_me) == 0 || errno == ENOENT);
{
SqlConnection encrypting_you(encrypt_me,
SqlConnection::Flag::CRW);
BOOST_REQUIRE_NO_THROW(encrypting_you.SetKey(raw_password));
BOOST_REQUIRE_NO_THROW(encrypting_you.ExecCommand(create_table));
BOOST_REQUIRE_NO_THROW(encrypting_you.ExecCommand(insert_table));
}
{
SqlConnection encrypting_you(encrypt_me,
SqlConnection::Flag::RW);
encrypting_you.SetKey(raw_password);
SqlConnection::DataCommandUniquePtr selectCommand;
BOOST_REQUIRE_NO_THROW(selectCommand = encrypting_you.
PrepareDataCommand(select_table));
BOOST_REQUIRE_NO_THROW(selectCommand->Step());
std::string value;
BOOST_REQUIRE_NO_THROW(value = selectCommand->GetColumnString(0));
BOOST_REQUIRE(value == "one for the money");
}
}
BOOST_AUTO_TEST_CASE(sqlTestConnectionEncryptedNegative) {
using namespace CKM::DB;
BOOST_CHECK(unlink(encrypt_me) == 0 || errno == ENOENT);
{
SqlConnection encrypting_you(encrypt_me,
SqlConnection::Flag::CRW);
BOOST_REQUIRE_NO_THROW(encrypting_you.SetKey(raw_password));
BOOST_REQUIRE_NO_THROW(encrypting_you.ExecCommand(create_table));
BOOST_REQUIRE_NO_THROW(encrypting_you.ExecCommand(insert_table));
}
{
SqlConnection encrypting_you(encrypt_me,
SqlConnection::Flag::RW);
CKM::RawBuffer wrong_password;
for(std::size_t i = 0; i < RAW_PASS_SIZE; i++) {
wrong_password.push_back(raw_password[i] + 1);
}
BOOST_REQUIRE_NO_THROW(encrypting_you.SetKey(wrong_password));
SqlConnection::DataCommandUniquePtr selectCommand;
BOOST_REQUIRE_THROW(selectCommand = encrypting_you.PrepareDataCommand(select_table),
SqlConnection::Exception::SyntaxError)
}
}
BOOST_AUTO_TEST_SUITE_END()
#pragma GCC diagnostic pop
| 38.49359 | 92 | 0.676436 | [
"vector"
] |
d027a84861399202650ea2820efc74e7366a4fb1 | 22,721 | cpp | C++ | code/wxWidgets/contrib/src/deprecated/propform.cpp | Bloodknight/NeuTorsion | a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea | [
"MIT"
] | 38 | 2016-02-20T02:46:28.000Z | 2021-11-17T11:39:57.000Z | code/wxWidgets/contrib/src/deprecated/propform.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 17 | 2016-02-20T02:19:55.000Z | 2021-02-08T15:15:17.000Z | code/wxWidgets/contrib/src/deprecated/propform.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 46 | 2016-02-20T02:47:33.000Z | 2021-01-31T15:46:05.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: propform.cpp
// Purpose: Property form classes
// Author: Julian Smart
// Modified by:
// Created: 04/01/98
// RCS-ID: $Id: propform.cpp,v 1.4 2004/09/27 19:24:44 ABX Exp $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#ifdef __GNUG__
#pragma implementation "propform.h"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/deprecated/setup.h"
#if wxUSE_PROPSHEET
#ifndef WX_PRECOMP
#include "wx/choice.h"
#include "wx/checkbox.h"
#include "wx/slider.h"
#include "wx/msgdlg.h"
#endif
#include "wx/deprecated/propform.h"
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
/*
* Property view
*/
IMPLEMENT_DYNAMIC_CLASS(wxPropertyFormView, wxPropertyView)
BEGIN_EVENT_TABLE(wxPropertyFormView, wxPropertyView)
EVT_BUTTON(wxID_OK, wxPropertyFormView::OnOk)
EVT_BUTTON(wxID_CANCEL, wxPropertyFormView::OnCancel)
EVT_BUTTON(wxID_HELP, wxPropertyFormView::OnHelp)
EVT_BUTTON(wxID_PROP_REVERT, wxPropertyFormView::OnRevert)
EVT_BUTTON(wxID_PROP_UPDATE, wxPropertyFormView::OnUpdate)
END_EVENT_TABLE()
bool wxPropertyFormView::sm_dialogCancelled = false;
wxPropertyFormView::wxPropertyFormView(wxWindow *propPanel, long flags):wxPropertyView(flags)
{
m_propertyWindow = propPanel;
m_managedWindow = NULL;
m_windowCloseButton = NULL;
m_windowCancelButton = NULL;
m_windowHelpButton = NULL;
m_detailedEditing = false;
}
wxPropertyFormView::~wxPropertyFormView(void)
{
}
void wxPropertyFormView::ShowView(wxPropertySheet *ps, wxWindow *panel)
{
m_propertySheet = ps;
AssociatePanel(panel);
// CreateControls();
// UpdatePropertyList();
}
// Update this view of the viewed object, called e.g. by
// the object itself.
bool wxPropertyFormView::OnUpdateView(void)
{
return true;
}
bool wxPropertyFormView::Check(void)
{
if (!m_propertySheet)
return false;
wxNode *node = m_propertySheet->GetProperties().GetFirst();
while (node)
{
wxProperty *prop = (wxProperty *)node->GetData();
wxPropertyValidator *validator = FindPropertyValidator(prop);
if (validator && validator->IsKindOf(CLASSINFO(wxPropertyFormValidator)))
{
wxPropertyFormValidator *formValidator = (wxPropertyFormValidator *)validator;
if (!formValidator->OnCheckValue(prop, this, m_propertyWindow))
return false;
}
node = node->GetNext();
}
return true;
}
bool wxPropertyFormView::TransferToPropertySheet(void)
{
if (!m_propertySheet)
return false;
wxNode *node = m_propertySheet->GetProperties().GetFirst();
while (node)
{
wxProperty *prop = (wxProperty *)node->GetData();
wxPropertyValidator *validator = FindPropertyValidator(prop);
if (validator && validator->IsKindOf(CLASSINFO(wxPropertyFormValidator)))
{
wxPropertyFormValidator *formValidator = (wxPropertyFormValidator *)validator;
formValidator->OnRetrieveValue(prop, this, m_propertyWindow);
}
node = node->GetNext();
}
return true;
}
bool wxPropertyFormView::TransferToDialog(void)
{
if (!m_propertySheet)
return false;
wxNode *node = m_propertySheet->GetProperties().GetFirst();
while (node)
{
wxProperty *prop = (wxProperty *)node->GetData();
wxPropertyValidator *validator = FindPropertyValidator(prop);
if (validator && validator->IsKindOf(CLASSINFO(wxPropertyFormValidator)))
{
wxPropertyFormValidator *formValidator = (wxPropertyFormValidator *)validator;
formValidator->OnDisplayValue(prop, this, m_propertyWindow);
}
node = node->GetNext();
}
return true;
}
bool wxPropertyFormView::AssociateNames(void)
{
if (!m_propertySheet || !m_propertyWindow)
return false;
wxWindowList::Node *node = m_propertyWindow->GetChildren().GetFirst();
while (node)
{
wxWindow *win = node->GetData();
if ( win->GetName() != wxEmptyString )
{
wxProperty *prop = m_propertySheet->GetProperty(win->GetName());
if (prop)
prop->SetWindow(win);
}
node = node->GetNext();
}
return true;
}
bool wxPropertyFormView::OnClose(void)
{
if (m_propertyWindow->IsKindOf(CLASSINFO(wxPropertyFormPanel)))
{
((wxPropertyFormPanel*)m_propertyWindow)->SetView(NULL);
}
delete this;
return true;
}
void wxPropertyFormView::OnOk(wxCommandEvent& WXUNUSED(event))
{
// Retrieve the value if any
if (!Check())
return;
sm_dialogCancelled = false;
TransferToPropertySheet();
m_managedWindow->Close(true);
}
void wxPropertyFormView::OnCancel(wxCommandEvent& WXUNUSED(event))
{
sm_dialogCancelled = true;
m_managedWindow->Close(true);
}
void wxPropertyFormView::OnHelp(wxCommandEvent& WXUNUSED(event))
{
}
void wxPropertyFormView::OnUpdate(wxCommandEvent& WXUNUSED(event))
{
if (Check())
TransferToPropertySheet();
}
void wxPropertyFormView::OnRevert(wxCommandEvent& WXUNUSED(event))
{
TransferToDialog();
}
void wxPropertyFormView::OnCommand(wxWindow& win, wxCommandEvent& event)
{
if (!m_propertySheet)
return;
if (win.GetName().empty())
return;
if (wxStrcmp(win.GetName(), wxT("ok")) == 0)
OnOk(event);
else if (wxStrcmp(win.GetName(), wxT("cancel")) == 0)
OnCancel(event);
else if (wxStrcmp(win.GetName(), wxT("help")) == 0)
OnHelp(event);
else if (wxStrcmp(win.GetName(), wxT("update")) == 0)
OnUpdate(event);
else if (wxStrcmp(win.GetName(), wxT("revert")) == 0)
OnRevert(event);
else
{
// Find a validator to route the command to.
wxNode *node = m_propertySheet->GetProperties().GetFirst();
while (node)
{
wxProperty *prop = (wxProperty *)node->GetData();
if (prop->GetWindow() && (prop->GetWindow() == &win))
{
wxPropertyValidator *validator = FindPropertyValidator(prop);
if (validator && validator->IsKindOf(CLASSINFO(wxPropertyFormValidator)))
{
wxPropertyFormValidator *formValidator = (wxPropertyFormValidator *)validator;
formValidator->OnCommand(prop, this, m_propertyWindow, event);
return;
}
}
node = node->GetNext();
}
}
}
// Extend event processing to call OnCommand
bool wxPropertyFormView::ProcessEvent(wxEvent& event)
{
if (wxEvtHandler::ProcessEvent(event))
return true;
else if (event.IsCommandEvent() && !event.IsKindOf(CLASSINFO(wxUpdateUIEvent)) && event.GetEventObject())
{
OnCommand(* ((wxWindow*) event.GetEventObject()), (wxCommandEvent&) event);
return true;
}
else
return false;
}
void wxPropertyFormView::OnDoubleClick(wxControl *item)
{
if (!m_propertySheet)
return;
// Find a validator to route the command to.
wxNode *node = m_propertySheet->GetProperties().GetFirst();
while (node)
{
wxProperty *prop = (wxProperty *)node->GetData();
if (prop->GetWindow() && ((wxControl *)prop->GetWindow() == item))
{
wxPropertyValidator *validator = FindPropertyValidator(prop);
if (validator && validator->IsKindOf(CLASSINFO(wxPropertyFormValidator)))
{
wxPropertyFormValidator *formValidator = (wxPropertyFormValidator *)validator;
formValidator->OnDoubleClick(prop, this, m_propertyWindow);
return;
}
}
node = node->GetNext();
}
}
/*
* Property form dialog box
*/
IMPLEMENT_DYNAMIC_CLASS(wxPropertyFormDialog, wxDialog)
BEGIN_EVENT_TABLE(wxPropertyFormDialog, wxDialog)
EVT_CLOSE(wxPropertyFormDialog::OnCloseWindow)
END_EVENT_TABLE()
wxPropertyFormDialog::wxPropertyFormDialog(wxPropertyFormView *v, wxWindow *parent, const wxString& title,
const wxPoint& pos, const wxSize& size, long style, const wxString& name):
wxDialog(parent, wxID_ANY, title, pos, size, style, name)
{
m_view = v;
m_view->AssociatePanel(this);
m_view->SetManagedWindow(this);
// SetAutoLayout(true);
}
void wxPropertyFormDialog::OnCloseWindow(wxCloseEvent& event)
{
if (m_view)
{
m_view->OnClose();
m_view = NULL;
this->Destroy();
}
else
event.Veto();
}
void wxPropertyFormDialog::OnDefaultAction(wxControl *item)
{
m_view->OnDoubleClick(item);
}
void wxPropertyFormDialog::OnCommand(wxWindow& win, wxCommandEvent& event)
{
if ( m_view )
m_view->OnCommand(win, event);
}
// Extend event processing to search the view's event table
bool wxPropertyFormDialog::ProcessEvent(wxEvent& event)
{
if ( !m_view || ! m_view->ProcessEvent(event) )
return wxEvtHandler::ProcessEvent(event);
else
return true;
}
/*
* Property form panel
*/
IMPLEMENT_DYNAMIC_CLASS(wxPropertyFormPanel, wxPanel)
void wxPropertyFormPanel::OnDefaultAction(wxControl *item)
{
m_view->OnDoubleClick(item);
}
void wxPropertyFormPanel::OnCommand(wxWindow& win, wxCommandEvent& event)
{
m_view->OnCommand(win, event);
}
// Extend event processing to search the view's event table
bool wxPropertyFormPanel::ProcessEvent(wxEvent& event)
{
if ( !m_view || ! m_view->ProcessEvent(event) )
return wxEvtHandler::ProcessEvent(event);
else
return true;
}
/*
* Property frame
*/
IMPLEMENT_DYNAMIC_CLASS(wxPropertyFormFrame, wxFrame)
BEGIN_EVENT_TABLE(wxPropertyFormFrame, wxFrame)
EVT_CLOSE(wxPropertyFormFrame::OnCloseWindow)
END_EVENT_TABLE()
void wxPropertyFormFrame::OnCloseWindow(wxCloseEvent& event)
{
if (m_view && m_view->OnClose())
this->Destroy();
else
event.Veto();
}
wxPanel *wxPropertyFormFrame::OnCreatePanel(wxFrame *parent, wxPropertyFormView *v)
{
return new wxPropertyFormPanel(v, parent);
}
bool wxPropertyFormFrame::Initialize(void)
{
m_propertyPanel = OnCreatePanel(this, m_view);
if (m_propertyPanel)
{
m_view->AssociatePanel(m_propertyPanel);
m_view->SetManagedWindow(this);
return true;
}
else
return false;
}
/*
* Property form specific validator
*/
IMPLEMENT_ABSTRACT_CLASS(wxPropertyFormValidator, wxPropertyValidator)
/*
* Default validators
*/
IMPLEMENT_DYNAMIC_CLASS(wxRealFormValidator, wxPropertyFormValidator)
///
/// Real number form validator
///
bool wxRealFormValidator::OnCheckValue( wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *parentWindow)
{
if (m_realMin == 0.0 && m_realMax == 0.0)
return true;
// The item used for viewing the real number: should be a text item.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow || !m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
return false;
wxString value(((wxTextCtrl *)m_propertyWindow)->GetValue());
float val = 0.0;
if (!StringToFloat(WXSTRINGCAST value, &val))
{
wxChar buf[200];
wxSprintf(buf, wxT("Value %s is not a valid real number!"), (const wxChar *)value);
wxMessageBox(buf, wxT("Property value error"), wxOK | wxICON_EXCLAMATION, parentWindow);
return false;
}
if (val < m_realMin || val > m_realMax)
{
wxChar buf[200];
wxSprintf(buf, wxT("Value must be a real number between %.2f and %.2f!"), m_realMin, m_realMax);
wxMessageBox(buf, wxT("Property value error"), wxOK | wxICON_EXCLAMATION, parentWindow);
return false;
}
return true;
}
bool wxRealFormValidator::OnRetrieveValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow) )
{
// The item used for viewing the real number: should be a text item.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow || !m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
return false;
wxString value(((wxTextCtrl *)m_propertyWindow)->GetValue());
if (value.Length() == 0)
return false;
float f = (float)wxAtof((const wxChar *)value);
property->GetValue() = f;
return true;
}
bool wxRealFormValidator::OnDisplayValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow) )
{
// The item used for viewing the real number: should be a text item.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow || !m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
return false;
wxTextCtrl *textItem = (wxTextCtrl *)m_propertyWindow;
textItem->SetValue(FloatToString(property->GetValue().RealValue()));
return true;
}
///
/// Integer validator
///
IMPLEMENT_DYNAMIC_CLASS(wxIntegerFormValidator, wxPropertyFormValidator)
bool wxIntegerFormValidator::OnCheckValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *parentWindow)
{
if (m_integerMin == 0.0 && m_integerMax == 0.0)
return true;
// The item used for viewing the real number: should be a text item or a slider
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow)
return false;
long val = 0;
if (m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
{
wxString value(((wxTextCtrl *)m_propertyWindow)->GetValue());
if (!StringToLong(WXSTRINGCAST value, &val))
{
wxChar buf[200];
wxSprintf(buf, wxT("Value %s is not a valid integer!"), (const wxChar *)value);
wxMessageBox(buf, wxT("Property value error"), wxOK | wxICON_EXCLAMATION, parentWindow);
return false;
}
}
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxSlider)))
{
val = (long)((wxSlider *)m_propertyWindow)->GetValue();
}
else
return false;
if (val < m_integerMin || val > m_integerMax)
{
wxChar buf[200];
wxSprintf(buf, wxT("Value must be an integer between %ld and %ld!"), m_integerMin, m_integerMax);
wxMessageBox(buf, wxT("Property value error"), wxOK | wxICON_EXCLAMATION, parentWindow);
return false;
}
return true;
}
bool wxIntegerFormValidator::OnRetrieveValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow))
{
// The item used for viewing the real number: should be a text item or a slider
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow)
return false;
if (m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
{
wxString value(((wxTextCtrl *)m_propertyWindow)->GetValue());
if (value.Length() == 0)
return false;
long i = wxAtol((const wxChar *)value);
property->GetValue() = i;
}
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxSlider)))
{
property->GetValue() = (long)((wxSlider *)m_propertyWindow)->GetValue();
}
else
return false;
return true;
}
bool wxIntegerFormValidator::OnDisplayValue( wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow))
{
// The item used for viewing the real number: should be a text item or a slider
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow)
return false;
if (m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
{
wxTextCtrl *textItem = (wxTextCtrl *)m_propertyWindow;
textItem->SetValue(LongToString(property->GetValue().IntegerValue()));
}
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxSlider)))
{
((wxSlider *)m_propertyWindow)->SetValue((int)property->GetValue().IntegerValue());
}
else
return false;
return true;
}
///
/// Boolean validator
///
IMPLEMENT_DYNAMIC_CLASS(wxBoolFormValidator, wxPropertyFormValidator)
bool wxBoolFormValidator::OnCheckValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow))
{
// The item used for viewing the boolean: should be a checkbox
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow || !m_propertyWindow->IsKindOf(CLASSINFO(wxCheckBox)))
return false;
return true;
}
bool wxBoolFormValidator::OnRetrieveValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow) )
{
// The item used for viewing the boolean: should be a checkbox.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow || !m_propertyWindow->IsKindOf(CLASSINFO(wxCheckBox)))
return false;
wxCheckBox *checkBox = (wxCheckBox *)m_propertyWindow;
property->GetValue() = (bool)checkBox->GetValue();
return true;
}
bool wxBoolFormValidator::OnDisplayValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow))
{
// The item used for viewing the boolean: should be a checkbox.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow || !m_propertyWindow->IsKindOf(CLASSINFO(wxCheckBox)))
return false;
wxCheckBox *checkBox = (wxCheckBox *)m_propertyWindow;
checkBox->SetValue((bool)property->GetValue().BoolValue());
return true;
}
///
/// String validator
///
IMPLEMENT_DYNAMIC_CLASS(wxStringFormValidator, wxPropertyFormValidator)
wxStringFormValidator::wxStringFormValidator(wxStringList *list, long flags):
wxPropertyFormValidator(flags)
{
m_strings = list;
}
bool wxStringFormValidator::OnCheckValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *parentWindow )
{
if (!m_strings)
return true;
// The item used for viewing the string: should be a text item, choice item or listbox.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow)
return false;
if (m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
{
wxTextCtrl *text = (wxTextCtrl *)m_propertyWindow;
if (!m_strings->Member(text->GetValue()))
{
wxString str( wxT("Value ") );
str += text->GetValue();
str += wxT(" is not valid.");
wxMessageBox(str, wxT("Property value error"), wxOK | wxICON_EXCLAMATION, parentWindow);
return false;
}
}
else
{
// Any other item constrains the string value,
// so we don't have to check it.
}
return true;
}
bool wxStringFormValidator::OnRetrieveValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow) )
{
// The item used for viewing the string: should be a text item, choice item or listbox.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow)
return false;
if (m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
{
wxTextCtrl *text = (wxTextCtrl *)m_propertyWindow;
property->GetValue() = text->GetValue();
}
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxListBox)))
{
wxListBox *lbox = (wxListBox *)m_propertyWindow;
if (lbox->GetSelection() != wxNOT_FOUND)
property->GetValue() = lbox->GetStringSelection();
}
/*
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxRadioBox)))
{
wxRadioBox *rbox = (wxRadioBox *)m_propertyWindow;
int n = 0;
if ((n = rbox->GetSelection()) != wxNOT_FOUND)
property->GetValue() = rbox->GetString(n);
}
*/
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxChoice)))
{
wxChoice *choice = (wxChoice *)m_propertyWindow;
if (choice->GetSelection() != wxNOT_FOUND)
property->GetValue() = choice->GetStringSelection();
}
else
return false;
return true;
}
bool wxStringFormValidator::OnDisplayValue(wxProperty *property, wxPropertyFormView *WXUNUSED(view),
wxWindow *WXUNUSED(parentWindow) )
{
// The item used for viewing the string: should be a text item, choice item or listbox.
wxWindow *m_propertyWindow = property->GetWindow();
if (!m_propertyWindow)
return false;
if (m_propertyWindow->IsKindOf(CLASSINFO(wxTextCtrl)))
{
wxTextCtrl *text = (wxTextCtrl *)m_propertyWindow;
text->SetValue(property->GetValue().StringValue());
}
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxListBox)))
{
wxListBox *lbox = (wxListBox *)m_propertyWindow;
if (lbox->GetCount() == 0 && m_strings)
{
// Try to initialize the listbox from 'strings'
wxStringList::Node *node = m_strings->GetFirst();
while (node)
{
wxChar *s = node->GetData();
lbox->Append(s);
node = node->GetNext();
}
}
lbox->SetStringSelection(property->GetValue().StringValue());
}
/*
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxRadioBox)))
{
wxRadioBox *rbox = (wxRadioBox *)m_propertyWindow;
rbox->SetStringSelection(property->GetValue().StringValue());
}
*/
else if (m_propertyWindow->IsKindOf(CLASSINFO(wxChoice)))
{
wxChoice *choice = (wxChoice *)m_propertyWindow;
if (choice->GetCount() == 0 && m_strings)
{
// Try to initialize the choice item from 'strings'
// XView doesn't allow this kind of thing.
wxStringList::Node *node = m_strings->GetFirst();
while (node)
{
wxChar *s = node->GetData();
choice->Append(s);
node = node->GetNext();
}
}
choice->SetStringSelection(property->GetValue().StringValue());
}
else
return false;
return true;
}
#endif // wxUSE_PROPSHEET
| 29.739529 | 117 | 0.641521 | [
"object"
] |
d028acc3a96527bea33d21b14b1665b43a1458e1 | 12,764 | cxx | C++ | couchbase/operations/management/eventing_upsert_function.cxx | avsej/couchbase-cxx-client | dd91c5bfe49953184db050db03fa181df257a281 | [
"Apache-2.0"
] | 1 | 2022-02-14T19:46:50.000Z | 2022-02-14T19:46:50.000Z | couchbase/operations/management/eventing_upsert_function.cxx | avsej/couchbase-cxx-client | dd91c5bfe49953184db050db03fa181df257a281 | [
"Apache-2.0"
] | 46 | 2021-09-15T13:49:29.000Z | 2022-02-22T15:12:16.000Z | couchbase/operations/management/eventing_upsert_function.cxx | avsej/couchbase-cxx-client | dd91c5bfe49953184db050db03fa181df257a281 | [
"Apache-2.0"
] | 5 | 2021-09-02T02:17:34.000Z | 2021-12-08T18:43:20.000Z | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2021 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <couchbase/errors.hxx>
#include <couchbase/operations/management/error_utils.hxx>
#include <couchbase/operations/management/eventing_upsert_function.hxx>
#include <couchbase/utils/json.hxx>
#include <tao/json/contrib/traits.hpp>
namespace couchbase::operations::management
{
std::error_code
eventing_upsert_function_request::encode_to(encoded_request_type& encoded, http_context& /* context */) const
{
tao::json::value body{};
body["appname"] = function.name;
body["appcode"] = function.code;
if (function.version) {
body["version"] = function.version.value();
}
if (function.enforce_schema) {
body["enforce_schema"] = function.enforce_schema.value();
}
if (function.handler_uuid) {
body["handleruuid"] = function.handler_uuid.value();
}
if (function.function_instance_id) {
body["function_instance_id"] = function.function_instance_id;
}
tao::json::value depcfg{};
depcfg["source_bucket"] = function.source_keyspace.bucket;
if (function.source_keyspace.scope) {
depcfg["source_scope"] = function.source_keyspace.scope;
}
if (function.source_keyspace.collection) {
depcfg["source_collection"] = function.source_keyspace.collection;
}
depcfg["metadata_bucket"] = function.metadata_keyspace.bucket;
if (function.metadata_keyspace.scope) {
depcfg["metadata_scope"] = function.metadata_keyspace.scope;
}
if (function.metadata_keyspace.collection) {
depcfg["metadata_collection"] = function.metadata_keyspace.collection;
}
if (!function.constant_bindings.empty()) {
std::vector<tao::json::value> constants{};
for (const auto& constant : function.constant_bindings) {
constants.emplace_back(tao::json::value{
{ "value", constant.alias },
{ "literal", constant.literal },
});
}
depcfg["constants"] = constants;
}
if (!function.url_bindings.empty()) {
std::vector<tao::json::value> urls{};
for (const auto& url : function.url_bindings) {
tao::json::value binding{
{ "value", url.alias },
{ "hostname", url.hostname },
{ "allow_cookies", url.allow_cookies },
{ "validate_ssl_certificate", url.validate_ssl_certificate },
};
if (std::holds_alternative<eventing::function_url_no_auth>(url.auth)) {
binding["auth_type"] = "no-auth";
} else if (std::holds_alternative<eventing::function_url_auth_basic>(url.auth)) {
const auto& auth = std::get<eventing::function_url_auth_basic>(url.auth);
binding["auth_type"] = "basic";
binding["username"] = auth.username;
binding["password"] = auth.password;
} else if (std::holds_alternative<eventing::function_url_auth_digest>(url.auth)) {
const auto& auth = std::get<eventing::function_url_auth_digest>(url.auth);
binding["auth_type"] = "digest";
binding["username"] = auth.username;
binding["password"] = auth.password;
} else if (std::holds_alternative<eventing::function_url_auth_bearer>(url.auth)) {
const auto& auth = std::get<eventing::function_url_auth_bearer>(url.auth);
binding["auth_type"] = "bearer";
binding["bearer_key"] = auth.key;
}
urls.emplace_back(binding);
}
depcfg["curl"] = urls;
}
if (!function.bucket_bindings.empty()) {
std::vector<tao::json::value> buckets{};
for (const auto& bucket : function.bucket_bindings) {
tao::json::value binding{
{ "alias", bucket.alias },
{ "bucket_name", bucket.name.bucket },
};
if (bucket.name.scope) {
binding["scope_name"] = bucket.name.scope;
}
if (bucket.name.collection) {
binding["collection_name"] = bucket.name.collection;
}
switch (bucket.access) {
case eventing::function_bucket_access::read_only:
binding["access"] = "r";
break;
case eventing::function_bucket_access::read_write:
binding["access"] = "rw";
break;
}
buckets.emplace_back(binding);
}
depcfg["buckets"] = buckets;
}
tao::json::value settings{};
if (function.settings.processing_status) {
switch (function.settings.processing_status.value()) {
case eventing::function_processing_status::running:
settings["processing_status"] = true;
break;
case eventing::function_processing_status::paused:
settings["processing_status"] = false;
break;
}
} else {
settings["processing_status"] = false;
}
if (function.settings.deployment_status) {
switch (function.settings.deployment_status.value()) {
case eventing::function_deployment_status::deployed:
settings["deployment_status"] = true;
break;
case eventing::function_deployment_status::undeployed:
settings["deployment_status"] = false;
break;
}
} else {
settings["deployment_status"] = false;
}
if (function.settings.cpp_worker_count) {
settings["cpp_worker_thread_count"] = function.settings.cpp_worker_count;
}
if (function.settings.dcp_stream_boundary) {
switch (function.settings.dcp_stream_boundary.value()) {
case eventing::function_dcp_boundary::everything:
settings["dcp_stream_boundary"] = "everything";
break;
case eventing::function_dcp_boundary::from_now:
settings["dcp_stream_boundary"] = "from_now";
break;
}
}
if (function.settings.description) {
settings["description"] = function.settings.description.value();
}
if (function.settings.log_level) {
switch (function.settings.log_level.value()) {
case eventing::function_log_level::info:
settings["log_level"] = "INFO";
break;
case eventing::function_log_level::error:
settings["log_level"] = "ERROR";
break;
case eventing::function_log_level::warning:
settings["log_level"] = "WARNING";
break;
case eventing::function_log_level::debug:
settings["log_level"] = "DEBUG";
break;
case eventing::function_log_level::trace:
settings["log_level"] = "TRACE";
break;
}
}
if (function.settings.language_compatibility) {
switch (function.settings.language_compatibility.value()) {
case eventing::function_language_compatibility::version_6_0_0:
settings["language_compatibility"] = "6.0.0";
break;
case eventing::function_language_compatibility::version_6_5_0:
settings["language_compatibility"] = "6.5.0";
break;
case eventing::function_language_compatibility::version_6_6_2:
settings["language_compatibility"] = "6.6.2";
break;
}
}
if (function.settings.execution_timeout) {
settings["execution_timeout"] = function.settings.execution_timeout.value().count();
}
if (function.settings.lcb_timeout) {
settings["lcb_timeout"] = function.settings.lcb_timeout.value().count();
}
if (function.settings.lcb_inst_capacity) {
settings["lcb_inst_capacity"] = function.settings.lcb_inst_capacity.value();
}
if (function.settings.lcb_retry_count) {
settings["lcb_retry_count"] = function.settings.lcb_retry_count.value();
}
if (function.settings.num_timer_partitions) {
settings["num_timer_partitions"] = function.settings.num_timer_partitions.value();
}
if (function.settings.sock_batch_size) {
settings["sock_batch_size"] = function.settings.sock_batch_size.value();
}
if (function.settings.tick_duration) {
settings["tick_duration"] = function.settings.tick_duration.value().count();
}
if (function.settings.timer_context_size) {
settings["timer_context_size"] = function.settings.timer_context_size.value();
}
if (function.settings.bucket_cache_size) {
settings["bucket_cache_size"] = function.settings.bucket_cache_size.value();
}
if (function.settings.bucket_cache_age) {
settings["bucket_cache_age"] = function.settings.bucket_cache_age.value().count();
}
if (function.settings.curl_max_allowed_resp_size) {
settings["curl_max_allowed_resp_size"] = function.settings.curl_max_allowed_resp_size.value();
}
if (function.settings.worker_count) {
settings["worker_count"] = function.settings.worker_count.value();
}
if (function.settings.app_log_max_size) {
settings["app_log_max_size"] = function.settings.app_log_max_size.value();
}
if (function.settings.app_log_max_files) {
settings["app_log_max_files"] = function.settings.app_log_max_files.value();
}
if (function.settings.checkpoint_interval) {
settings["checkpoint_interval"] = function.settings.checkpoint_interval.value().count();
}
if (!function.settings.handler_headers.empty()) {
settings["handler_headers"] = function.settings.handler_headers;
}
if (!function.settings.handler_footers.empty()) {
settings["handler_footers"] = function.settings.handler_footers;
}
if (function.settings.query_prepare_all) {
settings["n1ql_prepare_all"] = function.settings.query_prepare_all.value();
}
if (function.settings.enable_app_log_rotation) {
settings["enable_applog_rotation"] = function.settings.enable_app_log_rotation.value();
}
if (function.settings.user_prefix) {
settings["user_prefix"] = function.settings.user_prefix.value();
}
if (function.settings.app_log_dir) {
settings["app_log_dir"] = function.settings.app_log_dir.value();
}
if (function.settings.query_consistency) {
switch (function.settings.query_consistency.value()) {
case eventing::query_scan_consistency::not_bounded:
settings["n1ql_consistency"] = "none";
break;
case eventing::query_scan_consistency::request_plus:
settings["n1ql_consistency"] = "request";
break;
}
}
body["depcfg"] = depcfg;
body["settings"] = settings;
encoded.headers["content-type"] = "application/json";
encoded.method = "POST";
encoded.path = fmt::format("/api/v1/functions/{}", function.name);
encoded.body = utils::json::generate(body);
return {};
}
eventing_upsert_function_response
eventing_upsert_function_request::make_response(error_context::http&& ctx, const encoded_response_type& encoded) const
{
eventing_upsert_function_response response{ std::move(ctx) };
if (!response.ctx.ec) {
if (encoded.body.data().empty()) {
return response;
}
tao::json::value payload{};
try {
payload = utils::json::parse(encoded.body.data());
} catch (const tao::pegtl::parse_error&) {
response.ctx.ec = error::common_errc::parsing_failure;
return response;
}
auto [ec, problem] = extract_eventing_error_code(payload);
if (ec) {
response.ctx.ec = ec;
response.error.emplace(problem);
return response;
}
}
return response;
}
} // namespace couchbase::operations::management
| 37.321637 | 118 | 0.619477 | [
"vector"
] |
d02d9e39d195a90f9f8864c4706ce850e8666cb9 | 10,817 | hpp | C++ | include/Mono/Security/Cryptography/RSAManaged.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 23 | 2020-08-07T04:09:00.000Z | 2022-03-31T22:10:29.000Z | include/Mono/Security/Cryptography/RSAManaged.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 6 | 2021-09-29T23:47:31.000Z | 2022-03-30T20:49:23.000Z | include/Mono/Security/Cryptography/RSAManaged.hpp | sc2ad/BeatSaber-Quest-Codegen | ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab | [
"Unlicense"
] | 17 | 2020-08-20T19:36:52.000Z | 2022-03-30T18:28:24.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Security.Cryptography.RSA
#include "System/Security/Cryptography/RSA.hpp"
#include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Mono::Security::Cryptography
namespace Mono::Security::Cryptography {
}
// Forward declaring namespace: Mono::Math
namespace Mono::Math {
// Forward declaring type: BigInteger
class BigInteger;
}
// Forward declaring namespace: System::Security::Cryptography
namespace System::Security::Cryptography {
// Forward declaring type: RSAParameters
struct RSAParameters;
}
// Completed forward declares
// Type namespace: Mono.Security.Cryptography
namespace Mono::Security::Cryptography {
// Forward declaring type: RSAManaged
class RSAManaged;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(Mono::Security::Cryptography::RSAManaged);
DEFINE_IL2CPP_ARG_TYPE(Mono::Security::Cryptography::RSAManaged*, "Mono.Security.Cryptography", "RSAManaged");
// Type namespace: Mono.Security.Cryptography
namespace Mono::Security::Cryptography {
// Size: 0x70
#pragma pack(push, 1)
// Autogenerated type: Mono.Security.Cryptography.RSAManaged
// [TokenAttribute] Offset: FFFFFFFF
class RSAManaged : public System::Security::Cryptography::RSA {
public:
// Nested type: Mono::Security::Cryptography::RSAManaged::KeyGeneratedEventHandler
class KeyGeneratedEventHandler;
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// private System.Boolean isCRTpossible
// Size: 0x1
// Offset: 0x20
bool isCRTpossible;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean keypairGenerated
// Size: 0x1
// Offset: 0x21
bool keypairGenerated;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean m_disposed
// Size: 0x1
// Offset: 0x22
bool m_disposed;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: m_disposed and: d
char __padding2[0x5] = {};
// private Mono.Math.BigInteger d
// Size: 0x8
// Offset: 0x28
Mono::Math::BigInteger* d;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Math.BigInteger p
// Size: 0x8
// Offset: 0x30
Mono::Math::BigInteger* p;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Math.BigInteger q
// Size: 0x8
// Offset: 0x38
Mono::Math::BigInteger* q;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Math.BigInteger dp
// Size: 0x8
// Offset: 0x40
Mono::Math::BigInteger* dp;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Math.BigInteger dq
// Size: 0x8
// Offset: 0x48
Mono::Math::BigInteger* dq;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Math.BigInteger qInv
// Size: 0x8
// Offset: 0x50
Mono::Math::BigInteger* qInv;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Math.BigInteger n
// Size: 0x8
// Offset: 0x58
Mono::Math::BigInteger* n;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Math.BigInteger e
// Size: 0x8
// Offset: 0x60
Mono::Math::BigInteger* e;
// Field size check
static_assert(sizeof(Mono::Math::BigInteger*) == 0x8);
// private Mono.Security.Cryptography.RSAManaged/Mono.Security.Cryptography.KeyGeneratedEventHandler KeyGenerated
// Size: 0x8
// Offset: 0x68
Mono::Security::Cryptography::RSAManaged::KeyGeneratedEventHandler* KeyGenerated;
// Field size check
static_assert(sizeof(Mono::Security::Cryptography::RSAManaged::KeyGeneratedEventHandler*) == 0x8);
public:
// Get instance field reference: private System.Boolean isCRTpossible
bool& dyn_isCRTpossible();
// Get instance field reference: private System.Boolean keypairGenerated
bool& dyn_keypairGenerated();
// Get instance field reference: private System.Boolean m_disposed
bool& dyn_m_disposed();
// Get instance field reference: private Mono.Math.BigInteger d
Mono::Math::BigInteger*& dyn_d();
// Get instance field reference: private Mono.Math.BigInteger p
Mono::Math::BigInteger*& dyn_p();
// Get instance field reference: private Mono.Math.BigInteger q
Mono::Math::BigInteger*& dyn_q();
// Get instance field reference: private Mono.Math.BigInteger dp
Mono::Math::BigInteger*& dyn_dp();
// Get instance field reference: private Mono.Math.BigInteger dq
Mono::Math::BigInteger*& dyn_dq();
// Get instance field reference: private Mono.Math.BigInteger qInv
Mono::Math::BigInteger*& dyn_qInv();
// Get instance field reference: private Mono.Math.BigInteger n
Mono::Math::BigInteger*& dyn_n();
// Get instance field reference: private Mono.Math.BigInteger e
Mono::Math::BigInteger*& dyn_e();
// Get instance field reference: private Mono.Security.Cryptography.RSAManaged/Mono.Security.Cryptography.KeyGeneratedEventHandler KeyGenerated
Mono::Security::Cryptography::RSAManaged::KeyGeneratedEventHandler*& dyn_KeyGenerated();
// public System.Boolean get_PublicOnly()
// Offset: 0x1F876C0
bool get_PublicOnly();
// private System.Void GenerateKeyPair()
// Offset: 0x1F87030
void GenerateKeyPair();
// private System.Byte[] GetPaddedValue(Mono.Math.BigInteger value, System.Int32 length)
// Offset: 0x1F87AC4
::ArrayW<uint8_t> GetPaddedValue(Mono::Math::BigInteger* value, int length);
// public override System.Security.Cryptography.RSAParameters ExportParameters(System.Boolean includePrivateParameters)
// Offset: 0x1F87784
// Implemented from: System.Security.Cryptography.RSA
// Base method: System.Security.Cryptography.RSAParameters RSA::ExportParameters(System.Boolean includePrivateParameters)
System::Security::Cryptography::RSAParameters ExportParameters(bool includePrivateParameters);
// public override System.Void ImportParameters(System.Security.Cryptography.RSAParameters parameters)
// Offset: 0x1F87B84
// Implemented from: System.Security.Cryptography.RSA
// Base method: System.Void RSA::ImportParameters(System.Security.Cryptography.RSAParameters parameters)
void ImportParameters(System::Security::Cryptography::RSAParameters parameters);
}; // Mono.Security.Cryptography.RSAManaged
#pragma pack(pop)
static check_size<sizeof(RSAManaged), 104 + sizeof(Mono::Security::Cryptography::RSAManaged::KeyGeneratedEventHandler*)> __Mono_Security_Cryptography_RSAManagedSizeCheck;
static_assert(sizeof(RSAManaged) == 0x70);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Mono::Security::Cryptography::RSAManaged::get_PublicOnly
// Il2CppName: get_PublicOnly
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Mono::Security::Cryptography::RSAManaged::*)()>(&Mono::Security::Cryptography::RSAManaged::get_PublicOnly)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Mono::Security::Cryptography::RSAManaged*), "get_PublicOnly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Mono::Security::Cryptography::RSAManaged::GenerateKeyPair
// Il2CppName: GenerateKeyPair
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Mono::Security::Cryptography::RSAManaged::*)()>(&Mono::Security::Cryptography::RSAManaged::GenerateKeyPair)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(Mono::Security::Cryptography::RSAManaged*), "GenerateKeyPair", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: Mono::Security::Cryptography::RSAManaged::GetPaddedValue
// Il2CppName: GetPaddedValue
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<uint8_t> (Mono::Security::Cryptography::RSAManaged::*)(Mono::Math::BigInteger*, int)>(&Mono::Security::Cryptography::RSAManaged::GetPaddedValue)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("Mono.Math", "BigInteger")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Security::Cryptography::RSAManaged*), "GetPaddedValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value, length});
}
};
// Writing MetadataGetter for method: Mono::Security::Cryptography::RSAManaged::ExportParameters
// Il2CppName: ExportParameters
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Security::Cryptography::RSAParameters (Mono::Security::Cryptography::RSAManaged::*)(bool)>(&Mono::Security::Cryptography::RSAManaged::ExportParameters)> {
static const MethodInfo* get() {
static auto* includePrivateParameters = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Security::Cryptography::RSAManaged*), "ExportParameters", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{includePrivateParameters});
}
};
// Writing MetadataGetter for method: Mono::Security::Cryptography::RSAManaged::ImportParameters
// Il2CppName: ImportParameters
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Mono::Security::Cryptography::RSAManaged::*)(System::Security::Cryptography::RSAParameters)>(&Mono::Security::Cryptography::RSAManaged::ImportParameters)> {
static const MethodInfo* get() {
static auto* parameters = &::il2cpp_utils::GetClassFromName("System.Security.Cryptography", "RSAParameters")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Mono::Security::Cryptography::RSAManaged*), "ImportParameters", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{parameters});
}
};
| 49.619266 | 232 | 0.714339 | [
"vector"
] |
d0315ff49cdbaab5fa743c09555525e23a9c71c8 | 4,646 | cpp | C++ | tc bef160/PickTeam.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc bef160/PickTeam.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc bef160/PickTeam.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
class PickTeam {
public:
vector <string> pickPeople(int teamSize, vector <string> people) {
int n = (int)people.size();
int lim = 1<<n;
vector<string> names;
int a[20][20];
vector<string> sol(teamSize);
int best = -2000000000;
for (vector<string>::size_type i=0; i<people.size(); ++i) {
istringstream is(people[i]);
string t;
is >> t;
names.push_back(t);
for (int j=0; j<n; ++j) {
int x;
is >> x;
a[i][j] = x;
}
}
for (int i=0; i<lim; ++i) {
int cnt = 0;
vector<int> team;
for (int k=0; (1<<k) <= i; ++k)
if ((1<<k) & i) {
++cnt;
team.push_back(k);
}
if (cnt == teamSize) {
int sum = 0;
for (vector<int>::size_type j=0; j<team.size()-1; ++j)
for (vector<int>::size_type k=j+1; k<team.size(); ++k)
sum += a[team[j]][team[k]];
if (sum > best) {
for (vector<int>::size_type j=0; j<team.size(); ++j)
sol[j] = names[team[j]];
best = sum;
}
}
}
sort(sol.begin(), sol.end());
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <string> &Expected, const vector <string> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { int Arg0 = 3; string Arr1[] = {"ALICE 0 1 -1 3",
"BOB 1 0 2 -4",
"CAROL -1 2 0 2",
"DAVID 3 -4 2 0"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = { "ALICE", "CAROL", "DAVID" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, pickPeople(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 2; string Arr1[] = {"ALICE 0 1 -1 3",
"BOB 1 0 2 -4",
"CAROL -1 2 0 2",
"DAVID 3 -4 2 0"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = { "ALICE", "DAVID" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, pickPeople(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 2; string Arr1[] = {"A 0 -2 -2","B -2 0 -1","C -2 -1 0"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = { "B", "C" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, pickPeople(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 13; string Arr1[] = {"A 0 2 8 7 1 -4 -3 1 8 2 8 2 1 -3 7 1 3 9 -6 -5",
"A 2 0 0 7 -7 -5 8 -8 -9 -9 6 -9 -4 -8 8 1 7 0 3 3",
"A 8 0 0 -5 -5 -7 1 -3 1 9 -6 6 1 5 6 -9 8 6 -8 -8",
"A 7 7 -5 0 7 -5 3 9 8 3 -6 -5 -5 2 -6 2 -2 -1 -2 8",
"B 1 -7 -5 7 0 7 -2 -9 3 7 0 -2 1 1 -9 -3 -2 2 1 -2",
"B -4 -5 -7 -5 7 0 4 8 6 0 -1 4 1 -2 -9 4 0 -7 6 -2",
"B -3 8 1 3 -2 4 0 8 -1 1 -2 -7 5 0 -6 9 0 -3 1 3",
"B 1 -8 -3 9 -9 8 8 0 0 -2 5 0 5 8 3 5 2 4 5 4",
"C 8 -9 1 8 3 6 -1 0 0 8 -3 8 -6 -4 7 -4 1 -5 5 4",
"C 2 -9 9 3 7 0 1 -2 8 0 -9 -6 6 5 -8 -3 -8 2 2 4",
"C 8 6 -6 -6 0 -1 -2 5 -3 -9 0 2 7 8 2 -6 -4 -6 4 4",
"C 2 -9 6 -5 -2 4 -7 0 8 -6 2 0 0 -3 6 7 -1 2 -4 -2",
"D 1 -4 1 -5 1 1 5 5 -6 6 7 0 0 -7 -4 8 -6 -3 4 -6",
"D -3 -8 5 2 1 -2 0 8 -4 5 8 -3 -7 0 7 -3 5 -8 5 1",
"D 7 8 6 -6 -9 -9 -6 3 7 -8 2 6 -4 7 0 9 -5 -5 -8 3",
"D 1 1 -9 2 -3 4 9 5 -4 -3 -6 7 8 -3 9 0 -2 -7 8 -7",
"E 3 7 8 -2 -2 0 0 2 1 -8 -4 -1 -6 5 -5 -2 0 6 0 5",
"E 9 0 6 -1 2 -7 -3 4 -5 2 -6 2 -3 -8 -5 -7 6 0 4 8",
"E -6 3 -8 -2 1 6 1 5 5 2 4 -4 4 5 -8 8 0 4 0 1",
"E -5 3 -8 8 -2 -2 3 4 4 4 4 -2 -6 1 3 -7 5 8 1 0"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = { "A", "A", "B", "B", "B", "B", "C", "C", "C", "D", "D", "D", "E" }; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, pickPeople(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
PickTeam ___test;
___test.run_test(-1);
}
// END CUT HERE
| 43.018519 | 339 | 0.511408 | [
"vector"
] |
d0342de68dc4fe2d934fe2597fc873f26cd35db8 | 8,337 | cpp | C++ | earth_enterprise/src/fusion/portableglobe/cutspec_unittest.cpp | ezeeyahoo/earthenterprise | b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9 | [
"Apache-2.0"
] | 2,661 | 2017-03-20T22:12:50.000Z | 2022-03-30T09:43:19.000Z | earth_enterprise/src/fusion/portableglobe/cutspec_unittest.cpp | ezeeyahoo/earthenterprise | b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9 | [
"Apache-2.0"
] | 1,531 | 2017-03-24T17:20:32.000Z | 2022-03-16T18:11:14.000Z | earth_enterprise/src/fusion/portableglobe/cutspec_unittest.cpp | ezeeyahoo/earthenterprise | b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9 | [
"Apache-2.0"
] | 990 | 2017-03-24T11:54:28.000Z | 2022-03-22T11:51:47.000Z | // Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Unit Tests for portable packet bundles.
#include <limits.h>
#include <fstream> // NOLINT(readability/streams)
#include <iostream> // NOLINT(readability/streams)
#include <string>
#include <sstream>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "common/khFileUtils.h"
#include "common/qtpacket/quadtreepacket.h"
#include "fusion/portableglobe/cutspec.h"
#include "fusion/portableglobe/shared/packetbundle.h"
#include "fusion/portableglobe/shared/packetbundle_reader.h"
#include "fusion/portableglobe/shared/packetbundle_writer.h"
namespace fusion_portableglobe {
// Test class for cut specs.
class CutSpecTest : public testing::Test {
protected:
std::string test_directory;
HiresTree* hires_tree;
std::string qtnodes;
std::string exclusion_qtnodes;
virtual void SetUp() {
qtnodes.append("30132020333322002\n");
qtnodes.append("30132020333322003\n");
qtnodes.append("30132020333322012\n");
qtnodes.append("30132020333322013\n");
qtnodes.append("301320203333221022\n");
qtnodes.append("301320203333221023\n");
qtnodes.append("301320203333221032\n");
qtnodes.append("301320203333221033\n");
qtnodes.append("301320203333221132\n");
qtnodes.append("101323\n");
qtnodes.append("03212\n");
qtnodes.append("02\n");
exclusion_qtnodes.append("3013202033332301\n");
exclusion_qtnodes.append("3013202033332302\n");
hires_tree = NULL;
}
/**
* Helper routine to set up hi-res quadtree nodes.
*/
void SetUpTree() {
if (hires_tree != NULL) {
delete hires_tree;
}
hires_tree = new HiresTree();
std::stringstream nodes_stream(qtnodes);
hires_tree->LoadHiResQtNodes(&nodes_stream);
}
};
// Tests reading in a set of nodes and determining whether
// other strings are encompassed by the tree or not.
TEST_F(CutSpecTest, TestHiResTree) {
SetUpTree();
// Try ancestors of a specified node.
EXPECT_TRUE(hires_tree->IsTreePath("301320203"));
EXPECT_TRUE(hires_tree->IsTreePath("3013202033"));
EXPECT_TRUE(hires_tree->IsTreePath("301320203333"));
EXPECT_TRUE(hires_tree->IsTreePath("301320203333221"));
EXPECT_TRUE(hires_tree->IsTreePath("30132020333322103"));
// Try a specified node.
EXPECT_TRUE(hires_tree->IsTreePath("301320203333221032"));
// Try any child of a specified node.
EXPECT_TRUE(hires_tree->IsTreePath("3013202033332210320123"));
// Try any children of a specified node that is shorter than the
// default level.
EXPECT_TRUE(hires_tree->IsTreePath("02"));
EXPECT_TRUE(hires_tree->IsTreePath("020"));
EXPECT_TRUE(hires_tree->IsTreePath("021"));
EXPECT_TRUE(hires_tree->IsTreePath("022"));
EXPECT_TRUE(hires_tree->IsTreePath("023"));
EXPECT_TRUE(hires_tree->IsTreePath("020120121021021"));
EXPECT_TRUE(hires_tree->IsTreePath("02012012102102102210"));
// Try off by one at same levels.
// One off ancestors of a specified node.
EXPECT_FALSE(hires_tree->IsTreePath("301320201"));
EXPECT_FALSE(hires_tree->IsTreePath("3013202032"));
EXPECT_FALSE(hires_tree->IsTreePath("301320203330"));
EXPECT_FALSE(hires_tree->IsTreePath("301320203333222"));
EXPECT_FALSE(hires_tree->IsTreePath("30132020333322100"));
// One off a specified node.
EXPECT_FALSE(hires_tree->IsTreePath("301320203333221031"));
// Try all bad node.
EXPECT_FALSE(hires_tree->IsTreePath("22222"));
}
// Tests reading in a set of nodes from file and determining whether
// other strings are encompassed by the trees or not. Should be
// almost the same as the hires trees test except for the node
// below the default level and the one above the max level.
TEST_F(CutSpecTest, TestGlobeBuilderKeepNode) {
std::ofstream fout("/tmp/qtnodes.txt", std::ios::out);
fout.write(qtnodes.c_str(), qtnodes.size());
fout.close();
CutSpec cutspec("/tmp/qtnodes.txt", 0, 4, 18);
// Try ancestors of a specified node.
EXPECT_TRUE(cutspec.KeepNode("301320203"));
EXPECT_TRUE(cutspec.KeepNode("3013202033"));
EXPECT_TRUE(cutspec.KeepNode("301320203333"));
EXPECT_TRUE(cutspec.KeepNode("301320203333221"));
EXPECT_TRUE(cutspec.KeepNode("30132020333322103"));
// Try a specified node.
EXPECT_TRUE(cutspec.KeepNode("301320203333221032"));
// Even though hires tree says "yes", this fails because
// it is beyond the max level.
EXPECT_FALSE(cutspec.KeepNode("3013202033332210320123"));
// Try node below default level.
// This should pass because of the default level, even though
// the hires tree would say "no."
EXPECT_TRUE(cutspec.KeepNode("301"));
// Try any children of a specified node that is shorter than the
// default level.
EXPECT_TRUE(cutspec.KeepNode("02"));
EXPECT_TRUE(cutspec.KeepNode("020120121021021"));
EXPECT_FALSE(cutspec.KeepNode("02012012102102102210"));
// Try off by one at same levels.
// One off ancestors of a specified node.
EXPECT_FALSE(cutspec.KeepNode("301320201"));
EXPECT_FALSE(cutspec.KeepNode("3013202032"));
EXPECT_FALSE(cutspec.KeepNode("301320203330"));
EXPECT_FALSE(cutspec.KeepNode("301320203333222"));
EXPECT_FALSE(cutspec.KeepNode("30132020333322100"));
// One off a specified node.
EXPECT_FALSE(cutspec.KeepNode("301320203333221031"));
// Try all bad node.
EXPECT_FALSE(cutspec.KeepNode("22222"));
}
// Tests reading in a set of nodes from one file for inclusion
// and another file for exclusion.
TEST_F(CutSpecTest, TestGlobeBuilderKeepNodeExcludeNode) {
std::ofstream fout("/tmp/qtnodes.txt", std::ios::out);
fout.write(qtnodes.c_str(), qtnodes.size());
fout.close();
std::ofstream fout2("/tmp/exclusion_qtnodes.txt", std::ios::out);
fout2.write(exclusion_qtnodes.c_str(), exclusion_qtnodes.size());
fout2.close();
CutSpec cutspec("/tmp/qtnodes.txt", "/tmp/exclusion_qtnodes.txt", 0, 4, 18);
// Try ancestors of a specified node.
EXPECT_TRUE(cutspec.KeepNode("301320203"));
EXPECT_TRUE(cutspec.KeepNode("3013202033"));
EXPECT_TRUE(cutspec.KeepNode("301320203333"));
EXPECT_TRUE(cutspec.KeepNode("301320203333221"));
EXPECT_TRUE(cutspec.KeepNode("30132020333322103"));
// Try a specified node.
EXPECT_TRUE(cutspec.KeepNode("301320203333221032"));
// Even though hires tree says "yes", this fails because
// it is beyond the max level.
EXPECT_FALSE(cutspec.KeepNode("3013202033332210320123"));
// Try node below default level.
// This should pass because of the default level, even though
// the hires tree would say "no."
EXPECT_TRUE(cutspec.KeepNode("301"));
// Try any children of a specified node that is shorter than the
// default level.
EXPECT_TRUE(cutspec.KeepNode("02"));
EXPECT_TRUE(cutspec.KeepNode("020120121021021"));
EXPECT_FALSE(cutspec.KeepNode("02012012102102102210"));
// Try off by one at same levels.
// One off ancestors of a specified node.
EXPECT_FALSE(cutspec.KeepNode("301320201"));
EXPECT_FALSE(cutspec.KeepNode("3013202032"));
EXPECT_FALSE(cutspec.KeepNode("301320203330"));
EXPECT_FALSE(cutspec.KeepNode("301320203333222"));
EXPECT_FALSE(cutspec.KeepNode("30132020333322100"));
// One off a specified node.
EXPECT_FALSE(cutspec.KeepNode("301320203333221031"));
// Try all bad node.
EXPECT_FALSE(cutspec.KeepNode("22222"));
// Check exclusion
EXPECT_TRUE(cutspec.ExcludeNode("3013202033332301"));
EXPECT_TRUE(cutspec.ExcludeNode("3013202033332302"));
EXPECT_TRUE(cutspec.ExcludeNode("301320203333230"));
EXPECT_TRUE(cutspec.ExcludeNode("30132020333323"));
EXPECT_TRUE(cutspec.ExcludeNode("30132"));
EXPECT_FALSE(cutspec.ExcludeNode("3013"));
}
// TODO: Mock the gst server and do a test of whole system.
} // namespace fusion_portableglobe
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.029412 | 78 | 0.737795 | [
"vector"
] |
d03621848269b0a4046a2de9c4d8eb8405fa3b11 | 10,086 | cc | C++ | lite/backends/nnadapter/nnadapter/src/driver/imagination_nna/engine.cc | 714627034/Paddle-Lite | 015ba88a4d639db0b73603e37f83e47be041a4eb | [
"Apache-2.0"
] | 1 | 2022-03-18T19:48:40.000Z | 2022-03-18T19:48:40.000Z | lite/backends/nnadapter/nnadapter/src/driver/imagination_nna/engine.cc | 714627034/Paddle-Lite | 015ba88a4d639db0b73603e37f83e47be041a4eb | [
"Apache-2.0"
] | null | null | null | lite/backends/nnadapter/nnadapter/src/driver/imagination_nna/engine.cc | 714627034/Paddle-Lite | 015ba88a4d639db0b73603e37f83e47be041a4eb | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 PaddlePaddle Authors. 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.
#include "driver/imagination_nna/engine.h"
#include <unistd.h>
#include <algorithm>
#include <limits>
#include <utility>
#include <vector>
#include "driver/imagination_nna/converter/converter.h"
#include "optimizer/convert_quantization_symm_to_asymm.h"
#include "utility/debug.h"
#include "utility/logging.h"
#include "utility/modeling.h"
#include "utility/string.h"
#include "utility/utility.h"
namespace nnadapter {
namespace imagination_nna {
Context::Context(void* device, const char* properties) : device_(device) {
// TODO(hong19860320) create the raw context from imgdnnn
}
Context::~Context() {}
Program::~Program() { Clear(); }
void Program::Clear() {
tensors_.clear();
input_info_.clear();
output_info_.clear();
input_types_.clear();
output_types_.clear();
for (size_t i = 0; i < input_memory_.size(); i++) {
if (input_memory_[i].first) {
imgdnn_mgr_->DestroyMemory(input_memory_[i].first);
}
}
input_memory_.clear();
for (size_t i = 0; i < output_memory_.size(); i++) {
if (output_memory_[i].first) {
imgdnn_mgr_->DestroyMemory(output_memory_[i].first);
}
}
output_memory_.clear();
}
int Program::Build(core::Model* model, core::Cache* cache) {
Clear();
// Convert the quantization parameters of the operands in the NNAdapter model
NNADAPTER_VLOG(5) << "Origin model:" << std::endl << Visualize(model);
ConvertQuantizationSymmToAsymm(model);
NNADAPTER_VLOG(5) << "Optimized model:" << std::endl << Visualize(model);
// Convert a NNAdapter model to a imgdnn network
imgdnn_mgr_ = std::make_shared<ImgdnnManager>();
if (!imgdnn_mgr_) {
return NNADAPTER_OUT_OF_MEMORY;
}
Converter converter(imgdnn_mgr_.get(), &tensors_);
NNADAPTER_CHECK_EQ(converter.Apply(model), NNADAPTER_NO_ERROR);
// Indentify the inputs and outputs
auto input_count = model->input_operands.size();
NNADAPTER_VLOG(3) << "Model input count: " << input_count;
std::vector<imgdnn_tensor> input_tensors;
if (input_count > 0) {
input_tensors.resize(input_count);
input_types_.resize(input_count);
for (size_t i = 0; i < input_count; i++) {
auto operand = model->input_operands[i];
const auto& type = operand->type;
NNADAPTER_CHECK(tensors_.find(operand) != tensors_.end());
input_tensors[i] = tensors_[operand].front();
NNADAPTER_CHECK(input_tensors[i]);
input_types_[i] = type;
}
}
auto output_count = model->output_operands.size();
NNADAPTER_VLOG(3) << "Model output count: " << output_count;
NNADAPTER_CHECK_GT(output_count, 0);
std::vector<imgdnn_tensor> output_tensors(output_count);
output_types_.resize(output_count);
for (size_t i = 0; i < output_count; i++) {
auto operand = model->output_operands[i];
const auto& type = operand->type;
NNADAPTER_CHECK(tensors_.find(operand) != tensors_.end());
output_tensors[i] = tensors_[operand].back();
NNADAPTER_CHECK(output_tensors[i]);
output_types_[i] = type;
}
imgdnn_mgr_->CreateNetworkObject(input_tensors.size(),
input_tensors.data(),
output_tensors.size(),
output_tensors.data());
// Get the info of inputs and outputs, and check the count and buffer size of
// inputs and outputs
uint32_t num_inputs;
imgdnn_mgr_->GetNetworkObjectInputs(
std::numeric_limits<unsigned int>::max(), nullptr, &num_inputs);
NNADAPTER_CHECK_EQ(input_count, num_inputs);
if (input_count > 0) {
input_info_.resize(input_count);
input_memory_.resize(input_count,
std::pair<imgdnn_memory, size_t>(nullptr, 0));
imgdnn_mgr_->GetNetworkObjectInputs(
input_count, input_info_.data(), nullptr);
}
uint32_t num_outputs;
imgdnn_mgr_->GetNetworkObjectOutputs(
std::numeric_limits<unsigned int>::max(), nullptr, &num_outputs);
NNADAPTER_CHECK_EQ(output_count, num_outputs);
output_info_.resize(output_count);
output_memory_.resize(output_count,
std::pair<imgdnn_memory, size_t>(nullptr, 0));
imgdnn_mgr_->GetNetworkObjectOutputs(
output_count, output_info_.data(), nullptr);
NNADAPTER_VLOG(3) << "Build success.";
return NNADAPTER_NO_ERROR;
}
int Program::CheckInputsAndOutputs(uint32_t input_count,
core::Argument* input_arguments,
uint32_t output_count,
core::Argument* output_arguments) {
// Check inputs
for (uint32_t i = 0; i < input_count; i++) {
// Get actual type
auto& arg = input_arguments[i];
NNAdapterOperandType type;
arg.access(arg.memory, &type);
// Check dimensions count
uint32_t count = type.dimensions.count;
int32_t* data = type.dimensions.data;
auto& src_dimensions = input_types_[i].dimensions;
int32_t* src_data = src_dimensions.data;
if (count != src_dimensions.count) {
return NNADAPTER_INVALID_DIMENSIONS;
}
// Check dimensions data
for (uint32_t j = 0; j < count; j++) {
if (data[j] != src_data[j]) {
return NNADAPTER_INVALID_DIMENSIONS;
}
}
}
return NNADAPTER_NO_ERROR;
}
int Program::Execute(uint32_t input_count,
core::Argument* input_arguments,
uint32_t output_count,
core::Argument* output_arguments) {
int ret = CheckInputsAndOutputs(
input_count, input_arguments, output_count, output_arguments);
if (ret != NNADAPTER_NO_ERROR) return ret;
NNADAPTER_CHECK_EQ(input_types_.size(), input_count);
NNADAPTER_CHECK_EQ(output_types_.size(), output_count);
for (uint32_t i = 0; i < input_count; i++) {
auto& arg = input_arguments[i];
NNADAPTER_CHECK_GE(arg.index, 0);
NNADAPTER_CHECK_LT(arg.index, input_count);
NNADAPTER_CHECK(arg.memory);
NNADAPTER_CHECK(arg.access);
auto type = input_types_[arg.index];
auto host_ptr = arg.access(arg.memory, &type);
NNADAPTER_CHECK(host_ptr);
auto length = GetOperandTypeBufferLength(type);
auto& input_memory = input_memory_[arg.index];
if (!input_memory.first || input_memory.second < length) {
if (input_memory.first) {
imgdnn_mgr_->DestroyMemory(input_memory.first);
}
input_memory.first = imgdnn_mgr_->AllocateMemory(length);
NNADAPTER_CHECK(input_memory.first);
input_memory.second = length;
imgdnn_mgr_->AddBindingInput(input_info_[arg.index], input_memory.first);
}
auto device_ptr = imgdnn_mgr_->LockMemory(input_memory.first,
IMGDNN_LOCK_ACCESS_WRITE_ONLY);
if (IsUInt8AsymmPerLayerQuantType(type.precision)) {
Symm2AsymmData(reinterpret_cast<const int8_t*>(host_ptr),
length,
type.asymm_per_layer_params.zero_point,
reinterpret_cast<uint8_t*>(device_ptr));
} else {
memcpy(host_ptr, device_ptr, length);
}
imgdnn_mgr_->UnlockMemory(input_memory.first);
}
std::vector<std::pair<size_t, std::pair<void*, imgdnn_memory>>>
output_buffers(output_count);
for (uint32_t i = 0; i < output_count; i++) {
auto& arg = output_arguments[i];
NNADAPTER_CHECK_GE(arg.index, 0);
NNADAPTER_CHECK_LT(arg.index, output_count);
NNADAPTER_CHECK(arg.memory);
NNADAPTER_CHECK(arg.access);
auto type = &output_types_[arg.index];
// TODO(hong19860320) Get the dimensions of the outputs from imgdnn
// according to the dynamic dimensions of the inputs, fill them to 'type'
// and call the 'access' function to re-allocate the host output memory
auto host_ptr = arg.access(arg.memory, type);
NNADAPTER_CHECK(host_ptr);
auto length = GetOperandTypeBufferLength(*type);
auto& output_memory = output_memory_[arg.index];
if (!output_memory.first || output_memory.second < length) {
if (output_memory.first) {
imgdnn_mgr_->DestroyMemory(output_memory.first);
}
output_memory.first = imgdnn_mgr_->AllocateMemory(length);
NNADAPTER_CHECK(output_memory.first);
output_memory.second = length;
imgdnn_mgr_->AddBindingOutput(output_info_[arg.index],
output_memory.first);
}
output_buffers[arg.index].first = length;
output_buffers[arg.index].second.first = host_ptr;
output_buffers[arg.index].second.second = output_memory.first;
}
auto start_time = GetCurrentUS();
imgdnn_mgr_->ExecuteNetworkObject(true, 0, nullptr, nullptr);
NNADAPTER_VLOG(3) << "Process cost " << GetCurrentUS() - start_time << " us";
for (uint32_t i = 0; i < output_count; i++) {
auto type = &output_types_[i];
auto host_ptr = output_buffers[i].second.first;
auto length = output_buffers[i].first;
auto device_ptr = imgdnn_mgr_->LockMemory(output_buffers[i].second.second,
IMGDNN_LOCK_ACCESS_READ_ONLY);
if (IsUInt8AsymmPerLayerQuantType(type->precision)) {
Asymm2SymmData(reinterpret_cast<const uint8_t*>(device_ptr),
length,
type->asymm_per_layer_params.zero_point,
reinterpret_cast<int8_t*>(host_ptr));
} else {
memcpy(device_ptr, host_ptr, length);
}
imgdnn_mgr_->UnlockMemory(output_buffers[i].second.second);
}
return NNADAPTER_NO_ERROR;
}
} // namespace imagination_nna
} // namespace nnadapter
| 39.552941 | 79 | 0.676681 | [
"vector",
"model"
] |
d0388c0cf1e451e48cf1109677ba07de83433bdb | 250 | cpp | C++ | SDLCraft/SDLCraft/Model.cpp | iceklue/SDL | a7ee5fab6870b11603992241146a76adcf36b4a2 | [
"MIT"
] | null | null | null | SDLCraft/SDLCraft/Model.cpp | iceklue/SDL | a7ee5fab6870b11603992241146a76adcf36b4a2 | [
"MIT"
] | null | null | null | SDLCraft/SDLCraft/Model.cpp | iceklue/SDL | a7ee5fab6870b11603992241146a76adcf36b4a2 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Model.h"
Model::Model(int vaoID, int vertexCount)
{
this->vaoID = vaoID;
this->vertexCount = vertexCount;
}
int Model::GetVaoID() const
{
return vaoID;
}
int Model::GetVertexCount() const
{
return vertexCount;
}
| 12.5 | 40 | 0.7 | [
"model"
] |
d03d27921353d39e73591450f27ea29ce0974d5b | 15,853 | cpp | C++ | service/window_manager/src/input_windows_manager.cpp | openharmony-gitee-mirror/multimodalinput_input | 17303b7662d0382f27c972ad7d149bee61a14f23 | [
"Apache-2.0"
] | 1 | 2021-12-03T13:56:40.000Z | 2021-12-03T13:56:40.000Z | service/window_manager/src/input_windows_manager.cpp | openharmony-gitee-mirror/multimodalinput_input | 17303b7662d0382f27c972ad7d149bee61a14f23 | [
"Apache-2.0"
] | null | null | null | service/window_manager/src/input_windows_manager.cpp | openharmony-gitee-mirror/multimodalinput_input | 17303b7662d0382f27c972ad7d149bee61a14f23 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:18:23.000Z | 2021-09-13T11:18:23.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "input_windows_manager.h"
#include <cstdio>
#include <cstdlib>
#include "app_register.h"
#include "event_dump.h"
#include "mmi_server.h"
#include "util.h"
#include "util_ex.h"
namespace OHOS::MMI {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, MMI_LOG_DOMAIN, "InputWindowsManager"};
}
}
using namespace OHOS::MMI;
static void SeatsInfoDebugPrint(const struct SeatInfo** seats)
{
MMI_LOGT("Seats:");
for (int i = 0; seats[i]; i++) {
MMI_LOGT(" -Seat%{public}02d seatName:%{public}s, deviceFlags:%{public}d, focusWindowId:%{public}d", i + 1,
seats[i]->seatName, seats[i]->deviceFlags, seats[i]->focusWindowId);
MMI_LOGT(".");
}
}
OHOS::MMI::InputWindowsManager::InputWindowsManager()
{
}
OHOS::MMI::InputWindowsManager::~InputWindowsManager()
{
Clear();
}
/*
* FullName: Init
* Returns: bool
* Qualifier: init windows manager server
*/
bool OHOS::MMI::InputWindowsManager::Init(UDSServer& udsServer)
{
// save server handle
udsServer_ = &udsServer;
SetSeatListener([]() {
WinMgr->UpdateSeatsInfo();
});
SetScreenListener([]() {
WinMgr->UpdateScreensInfo();
});
UpdateSeatsInfo();
UpdateScreensInfo();
return true;
}
void OHOS::MMI::InputWindowsManager::UpdateSeatsInfo()
{
std::lock_guard<std::mutex> lock(mu_);
if (seatsInfo_ != nullptr) {
FreeSeatsInfo(seatsInfo_);
}
seatsInfo_ = GetSeatsInfo();
if (seatsInfo_ == nullptr) {
MMI_LOGE("InputWindowsManager::UpdateSeatsInfo seatsInfo = nullptr");
return;
}
if (seatsInfo_[0] && seatsInfo_[0]->focusWindowId > 0) {
SetFocusId(seatsInfo_[0]->focusWindowId);
}
SeatsInfoDebugPrint(const_cast<const SeatInfo**>(seatsInfo_));
}
// LCOV_EXCL_STOP
void OHOS::MMI::InputWindowsManager::UpdateScreensInfo()
{
std::lock_guard<std::mutex> lock(mu_);
// free the last screen info
if (screensInfo_ != nullptr) {
FreeScreensInfo(screensInfo_);
}
screensInfo_ = GetScreensInfo();
if (screensInfo_ == nullptr) {
MMI_LOGE("InputWindowsManager::UpdateScreensInfo screensInfo_ = nullptr");
return;
}
// save windows info
SaveScreenInfoToMap(const_cast<const ScreenInfo**>(screensInfo_));
PrintDebugInfo();
}
const std::vector<ScreenInfo>& OHOS::MMI::InputWindowsManager::GetScreenInfo() const
{
return screenInfoVec_;
}
const CLMAP<int32_t, LayerInfo>& OHOS::MMI::InputWindowsManager::GetLayerInfo() const
{
return layers_;
}
const CLMAP<int32_t, MMISurfaceInfo>& OHOS::MMI::InputWindowsManager::GetSurfaceInfo() const
{
return surfaces_;
}
void OHOS::MMI::InputWindowsManager::InsertSurfaceInfo(const MMISurfaceInfo& tmpSurfaceInfo)
{
std::lock_guard<std::mutex> lock(mu_);
surfaces_.insert(std::pair<int32_t, MMISurfaceInfo>(tmpSurfaceInfo.surfaceId, tmpSurfaceInfo));
MMI_LOGW("OnWindow InsertSurfaceInfo ChangeFocusSurfaceId old:%{public}d new:%{public}d", focusInfoID_,
tmpSurfaceInfo.surfaceId);
focusInfoID_ = tmpSurfaceInfo.surfaceId;
}
void OHOS::MMI::InputWindowsManager::PrintAllNormalSurface()
{
std::lock_guard<std::mutex> lock(mu_);
PrintDebugInfo();
}
void OHOS::MMI::InputWindowsManager::SetFocusSurfaceId(int32_t id)
{
std::lock_guard<std::mutex> lock(mu_);
SetFocusId(id);
}
void OHOS::MMI::InputWindowsManager::SetTouchFocusSurfaceId(int32_t id)
{
std::lock_guard<std::mutex> lock(mu_);
touchFocusId_ = id;
}
int32_t OHOS::MMI::InputWindowsManager::GetFocusSurfaceId() const
{
return focusInfoID_;
}
int32_t OHOS::MMI::InputWindowsManager::GetTouchFocusSurfaceId() const
{
return touchFocusId_;
}
void OHOS::MMI::InputWindowsManager::SetFocusId(int32_t id)
{
MMI_LOGD("SetFocusId old:%{public}d new:%{public}d", focusInfoID_, id);
focusInfoID_ = id;
}
void OHOS::MMI::InputWindowsManager::PrintDebugInfo()
{
MMI_LOGT("***********seats info***********");
if (seatsInfo_ == nullptr) {
MMI_LOGT("seatsInfo_ is nullptr");
return;
}
int32_t idx = 0;
for (int i = 0; seatsInfo_[i]; i++) {
idx = i + 1;
MMI_LOGT(" -Seat%{public}02d: seatName: %{public}s, deviceFlags: %{public}d, focusWindowId: %{public}d", idx,
seatsInfo_[i]->seatName, seatsInfo_[i]->deviceFlags, seatsInfo_[i]->focusWindowId);
}
MMI_LOGT("***********screen info***********");
for (auto& j : screenInfoVec_) {
MMI_LOGT(" -screenId: %{public}d, connectorName: %{public}s, screenWidth: %{public}d, screenHeight: "
"%{public}d, screenNlayers: %{public}d", j.screenId, j.connectorName, j.width, j.height, j.nLayers);
}
MMI_LOGT("***********layer info***********");
for (auto& k : layers_) {
MMI_LOGT(" -layer_id: %{public}d, on_screen_id: %{public}d, nSurfaces: %{public}d src(xywh): [%{public}d, "
"%{public}d, %{public}d, %{public}d], dest(xywh): [%{public}d, %{public}d, %{public}d, %{public}d] "
"visibility: %{public}d, opacity: %{public}lf",
k.second.layerId, k.second.onScreenId, k.second.nSurfaces, k.second.srcX, k.second.srcY,
k.second.srcW, k.second.srcH, k.second.dstX, k.second.dstY, k.second.dstW, k.second.dstH,
k.second.visibility, k.second.opacity);
}
MMI_LOGT("***********window info***********");
for (auto& m : surfaces_) {
auto appFd = AppRegs->FindByWinId(m.second.surfaceId);
MMI_LOGT(" -surface_id: %{public}d, on_screen_id: %{public}d, on_layer_id: %{public}d, src(xywh): [%{public}d,"
" %{public}d, %{public}d, %{public}d] desc(xywh): [%{public}d, %{public}d, %{public}d, %{public}d], "
"visibility: %{public}d, opacity: %{public}lf, appFd: %{public}d bundlerName: %{public}s appName: "
"%{public}s",
m.second.surfaceId, m.second.screenId, m.second.onLayerId, m.second.srcX, m.second.srcY,
m.second.srcW, m.second.srcH, m.second.dstX, m.second.dstY, m.second.dstW, m.second.dstH,
m.second.visibility, m.second.opacity, appFd.fd, appFd.bundlerName.c_str(), appFd.appName.c_str());
}
}
size_t OHOS::MMI::InputWindowsManager::GetSurfaceIdList(IdsList& ids)
{
const int32_t TEST_THREE_WINDOWS = 3;
std::lock_guard<std::mutex> lock(mu_);
for (auto i : surfaces_) {
if (i.second.surfaceId != focusInfoID_ && TEST_THREE_WINDOWS != i.second.surfaceId) {
ids.push_back(i.second.surfaceId);
}
}
ids.push_back(focusInfoID_);
return ids.size();
}
std::string OHOS::MMI::InputWindowsManager::GetSurfaceIdListString()
{
IdsList ids;
std::string str;
auto idsSize = GetSurfaceIdList(ids);
if (idsSize > 0) {
str = IdsListToString(ids, ",");
}
return str;
}
void OHOS::MMI::InputWindowsManager::Clear()
{
std::lock_guard<std::mutex> lock(mu_);
if (seatsInfo_) {
FreeSeatsInfo(seatsInfo_);
seatsInfo_ = nullptr;
}
if (screensInfo_) {
FreeScreensInfo(screensInfo_);
screensInfo_ = nullptr;
}
focusInfoID_ = 0;
screenInfoVec_.clear();
layers_.clear();
surfaces_.clear();
surfacesList_.clear();
}
void OHOS::MMI::InputWindowsManager::Dump(int32_t fd)
{
std::lock_guard<std::mutex> lock(mu_);
mprintf(fd, "screenInfos count=%zu", screenInfoVec_.size());
for (auto& screen_info : screenInfoVec_) {
mprintf(fd, "\tscreenId=%d connectorName=%s screenWidth= %d screenHeight=%d screenNlayers=%d",
screen_info.screenId, screen_info.connectorName, screen_info.width, screen_info.height,
screen_info.nLayers);
}
mprintf(fd, "layerInfos count=%zu", layers_.size());
for (auto& layer_info : layers_) {
mprintf(fd, "\tlayerId=%d dstX=%d dstY=%d dstW=%d dstH=%d srcX=%d"
"srcY=%d srcW=%d srcH=%d opacity=%f visibility=%d onScreenId=%d nsurfaces=%d",
layer_info.second.layerId, layer_info.second.dstX, layer_info.second.dstY,
layer_info.second.dstW, layer_info.second.dstH, layer_info.second.srcX,
layer_info.second.srcY, layer_info.second.srcW, layer_info.second.srcH,
layer_info.second.opacity, layer_info.second.visibility,
layer_info.second.onScreenId, layer_info.second.nSurfaces);
}
mprintf(fd, "surfaceInfos count=%zu", surfaces_.size());
for (auto& mysurface_info : surfaces_) {
auto appFd = AppRegs->FindByWinId(mysurface_info.second.surfaceId);
mprintf(fd, "\tsurfaceId=%d dstX=%d dstY=%d dstW=%d dstH=%d srcX=%d"
"srcY=%d srcW=%d srcH=%d opacity=%f visibility=%d onLayerId=%d appFd=%d bundlerName=%s appName=%s",
mysurface_info.second.surfaceId, mysurface_info.second.dstX,
mysurface_info.second.dstY, mysurface_info.second.dstW, mysurface_info.second.dstH,
mysurface_info.second.srcX, mysurface_info.second.srcY, mysurface_info.second.srcW,
mysurface_info.second.srcH, mysurface_info.second.opacity, mysurface_info.second.visibility,
mysurface_info.second.onLayerId, appFd.fd, appFd.bundlerName.c_str(), appFd.appName.c_str());
}
}
/*
* FullName: SaveScreenInfoToMap
* Returns: void
* Qualifier: save screen info to MAP
* Parameter: screen_info**
*/
void OHOS::MMI::InputWindowsManager::SaveScreenInfoToMap(const ScreenInfo** screenInfo)
{
// check param
CHK(udsServer_, NULL_POINTER);
CHK(screenInfo, NULL_POINTER);
CHK(*screenInfo, NULL_POINTER);
// clear windows info
screenInfoVec_.clear();
layers_.clear();
surfaces_.clear();
// save windows info
IdsList surfaceList;
for (int32_t i = 0; screenInfo[i]; i++) {
// save screen
screenInfoVec_.push_back(*(screenInfo[i]));
int32_t nlayers = screenInfo[i]->nLayers;
LayerInfo** pstrLayerInfo = screenInfo[i]->layers;
for (int32_t j = 0; j < nlayers; j++) {
// save
layers_.insert(std::pair<int32_t, LayerInfo>(pstrLayerInfo[j]->layerId, *(pstrLayerInfo[j])));
// get nsurfaces
int32_t nsurfaces = pstrLayerInfo[j]->nSurfaces;
SurfaceInfo** pstrSurface = pstrLayerInfo[j]->surfaces;
for (int32_t k = 0; k < nsurfaces; k++) {
MMISurfaceInfo mySurfaceTmp = {};
CHK(EOK == memcpy_s(&mySurfaceTmp, sizeof(mySurfaceTmp), pstrSurface[k], sizeof(SurfaceInfo)),
MEMCPY_SEC_FUN_FAIL);
mySurfaceTmp.screenId = screenInfo[i]->screenId;
surfaces_.insert(std::pair<int32_t, MMISurfaceInfo>(mySurfaceTmp.surfaceId, mySurfaceTmp));
AddId(surfaceList, mySurfaceTmp.surfaceId);
}
}
}
// Destroyed windows
if (!surfacesList_.empty()) {
IdsList delList;
auto delSize = CalculateDifference(surfacesList_, surfaceList, delList);
if (delSize > 0) {
// Processing destroyed windows
AppRegs->SurfacesDestroyed(delList);
auto winIdsStr = IdsListToString(delList, ",");
MMI_LOGD("InputWindowsManager Some windows were destroyed... winIds:[%{public}s]", winIdsStr.c_str());
}
}
surfacesList_ = surfaceList;
}
bool OHOS::MMI::InputWindowsManager::FindSurfaceByCoordinate(double x, double y, const SurfaceInfo& pstrSurface)
{
if (x >= pstrSurface.srcX && x <= (pstrSurface.srcX + pstrSurface.srcW) &&
y >= pstrSurface.srcY && y <= (pstrSurface.srcY + pstrSurface.srcH)) {
return true;
}
return false;
}
bool OHOS::MMI::InputWindowsManager::GetTouchSurfaceId(const double x, const double y, std::vector<int32_t>& ids)
{
std::lock_guard<std::mutex> lock(mu_);
// check map empty
if (!surfaces_.empty()) {
int32_t newLayerId = -1;
int32_t newSurfaceId = -1;
for (auto it : surfaces_) {
auto res = static_cast<MMISurfaceInfo*>(&it.second);
CHKF(res, NULL_POINTER);
// find window by coordinate
if (FindSurfaceByCoordinate(x, y, *res)) {
if (res->onLayerId > newLayerId) {
newLayerId = res->onLayerId;
newSurfaceId = res->surfaceId;
}
}
}
// push id
if ((newSurfaceId != -1) && (newSurfaceId != focusInfoID_)) {
ids.push_back(focusInfoID_);
ids.push_back(newSurfaceId);
} else if (newSurfaceId != -1) {
ids.push_back(focusInfoID_);
}
return true;
}
return false;
}
const ScreenInfo* OHOS::MMI::InputWindowsManager::GetScreenInfo(int32_t screenId)
{
std::lock_guard<std::mutex> lock(mu_);
for (auto& it : screenInfoVec_) {
if (it.screenId == screenId) {
return ⁢
}
}
return nullptr;
}
const LayerInfo* OHOS::MMI::InputWindowsManager::GetLayerInfo(int32_t layerId)
{
std::lock_guard<std::mutex> lock(mu_);
auto it = layers_.find(layerId);
if (it == layers_.end()) {
return nullptr;
}
return &it->second;
}
const MMISurfaceInfo* OHOS::MMI::InputWindowsManager::GetSurfaceInfo(int32_t sufaceId)
{
std::lock_guard<std::mutex> lock(mu_);
auto it = surfaces_.find(sufaceId);
if (it == surfaces_.end()) {
return nullptr;
}
return &it->second;
}
bool OHOS::MMI::InputWindowsManager::CheckFocusSurface(double x, double y, const MMISurfaceInfo& info) const
{
if (x >= info.dstX && x <= (info.dstX + info.dstW) &&
y >= info.dstY && y <= (info.dstY + info.dstH)) {
return true;
}
return false;
}
const MMISurfaceInfo* OHOS::MMI::InputWindowsManager::GetTouchSurfaceInfo(double x, double y)
{
std::lock_guard<std::mutex> lock(mu_);
int32_t newLayerId = -1;
const MMISurfaceInfo* surfacePtr = nullptr;
for (auto& it : surfaces_) {
// find window by coordinate
if (CheckFocusSurface(x, y, it.second) && it.second.onLayerId >= newLayerId) {
newLayerId = it.second.onLayerId;
if (it.second.visibility == 1 && AppRegs->FindByWinId(it.second.surfaceId).fd > 0) {
surfacePtr = &it.second;
}
}
}
return surfacePtr;
}
void OHOS::MMI::InputWindowsManager::TransfromToSurfaceCoordinate(double& x, double& y, const MMISurfaceInfo& info,
bool debug)
{
double oldX = x;
double oldY = y;
x = x - info.dstX;
y = y - info.dstY;
if (debug) {
auto appFd = AppRegs->FindByWinId(info.surfaceId);
MMI_LOGD("Transfrom touch coordinate... src:[%{public}lf, %{public}lf] focusSurface:%{public}d "
"surface:[%{public}d, %{public}d, %{public}d, %{public}d] dest:[%{public}lf, %{public}lf] "
"fd:%{public}d bundler:%{public}s appName:%{public}s",
oldX, oldY, info.surfaceId, info.dstX, info.dstY, info.dstW, info.dstH, x, y, appFd.fd,
appFd.bundlerName.c_str(), appFd.appName.c_str());
}
}
| 35.465324 | 119 | 0.630985 | [
"vector"
] |
d03e1fd224facd8dcf86e64f59dca860e8eb70ca | 4,415 | cpp | C++ | src/bustools_capture.cpp | Yenaled/bustools | 6fa0731f7f32c68645f0f60b1c1c89771b1c8061 | [
"BSD-2-Clause"
] | null | null | null | src/bustools_capture.cpp | Yenaled/bustools | 6fa0731f7f32c68645f0f60b1c1c89771b1c8061 | [
"BSD-2-Clause"
] | null | null | null | src/bustools_capture.cpp | Yenaled/bustools | 6fa0731f7f32c68645f0f60b1c1c89771b1c8061 | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include <fstream>
#include <algorithm>
#include "Common.hpp"
#include "BUSData.h"
#include "bustools_capture.h"
void bustools_capture(Bustools_opt &opt) {
BUSHeader h;
std::unordered_set<uint64_t> captures;
std::vector<std::vector<int32_t>> ecmap;
std::unordered_map<std::vector<int32_t>, int32_t, SortedVectorHasher> ecmapinv;
if (opt.type == CAPTURE_TX) {
// parse ecmap and capture list
std::unordered_map<std::string, int32_t> txnames;
std::cerr << "Parsing transcripts .. "; std::cerr.flush();
parseTranscripts(opt.count_txp, txnames);
std::cerr << "done" << std::endl;
std::cerr << "Parsing ECs .. "; std::cerr.flush();
parseECs(opt.count_ecs, h);
std::cerr << "done" << std::endl;
ecmap = h.ecs; // copy
ecmapinv.reserve(ecmap.size());
for (int32_t ec = 0; ec < ecmap.size(); ec++) {
ecmapinv.insert({ecmap[ec], ec});
}
std::cerr << "Parsing capture list .. "; std::cerr.flush();
parseTxCaptureList(opt.capture, txnames, captures);
std::cerr << "done" << std::endl;
} else if (opt.type == CAPTURE_UMI || opt.type == CAPTURE_BC) {
parseBcUmiCaptureList(opt.capture, captures);
} else if (opt.type == CAPTURE_F) {
parseFlagsCaptureList(opt.capture, captures);
} else { // Should never happen
std::cerr << "ERROR: Unknown capture type" << std::endl;
exit(1);
}
bool outheader_written = false;
std::string output = opt.output;
if (opt.filter) {
output += ".bus";
}
std::streambuf *buf = nullptr;
std::ofstream of;
if (!opt.stream_out) {
of.open(output);
buf = of.rdbuf();
} else {
buf = std::cout.rdbuf();
}
std::ostream o(buf);
size_t nr = 0, nw = 0;
size_t N = 100000;
uint32_t bclen = 0;
BUSData* p = new BUSData[N];
BUSData bd;
for (const auto& infn : opt.files) {
std::streambuf *inbuf;
std::ifstream inf;
if (!opt.stream_in) {
inf.open(infn.c_str(), std::ios::binary);
inbuf = inf.rdbuf();
} else {
inbuf = std::cin.rdbuf();
}
std::istream in(inbuf);
parseHeader(in, h);
if (!outheader_written) {
writeHeader(o, h);
outheader_written = true;
}
while(true) {
in.read((char*)p, N*sizeof(BUSData));
size_t rc = in.gcount() / sizeof(BUSData);
if (rc == 0) {
break;
}
nr += rc;
for (size_t i = 0; i < rc; i++) {
bd = p[i];
bool capt = false;
if (opt.type == CAPTURE_TX) {
if (bd.ec < 0 || bd.ec > ecmap.size()) {
continue;
}
for (auto x : ecmap[bd.ec]) {
if (captures.count((uint64_t) x) > 0) {
capt = true;
break;
}
}
} else if (opt.type == CAPTURE_BC) {
capt = captures.count(bd.barcode) > 0;
} else if (opt.type == CAPTURE_UMI) {
capt = captures.count(bd.UMI) > 0;
} else if (opt.type == CAPTURE_F) {
capt = captures.count(bd.flags) > 0;
} else { // Should never happen
std::cerr << "error: unknown capture type" << std::endl;
exit(1);
}
if (capt != opt.complement) {
if (opt.filter) { // modify the ec
std::vector<int32_t> v;
for (auto x : ecmap[bd.ec]) {
if (captures.count((uint64_t) x) > 0) {
v.push_back(x);
}
}
if (v.empty()) {
continue; // should never happen
} else {
std::sort(v.begin(), v.end());
}
auto it = ecmapinv.find(v);
if (it == ecmapinv.end()) {
// create new ec;
int32_t ec = ecmap.size();
ecmap.push_back(v);
ecmapinv.insert({v,ec});
bd.ec = ec;
} else {
bd.ec = it->second;
}
}
++nw;
o.write((char *) &bd, sizeof(bd));
}
}
}
if (!opt.stream_in) {
inf.close();
}
}
if (opt.filter) {
h.ecs = ecmap; // modified map
// TODO: trim down the ecs for the capture list
writeECs(opt.output + ".ec", h);
}
if (of.is_open()) {
of.close();
}
std::cerr << "Read in " << nr << " BUS records, wrote " << nw << " BUS records" << std::endl;
}
| 26.12426 | 95 | 0.510306 | [
"vector"
] |
d03ea463cb9ad701f02a4644fb98712ce763b1eb | 2,985 | hh | C++ | src/modules/Common/ComputeDescription.hh | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 31 | 2015-12-15T19:14:10.000Z | 2021-12-31T17:40:21.000Z | src/modules/Common/ComputeDescription.hh | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 5 | 2015-12-04T08:06:47.000Z | 2020-08-09T21:49:46.000Z | src/modules/Common/ComputeDescription.hh | cdsc-github/parade-ara-simulator | 00c977200a8e7aa31b03d560886ec80840a3c416 | [
"BSD-3-Clause"
] | 21 | 2015-11-05T08:25:45.000Z | 2021-06-19T02:24:50.000Z | #ifndef COMPUTE_DESCRIPTION_H
#define COMPUTE_DESCRIPTION_H
#include <vector>
#include <stdint.h>
#include "Packetizer.hh"
#define INVALID_ARG_BASE_ADDR 0x0FFFFFFF
class ComputeDescription
{
public:
uint32_t opcode;
uint32_t spmWindowSize;
uint32_t spmWindowCount;
std::vector<bool> argActive;
std::vector<uint32_t> argBaseAddr;
std::vector<std::vector<int32_t> > argStride;
std::vector<std::vector<uint32_t> > argSize;
std::vector<uint32_t> argElementSize;
std::vector<uint64_t> controlRegister;
void WriteOut(PacketBuilder& pb) const
{
pb.Write((uint32_t)opcode);
pb.Write((uint32_t)spmWindowCount);
pb.Write((uint32_t)spmWindowSize);
pb.Write((uint8_t)(argBaseAddr.size()));
for(size_t i = 0; i < argBaseAddr.size(); i++)
{
if(argActive[i])
{
pb.Write((uint32_t)(argBaseAddr[i]));
}
else
{
pb.Write((uint32_t)(INVALID_ARG_BASE_ADDR));
}
pb.Write((uint8_t)(argSize[i].size()));
for(size_t x = 0; x < argSize[i].size(); x++)
{
pb.Write((uint32_t)(argSize[i][x]));
pb.Write((int32_t)(argStride[i][x]));
}
pb.Write((uint32_t)argElementSize[i]);
}
pb.Write((uint8_t)(controlRegister.size()));
for(size_t i = 0; i < controlRegister.size(); i++)
{
pb.Write((uint64_t)(controlRegister[i]));
}
}
void ReadIn(PacketReader& pr)
{
opcode = pr.Read<uint32_t>();
spmWindowCount = pr.Read<uint32_t>();
spmWindowSize = pr.Read<uint32_t>();
int argCount = pr.Read<uint8_t>();
//std::cout << "opcode : " << opcode << " spm window : " << spmWindowSize << "[" << spmWindowCount << "] arg count : " << argCount << std::endl;
assert(spmWindowCount > 1);
for(int i = 0; i < argCount; i++)
{
uint32_t baseAddr = pr.Read<uint32_t>();
if(baseAddr == INVALID_ARG_BASE_ADDR)
{
argBaseAddr.push_back(0);
argActive.push_back(false);
}
else
{
argBaseAddr.push_back(baseAddr);
argActive.push_back(true);
}
int count = pr.Read<uint8_t>();
//std::cout << "Arg " << i << " base: " << argBaseAddr[argBaseAddr.size() - 1] << " dimension count: " << count << " ";
std::vector<uint32_t> size;
std::vector<int32_t> stride;
for(int x = 0; x < count; x++)
{
uint32_t sizeVal = pr.Read<uint32_t>();
int32_t strideVal = pr.Read<int32_t>();
size.push_back(sizeVal);
stride.push_back(strideVal);
//std::cout << "[" << sizeVal << ", " << strideVal << "]";
}
//std::cout << std::endl;
argElementSize.push_back(pr.Read<uint32_t>());
assert(argElementSize[i] > 0);
argSize.push_back(size);
argStride.push_back(stride);
}
int regCount = pr.Read<uint8_t>();
//std::cout << "Register count : " << regCount << " ";
for(int i = 0; i < regCount; i++)
{
uint64_t val = pr.Read<uint64_t>();
//std::cout << "[" << val << "]";
controlRegister.push_back(val);
}
//std::cout << std::endl;
}
ComputeDescription()
{
opcode = 0;
}
ComputeDescription(PacketReader& pr)
{
opcode = 0;
ReadIn(pr);
}
};
#endif
| 26.184211 | 148 | 0.629481 | [
"vector"
] |
d03fe2979d79a23b4d90e16aa573e3acc8e7dd98 | 7,708 | cpp | C++ | lib_graphd/test/GraphTest.cpp | spowers/INDDGO-survey | 860f15376f7be074f47280a74b912a8f0baa37bf | [
"BSD-3-Clause"
] | null | null | null | lib_graphd/test/GraphTest.cpp | spowers/INDDGO-survey | 860f15376f7be074f47280a74b912a8f0baa37bf | [
"BSD-3-Clause"
] | null | null | null | lib_graphd/test/GraphTest.cpp | spowers/INDDGO-survey | 860f15376f7be074f47280a74b912a8f0baa37bf | [
"BSD-3-Clause"
] | null | null | null | /*
This file is part of INDDGO.
Copyright (C) 2012, Oak Ridge National Laboratory
This product includes software produced by UT-Battelle, LLC under Contract No.
DE-AC05-00OR22725 with the Department of Energy.
This program is free software; you can redistribute it and/or modify
it under the terms of the New BSD 3-clause software license (LICENSE).
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
LICENSE for more details.
For more information please contact the INDDGO developers at:
inddgo-info@googlegroups.com
*/
#include "Log.h"
#include "Node.h"
#include "Graph.h"
#include "GraphCreator.h"
#include "GraphCreatorFile.h"
#include <gtest/gtest.h>
#include <fstream>
using namespace std;
class GraphTest : public testing::Test {
public:
Graph::GraphCreatorFile creator;
Graph::Graph *g;
Graph::Graph *g_five;
virtual void SetUp(){
LOG_INIT("test.log", NULL, 0);
//creator.set_file_name("../data/1dc.128.txt");
creator.set_file_name("data/1dc.128.txt");
creator.set_graph_type("DIMACS");
g = creator.create_graph();
g_five = new Graph::Graph(5);
}
virtual void TearDown(){
LOG_CLOSE();
}
};
TEST_F(GraphTest, testNumNodes)
{
EXPECT_EQ(128, g->get_num_nodes());
}
TEST_F(GraphTest, testNumEdges)
{
EXPECT_EQ(1471, g->get_num_edges());
}
TEST_F(GraphTest, testGraphType)
{
EXPECT_EQ("DIMACS", g->get_graph_type());
}
TEST_F(GraphTest, testGetNode)
{
Graph::Node *n;
n = g->get_node(108);
list<int> nbrs = n->get_nbrs();
EXPECT_EQ(24, nbrs.size());
}
TEST_F(GraphTest, testNextLabel){
int n = g_five->get_next_label();
EXPECT_EQ(6, n);
}
TEST_F(GraphTest, testIsEdge)
{
Graph::Node *n;
n = g->get_node(108);
list<int> nbrs = n->get_nbrs();
EXPECT_EQ(24, nbrs.size());
EXPECT_TRUE(g->is_edge(108, 100));
}
TEST_F(GraphTest, testGetDegree)
{
EXPECT_EQ(19, g->get_degree(28));
}
TEST_F(GraphTest, testNodeNbrs)
{
vector<Graph::Node> n;
int i;
n = g->get_nodes();
EXPECT_EQ(128, n.size());
list<int> nbrlist = n[35].get_nbrs();
vector<int> nbrs(nbrlist.begin(), nbrlist.end());
EXPECT_EQ(75, nbrs[20]);
nbrlist = n[127].get_nbrs();
nbrs.clear();
nbrs.insert(nbrs.end(), nbrlist.begin(), nbrlist.end());
EXPECT_EQ(111, nbrs[2]);
nbrlist = n[0].get_nbrs();
nbrs.clear();
nbrs.insert(nbrs.end(), nbrlist.begin(), nbrlist.end());
EXPECT_EQ(1, nbrs[0]);
EXPECT_EQ(64, nbrs[6l]);
EXPECT_EQ(8, nbrs[3l]);
}
TEST_F(GraphTest, testGetDegrees)
{
vector<int> degree = g->get_degree();
ofstream outFile;
outFile.open("degrees.txt");
for(int i = 0; i < degree.size(); i++){
outFile << i << " " << degree[i] << endl;
}
EXPECT_EQ(31, degree[86]);
}
TEST_F(GraphTest, testGetNumComponents)
{
EXPECT_EQ(1, g->get_num_components());
}
TEST_F(GraphTest, testGetNextLabel)
{
EXPECT_EQ(129, g->get_next_label());
}
TEST_F(GraphTest, testSetNextLabel)
{
EXPECT_EQ(129, g->get_next_label());
g->set_next_label(140);
EXPECT_EQ(140, g->get_next_label());
}
TEST_F(GraphTest, testComplement)
{
int d = g->get_degree(86);
int n = g->get_num_nodes();
int comp = n * (n - 1) / 2;
EXPECT_EQ(31, d);
EXPECT_TRUE(g->is_edge(108, 100));
EXPECT_EQ(128, g->get_num_nodes());
EXPECT_EQ(1471, g->get_num_edges());
g->complement();
EXPECT_EQ(128, g->get_num_nodes());
EXPECT_EQ(comp - 1471, g->get_num_edges());
d = g->get_degree(86);
EXPECT_EQ(96, d);
EXPECT_FALSE(g->is_edge(108, 100));
}
TEST_F(GraphTest, testAddEdge)
{
EXPECT_FALSE(g->is_edge(80, 12));
EXPECT_EQ(1471, g->get_num_edges());
EXPECT_EQ(22, g->get_degree(80));
EXPECT_EQ(19, g->get_degree(12));
g->add_edge(80, 12);
EXPECT_TRUE(g->is_edge(80, 12));
EXPECT_TRUE(g->is_edge(12, 80));
EXPECT_EQ(1472, g->get_num_edges());
EXPECT_EQ(23, g->get_degree(80));
EXPECT_EQ(20, g->get_degree(12));
}
TEST_F(GraphTest, testAddEdgeAdvance)
{
EXPECT_FALSE(g->is_edge(80, 12));
EXPECT_EQ(1471, g->get_num_edges());
EXPECT_EQ(22, g->get_degree(80));
EXPECT_EQ(19, g->get_degree(12));
g->add_edge_advance(80, 12);
EXPECT_TRUE(g->is_edge(80, 12));
EXPECT_TRUE(g->is_edge(12, 80));
EXPECT_EQ(1472, g->get_num_edges());
EXPECT_EQ(23, g->get_degree(80));
EXPECT_EQ(20, g->get_degree(12));
}
TEST_F(GraphTest, testRemoveEdge)
{
EXPECT_TRUE(g->is_edge(108, 100));
EXPECT_EQ(1471, g->get_num_edges());
EXPECT_EQ(24, g->get_degree(108));
EXPECT_EQ(24, g->get_degree(100));
g->remove_edge(108, 100);
EXPECT_FALSE(g->is_edge(108, 100));
EXPECT_FALSE(g->is_edge(100, 108));
EXPECT_EQ(1470, g->get_num_edges());
EXPECT_EQ(23, g->get_degree(100));
EXPECT_EQ(23, g->get_degree(108));
}
TEST_F(GraphTest, testRemoveVertex)
{
EXPECT_TRUE(g->is_edge(108, 100));
EXPECT_EQ(1471, g->get_num_edges());
EXPECT_EQ(24, g->get_degree(108));
EXPECT_EQ(24, g->get_degree(100));
g->remove_vertex(108);
EXPECT_FALSE(g->is_edge(108, 100));
EXPECT_FALSE(g->is_edge(100, 108));
EXPECT_EQ(1447, g->get_num_edges());
EXPECT_EQ(23, g->get_degree(100));
EXPECT_EQ(0, g->get_degree(108));
}
TEST_F(GraphTest, testContractEdge)
{
EXPECT_TRUE(g->is_edge(108, 100));
EXPECT_EQ(1471, g->get_num_edges());
EXPECT_EQ(24, g->get_degree(108));
EXPECT_EQ(24, g->get_degree(100));
Graph::Node *na;
na = g->get_node(108);
list<int> nbrs_a = na->get_nbrs();
vector<int> nbrsvec_a(nbrs_a.begin(), nbrs_a.end());
Graph::Node *nb;
nb = g->get_node(100);
list<int> nbrs_b = nb->get_nbrs();
vector<int> nbrsvec_b(nbrs_b.begin(), nbrs_b.end());
int common_nbrs = 0;
int final_degree = 0;
int new_edges = 0;
for(int ia = 0; ia < nbrsvec_a.size(); ia++){
for(int ib = 0; ib < nbrsvec_b.size(); ib++){
if(nbrsvec_a[ia] == nbrsvec_b[ib]){
common_nbrs++;
}
}
}
final_degree = g->get_degree(108) + g->get_degree(100) - common_nbrs - 2;
new_edges = g->get_num_edges() - common_nbrs - 1;
int x = g->contract_edge(108, 100);
EXPECT_FALSE(g->is_edge(108, 100));
EXPECT_FALSE(g->is_edge(100, 108));
EXPECT_EQ(0, g->get_degree(100));
EXPECT_EQ(new_edges, g->get_num_edges());
EXPECT_EQ(final_degree, g->get_degree(108));
}
TEST_F(GraphTest, testEliminateVertex)
{
EXPECT_TRUE(g->is_edge(108, 100));
EXPECT_EQ(1471, g->get_num_edges());
EXPECT_EQ(24, g->get_degree(108));
EXPECT_EQ(24, g->get_degree(100));
Graph::Node *na;
na = g->get_node(108);
list<int> nbrs_a = na->get_nbrs();
vector<int> nbrsvec_a(nbrs_a.begin(), nbrs_a.end());
Graph::Node *nb;
nb = g->get_node(100);
list<int> nbrs_b = nb->get_nbrs();
vector<int> nbrsvec_b(nbrs_b.begin(), nbrs_b.end());
int common_nbrs = 0;
int final_degree = 0;
int new_edges = 0;
for(int ia = 0; ia < nbrsvec_a.size(); ia++){
for(int ib = 0; ib < nbrsvec_b.size(); ib++){
if(nbrsvec_a[ia] == nbrsvec_b[ib]){
common_nbrs++;
}
}
}
new_edges = g->get_degree(108) - common_nbrs - 1;
new_edges = new_edges + g->get_degree(100) - 1;
g->eliminate_vertex(108, NULL, true);
EXPECT_FALSE(g->is_edge(108, 100));
EXPECT_FALSE(g->is_edge(100, 108));
EXPECT_EQ(1597, g->get_num_edges());
EXPECT_EQ(new_edges, g->get_degree(100));
EXPECT_EQ(0, g->get_degree(108));
}
| 24.705128 | 81 | 0.633757 | [
"vector"
] |
d04598433813aa30e9ffc315be1a554544ee8017 | 789 | hpp | C++ | DepthPass.hpp | itachoco19/graphics-lib-template-project | a395126c7c1cf4734332c255b8c04be2c8a8d7a2 | [
"MIT"
] | null | null | null | DepthPass.hpp | itachoco19/graphics-lib-template-project | a395126c7c1cf4734332c255b8c04be2c8a8d7a2 | [
"MIT"
] | null | null | null | DepthPass.hpp | itachoco19/graphics-lib-template-project | a395126c7c1cf4734332c255b8c04be2c8a8d7a2 | [
"MIT"
] | 1 | 2020-12-15T15:20:56.000Z | 2020-12-15T15:20:56.000Z | #pragma once
#include "DepthRenderPipeline.hpp"
#include "RenderPipelineWithImGuiComponents.hpp"
class DepthPass
: public RenderPipelineWithImGuiComponents
{
public:
using DepthRenderPipelineList = std::list<std::shared_ptr<DepthRenderPipeline>>;
private:
std::shared_ptr<cg::IDepthStencilBuffer> m_depthStencilBuffer;
DepthRenderPipelineList m_zRenderPipelineList;
bool m_shouldResolveDepthStencilBuffer;
public:
DepthPass(const std::string& name, const DepthRenderPipelineList& zRenderPipelineList, std::shared_ptr<cg::IDepthStencilBuffer> depthStencilBuffer, bool shouldResolveDepthStencilBuffer);
void render(const cg::Scene& scene, cg::Camera& customCamera);
void render(const cg::Scene& scene) override;
void render() override;
void drawImGuiComponents() override;
}; | 31.56 | 187 | 0.821293 | [
"render"
] |
d0460f1cc17240ffb6c671bc90698f8d1b4ec0b8 | 6,266 | cpp | C++ | main/src/Objects/CObjectRotationalMass1D.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2020-10-06T08:06:25.000Z | 2020-10-06T08:06:25.000Z | main/src/Objects/CObjectRotationalMass1D.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | main/src/Objects/CObjectRotationalMass1D.cpp | eapcivil/EXUDYN | 52bddc8c258cda07e51373f68e1198b66c701d03 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /** ***********************************************************************************************
* @brief CObjectRotationalMass1D implementation
*
* @author Gerstmayr Johannes
* @date 2019-06-15 (generated)
*
* @copyright This file is part of Exudyn. Exudyn is free software: you can redistribute it and/or modify it under the terms of the Exudyn license. See "LICENSE.txt" for more details.
* @note Bug reports, support and further information:
- email: johannes.gerstmayr@uibk.ac.at
- weblink: missing
************************************************************************************************ */
#include "Main/CSystemData.h"
#include "Autogenerated/CObjectRotationalMass1D.h"
#include "Utilities/RigidBodyMath.h"
//! Computational function: compute mass matrix
void CObjectRotationalMass1D::ComputeMassMatrix(Matrix& massMatrix) const
{
massMatrix.SetScalarMatrix(1, parameters.physicsInertia);
}
//! Computational function: compute right-hand-side (RHS) of second order ordinary differential equations (ODE) to "ode2rhs"
void CObjectRotationalMass1D::ComputeODE2RHS(Vector& ode2Rhs) const
{
ode2Rhs.SetNumberOfItems(1);
ode2Rhs.SetAll(0.);
}
//! Flags to determine, which access (forces, moments, connectors, ...) to object are possible
AccessFunctionType CObjectRotationalMass1D::GetAccessFunctionTypes() const
{
return (AccessFunctionType)((Index)AccessFunctionType::TranslationalVelocity_qt + (Index)AccessFunctionType::AngularVelocity_qt);
}
//! provide Jacobian at localPosition in "value" according to object access
void CObjectRotationalMass1D::GetAccessFunctionBody(AccessFunctionType accessType, const Vector3D& localPosition, Matrix& value) const
{
switch (accessType)
{
case AccessFunctionType::TranslationalVelocity_qt:
{
value.SetMatrix(3, 1, { 0.,0.,0. }); //a ForceVector has no action on RotationalMass1D
break;
}
case AccessFunctionType::AngularVelocity_qt:
{
//this function relates a 3D angular velocity to the time derivative of all coordinates: omega = Jac*q_dot
Vector3D v = parameters.referenceRotation * Vector3D({ 0.,0.,1. }); //local angular velocity is around z-axis!
value.SetMatrix(3, 1, {v[0], v[1], v[2]}); //the 3D torque vector (only z-component) acts on the 3rd coordinate phi_t
break;
}
//case AccessFunctionType::DisplacementMassIntegral_q:
//{
// value.SetMatrix(3, 1, { 0.,0.,0. }); //no action of gravity!
// break;
//}
default:
SysError("CObjectRotationalMass1D:GetAccessFunctionBody illegal accessType");
}
}
//! provide according output variable in "value"
void CObjectRotationalMass1D::GetOutputVariableBody(OutputVariableType variableType, const Vector3D& localPosition, ConfigurationType configuration, Vector& value) const
{
switch (variableType)
{
case OutputVariableType::Position: value.CopyFrom(GetPosition(localPosition, configuration)); break;
case OutputVariableType::Displacement: value.CopyFrom(GetPosition(localPosition, configuration) - GetPosition(localPosition, ConfigurationType::Reference)); break;
case OutputVariableType::Velocity: value.CopyFrom(GetVelocity(localPosition, configuration)); break;
case OutputVariableType::Rotation: value.CopyFrom(Vector1D( GetRotationAngle(configuration))); break;
case OutputVariableType::AngularVelocity: value.CopyFrom(GetAngularVelocity(localPosition, configuration)); break;
case OutputVariableType::RotationMatrix: {
Matrix3D rot = GetRotationMatrix(localPosition, configuration);
value.SetVector(rot.NumberOfColumns()*rot.NumberOfRows(), rot.GetDataPointer());
break;
}
default:
SysError("CObjectRotationalMass1D::GetOutputVariableBody failed"); //error should not occur, because types are checked!
}
}
//! return the rotation angle (reference+current) according to configuration type
Real CObjectRotationalMass1D::GetRotationAngle(ConfigurationType configuration) const
{
Real phiRef = ((CNodeODE2*)GetCNode(0))->GetReferenceCoordinateVector()[0];
if (configuration == ConfigurationType::Reference) { return phiRef; }
return phiRef + ((CNodeODE2*)GetCNode(0))->GetCoordinateVector(configuration)[0];
}
// return the (global) position of "localPosition" according to configuration type
Vector3D CObjectRotationalMass1D::GetPosition(const Vector3D& localPosition, ConfigurationType configuration) const
{
return GetRotationMatrix(localPosition, configuration) * localPosition + parameters.referencePosition;
}
// return the (global) position of "localPosition" according to configuration type
Vector3D CObjectRotationalMass1D::GetVelocity(const Vector3D& localPosition, ConfigurationType configuration) const
{
// \dot R + A * \localOmega x \localPosition
return GetRotationMatrix(localPosition, configuration) * GetAngularVelocityLocal(localPosition, configuration).CrossProduct(localPosition); //add omega x r
}
//! return the (global) position of "localPosition" according to configuration type
Vector3D CObjectRotationalMass1D::GetDisplacement(const Vector3D& localPosition, ConfigurationType configuration) const
{
return GetPosition(localPosition,configuration) - GetPosition(localPosition, ConfigurationType::Reference); //this also works for NodePointGround
}
Matrix3D CObjectRotationalMass1D::GetRotationMatrix(const Vector3D& localPosition, ConfigurationType configuration) const
{
Real phi = GetRotationAngle(configuration);
return parameters.referenceRotation * RigidBodyMath::RotationMatrix3(phi); //rotation around local z-axis
}
//! return configuration dependent velocity of node; returns always a 3D Vector
Vector3D CObjectRotationalMass1D::GetAngularVelocity(const Vector3D& localPosition, ConfigurationType configuration) const
{
Real omega = ((CNodeODE2*)GetCNode(0))->GetCoordinateVector_t(configuration)[0];
return parameters.referenceRotation * Vector3D({ 0.,0.,omega }); //rotation around local z-axis
}
//! return configuration dependent velocity of node; returns always a 3D Vector
Vector3D CObjectRotationalMass1D::GetAngularVelocityLocal(const Vector3D& localPosition, ConfigurationType configuration) const
{
Real omega = ((CNodeODE2*)GetCNode(0))->GetCoordinateVector_t(configuration)[0];
return Vector3D({ 0.,0.,omega });//rotation around local z-axis
}
| 47.469697 | 185 | 0.759815 | [
"object",
"vector",
"3d"
] |
d04fed5d4e44087bebec05ce2a6e36c338f8f32a | 8,016 | cc | C++ | dacbench/envs/rl-plan/fast-downward/src/search/merge_and_shrink/merge_strategy_factory_sccs.cc | ndangtt/LeadingOnesDAC | 953747d8702f179851d7973c65779a1f830e03a1 | [
"Apache-2.0"
] | 1 | 2021-09-09T13:03:02.000Z | 2021-09-09T13:03:02.000Z | dacbench/envs/rl-plan/fast-downward/src/search/merge_and_shrink/merge_strategy_factory_sccs.cc | ndangtt/LeadingOnesDAC | 953747d8702f179851d7973c65779a1f830e03a1 | [
"Apache-2.0"
] | null | null | null | dacbench/envs/rl-plan/fast-downward/src/search/merge_and_shrink/merge_strategy_factory_sccs.cc | ndangtt/LeadingOnesDAC | 953747d8702f179851d7973c65779a1f830e03a1 | [
"Apache-2.0"
] | null | null | null | #include "merge_strategy_factory_sccs.h"
#include "merge_strategy_sccs.h"
#include "merge_selector.h"
#include "merge_tree_factory.h"
#include "transition_system.h"
#include "../task_proxy.h"
#include "../algorithms/sccs.h"
#include "../options/option_parser.h"
#include "../options/options.h"
#include "../options/plugin.h"
#include "../task_utils/causal_graph.h"
#include "../utils/logging.h"
#include "../utils/markup.h"
#include "../utils/system.h"
#include <algorithm>
#include <cassert>
#include <iostream>
using namespace std;
namespace merge_and_shrink {
bool compare_sccs_increasing(const vector<int> &lhs, const vector<int> &rhs) {
return lhs.size() < rhs.size();
}
bool compare_sccs_decreasing(const vector<int> &lhs, const vector<int> &rhs) {
return lhs.size() > rhs.size();
}
MergeStrategyFactorySCCs::MergeStrategyFactorySCCs(const options::Options &options)
: order_of_sccs(static_cast<OrderOfSCCs>(options.get_enum("order_of_sccs"))),
merge_tree_factory(nullptr),
merge_selector(nullptr) {
if (options.contains("merge_tree")) {
merge_tree_factory = options.get<shared_ptr<MergeTreeFactory>>("merge_tree");
}
if (options.contains("merge_selector")) {
merge_selector = options.get<shared_ptr<MergeSelector>>("merge_selector");
}
}
unique_ptr<MergeStrategy> MergeStrategyFactorySCCs::compute_merge_strategy(
const TaskProxy &task_proxy,
const FactoredTransitionSystem &fts) {
VariablesProxy vars = task_proxy.get_variables();
int num_vars = vars.size();
// Compute SCCs of the causal graph.
vector<vector<int>> cg;
cg.reserve(num_vars);
for (VariableProxy var : vars) {
const vector<int> &successors =
task_proxy.get_causal_graph().get_successors(var.get_id());
cg.push_back(successors);
}
vector<vector<int>> sccs(sccs::compute_maximal_sccs(cg));
// Put the SCCs in the desired order.
switch (order_of_sccs) {
case OrderOfSCCs::TOPOLOGICAL:
// SCCs are computed in topological order.
break;
case OrderOfSCCs::REVERSE_TOPOLOGICAL:
// SCCs are computed in topological order.
reverse(sccs.begin(), sccs.end());
break;
case OrderOfSCCs::DECREASING:
sort(sccs.begin(), sccs.end(), compare_sccs_decreasing);
break;
case OrderOfSCCs::INCREASING:
sort(sccs.begin(), sccs.end(), compare_sccs_increasing);
break;
}
/*
Compute the indices at which the merged SCCs can be found when all
SCCs have been merged.
*/
int index = num_vars - 1;
cout << "SCCs of the causal graph:" << endl;
vector<vector<int>> non_singleton_cg_sccs;
vector<int> indices_of_merged_sccs;
indices_of_merged_sccs.reserve(sccs.size());
for (const vector<int> &scc : sccs) {
cout << scc << endl;
int scc_size = scc.size();
if (scc_size == 1) {
indices_of_merged_sccs.push_back(scc.front());
} else {
index += scc_size - 1;
indices_of_merged_sccs.push_back(index);
non_singleton_cg_sccs.push_back(scc);
}
}
if (sccs.size() == 1) {
cout << "Only one single SCC" << endl;
}
if (static_cast<int>(sccs.size()) == num_vars) {
cout << "Only singleton SCCs" << endl;
assert(non_singleton_cg_sccs.empty());
}
if (merge_selector) {
merge_selector->initialize(task_proxy);
}
return utils::make_unique_ptr<MergeStrategySCCs>(
fts,
task_proxy,
merge_tree_factory,
merge_selector,
move(non_singleton_cg_sccs),
move(indices_of_merged_sccs));
}
bool MergeStrategyFactorySCCs::requires_init_distances() const {
if (merge_tree_factory) {
return merge_tree_factory->requires_init_distances();
} else {
return merge_selector->requires_init_distances();
}
}
bool MergeStrategyFactorySCCs::requires_goal_distances() const {
if (merge_tree_factory) {
return merge_tree_factory->requires_goal_distances();
} else {
return merge_selector->requires_goal_distances();
}
}
void MergeStrategyFactorySCCs::dump_strategy_specific_options() const {
cout << "Merge order of sccs: ";
switch (order_of_sccs) {
case OrderOfSCCs::TOPOLOGICAL:
cout << "topological";
break;
case OrderOfSCCs::REVERSE_TOPOLOGICAL:
cout << "reverse topological";
break;
case OrderOfSCCs::DECREASING:
cout << "decreasing";
break;
case OrderOfSCCs::INCREASING:
cout << "increasing";
break;
}
cout << endl;
cout << "Merge strategy for merging within sccs: " << endl;
if (merge_tree_factory) {
merge_tree_factory->dump_options();
}
if (merge_selector) {
merge_selector->dump_options();
}
}
string MergeStrategyFactorySCCs::name() const {
return "sccs";
}
static shared_ptr<MergeStrategyFactory>_parse(options::OptionParser &parser) {
parser.document_synopsis(
"Merge strategy SSCs",
"This merge strategy implements the algorithm described in the paper "
+ utils::format_conference_reference(
{"Silvan Sievers", "Martin Wehrle", "Malte Helmert"},
"An Analysis of Merge Strategies for Merge-and-Shrink Heuristics",
"https://ai.dmi.unibas.ch/papers/sievers-et-al-icaps2016.pdf",
"Proceedings of the 26th International Conference on Planning and "
"Scheduling (ICAPS 2016)",
"2358-2366",
"AAAI Press",
"2016") +
"In a nutshell, it computes the maximal SCCs of the causal graph, "
"obtaining a partitioning of the task's variables. Every such "
"partition is then merged individually, using the specified fallback "
"merge strategy, considering the SCCs in a configurable order. "
"Afterwards, all resulting composite abstractions are merged to form "
"the final abstraction, again using the specified fallback merge "
"strategy and the configurable order of the SCCs.");
vector<string> order_of_sccs;
order_of_sccs.push_back("topological");
order_of_sccs.push_back("reverse_topological");
order_of_sccs.push_back("decreasing");
order_of_sccs.push_back("increasing");
parser.add_enum_option(
"order_of_sccs",
order_of_sccs,
"choose an ordering of the SCCs: topological/reverse_topological or "
"decreasing/increasing in the size of the SCCs. The former two options "
"refer to the directed graph where each obtained SCC is a "
"'supervertex'. For the latter two options, the tie-breaking is to "
"use the topological order according to that same graph of SCC "
"supervertices.",
"topological");
parser.add_option<shared_ptr<MergeTreeFactory>>(
"merge_tree",
"the fallback merge strategy to use if a precomputed strategy should "
"be used.",
options::OptionParser::NONE);
parser.add_option<shared_ptr<MergeSelector>>(
"merge_selector",
"the fallback merge strategy to use if a stateless strategy should "
"be used.",
options::OptionParser::NONE);
options::Options options = parser.parse();
if (parser.help_mode()) {
return nullptr;
} else if (parser.dry_run()) {
bool merge_tree = options.contains("merge_tree");
bool merge_selector = options.contains("merge_selector");
if ((merge_tree && merge_selector) || (!merge_tree && !merge_selector)) {
cerr << "You have to specify exactly one of the options merge_tree "
"and merge_selector!" << endl;
utils::exit_with(utils::ExitCode::SEARCH_INPUT_ERROR);
}
return nullptr;
} else {
return make_shared<MergeStrategyFactorySCCs>(options);
}
}
static options::Plugin<MergeStrategyFactory> _plugin("merge_sccs", _parse);
}
| 34.551724 | 85 | 0.659306 | [
"vector"
] |
d05089d65651cfb34dc39d798567c9815348eb33 | 26,029 | cc | C++ | sealed_storage/sealed_storage.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | sealed_storage/sealed_storage.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | sealed_storage/sealed_storage.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <cstdint>
#include <string>
#include <utility>
#include <base/bind.h>
#include <base/callback_helpers.h>
#include <base/check.h>
#include <base/hash/sha1.h>
#include <base/logging.h>
#include <base/run_loop.h>
#include <base/strings/string_number_conversions.h>
#include <crypto/scoped_openssl_types.h>
#include <crypto/sha2.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <trunks/error_codes.h>
#include <trunks/trunks_factory_impl.h>
#include "sealed_storage/sealed_storage.h"
namespace {
// Default D-Bus call Timeout
constexpr base::TimeDelta kDefaultTimeout = base::Minutes(2);
// Version tag at the start of serialized sealed blob.
enum SerializedVer : char {
kSerializedVer1 = 0x01,
kSerializedVer2 = 0x02,
};
// Magic value, sha256 of which is extended to PCRs when requested.
constexpr char kExtendMagic[] = "SealedStorage";
constexpr size_t kPolicySize = crypto::kSHA256Length;
constexpr size_t kPCRSize = crypto::kSHA256Length;
// RAII version of SHA256_CTX, with auto-initialization on instantiation
// and auto-cleanup on leaving scope.
class SecureSHA256_CTX {
public:
SecureSHA256_CTX() { SHA256_Init(&ctx_); }
~SecureSHA256_CTX() { OPENSSL_cleanse(&ctx_, sizeof(ctx_)); }
SHA256_CTX* get() { return &ctx_; }
private:
SHA256_CTX ctx_;
};
// Get value to extend to a requested PCR.
std::string GetExtendValue() {
return crypto::SHA256HashString(kExtendMagic);
}
// Get the expected initial PCR value before anything is extended to it.
std::string GetInitialPCRValue() {
return std::string(kPCRSize, 0);
}
// Generate AES-256 key from Z point: key = SHA256(z.x)
brillo::SecureBlob GetKeyFromZ(const trunks::TPM2B_ECC_POINT& z) {
SecureSHA256_CTX ctx;
const trunks::TPM2B_ECC_PARAMETER& x = z.point.x;
SHA256_Update(ctx.get(), x.buffer, x.size);
brillo::SecureBlob key(crypto::kSHA256Length);
SHA256_Final(key.data(), ctx.get());
return key;
}
// Get a PCR0 value corresponding to one of the known modes.
std::string GetPCR0ValueForMode(const sealed_storage::BootMode& mode) {
std::string mode_str(std::cbegin(mode), std::cend(mode));
std::string mode_digest = base::SHA1HashString(mode_str);
mode_digest.resize(kPCRSize);
return crypto::SHA256HashString(GetInitialPCRValue() + mode_digest);
}
// Universal hex dump of any container with .data() and .size()
template <typename T>
std::string HexDump(const T& obj) {
return base::HexEncode(obj.data(), obj.size());
}
// Checks error code returned from the TPM. On error, prints to the log and
// returns false. On success, returns true.
bool CheckTpmResult(trunks::TPM_RC result, std::string op) {
if (result == trunks::TPM_RC_SUCCESS) {
return true;
}
LOG(ERROR) << "Failed to " << op << ": " << trunks::GetErrorString(result);
return false;
}
// Returns the string representing the openssl error.
std::string GetOpenSSLError() {
BIO* bio = BIO_new(BIO_s_mem());
ERR_print_errors(bio);
char* data = NULL;
int data_len = BIO_get_mem_data(bio, &data);
std::string error_string(data, data_len);
BIO_free(bio);
return error_string;
}
void ReportOpenSSLError(const std::string& op_name) {
LOG(ERROR) << "Failed to " << op_name;
VLOG(1) << "Error details: " << GetOpenSSLError();
}
// Gets policy data from serialized blob.
// Returns base::nullopt in case of error.
base::Optional<std::string> DeserializePolicyDigest(
std::string* serialized_data) {
DCHECK(serialized_data);
uint16_t size;
if (trunks::Parse_uint16_t(serialized_data, &size,
nullptr /* value_bytes */) !=
trunks::TPM_RC_SUCCESS) {
LOG(ERROR) << "Failed to parse policy digest size";
return base::nullopt;
}
if (serialized_data->size() < size) {
LOG(ERROR) << "Policy digest longer than the remaining sealed data: "
<< serialized_data->size() << " < " << size;
return base::nullopt;
}
std::string policy_digest = serialized_data->substr(0, size);
serialized_data->erase(0, size);
if (policy_digest.size() != kPolicySize) {
LOG(ERROR) << "Unexpected policy digest size: " << policy_digest.size();
return base::nullopt;
}
return policy_digest;
}
} // namespace
namespace sealed_storage {
// Structure to hold the key and IV for software-based AES encryption and
// decryption.
struct Key {
public:
static const EVP_CIPHER* GetCipher() { return EVP_aes_256_cbc(); }
static uint16_t GetIVSize() { return EVP_CIPHER_iv_length(GetCipher()); }
static uint16_t GetKeySize() { return EVP_CIPHER_key_length(GetCipher()); }
static uint16_t GetBlockSize() { return EVP_CIPHER_block_size(GetCipher()); }
// Initializes the structure from private and public seeds resulting from
// TPM-based ECDHE operation.
bool Init(const PrivSeeds& priv_seeds, const PubSeeds& pub_seeds);
// Encrypts the plain data using the initialized key and IV. In case of error,
// returns nullopt.
base::Optional<Data> Encrypt(const SecretData& plain_data) const;
// Decrypts the data using the initialized key and IV. Verifies that the
// resulting plaintext size matches the |expected size_|. In case of error,
// returns nullopt.
base::Optional<SecretData> Decrypt(const Data& encrypted_data) const;
private:
brillo::SecureBlob key_;
brillo::Blob iv_;
uint16_t expected_size_;
};
Policy::PcrMap::value_type Policy::BootModePCR(const BootMode& mode) {
return {0, GetPCR0ValueForMode(mode)};
}
Policy::PcrMap::value_type Policy::UnchangedPCR(uint32_t pcr_num) {
return {pcr_num, GetInitialPCRValue()};
}
SealedStorage::SealedStorage(
const Policy& policy,
trunks::TrunksFactory* trunks_factory,
org::chromium::TpmManagerProxyInterface* tpm_ownership)
: policy_(policy),
trunks_factory_(trunks_factory),
tpm_ownership_(tpm_ownership) {
DCHECK(trunks_factory_);
DCHECK(tpm_ownership_);
}
SealedStorage::SealedStorage(const Policy& policy)
: policy_(policy),
dft_trunks_factory_(CreateTrunksFactory()),
dft_tpm_ownership_(CreateTpmOwnershipInterface()) {
trunks_factory_ = dft_trunks_factory_.get();
tpm_ownership_ = dft_tpm_ownership_.get();
DCHECK(trunks_factory_);
DCHECK(tpm_ownership_);
}
ScopedTrunksFactory SealedStorage::CreateTrunksFactory() {
auto factory = std::make_unique<trunks::TrunksFactoryImpl>();
if (!factory->Initialize()) {
LOG(ERROR) << "Failed to initialize TrunksFactory";
factory.reset(nullptr);
}
return factory;
}
ScopedTpmOwnership SealedStorage::CreateTpmOwnershipInterface() {
static scoped_refptr<dbus::Bus> bus;
if (!bus) {
dbus::Bus::Options options;
options.bus_type = dbus::Bus::SYSTEM;
bus = base::MakeRefCounted<dbus::Bus>(options);
CHECK(bus->Connect()) << "Failed to connect to system D-Bus";
}
auto proxy = std::make_unique<org::chromium::TpmManagerProxy>(bus);
return proxy;
}
base::Optional<Data> SealedStorage::Seal(const SecretData& plain_data) const {
if (!CheckInitialized()) {
return base::nullopt;
}
PrivSeeds priv_seeds;
PubSeeds pub_seeds;
if (!CreateEncryptionSeeds(&priv_seeds, &pub_seeds)) {
return base::nullopt;
}
pub_seeds.plain_size = plain_data.size();
VLOG(2) << "Created encryption seeds";
Key key;
if (!key.Init(priv_seeds, pub_seeds)) {
return base::nullopt;
}
VLOG(2) << "Created encryption key";
auto encrypted_data = key.Encrypt(plain_data);
if (!encrypted_data) {
return base::nullopt;
}
VLOG(2) << "Encrypted data";
return SerializeSealedBlob(pub_seeds, encrypted_data.value());
}
base::Optional<SecretData> SealedStorage::Unseal(
const Data& sealed_data) const {
if (!CheckInitialized()) {
return base::nullopt;
}
PubSeeds pub_seeds;
Data encrypted_data;
if (!DeserializeSealedBlob(sealed_data, &pub_seeds, &encrypted_data)) {
return base::nullopt;
}
VLOG(2) << "Deserialized sealed blob";
PrivSeeds priv_seeds;
if (!RestoreEncryptionSeeds(pub_seeds, &priv_seeds)) {
return base::nullopt;
}
VLOG(2) << "Restored encryption seeds";
Key key;
if (!key.Init(priv_seeds, pub_seeds)) {
return base::nullopt;
}
VLOG(2) << "Created encryption key";
return key.Decrypt(encrypted_data);
}
bool SealedStorage::ExtendPCR(uint32_t pcr_num) const {
if (!CheckInitialized()) {
return false;
}
auto tpm_utility = trunks_factory_->GetTpmUtility();
return CheckTpmResult(
tpm_utility->ExtendPCR(pcr_num, GetExtendValue(), nullptr), "extend PCR");
}
base::Optional<bool> SealedStorage::CheckState() const {
if (!CheckInitialized()) {
return base::nullopt;
}
auto tpm_utility = trunks_factory_->GetTpmUtility();
for (const auto& pcr_val : policy_.pcr_map) {
if (pcr_val.second.empty()) {
continue;
}
std::string value;
auto result = tpm_utility->ReadPCR(pcr_val.first, &value);
if (!CheckTpmResult(result, "read PCR")) {
return base::nullopt;
}
if (value != pcr_val.second) {
return false;
}
}
return true;
}
bool SealedStorage::PrepareSealingKeyObject(
const base::Optional<std::string>& expected_digest,
trunks::TPM_HANDLE* key_handle,
std::string* key_name,
std::string* resulting_digest) const {
CHECK(key_handle);
CHECK(key_name);
std::string endorsement_password;
if (!GetEndorsementPassword(&endorsement_password)) {
return false;
}
VLOG(2) << "Obtained endorsement password";
std::unique_ptr<trunks::PolicySession> trial_session =
trunks_factory_->GetTrialSession();
trunks::TPM_RC result = trial_session->StartUnboundSession(true, false);
if (!CheckTpmResult(result, "start trial session")) {
return false;
}
if (!policy_.pcr_map.empty()) {
auto tpm_utility = trunks_factory_->GetTpmUtility();
result = tpm_utility->AddPcrValuesToPolicySession(
policy_.pcr_map, false /* use_auth_value */, trial_session.get());
if (!CheckTpmResult(result, "calculate pcr policy")) {
return false;
}
}
if (!policy_.secret.empty()) {
if (!AddSecretToSession(trial_session.get())) {
return false;
}
}
std::string policy_digest;
result = trial_session->GetDigest(&policy_digest);
if (!CheckTpmResult(result, "Get policy digest")) {
return false;
}
VLOG(2) << "Created policy digest: " << HexDump(policy_digest);
if (expected_digest.has_value() && expected_digest.value() != policy_digest) {
VLOG(2) << "Expected policy digest: " << HexDump(expected_digest.value());
LOG(ERROR) << "Policy mismatch";
return false;
}
if (resulting_digest) {
*resulting_digest = policy_digest;
}
trunks::TPMS_SENSITIVE_CREATE sensitive = {};
memset(&sensitive, 0, sizeof(sensitive));
sensitive.user_auth = trunks::Make_TPM2B_DIGEST("");
sensitive.data = trunks::Make_TPM2B_SENSITIVE_DATA("");
trunks::TPMT_PUBLIC public_area = {};
memset(&public_area, 0, sizeof(public_area));
public_area.type = trunks::TPM_ALG_ECC;
public_area.name_alg = trunks::TPM_ALG_SHA256;
public_area.auth_policy = trunks::Make_TPM2B_DIGEST(policy_digest);
public_area.object_attributes =
trunks::kFixedTPM | trunks::kFixedParent | trunks::kSensitiveDataOrigin |
trunks::kAdminWithPolicy | trunks::kDecrypt | trunks::kNoDA;
public_area.parameters.ecc_detail.symmetric.algorithm = trunks::TPM_ALG_NULL;
public_area.parameters.ecc_detail.scheme.scheme = trunks::TPM_ALG_NULL;
public_area.parameters.ecc_detail.curve_id = trunks::TPM_ECC_NIST_P256;
public_area.parameters.ecc_detail.kdf.scheme = trunks::TPM_ALG_NULL;
public_area.unique.ecc.x = trunks::Make_TPM2B_ECC_PARAMETER("");
public_area.unique.ecc.y = trunks::Make_TPM2B_ECC_PARAMETER("");
auto endorsement_auth =
trunks_factory_->GetPasswordAuthorization(endorsement_password);
std::string rh_endorsement_name;
trunks::Serialize_TPM_HANDLE(trunks::TPM_RH_ENDORSEMENT,
&rh_endorsement_name);
return CreatePrimaryKeyObject(
"sealing key object", trunks::TPM_RH_ENDORSEMENT, rh_endorsement_name,
sensitive, public_area, endorsement_auth.get(), key_handle, key_name);
}
bool SealedStorage::GetEndorsementPassword(std::string* password) const {
CHECK(password);
if (!tpm_ownership_) {
LOG(ERROR) << "TpmOwnershipInterface is not initialized";
return false;
}
tpm_manager::GetTpmStatusRequest request;
tpm_manager::GetTpmStatusReply tpm_status;
brillo::ErrorPtr error;
if (!tpm_ownership_->GetTpmStatus(request, &tpm_status, &error,
kDefaultTimeout.InMilliseconds())) {
LOG(ERROR) << "Failed to call DefineSpace: " << error->GetMessage();
return false;
}
if (tpm_status.status() != tpm_manager::STATUS_SUCCESS) {
LOG(ERROR) << "Failed to get TpmStatus: " << tpm_status.status();
return false;
}
*password = tpm_status.local_data().endorsement_password();
return true;
}
bool SealedStorage::CreatePrimaryKeyObject(
const std::string& object_descr,
trunks::TPM_HANDLE parent_handle,
const std::string& parent_name,
const trunks::TPMS_SENSITIVE_CREATE& sensitive,
const trunks::TPMT_PUBLIC& public_area,
trunks::AuthorizationDelegate* auth_delegate,
trunks::TPM_HANDLE* object_handle,
std::string* object_name) const {
DCHECK(object_handle);
DCHECK(object_name);
trunks::TPML_PCR_SELECTION creation_pcrs = {};
trunks::TPM2B_PUBLIC out_public = {};
trunks::TPM2B_CREATION_DATA out_creation_data = {};
trunks::TPM2B_DIGEST out_creation_hash = {};
trunks::TPMT_TK_CREATION out_creation_ticket = {};
trunks::TPM2B_NAME out_name = {};
auto result = trunks_factory_->GetTpm()->CreatePrimarySync(
parent_handle, parent_name,
trunks::Make_TPM2B_SENSITIVE_CREATE(sensitive),
trunks::Make_TPM2B_PUBLIC(public_area),
trunks::Make_TPM2B_DATA("") /* outside_info */, creation_pcrs,
object_handle, &out_public, &out_creation_data, &out_creation_hash,
&out_creation_ticket, &out_name, auth_delegate);
if (!CheckTpmResult(result, std::string("create ") + object_descr)) {
return false;
}
*object_name = trunks::StringFrom_TPM2B_NAME(out_name);
VLOG(2) << "Created " << object_descr << ": " << *object_handle;
return true;
}
bool SealedStorage::CheckInitialized() const {
if (!trunks_factory_ || !trunks_factory_->GetTpm()) {
LOG(ERROR) << "TrunksFactory is not initialized";
return false;
}
return true;
}
bool SealedStorage::CreateEncryptionSeeds(PrivSeeds* priv_seeds,
PubSeeds* pub_seeds) const {
DCHECK(priv_seeds);
DCHECK(pub_seeds);
trunks::TPM_HANDLE key_handle;
std::string key_name;
std::string resulting_digest;
if (!PrepareSealingKeyObject(base::nullopt, &key_handle, &key_name,
&resulting_digest)) {
return false;
}
pub_seeds->policy_digest = std::move(resulting_digest);
auto result = trunks_factory_->GetTpm()->ECDH_KeyGenSync(
key_handle, key_name, &priv_seeds->z_point, &pub_seeds->pub_point,
nullptr /* authorization_delegate */);
if (!CheckTpmResult(result, "generate ECDH keypair")) {
return false;
}
VLOG(2) << "Generated ECDH keypair";
result = trunks_factory_->GetTpm()->GetRandomSync(
Key::GetIVSize(), &pub_seeds->iv, nullptr /* authorization_delegate */);
if (!CheckTpmResult(result, "generate IV")) {
return false;
}
VLOG(2) << "Generated IV";
return true;
}
bool SealedStorage::RestoreEncryptionSeeds(const PubSeeds& pub_seeds,
PrivSeeds* priv_seeds) const {
DCHECK(priv_seeds);
trunks::TPM_HANDLE key_handle;
std::string key_name;
if (!PrepareSealingKeyObject(pub_seeds.policy_digest, &key_handle, &key_name,
nullptr)) {
return false;
}
auto policy_session = trunks_factory_->GetPolicySession();
auto result = policy_session->StartUnboundSession(true, false);
if (!CheckTpmResult(result, "start policy session")) {
return false;
}
if (!policy_.pcr_map.empty()) {
result = policy_session->PolicyPCR(policy_.pcr_map);
if (!CheckTpmResult(result, "restrict policy to PCRs")) {
return false;
}
}
if (!policy_.secret.empty()) {
if (!AddSecretToSession(policy_session.get())) {
return false;
}
}
VLOG(2) << "Created policy session";
result = trunks_factory_->GetTpm()->ECDH_ZGenSync(
key_handle, key_name, pub_seeds.pub_point, &priv_seeds->z_point,
policy_session->GetDelegate());
if (!CheckTpmResult(result, "restore ECDH Z point")) {
return false;
}
VLOG(2) << "Restored ECDH Z point";
return true;
}
base::Optional<Data> SealedStorage::SerializeSealedBlob(
const PubSeeds& pub_seeds, const Data& encrypted_data) const {
std::string serialized_data(1, kSerializedVer2);
trunks::Serialize_uint16_t(pub_seeds.plain_size, &serialized_data);
if (!pub_seeds.policy_digest.has_value()) {
LOG(ERROR) << "Missing policy digest during serialization";
return base::nullopt;
}
if (pub_seeds.policy_digest->size() != kPolicySize) {
LOG(ERROR) << "Unexpected policy digest size during serialization: "
<< pub_seeds.policy_digest->size();
return base::nullopt;
}
trunks::Serialize_uint16_t(pub_seeds.policy_digest->size(), &serialized_data);
serialized_data.append(pub_seeds.policy_digest->begin(),
pub_seeds.policy_digest->end());
if (trunks::Serialize_TPM2B_ECC_POINT(
pub_seeds.pub_point, &serialized_data) != trunks::TPM_RC_SUCCESS) {
LOG(ERROR) << "Failed to serialize public point";
return base::nullopt;
}
if (trunks::Serialize_TPM2B_DIGEST(pub_seeds.iv, &serialized_data) !=
trunks::TPM_RC_SUCCESS) {
LOG(ERROR) << "Failed to serialize IV";
return base::nullopt;
}
if (encrypted_data.size() > UINT16_MAX) {
LOG(ERROR) << "Too long encrypted data: " << encrypted_data.size();
return base::nullopt;
}
uint16_t size = encrypted_data.size();
trunks::Serialize_uint16_t(size, &serialized_data);
serialized_data.append(encrypted_data.begin(), encrypted_data.end());
return Data(serialized_data.begin(), serialized_data.end());
}
bool SealedStorage::DeserializeSealedBlob(const Data& sealed_data,
PubSeeds* pub_seeds,
Data* encrypted_data) const {
DCHECK(pub_seeds);
DCHECK(encrypted_data);
std::string serialized_data(sealed_data.begin(), sealed_data.end());
if (serialized_data.empty()) {
LOG(ERROR) << "Empty sealed data";
return false;
}
uint8_t version = serialized_data[0];
serialized_data.erase(0, 1);
switch (version) {
case kSerializedVer1:
pub_seeds->plain_size = plain_size_for_v1_;
pub_seeds->policy_digest.reset();
break;
case kSerializedVer2:
if (trunks::Parse_uint16_t(&serialized_data, &pub_seeds->plain_size,
nullptr /* value_bytes */) !=
trunks::TPM_RC_SUCCESS) {
LOG(ERROR) << "Failed to parse plain data size";
return false;
}
pub_seeds->policy_digest = DeserializePolicyDigest(&serialized_data);
if (!pub_seeds->policy_digest.has_value()) {
LOG(ERROR) << "Failed to parse policy digest";
return false;
}
break;
default:
LOG(ERROR) << "Unexpected serialized version: " << version;
return false;
}
if (trunks::Parse_TPM2B_ECC_POINT(&serialized_data, &pub_seeds->pub_point,
nullptr /* value_bytes */) !=
trunks::TPM_RC_SUCCESS ||
!pub_seeds->pub_point.size) {
LOG(ERROR) << "Failed to parse public point";
return false;
}
if (trunks::Parse_TPM2B_DIGEST(&serialized_data, &pub_seeds->iv,
nullptr /* value_bytes */) !=
trunks::TPM_RC_SUCCESS) {
LOG(ERROR) << "Failed to parse IV";
return false;
}
uint16_t size;
if (trunks::Parse_uint16_t(&serialized_data, &size,
nullptr /* value_bytes */) !=
trunks::TPM_RC_SUCCESS) {
LOG(ERROR) << "Failed to parse encrypted data size";
return false;
}
if (serialized_data.size() != size) {
LOG(ERROR) << "Unexpected encrypted data size: " << serialized_data.size()
<< " != " << size;
return false;
}
encrypted_data->assign(serialized_data.begin(), serialized_data.end());
return true;
}
bool Key::Init(const PrivSeeds& priv_seeds, const PubSeeds& pub_seeds) {
if (pub_seeds.iv.size != GetIVSize()) {
LOG(ERROR) << "Unexpected input IV size: " << pub_seeds.iv.size;
return false;
}
iv_.assign(pub_seeds.iv.buffer, pub_seeds.iv.buffer + pub_seeds.iv.size);
if (iv_.size() != GetIVSize()) {
LOG(ERROR) << "Unexpected IV size: " << iv_.size();
return false;
}
key_ = GetKeyFromZ(priv_seeds.z_point);
if (key_.size() != GetKeySize()) {
LOG(ERROR) << "Unexpected key size: " << key_.size();
return false;
}
expected_size_ = pub_seeds.plain_size;
return true;
}
base::Optional<Data> Key::Encrypt(const SecretData& plain_data) const {
if (plain_data.size() != expected_size_) {
LOG(ERROR) << "Unexpected plain data size: " << plain_data.size()
<< " != " << expected_size_;
return base::nullopt;
}
crypto::ScopedEVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (!ctx) {
ReportOpenSSLError("allocate encryption context");
return base::nullopt;
}
if (!EVP_EncryptInit_ex(ctx.get(), GetCipher(), nullptr, key_.data(),
iv_.data())) {
ReportOpenSSLError("initialize encryption context");
return base::nullopt;
}
const size_t max_encrypted_size = plain_data.size() + GetBlockSize();
Data encrypted_data(max_encrypted_size);
int encrypted_size;
if (!EVP_EncryptUpdate(
ctx.get(), static_cast<unsigned char*>(encrypted_data.data()),
&encrypted_size, plain_data.data(), plain_data.size())) {
ReportOpenSSLError("encrypt");
return base::nullopt;
}
if (encrypted_size < 0 || encrypted_size > max_encrypted_size) {
LOG(ERROR) << "Unexpected encrypted data size: " << encrypted_size << " > "
<< max_encrypted_size;
return base::nullopt;
}
unsigned char* final_buf = nullptr;
if (encrypted_size < max_encrypted_size) {
final_buf =
static_cast<unsigned char*>(encrypted_data.data() + encrypted_size);
}
int encrypted_size_final = 0;
if (!EVP_EncryptFinal_ex(ctx.get(), final_buf, &encrypted_size_final)) {
ReportOpenSSLError("finalize encryption");
return base::nullopt;
}
if (encrypted_size_final < 0) {
LOG(ERROR) << "Unexpected size for final encryption block: "
<< encrypted_size_final;
return base::nullopt;
}
encrypted_size += encrypted_size_final;
if (encrypted_size > max_encrypted_size) {
LOG(ERROR) << "Unexpected encrypted data size after finalization: "
<< encrypted_size << " > " << max_encrypted_size;
return base::nullopt;
}
encrypted_data.resize(encrypted_size);
return encrypted_data;
}
base::Optional<SecretData> Key::Decrypt(const Data& encrypted_data) const {
crypto::ScopedEVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (!ctx) {
ReportOpenSSLError("allocate decryption context");
return base::nullopt;
}
if (!EVP_DecryptInit_ex(ctx.get(), GetCipher(), nullptr, key_.data(),
iv_.data())) {
ReportOpenSSLError("initialize decryption context");
return base::nullopt;
}
const size_t max_decrypted_size = encrypted_data.size() + GetBlockSize();
if (max_decrypted_size < expected_size_) {
LOG(ERROR) << "Not enough data for expected size: " << encrypted_data.size()
<< " leads to max " << max_decrypted_size << " < "
<< expected_size_;
return base::nullopt;
}
SecretData decrypted_data(max_decrypted_size);
int decrypted_size;
if (!EVP_DecryptUpdate(
ctx.get(), static_cast<unsigned char*>(decrypted_data.data()),
&decrypted_size, encrypted_data.data(), encrypted_data.size())) {
ReportOpenSSLError("decrypt");
return base::nullopt;
}
if (decrypted_size < 0 || decrypted_size > max_decrypted_size) {
LOG(ERROR) << "Unexpected decrypted data size: " << decrypted_size << " > "
<< max_decrypted_size;
return base::nullopt;
}
unsigned char* final_buf = nullptr;
if (decrypted_size < max_decrypted_size) {
final_buf =
static_cast<unsigned char*>(decrypted_data.data() + decrypted_size);
}
int decrypted_size_final = 0;
if (!EVP_DecryptFinal_ex(ctx.get(), final_buf, &decrypted_size_final)) {
ReportOpenSSLError("finalize decryption");
return base::nullopt;
}
if (decrypted_size_final < 0) {
LOG(ERROR) << "Unexpected size for final decryption block: "
<< decrypted_size_final;
return base::nullopt;
}
decrypted_size += decrypted_size_final;
if (decrypted_size != expected_size_) {
LOG(ERROR) << "Unexpected decrypted data size: " << decrypted_size
<< " != " << expected_size_;
return base::nullopt;
}
decrypted_data.resize(decrypted_size);
return decrypted_data;
}
bool SealedStorage::AddSecretToSession(trunks::PolicySession* session) const {
DCHECK(!policy_.secret.empty());
DCHECK(session);
std::string policy_digest;
trunks::TPM_RC result = session->GetDigest(&policy_digest);
if (!CheckTpmResult(result, "Get policy digest")) {
return false;
}
result = session->PolicyOR({policy_digest, policy_.secret.to_string()});
if (!CheckTpmResult(result, "create policy with secret included in digest")) {
return false;
}
return true;
}
} // namespace sealed_storage
| 32.455112 | 80 | 0.687656 | [
"object"
] |
d051d448af726667f5b85cca3ccab5adb777b920 | 18,018 | cpp | C++ | gcpp/classes/oif.cpp | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | 2 | 2015-10-15T19:32:42.000Z | 2021-12-20T15:56:04.000Z | gcpp/classes/oif.cpp | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | null | null | null | gcpp/classes/oif.cpp | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | null | null | null | /*====================================================================*
*
* oif.cpp - oif class definition;
*
* host interface information;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef oIF_SOURCE
#define oIF_SOURCE
/*====================================================================*
* system header files;
*--------------------------------------------------------------------*/
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cerrno>
/*====================================================================*
* system header files (environment dependent);
*--------------------------------------------------------------------*/
#if defined (__linux__)
# include <sys/ioctl.h>
# include <netinet/in.h>
#elif defined (__APPLE__)
# include <net/bpf.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <net/if_dl.h>
# include <ifaddrs.h>
# include <sys/ioctl.h>
# include <fcntl.h>
#elif defined (__OpenBSD__)
# include <net/if_dl.h>
# include <sys/poll.h>
#elif defined (WINPCAP)
# include <pcap.h>
# include <pcap/Packet32.h>
# include <pcap/ntddndis.h>
#else
#error "Unknown environment."
#endif
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../classes/oif.hpp"
#include "../classes/omemory.hpp"
#include "../classes/oerror.hpp"
/*====================================================================*
*
* unsigned Index (void) const;
*
* return the index of the selected interface; on some systems, the
* index is sequential; on others, it is not;
*
*--------------------------------------------------------------------*/
unsigned oif::Index (void) const
{
return (this->mindex);
}
/*====================================================================*
*
* char const * Name (void) const;
*
* return the NUL terminated interface name string;
*
*--------------------------------------------------------------------*/
char const * oif::Name (void) const
{
return (this->mname);
}
/*====================================================================*
*
* char const * Text (void) const;
*
* return the NUL terminated interface text string; on some systems
* this may be identical to the name string; on other it may not be;
*
*--------------------------------------------------------------------*/
char const * oif::Text (void) const
{
return (this->mtext);
}
/*====================================================================*
*
* char const * HardwareAddress (void) const;
*
* return the NUL terminated internet address string; the string is
* a sequence of hex octets seperated by colons;
*
*--------------------------------------------------------------------*/
char const * oif::HardwareAddress (void) const
{
return (this->mhwstring);
}
/*====================================================================*
*
* char const * EthernetAddress (void) const;
*
* return the NUL terminated internet address string; the string is
* a sequence of hex octets seperated by colons;
*
*--------------------------------------------------------------------*/
char const * oif::EthernetAddress (void) const
{
return (this->mhwstring);
}
/*====================================================================*
*
* char const * InternetAddress (void) const;
*
* return the NUL terminated hardware address string; the string is
* a sequence of decimal octets seperated by periods;
*
*--------------------------------------------------------------------*/
char const * oif::InternetAddress (void) const
{
return (this->mipstring);
}
/*====================================================================*
*
* oif & GetHardwareAddress (void * memory);
*
* copy the stored hardware address to external memory; this is a
* binary copy operation; return the object instance reference;
*
*--------------------------------------------------------------------*/
oif & oif::GetHardwareAddress (void * memory)
{
std::memcpy (memory, this->mhwaddr, sizeof (this->mhwaddr));
return (* this);
}
/*====================================================================*
*
* oif & GetEthernetAddress (void * memory);
*
* copy the stored hardware address to external memory; this is a
* binary copy operation; return the object instance reference;
*
*--------------------------------------------------------------------*/
oif & oif::GetEthernetAddress (void * memory)
{
std::memcpy (memory, this->mhwaddr, sizeof (this->mhwaddr));
return (* this);
}
/*====================================================================*
*
* oif & GetInternetAddress (void * memory);
*
* copy the stored internet address to external memory; this is a
* binary copy operation; return the object instance reference;
*
*--------------------------------------------------------------------*/
oif & oif::GetInternetAddress (void * memory)
{
std::memcpy (memory, this->mipaddr, sizeof (this->mipaddr));
return (* this);
}
/*====================================================================*
*
* oif & Print (void);
*
* print interface index, hardware address, internet address, name
* and text on stdout; return the object instance reference;
*
*--------------------------------------------------------------------*/
oif & oif::Print (void)
{
std::cout << this->Index () << " ";
std::cout << this->HardwareAddress () << " ";
std::cout << this->InternetAddress () << " ";
std::cout << this->Name () << " ";
std::cout << this->Text () << std::endl;
return (* this);
}
/*====================================================================*
*
* oif & SetIndex (unsigned index);
*
* change the interface index; automatically update the name and
* text strings plus the hardware and internet addresses and their
* strings;
*
* Microsoft claims to support function if_indextoname with Vista
* and beyond; pcap_indextoname is a temporary solution;
*
*--------------------------------------------------------------------*/
oif & oif::SetIndex (unsigned index)
{
this->mindex = index;
#if defined (WINPCAP)
oif::pcap_indextoname (this->mindex, this->mname);
#else
if_indextoname (this->mindex, this->mname);
#endif
std::memcpy (this->mtext, this->mname, sizeof (this->mname));
oif::lookup ();
return (* this);
}
/*====================================================================*
*
* oif & oif::SetName (char const * name);
*
* change the interface name string; automatically update the index
* and text string plus the hardware and internet addresses and their
* strings; return the object instance reference;
*
* Microsoft claims to support function if_nametoindex with Vista
* and beyond; pcap_nametoindex is a temporary solution;
*
*--------------------------------------------------------------------*/
oif & oif::SetName (char const * name)
{
#if defined (WINPCAP)
this->mindex = oif::pcap_nametoindex (name);
#else
this->mindex = if_nametoindex (name);
#endif
std::memcpy (this->mname, name, std::strlen (name));
std::memcpy (this->mtext, name, std::strlen (name));
oif::lookup ();
return (* this);
}
/*====================================================================*
*
* oif & oif::SetText (char const * text);
*
* replace interface text string and return the object instance
* reference; this string may change whenever the index or name
* are changed but changing the text string does not affect the
* other properties;
*
*--------------------------------------------------------------------*/
oif & oif::SetText (char const * text)
{
std::memcpy (this->mtext, text, std::strlen (text));
return (* this);
}
/*====================================================================*
*
* oif & SetHardwareAddress (void const * memory);
*
* copy the hardware address from external memory and return the
* object instance referenc;
*
* format the hardware and internet address strings now to avoid
* decoding them each time they are displayed;
*
*--------------------------------------------------------------------*/
oif & oif::SetHardwareAddress (void const * memory)
{
std::memcpy (this->mhwaddr, memory, sizeof (this->mhwaddr));
oif::format ();
return (* this);
}
/*====================================================================*
*
* oif & SetEthernetAddress (void const * memory);
*
* copy the hardware address from external memory and return the
* object instance referenc;
*
* format the hardware and internet address strings now to avoid
* decoding them each time they are displayed;
*
*--------------------------------------------------------------------*/
oif & oif::SetEthernetAddress (void const * memory)
{
std::memcpy (this->mhwaddr, memory, sizeof (this->mhwaddr));
oif::format ();
return (* this);
}
/*====================================================================*
*
* oif & SetInternetAddress (void const * memory);
*
* copy the internet address from external memory and return the
* object instance reference;
*
* format the hardware and internet address strings now to avoid
* decoding them each time they are displayed;
*
*--------------------------------------------------------------------*/
oif & oif::SetInternetAddress (void const * memory)
{
std::memcpy (this->mipaddr, memory, sizeof (this->mipaddr));
oif::format ();
return (* this);
}
/*====================================================================*
*
* oif & oif::lookup ();
*
* update hardware and internet addresses after the index and name
* are known; this is a rat's nest but that's life so deal with it!
*
*--------------------------------------------------------------------*/
oif & oif::lookup ()
{
#if defined (__linux__)
struct ifreq ifreq;
struct sockaddr_in * sockaddr_in = (struct sockaddr_in *) (& ifreq.ifr_ifru.ifru_addr);
int fd;
if ((fd = socket (AF_INET, SOCK_RAW, 0)) < 0)
{
oerror::error (1, errno, "Can't open socket: %s", this->mname);
}
std::memcpy (ifreq.ifr_name, this->mname, sizeof (ifreq.ifr_name));
if (ioctl (fd, SIOCGIFHWADDR, & ifreq) == -1)
{
oerror::error (1, errno, "Can't fetch hardware address: %s", this->mname);
close (fd);
return (* this);
}
std::memcpy (this->mhwaddr, ifreq.ifr_ifru.ifru_hwaddr.sa_data, sizeof (this->mhwaddr));
if (ioctl (fd, SIOCGIFADDR, & ifreq) == -1)
{
oerror::error (1, errno, "Can't fetch ethernet address: %s", this->mname);
close (fd);
return (* this);
}
std::memcpy (this->mipaddr, & sockaddr_in->sin_addr.s_addr, sizeof (this->mipaddr));
close (fd);
#elif defined (__APPLE__)
oif::osx_gethwaddr ();
#elif defined (WINPCAP)
oif::pcap_gethwaddr ();
oif::pcap_getipaddr ();
#else
#error "Unknown environment."
#endif
oif::format ();
return (* this);
}
/*====================================================================*
*
* oif & oif::format ();
*
* format hardware and internet address strings; this is a private
* method that should be called whenever either address changes;
*
*--------------------------------------------------------------------*/
oif & oif::format ()
{
omemory::hexdecode (this->mhwaddr, sizeof (this->mhwaddr), this->mhwstring, sizeof (this->mhwstring));
omemory::decdecode (this->mipaddr, sizeof (this->mipaddr), this->mipstring, sizeof (this->mipstring));
return (* this);
}
/*====================================================================*
*
* void osx_gethwaddr ();
*
* update the hardware address based on interface name in Mac OSX
* environment only;
*
*--------------------------------------------------------------------*/
void oif::osx_gethwaddr ()
{
#if defined (__APPLE__)
struct ifaddrs * ifaddrs;
struct ifaddrs * ifaddr;
if (getifaddrs (& ifaddrs) == -1)
{
oerror::error (1, errno, "No interfaces available");
}
for (ifaddr = ifaddrs; ifaddr; ifaddr = ifaddr->ifa_next)
{
if (std::strcmp (this->mname, ifaddr->ifa_name))
{
continue;
}
if (! ifaddr->ifa_addr)
{
continue;
}
if (ifaddr->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in * sockaddr_in = (struct sockaddr_in *) (ifaddr->ifa_addr);
std::memcpy (this->mipaddr, & sockaddr_in->sa_data.s_addr, sizeof (this->mipaddr));
continue;
}
if (ifaddr->ifa_addr->sa_family == AF_LINK)
{
struct sockaddr_dl * sockaddr_dl = (struct sockaddr_dl *) (ifaddr->ifa_addr);
std::memcpy (this->mhwaddr, LLADDR (sockaddr_dl), sizeof (this->mhwaddr));
continue;
}
}
freeifaddrs (ifaddrs);
#endif
return;
}
/*====================================================================*
*
* unsigned pcap_nametoindex (char const * name) const;
*
* WinPcap version of POSIX if_nametoindex function; return error
* in non-pcap environments; Microsoft will support this function
* on Vista and future systems;
*
* see The Open Group Base Specifications Issue 6 IEEE Std 1003.1,
* 2004 Edition for a description of this method;
*
*--------------------------------------------------------------------*/
unsigned oif::pcap_nametoindex (char const * name) const
{
#if defined (WINPCAP)
char buffer [PCAP_ERRBUF_SIZE];
pcap_if_t * devices = (pcap_if_t *) (0);
pcap_if_t * device;
if (pcap_findalldevs (& devices, buffer) != -1)
{
unsigned index = 1;
for (device = devices; device; device = device->next)
{
if (std::strcmp (name, device->name))
{
index++;
continue;
}
pcap_freealldevs (devices);
return (index);
}
pcap_freealldevs (devices);
}
#endif
errno = ENXIO;
return (0);
}
/*====================================================================*
*
* char * pcap_indextoname (unsigned ifindex, char * ifname) const;
*
* WinPcap version of POSIX if_indextoname function; return error
* in non-pcap enviroements; Microsoft will support this function
* on Vista and future systems;
*
* see The Open Group Base Specifications Issue 6 IEEE Std 1003.1,
* 2004 Edition for a description of this method;
*
*--------------------------------------------------------------------*/
char * oif::pcap_indextoname (unsigned ifindex, char * ifname) const
{
#if defined (WINPCAP)
char buffer [PCAP_ERRBUF_SIZE];
pcap_if_t * devices = (pcap_if_t *) (0);
pcap_if_t * device;
if ((ifindex--) && (pcap_findalldevs (& devices, buffer) != -1))
{
for (device = devices; device; device = device->next)
{
if (! ifindex--)
{
std::memcpy (ifname, device->name, std::strlen (device->name));
pcap_freealldevs (devices);
return (ifname);
}
}
pcap_freealldevs (devices);
}
#endif
errno = ENXIO;
return ((char *) (0));
}
/*====================================================================*
*
* void pcap_gethwaddr ();
*
* update the hardware address based on interface name in winpcap
* environment only; it has no effect in non-pcap environments;
*
*--------------------------------------------------------------------*/
void oif::pcap_gethwaddr ()
{
#if defined (WINPCAP)
LPADAPTER adapter = PacketOpenAdapter ((PCHAR) (this->mname));
PPACKET_OID_DATA data = (PPACKET_OID_DATA) (std::malloc (ETHER_ADDR_LEN + sizeof (PACKET_OID_DATA)));
if (! data)
{
oerror::error (1, 0, "Can't allocate packet: %s", this->mname);
}
data->Oid = OID_802_3_CURRENT_ADDRESS;
data->Length = ETHER_ADDR_LEN;
if ((! adapter) || (adapter->hFile == INVALID_HANDLE_VALUE))
{
oerror::error (1, 0, "Can't access %s", this->mname);
}
std::memset (this->mhwaddr, 0, sizeof (this->mhwaddr));
if (PacketRequest (adapter, FALSE, data))
{
std::memcpy (this->mhwaddr, data->Data, data->Length);
}
PacketCloseAdapter (adapter);
std::free (data);
#endif
return;
}
/*====================================================================*
*
* void pcap_getipaddr ();
*
* update the internet address based on interface name in winpcap
* environment only; it has no effect in non-pcap environments;
*
*--------------------------------------------------------------------*/
void oif::pcap_getipaddr ()
{
#if defined (WINPCAP)
char buffer [PCAP_ERRBUF_SIZE];
pcap_if_t * devices = (pcap_if_t *) (0);
pcap_if_t * device;
if (pcap_findalldevs (& devices, buffer) == -1)
{
oerror::error (1, errno, "Can't enumerate interfaces");
}
for (device = devices; device; device = device->next)
{
if (std::strcmp (this->mname, device->name))
{
continue;
}
std::memcpy (this->mtext, device->description, std::strlen (device->description));
if (device->addresses)
{
struct pcap_addr * pcap_addr = device->addresses;
struct sockaddr_in * sockaddr_in = (struct sockaddr_in *) (pcap_addr->addr->sa_data);
std::memcpy (this->mipaddr, & sockaddr_in->sin_addr.s_addr, sizeof (this->mipaddr));
}
break;
}
pcap_freealldevs (devices);
#endif
return;
}
/*====================================================================*
*
* oif ()
*
*--------------------------------------------------------------------*/
oif::oif ()
{
this->mindex = 0;
std::memset (this->mname, 0, sizeof (this->mname));
std::memset (this->mtext, 0, sizeof (this->mtext));
std::memset (this->mhwaddr, 0, sizeof (this->mhwaddr));
std::memset (this->mipaddr, 0, sizeof (this->mipaddr));
oif::format ();
return;
}
/*====================================================================*
*
* ~oif ()
*
*--------------------------------------------------------------------*/
oif::~ oif ()
{
return;
}
/*====================================================================*
* end definition;
*--------------------------------------------------------------------*/
#endif
| 26.037572 | 103 | 0.506549 | [
"object"
] |
d067a4da0f7c541e3cd24a5d352186671f0aff69 | 13,352 | cc | C++ | mindspore/lite/src/delegate/tensorrt/op/matmul_tensorrt.cc | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/lite/src/delegate/tensorrt/op/matmul_tensorrt.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/lite/src/delegate/tensorrt/op/matmul_tensorrt.cc | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/delegate/tensorrt/op/matmul_tensorrt.h"
#include <memory>
#include "src/delegate/tensorrt/tensorrt_utils.h"
#include "src/delegate/tensorrt/op/activation_tensorrt.h"
#include "src/delegate/tensorrt/op/matmul_opt_plugin.h"
#include "src/delegate/tensorrt/tensorrt_runtime.h"
namespace mindspore::lite {
MatMulTensorRT::~MatMulTensorRT() {
if (weight_ptr_ != nullptr) {
free(weight_ptr_);
weight_ptr_ = nullptr;
}
}
int MatMulTensorRT::IsSupport(const mindspore::schema::Primitive *primitive,
const std::vector<mindspore::MSTensor> &in_tensors,
const std::vector<mindspore::MSTensor> &out_tensors) {
if (!IsShapeKnown()) {
MS_LOG(ERROR) << "Unsupported input tensor unknown shape: " << op_name_;
return RET_ERROR;
}
if (in_tensors.size() != INPUT_SIZE2 && in_tensors.size() != INPUT_SIZE3) {
MS_LOG(ERROR) << "Unsupported input tensor size, size is " << in_tensors.size();
return RET_ERROR;
}
if (out_tensors.size() != 1) {
MS_LOG(ERROR) << "Unsupported output tensor size, size is " << out_tensors.size();
return RET_ERROR;
}
return RET_OK;
}
int MatMulTensorRT::AddInnerOp(nvinfer1::INetworkDefinition *network) {
if (type_ == schema::PrimitiveType_MatMulFusion) {
auto primitive = this->GetPrimitive()->value_as_MatMulFusion();
if (primitive == nullptr) {
MS_LOG(ERROR) << "convert to primitive matmul failed for " << op_name_;
return RET_ERROR;
}
transpose_a_ = primitive->transpose_a();
transpose_b_ = primitive->transpose_b();
activation_ = primitive->activation_type();
}
nvinfer1::ITensor *out_tensor = nullptr;
if (RunOptPlugin()) {
out_tensor = AddAsOptPlugin(network);
} else if (RunFullConnect()) {
MS_LOG(DEBUG) << "use fully connected instead of matmul for " << op_name_;
out_tensor = AddAsFullConnect(network);
} else {
MS_LOG(DEBUG) << "use origin tensorrt matmul for " << op_name_;
out_tensor = AddAsMatmul(network);
}
if (out_tensor == nullptr) {
MS_LOG(ERROR) << "add matmul failed for " << op_name_;
return RET_ERROR;
}
// add activation
if (activation_ != schema::ActivationType::ActivationType_NO_ACTIVATION) {
nvinfer1::ILayer *activation_layer = ActivationTensorRT::AddActivation(network, activation_, 0, 0, 0, out_tensor);
if (activation_layer == nullptr) {
MS_LOG(ERROR) << "addActivation for matmul failed";
return RET_ERROR;
}
activation_layer->setName((op_name_ + "_activation").c_str());
out_tensor = activation_layer->getOutput(0);
}
out_tensor->setName((op_name_ + "_output").c_str());
MS_LOG(DEBUG) << "output " << GetTensorFormat(out_tensor, out_format_, true);
this->AddInnerOutTensors(ITensorHelper{out_tensor, out_format_});
return RET_OK;
}
int MatMulTensorRT::PreprocessMatMulInputs(nvinfer1::INetworkDefinition *network, ITensorHelper *matmul_a,
ITensorHelper *matmul_b) {
if (tensorrt_in_tensors_.size() == INPUT_SIZE2) {
int a_index =
GetDimsVolume(tensorrt_in_tensors_[0].trt_tensor_->getDimensions()) == GetDimsVolume(in_tensors_[0].Shape()) ? 0
: 1;
int ret = PreprocessInputs2SameDim(network, tensorrt_in_tensors_[a_index], matmul_a);
ret += PreprocessInputs2SameDim(network, tensorrt_in_tensors_[1 - a_index], matmul_b);
if (ret != RET_OK || matmul_a->trt_tensor_ == nullptr || matmul_b->trt_tensor_ == nullptr) {
MS_LOG(ERROR) << "PreprocessInputs2SameDim of matmul inputs failed for " << op_name_;
return ret;
}
out_format_ = matmul_a->format_;
if (matmul_a->format_ != matmul_b->format_) {
MS_LOG(WARNING) << "matmul input tensor has different format " << op_name_;
out_format_ = Format::NHWC;
}
} else if (tensorrt_in_tensors_.size() == 1) {
auto weight = ProcessWeightTensor(network);
if (weight == nullptr) {
MS_LOG(ERROR) << "create constant weight tensor failed for " << op_name_;
return RET_ERROR;
}
int weight_index = in_tensors_[1].Data() != nullptr ? 1 : 0;
ITensorHelper *weight_helper = (weight_index == 1) ? matmul_b : matmul_a;
ITensorHelper *var_helper = (weight_index == 1) ? matmul_a : matmul_b;
weight_helper->trt_tensor_ = weight;
int ret = PreprocessInputs2SameDim(network, tensorrt_in_tensors_[1 - weight_index], var_helper);
if (ret != RET_OK || var_helper->trt_tensor_ == nullptr) {
MS_LOG(ERROR) << "PreprocessInputs2SameDim of matmul input var_helper failed for " << op_name_;
return ret;
}
out_format_ = var_helper->format_;
} else {
MS_LOG(ERROR) << op_name_ << " tensorrt in tensor size is invalid " << tensorrt_in_tensors_.size();
return RET_ERROR;
}
return RET_OK;
}
nvinfer1::ITensor *MatMulTensorRT::ProcessWeightTensor(nvinfer1::INetworkDefinition *network) {
nvinfer1::ITensor *weight = nullptr;
int weight_index = in_tensors_[1].Data() != nullptr ? 1 : 0;
if (in_tensors_[weight_index].Shape().size() <
static_cast<size_t>(tensorrt_in_tensors_[0].trt_tensor_->getDimensions().nbDims)) {
weight = ConvertTensorWithExpandDims(network, in_tensors_[weight_index],
in_tensors_[1 - weight_index].Shape().size(), op_name_);
} else if (in_tensors_[weight_index].Shape().size() ==
static_cast<size_t>(tensorrt_in_tensors_[0].trt_tensor_->getDimensions().nbDims)) {
weight = ConvertConstantTensor(network, in_tensors_[weight_index], op_name_);
} else {
MS_LOG(ERROR) << "input tensor shape is invalid for " << op_name_;
return nullptr;
}
return weight;
}
nvinfer1::ITensor *MatMulTensorRT::AddAsMatmul(nvinfer1::INetworkDefinition *network) {
ITensorHelper matmul_a;
ITensorHelper matmul_b;
int ret = PreprocessMatMulInputs(network, &matmul_a, &matmul_b);
if (ret != RET_OK || matmul_a.trt_tensor_ == nullptr || matmul_b.trt_tensor_ == nullptr) {
MS_LOG(ERROR) << "PreprocessMatMulInputs matmul failed for " << op_name_;
return nullptr;
}
MS_LOG(DEBUG) << "matmul input a " << GetTensorFormat(matmul_a);
MS_LOG(DEBUG) << "matmul input b " << GetTensorFormat(matmul_b);
auto matmul_layer = network->addMatrixMultiply(
*matmul_a.trt_tensor_, transpose_a_ ? nvinfer1::MatrixOperation::kTRANSPOSE : nvinfer1::MatrixOperation::kNONE,
*matmul_b.trt_tensor_, transpose_b_ ? nvinfer1::MatrixOperation::kTRANSPOSE : nvinfer1::MatrixOperation::kNONE);
if (matmul_layer == nullptr) {
MS_LOG(ERROR) << "addMatrixMultiply failed for " << op_name_;
return nullptr;
}
this->layer_ = matmul_layer;
matmul_layer->setName(op_name_.c_str());
return AddBias(network, matmul_layer->getOutput(0));
}
nvinfer1::ITensor *MatMulTensorRT::AddAsFullConnect(nvinfer1::INetworkDefinition *network) {
nvinfer1::Weights weight;
nvinfer1::Weights bias = ConvertWeight(in_tensors_[kBiasIndex]);
nvinfer1::ITensor *input_a = tensorrt_in_tensors_[0].trt_tensor_;
out_format_ = tensorrt_in_tensors_[0].format_;
if (input_a->getDimensions().nbDims != DIMENSION_4D) {
nvinfer1::Dims in_dims(input_a->getDimensions());
in_dims.nbDims = DIMENSION_4D;
for (int i = input_a->getDimensions().nbDims; i < DIMENSION_4D; i++) {
in_dims.d[i] = 1;
}
input_a = Reshape(network, input_a, in_dims);
if (input_a == nullptr) {
MS_LOG(ERROR) << "reshape input failed for " << op_name_;
return nullptr;
}
MS_LOG(DEBUG) << "full connect expand input a to " << GetTensorFormat(input_a);
} else {
ITensorHelper tmp_input;
int ret = PreprocessInputs2SameDim(network, tensorrt_in_tensors_[0], &tmp_input);
if (ret != RET_OK || tmp_input.trt_tensor_ == nullptr) {
MS_LOG(ERROR) << "rPreprocessInputs2SameDim failed for " << op_name_;
return nullptr;
}
input_a = tmp_input.trt_tensor_;
out_format_ = tmp_input.format_;
MS_LOG(DEBUG) << "full connect preprocess input a to " << GetTensorFormat(tmp_input);
}
if (!transpose_b_) {
// transpose weight
weight = TransposeWeight2D(in_tensors_[1], &weight_ptr_);
if (weight.values == nullptr || weight_ptr_ == nullptr) {
MS_LOG(ERROR) << "TransposeWeight2D input weight failed for " << op_name_;
return nullptr;
}
} else {
weight = ConvertWeight(in_tensors_[1]);
}
int output_cnt = in_tensors_[kBiasIndex].Shape()[0];
auto fc_layer = network->addFullyConnected(*input_a, output_cnt, weight, bias);
if (fc_layer == nullptr) {
MS_LOG(ERROR) << "add fully connected layer failed for " << op_name_;
return nullptr;
}
this->layer_ = fc_layer;
fc_layer->setName((op_name_ + "_fullyconnected").c_str());
nvinfer1::ITensor *out_tensor = fc_layer->getOutput(0);
if (out_tensor->getDimensions().nbDims != out_tensors_[0].Shape().size()) {
std::vector<int64_t> out_dims(out_tensors_[0].Shape());
out_dims[0] = out_tensor->getDimensions().d[0];
out_tensor = Reshape(network, out_tensor, out_dims);
}
return out_tensor;
}
nvinfer1::ITensor *MatMulTensorRT::AddAsOptPlugin(nvinfer1::INetworkDefinition *network) {
nvinfer1::ITensor *weight_tensor = nullptr;
if (tensorrt_in_tensors_.size() >= INPUT_SIZE2) {
weight_tensor = tensorrt_in_tensors_[1].trt_tensor_;
} else {
weight_tensor = ConvertConstantTensor(network, in_tensors_[1], in_tensors_[1].Name());
}
auto plugin = std::make_shared<MatmulOptPlugin>(op_name_, transpose_a_, transpose_b_);
if (plugin == nullptr) {
MS_LOG(ERROR) << "create MatmulOptPlugin failed for " << op_name_;
return nullptr;
}
nvinfer1::ITensor *inputTensors[] = {tensorrt_in_tensors_[0].trt_tensor_, weight_tensor};
nvinfer1::IPluginV2Layer *matmul_layer = network->addPluginV2(inputTensors, INPUT_SIZE2, *plugin);
if (matmul_layer == nullptr) {
MS_LOG(ERROR) << "add matmul opt plugin layer failed for " << op_name_;
return nullptr;
}
layer_ = matmul_layer;
return AddBias(network, matmul_layer->getOutput(0));
}
nvinfer1::ITensor *MatMulTensorRT::AddBias(nvinfer1::INetworkDefinition *network, nvinfer1::ITensor *input_tensor) {
nvinfer1::ITensor *out_tensor = input_tensor;
if (in_tensors_.size() == kBiasIndex + 1) {
nvinfer1::ITensor *bias = nullptr;
if (in_tensors_[kBiasIndex].Shape().size() < static_cast<size_t>(out_tensor->getDimensions().nbDims)) {
bias =
ConvertTensorWithExpandDims(network, in_tensors_[kBiasIndex], out_tensor->getDimensions().nbDims, op_name_);
} else if (in_tensors_[kBiasIndex].Shape().size() == static_cast<size_t>(out_tensor->getDimensions().nbDims)) {
bias = ConvertConstantTensor(network, in_tensors_[kBiasIndex], op_name_);
} else {
MS_LOG(ERROR) << "input tensor shape is invalid for " << op_name_;
return nullptr;
}
if (bias == nullptr) {
MS_LOG(ERROR) << "create constant bias tensor failed for " << op_name_;
return nullptr;
}
auto bias_layer = network->addElementWise(*out_tensor, *bias, nvinfer1::ElementWiseOperation::kSUM);
if (bias_layer == nullptr) {
MS_LOG(ERROR) << "add bias add layer failed for " << op_name_;
return nullptr;
}
auto bias_layer_name = op_name_ + "_bias";
bias_layer->setName(bias_layer_name.c_str());
out_tensor = bias_layer->getOutput(0);
}
return out_tensor;
}
bool MatMulTensorRT::RunOptPlugin() {
if (quant_type_ == schema::QuantType_QUANT_NONE &&
runtime_->GetRuntimePrecisionMode() == RuntimePrecisionMode::RuntimePrecisionMode_FP32) {
if (in_tensors_[0].Shape().size() == DIMENSION_2D && in_tensors_[1].Shape().size() == DIMENSION_2D &&
in_tensors_[0].Shape()[0] > 1 && tensorrt_in_tensors_[0].trt_tensor_->getDimensions().d[0] == -1) {
MS_LOG(INFO) << op_name_ << " uses optimize matmul plugin for 2D dynamic batchsize";
return true;
} else if (in_tensors_[0].Shape().size() == DIMENSION_3D && in_tensors_[1].Shape().size() == DIMENSION_3D) {
// batched matmul using opt
MS_LOG(INFO) << op_name_ << " uses optimize matmul plugin for 3D batchsized";
return true;
}
}
return false;
}
bool MatMulTensorRT::RunFullConnect() {
if (in_tensors_.size() == INPUT_SIZE3 && in_tensors_[1].Data() != nullptr &&
in_tensors_[kBiasIndex].Data() != nullptr && !transpose_a_ && in_tensors_[1].Shape().size() == DIMENSION_2D &&
(in_tensors_[0].Shape().size() == DIMENSION_2D || in_tensors_[0].Shape().size() == DIMENSION_4D)) {
return true;
}
return false;
}
REGISTER_TENSORRT_CREATOR(schema::PrimitiveType_MatMulFusion, MatMulTensorRT)
} // namespace mindspore::lite
| 43.633987 | 119 | 0.688212 | [
"shape",
"vector",
"3d"
] |
d069e115b7307361d02d5a26775a458e93154f19 | 33,991 | hh | C++ | src/hkl_unmerge.hh | maciejwlodek/blend | 00c892363876692c5370def0e37a106ad5f7b07e | [
"BSD-3-Clause"
] | null | null | null | src/hkl_unmerge.hh | maciejwlodek/blend | 00c892363876692c5370def0e37a106ad5f7b07e | [
"BSD-3-Clause"
] | null | null | null | src/hkl_unmerge.hh | maciejwlodek/blend | 00c892363876692c5370def0e37a106ad5f7b07e | [
"BSD-3-Clause"
] | 1 | 2019-01-24T16:14:56.000Z | 2019-01-24T16:14:56.000Z | // hkl_unmerge.hh
// Phil Evans August 2003-2004 etc
//
// Classes for unmerged hkl lists
// at present just for the items used by Mosflm & Scala
// These data structures are primarily directed at Scala so are
// in its namespace
#ifndef HKL_UNMERGE_HEADER
#define HKL_UNMERGE_HEADER
#include <map>
#include "hkl_datatypes.hh"
#include "hkl_controls.hh"
#include "controls.hh"
#include "hkl_symmetry.hh"
#include "icering.hh"
#include "observationflags.hh"
#include "range.hh"
#include "hash.hh"
#include "runthings.hh"
namespace scala {
//==============================================================
class data_flags
//! Data column flags to indicate which columns are present in the file
// True if column is present
{
public:
data_flags(); //!< Compulsory flags set true, others false
void print() const; // for debugging
bool is_h, is_k, is_l, is_misym, is_batch,
is_I, is_sigI, is_Ipr, is_sigIpr, is_fractioncalc,
is_Xdet, is_Ydet, is_Rot, is_Width, is_LP, is_Mpart,
is_ObsFlag, is_BgPkRatio, is_scale, is_sigscale, is_time;
}; // data_flags
//===================================================================
// ******************* observation, reflections etc
class SelectI
{
//!< A static class to select profile-fitted, summeation integrated, or combined intensity
//
public:
SelectI(){}
// Algorithm for selection as in Scala
// INTEGRATED integrated intensity I (SelectIcolFlag=0)
// PROFILE profile-fitted intensity IPR (SelectIcolFlag=-1)
// COMBINE weighted mean after combining partials (SelectIcolFlag=+1)
// combine integrated intensity Iint and
// profile-fitted intensity Ipr as
// I = w * Ipr + (1-w) * Iint
// where w = 1/(1+(Iint/Imid)**IPOWER)
// Imid (= IcolFlag) is the point of equal weight, and
// should be about the mean intensity.
// Ipower default = 3
// return true if COMBINE
static bool Combine() {return (selecticolflag > 0);}
// If IcolFlag > 0, set selecticolflag and set imid = Imid, ie COMBINE
// If IcolFlag = 0, select Iint, < 0 select Ipr
static void SetIcolFlag(const int& IcolFlag, const double& Imid, const int Ipower=3);
// Set SelectIcolFlag
static int& SelectIcolFlag() {return selecticolflag;}
// store imid = overall <I> if needed and not set
static void SetAverageIntensity(const double& meanI);
// store imid = overall <I> if needed
static void ResetAverageIntensity(const double& meanI);
static IsigI GetCombinedI(const Rtype& Iraw, const Rtype& Ic, const Rtype& varIc,
const Rtype& Ipr, const Rtype& varIpr);
static IsigI GetCombinedI(const Rtype& Iraw, const IsigI& Isc, const IsigI& Ispr);
//! set true if we have a second intensity Ipr stored
static void SetIprPresent(const bool& Isiprpresent) {iprpresent = Isiprpresent;}
//! return true if we have a second intensity Ipr stored
static bool IsIprPresent() {return iprpresent;}
static std::string format();
private:
static int selecticolflag;
static int ipowercomb;
static double imid;
static bool iprpresent; // true if we have a second intensity Ipr stored
//===================================================================
}; // SelectI
// PartFlagSwitch
// EMPTY nothing stored
// FULL fully recorded reflection (1 part)
// COMPLETE_CHECKED complete, all Mpart flags consistent
// COMPLETE passed total fraction checks
// SCALE passed checks to be scaled
// INCOMPLETE
// EXCLUDED
enum PartFlagSwitch
{EMPTY, FULL, COMPLETE_CHECKED, COMPLETE, SCALE, INCOMPLETE, EXCLUDED};
//===================================================================
//! An observation of an intensity: may be a partial
class observation_part
// hkl is the reduced indices in the "current" spacegroup
// run is set by call from hkl_unmerge_list::organise
{
public:
// constructors
observation_part(); // don't use
observation_part(const Hkl& hkl_in,
const int& isym_in, const int& batch_in,
const Rtype& I_in, const Rtype& sigI_in,
const Rtype& I_pr, const Rtype& sigIpr_in,
const Rtype& Xdet_in, const Rtype& Ydet_in,
const Rtype& phi_in, const Rtype& time_in,
const Rtype& fraction_calc_in, const Rtype& width_in,
const Rtype& LP_in,
const int& Npart_in, const int& Ipart_in,
const ObservationFlag& ObsFlag_in);
// Npart is number of parts, from input (MPART)
// = 1 for full, = -1 unknown but partial
// Ipart serial number in parts, from input (MPART)
// = 1 for full or unknown
void set_run(const int& run) {run_ = run;} //!< set by call from hkl_unmerge_list::organise
inline IsigI I_sigI() const {return IsigI(I_, sigI_);}
inline Rtype Ic() const {return I_;} // actual I column
inline Rtype sigIc() const {return sigI_;}
inline IsigI I_sigIpr() const {return IsigI(Ipr_, sigIpr_);}
inline Rtype Ipr() const {return Ipr_;} // Ipr column
inline Rtype sigIpr() const {return sigIpr_;}
void StoreIsigI(const IsigI& Is) {I_ = Is.I(); sigI_ = Is.sigI();}
void StoreIsigIpr(const IsigI& Ipr) {Ipr_ = Ipr.I(); sigIpr_ = Ipr.sigI();}
void StoreLP(const Rtype& LP) {LP_ = LP;}
// selected I column
// selIcolFlag = 0 Ic, = -1 Ipr
inline Rtype Ic(const int& selIcolFlag) const
{return (selIcolFlag == 0) ? I_ : Ipr_;}
inline Rtype sigIc(const int& selIcolFlag) const
{return (selIcolFlag == 0) ? sigI_ : sigIpr_;}
inline Rtype Xdet() const {return Xdet_;}
inline Rtype Ydet() const {return Ydet_;}
inline Rtype phi() const {return phi_;}
inline Rtype time() const {return time_;}
inline Rtype fraction_calc() const {return fraction_calc_;}
inline Rtype width() const {return width_;}
inline Rtype LP() const {return LP_;} // divide by this to get raw intensity
inline int isym() const {return isym_;}
inline int batch() const {return batch_;}
inline int Npart() const {return Npart_;}
inline int Ipart() const {return Ipart_;}
inline ObservationFlag ObsFlag() const {return ObsFlag_;}
inline int run() const {return run_;}
inline Hkl hkl() const {return hkl_;};
void set_isym(const int& isym) {isym_ = isym;} // set isym
void set_hkl(const Hkl& hkl) {hkl_ = hkl;} // set hkl
void set_batch(const int& Batch) {batch_ = Batch;} // set batch number
void set_phi(const Rtype& Phi) {phi_ = Phi;} // set Phi
void offset_phi(const Rtype& Offset) {phi_ += Offset;} // offset Phi
void offset_time(const Rtype& Offset) {time_ += Offset;} // offset Time
void negate_time() {time_ = -time_;} // negate Time
private:
Hkl hkl_;
int isym_, batch_;
Rtype I_, sigI_; // from column I
Rtype Ipr_, sigIpr_; // from column Ipr (if present)
Rtype Xdet_, Ydet_, phi_, time_;
Rtype fraction_calc_, width_, LP_;
int Npart_, Ipart_;
ObservationFlag ObsFlag_;
int run_;
}; // class observation_part
//===================================================================
//! An observation of a reflection, which may consist of one or more parts
class observation
{
public:
observation();
observation(const Hkl hkl_in,
const int& isym_in,
const int& run_in,
const int& datasetIndex_in,
const int& Npart_in,
observation_part ** const part1_in,
const Rtype& TotFrac,
const PartFlagSwitch& partialstatus_in,
const ObservationFlag& obsflag_in);
// Accessors
Rtype I() const {return I_;} //!< return I
Rtype sigI() const {return sigI_;} //!< return sigI
IsigI I_sigI() const {return IsigI(I_,sigI_);} //!< return I, sigI
Rtype kI() const {return I_/gscale;} //!< return scaled I
Rtype ksigI() const {return sigI_/gscale;} //!< return scaled sigI
IsigI kI_sigI() const {return IsigI(I_/gscale,sigI_/gscale);} //!< return scaled I, sigI
//! Return "summation" integration IsigI, summed over partials if necessary
// This is also the sole intensity if there is only one
// Also sets mean phi, time, LP
IsigI IsigIsummation();
// Return "profile" integration I sigI, summed over partials if necessary
IsigI IsigIpr() const;
// Sum (or scale) all partials for this observation
// Assumes that SelectI has been set up correctly to choose
// either summation, profile or combined intensity measurements
// Sets I_, sigI_, phi_, time_, LP_, batch_
void sum_partials();
Rtype phi() const {return phi_;} //!< return rotation angle "phi"
Rtype time() const {return time_;} //!< return "time"
int Isym() const {return isym_;} //!< return symmetry number ISYM
Rtype LP() const {return LP_;}
//! return run number
int run() const {return run_;};
int datasetIndex() const {return datasetIndex_;} //!< return dataset index
bool IsAccepted() const {return obs_status.IsAccepted();} //!< return "accepted" flag
int num_parts() const; //!< return number of parts
observation_part get_part(const int& kpart) const; //!< return kpart'th part
void replace_part(const int& kpart, const observation_part& obs_part); //!< replace kpart'th part
Hkl hkl_original() const {return hkl_original_;} //!< return original indices hkl
bool IsFull() const {return part_flag == FULL;} //!< return true if fully recorded
Rtype Gscale() const {return gscale;} //!< return stored inverse (dividing) scale
std::pair<float,float> XYdet() const; //!< return average detector coordinates
float TotalFraction() const {return totalfraction;} //!< return total fraction
int Batch() const; //!< return central batch number
// Partial status flag
PartFlagSwitch PartFlag() const {return part_flag;} //!< return partial status
//! Store I, sigI incomplete partials are scaled if necessary, return true if scaled
bool set_IsigI_phi_time(const Rtype& I, const Rtype& sigI,
const Rtype& phi, const Rtype& time,
const Rtype& LP);
//! Set batch number for "central" batch
void set_batch(const int& batch) {batch_ = batch;}
//! Store updated sigI
void set_sigI(Rtype& sigI) {sigI_ = sigI;}
//! Store inverse scale g
void SetGscale(const Rtype& g) {gscale = g;}
//! Store secondary beam directions
void StoreS2(const float& Thetap, const float& Phip)
{thetap=Thetap; phip=Phip;}
//! Return secondary beam directions
void GetS2(double& Thetap, double& Phip) const
{Thetap=thetap; Phip=phip;}
//! Store diffraction vector
void StoreS(const FVect3& dStarvec) {s_dif = dStarvec;}
//! Return diffraction vector at this phi, diffractometer frame
FVect3 GetS() const {return s_dif;}
//! Reset status flag from ObservationFlag according to control settings
/*! ObservationFlag obs_flag is the set of bit flags read from the input file
eg overload: flagged observations may be conditionally accepted by setting
obs_status.
ObservationStatus obs_status is a volatile flag indicating the
current status of the observation
*/
void ResetObsAccept(ObservationFlagControl& ObsFlagControl);
//! return observation flag
ObservationFlag Observationflag() const {return obs_flag;}
//! return current value of volatile status flag
ObservationStatus ObsStatus() const {return obs_status;}
//! set status flag
void UpdateStatus(const ObservationStatus& Status) {obs_status = Status;}
private:
Hkl hkl_original_;
int isym_;
int run_;
int datasetIndex_;
int Npart_;
observation_part ** part1;
int batch_; // batch number of "central" batch
Rtype totalfraction;
PartFlagSwitch part_flag;
ObservationFlag obs_flag;
Rtype gscale; // inverse scale g
Rtype I_, sigI_;
Rtype phi_;
Rtype time_;
Rtype LP_;
ObservationStatus obs_status;
Rtype thetap, phip; // secondary beam direction polar angles
FVect3 s_dif; // diffraction vector at Phi setting, 1/A units
}; // class observation
//===================================================================
//! A unique reflection, containing a list of observations
class reflection
{
public:
reflection(); //!< dummy, don't use
//! constructor with index into observation_part list from hkl_unmerge_list object
/*! \param hkl hkl indices
\param index_obs1 index of first part in observation_part list
\param s 1/d^2 (invresolsq)
*/
reflection(const Hkl& hkl, const int& index_obs1, const Dtype& s);
reflection(const reflection& refl); //!< copy constructor, resets NextObs
reflection& operator= (const reflection& refl); //!< copy, resets NextObs
// Storage
//! store index of last part in observation_part list
void store_last_index(const int& index_obs2);
inline int first_index() const {return index_first_obs_;} //!< return 1st index
inline int last_index() const {return index_last_obs_;} //!< return last index
inline Hkl hkl() const {return hkl_reduced_;} //!< return reduced hkl
//! add in an observation
void add_observation_list(const std::vector<observation>& obs_in);
//! add all partials, no scales, returns smallest sigma found, return = -1 if no valid observations
/*! On exit:
Nfull, number of fulls; Npart, number of partials; Nscaled, number scaled */
Rtype sum_partials(int& Nfull, int& Npart, int& Nscaled);
// Retrieval
int num_observations() const; //!< return number of observations
int NvalidObservations() const; //!< return number of valid observations
observation get_observation(const int& lobs) const; //!< return lobs'th observation
//! Return next valid observation in obs, returns index number, = -1 if end
int next_observation(observation& obs) const;
//! Reset NextObs count
void reset() const {NextObs = -1;} // (NextObs is mutable)
//! replace current observation with updated version
void replace_observation(const observation& obs);
//! replace lobs'th observation with updated version
void replace_observation(const observation& obs, const int& lobs);
// Count valid observations
void CountNValid();
Rtype invresolsq() const {return invresolsq_;} //!< return 1/d^2
//! Reset observation accepted flags to allow for acceptance of observations flagged as possible errors
// Counts observations reclassified in ObsFlagControl
void ResetObsAccept(ObservationFlagControl& ObsFlagControl);
void SetStatus(const int& istat) {statusflag = istat;} //!< set status (internal use)
int Status() const {return statusflag;} //!< return status (internal use)
private:
Hkl hkl_reduced_; // reduced indices
std::vector<observation> observations;
int index_first_obs_, index_last_obs_;
Rtype invresolsq_;
mutable int NextObs;
int NvalidObs;
int statusflag; // 0 OK accept, !=0 reject
}; //class reflection
//===================================================================
class hkl_unmerge_list
//! This is the top-level unmerged reflection object
/*!
It contains :-
\li 1) obs_part_list a list of raw observations
(almost a mirror of the file) created by a series of
calls to store_part followed by close_part_list
\li 2) refl_list a list of unique reflections, created by
a call to "organise"
\li 3) within each reflection, a list of observations which
may have multiple parts (spots), assembled by a call to "partials"
ie the hierarchy is
\n part < observation < reflection
To fill this object:
\li 1) Construct as dummy
\li 2) call "init" to set up
init may be called with or without dataset & batch
information: if without, then this must be added later
with a call to either (a) StoreDatasetBatch, or
(b) a series of calls to AddDatasetBatch
\li 3) call "store_part" to add each observation part
\li 4) call "close_part_list" to finish list
\li 5) call "StoreDataFlags" to marked which data items are actually present
\li 6) call "prepare" to classify into observations &
reflections etc
Note that objects of this class may not be copied, unless they are empty
(ie created with the default constructor), and also a copy constructor will fail.
However, you may "append" to an empty object, as a way of copying.
These objects may be very large, so copying should be avoided where possible.
No reading of external files (eg MTZ file) is done within this class
*/
{
public:
//! construct empty object, must be followed by init
hkl_unmerge_list();
//! Initialise for internal writing, with dataset and batch information
void init(const std::string& Title,
const int& NreflReserve,
const hkl_symmetry& symmetry,
const all_controls& controls,
const std::vector<Xdataset>& DataSets,
const std::vector<Batch>& Batches);
//! Initialise for internal writing,dataset and batch information added later
void init(const std::string& Title,
const int& NreflReserve,
const hkl_symmetry& symmetry,
const all_controls& controls);
//! Clear out list ready for new init
void clear();
//! true if list is empty
bool IsEmpty() const {return (status == EMPTY);}
//!true if list processed ready for use
bool IsReady() const {return (status == SUMMED);}
//! Store datasets & batch info following previous call to init
void StoreDatasetBatch(const std::vector<Xdataset>& DataSets,
const std::vector<Batch>& Batches);
//! append datasets & batch info following previous call to init
/*! This may be one of several calls*/
void AddDatasetBatch(const std::vector<Xdataset>& DataSets,
const std::vector<Batch>& Batches);
//! Add in another hkl_unmerge_list to this one
/*! Returns status = 0 OK
= +1 different symmetry (point group) */
int append(const hkl_unmerge_list& OtherList);
//----
//! Copy constructor throws exception unless object is EMPTY
hkl_unmerge_list(const hkl_unmerge_list& List);
//! Copy operator throws exception unless object is EMPTY
hkl_unmerge_list& operator= (const hkl_unmerge_list& List);
// Set controls, limits, etc ----------
void SetResoLimits(const float& LowReso, const float& HighReso); //!< set resolution
//! reset to file limits
void ResetResoLimits();
//! store ice rings, only store ones flagged as "reject"
void SetIceRings(const Rings& rings);
//! If there are any resolution limits set by run, go through the observation
// list and flag observations which are outside these limits
void ImposeResoByRunLimits();
// Retrieve information -------------------------------
//! total number of reflections
int num_reflections() const;
//! number of valid reflections
int num_reflections_valid() const {return Nref_valid;}
//! number of reflections in ice rings
int num_reflections_icering() const {return Nref_icering;}
//! total number of observations
int num_observations() const;
//! number of fully-recorded observations
int num_observations_full() const {return Nobs_full;}
//! number of partially-recorded observations
int num_observations_part() const {return Nobs_partial;}
//! number of scaled partial observations
int num_observations_scaled() const {return Nobs_scaled;}
//! number of partial observations rejected for too small fraction
int num_observations_rejected_FracTooSmall() const
{return partial_flags.NrejFractionTooSmall();}
//! number of partial observations rejected for too large fraction
int num_observations_rejected_FracTooLarge() const
{return partial_flags.NrejFractionTooLarge();}
//! number of partial observations rejected for gap
int num_observations_rejected_Gap() const {return partial_flags.NrejGap();}
//! Minimum sigma(I) of summed partials
Rtype MinSigma() const {return sigmamin;}
//! return unit cell for named dataset: if name is blank return average cell for all datasets
Scell cell(const PxdName& PXDsetName = PxdName()) const;
Scell Cell() const {return cell(PxdName());} //!< returns average cell
//! returns symmetry
hkl_symmetry symmetry() const {return refl_symm;}
//! Store MTZ symmetry (just for checking if next file has same symmetry)
void SetMtzSym(const CMtz::SYMGRP& Mtzsym) {mtzsym = Mtzsym;}
//! Return MTZ symmetry (for file output)
CMtz::SYMGRP MtzSym() const {return mtzsym;}
//! Total reindexing so far (cumulative)
ReindexOp TotalReindex() const {return totalreindex;}
// Return resolution
ResoRange ResRange() const {return ResolutionRange;} //!< Resolution
Range Srange() const {return ResolutionRange.SRange();} //!< smin, smax (1/d^2)
Range RRange() const {return ResolutionRange.RRange();} //!< low, high, A
ResoRange ResLimRange() const {return ResoLimRange;} //!< Resolution limits
Rtype DstarMax() const; //!< maximum d* = lambda/d
// Return dataset stuff
int num_datasets() const {return ndatasets;} //!< number of datasets
Xdataset xdataset(const int& jset) const {return datasets.at(jset);} //!< jset'th dataset
std::vector<Xdataset> AllXdatasets() const {return datasets;} //!< all datasets
// Return batch stuff
int num_batches() const {return nbatches;} //!< number of batches
int num_accepted_batches() const; //!< number of accepted batches
std::vector<Batch> Batches() const {return batches;} //!< all batches
//! Actual batch number for batch serial
Batch batch(const int& jbat) const {return batches.at(jbat);}
//! Batch serial for given batch
int batch_serial(const int& batch) const {return batch_lookup.lookup(batch);}
// Return batch serial number for batch batchnum, or if this one is
// not present, search upwards until one is found or maxbatchnum is reached.
// Return -1 if nothing found
int NextBatchSerial(const int& batchnum, const int& maxbatchnum) const;
// Return batch serial number for batch batchnum, or if this one is
// not present, search backwards until one is found or 0 is reached.
// Return -1 if nothing found
int LastBatchSerial(const int& batchnum) const;
// Run stuff
int num_runs() const {return runlist.size();} //!< number of runs
std::vector<Run> RunList() const {return runlist;} //!< all runs
//! Apply offset to batch numbers, one offset for each run
void OffsetBatchNumbers(const std::vector<int>& runOffsets);
//! Mark batch number ibatch as not accepted
/*! Data records are not changed */
void RejectBatch(const int& batch);
//! Mark batch with serial number jbat as not accepted
/*! Data records are not changed */
void RejectBatchSerial(const int& jbat);
//! Remove all observation parts belonging to rejected batches: returns number of parts rejected
int PurgeRejectedBatches();
//! Remove all observation parts belonging to specified rejected batches and remove them entirely from the list
/*! Returns number of parts rejected */
int EliminateBatches(const std::vector<int> RejectedBatches);
//! Title from file
std::string Title() const {return FileTitle;}
//! Append filename to list of names
void AppendFileName(const std::string& Name);
std::string Filename() const {return filename;} //!< returns filename list
//! return one reflection for index jref, unconditional, no checks
reflection get_reflection(const int& lref) const;
//! Return reflection for given (reduced) hkl in refl. Returns index number or -1 if missing
/*! Records current reflection */
int get_reflection(reflection& refl, const Hkl& hkl) const;
//! Return next accepted reflection in argument refl, returns index number = -1 if end
int next_reflection(reflection& refl) const;
//! replace current reflection with updated version
void replace_reflection(const reflection& refl);
//! Get reflection jref, if accepted, else next acceptable one
//! Return index of returned reflection, = -1 if end of list
//! Thread safe, no change in mutable data
int get_accepted_reflection(const int& jref, reflection& this_refl) const;
//! replace lobs'th observation in current reflection with updated version
void replace_observation(const observation& obs, const int& lobs);
//! Reset reflection counter to beginning for "next_reflection"
/*! not always needed since next_reflection resets it at end */
void rewind() const;
//! Retrieve i'th obs_part using pointer list
observation_part& find_part(const int& i) const;
//! Total number of parts. Required for MTZ dump, otherwise for internal use
int num_parts() const {return int(N_part_list);} // length of part list
// Do things -------------------------------
//! Change symmetry or reindex
/*! If AllowFractIndex true, allow discarding of fractional index
observations after reindexing, otherwise this is a fatal error
Returns number of fractional index reflections discarded */
int change_symmetry(const hkl_symmetry& new_symm,
const ReindexOp& reindex_op,
const bool& AllowFractIndex = false);
//! Prepare list for reflection processing
/*! if required, sort, organise, partials
returns number of unique reflections */
int prepare();
//! Sum partials
/*! return number of partials */
/*! If forcesum is true, sum them even if already summed */
int sum_partials(const bool& forcesum=false);
//! Calculate all secondary beam directions, in chosen frame
/*! On entry:
\param pole = 0 SECONDARY camera frame
!= 0 ABSORPTION, crystal frame = 1,2,3 for h,k,l,
= -1 unspecified, use closest reciprocal axis for each run */
void CalcSecondaryBeams(const int& pole);
//! Set up poles for Absorption
void SetPoles(const int& pole);
//! Calculate secondary beam direction for one observation
/*! On entry
\param batchNum [in] batch number
\param hkl_original [in] original hkl
\param phi [in] incident beam rotation, degrees
\param sPhi [out] diffraction vector at actual phi position
Returns: pair(thetap, phip) secondary beam directions, radians
*/
std::pair<float, float> CalcSecondaryBeamPolar
(const int& batchNum, const Hkl& hkl_original, const float& phi,
DVect3& sPhi) const;
//! Calculate secondary beam directions
/*! On entry
\param batchNum [in] batch number
\param hkl_original [in] original hkl
\param phi [in] incident beam rotation, degrees
\param sPhi [out] diffraction vector at actual phi position
Returns DVect3 secondary beam directions, direction cosines
*/
DVect3 CalcSecondaryBeam
(const int& batchNum, const Hkl& hkl_original, const float& phi,
DVect3& sPhi) const;
//! Reset all observation accepted flags
/*! Reset all observation accepted flags to allow for acceptance of observations
flagged as possible errors
Counts observations reclassified them in ObsFlagControl */
void ResetObsAccept(ObservationFlagControl& ObsFlagControl);
//! Reset reflection accepted flags to accept all (subject to resolution checks etc)
void ResetReflAccept();
//! Update polarisation corrections for all parts, returns range of corrections
Range UpdatePolarisationCorrections(const bool& Total,
const double& polarisationfactor);
// If Total == true, then apply complete correction
// else assume the unpolarised correction is already applied, apply
// additional correction for polarised incident beam
// polarisationfactor if fraction polarised, = 0 for unpolarised, ~ 0.9 for synchrotrons
//! Adding observation parts (spots)
void store_part(const Hkl& hkl_in,
const int& isym_in, const int& batch_in,
const Rtype& I_in, const Rtype& sigI_in,
const Rtype& Ipr, const Rtype& sigIpr,
const Rtype& Xdet_in, const Rtype& Ydet_in,
const Rtype& phi_in, const Rtype& time_in,
const Rtype& fraction_calc_in, const Rtype& width_in,
const Rtype& LP_in,
const int& Npart_in, const int& Ipart_in,
const ObservationFlag& ObsFlag_in);
//! finish adding parts
int close_part_list(const ResoRange& RRange,
const bool& Sorted); // returns number of observations
//! Put data flags to indicate which data items are actually present
void StoreDataFlags(const data_flags& DataFlags) {dataflags = DataFlags;}
//! Get data flags to indicate which data items are actually present
data_flags DataFlags() const {return dataflags;}
// dump given reflection, for debugging
void dump_reflection(const Hkl& hkl) const;
// Set runs
void AutoSetRun();
private:
void initialise(const int NreflReserve,
const hkl_symmetry& symmetry);
// organise observations into reflections
int organise(); // returns number of reflections
// assemble partials into observations, returns number of observations
int partials();
void MakeHklLookup() const;
void SetBatchList();
void AverageBatchData();
// Status:-
// EMPTY initial state
// RAWLIST raw observation list read in
// SORTED sorted
// ORGANISED organised into reflections
// PREPARED reflections split into observations
// (ie partials checked and assembled,
// but not summed)
// SUMMED partials summed, reflection.observations valid
enum rfl_status
{EMPTY, RAWLIST, SORTED, ORGANISED, PREPARED, SUMMED};
rfl_status status;
bool ChangeIndex;
ReindexOp totalreindex; // cumulative from original HKLIN setting
std::vector <observation_part> obs_part_list;
std::vector <observation_part *> obs_part_pointer;
std::vector <reflection> refl_list;
Rtype sigmamin;
size_t N_part_list;
int Nref;
int Nref_valid;
int Nobservations;
int Nobs_full;
int Nobs_partial;
int Nobs_scaled;
// hkl index list: only generated if needed
mutable clipper::HKL_lookup hkl_lookup;
mutable bool is_hkl_lookup; // initially false, true if hkl_lookup has been generated
mutable int Nref_icering;
mutable int NextRefNum; // for next_reflection
hkl_symmetry refl_symm;
CMtz::SYMGRP mtzsym; // Mtz-style symmetry, may be null
// null is mtzsym.spcgrp = -1
// Average cell (over all datasets)
Scell averagecell;
ResoRange ResolutionRange; // low, high, in stored array
ResoRange ResoLimRange; // resolution range limits
// reflections outside this range will
// not be "accept"ed
// Controls
int run_set; // has run be set in part list?
// = -1 no controls, = 0 not set, = +1 set
run_controls run_flags;
bool partial_set; // Has partial_flags been set?
partial_controls partial_flags;
// Ice rings
Rings Icerings;
// Datasets & batches
std::vector<Xdataset> datasets;
int ndatasets;
std::vector<Batch> batches; // list of batches
int nbatches;
hash_table batch_lookup;
// IsPhiOffset initially false, reset in AutoSetRun
// true if batch list set up & offset needed
// Used in store_part to apply offset to data as it is stored,
// or if StoreDatasetBatch (which calls AutoSetRun) is called
// after storing the data, then offsets are applied in AutoSetRun
// Reset to false in close_part_list
bool IsPhiOffset;
// Runs
std::vector<Run> runlist;
std::string FileTitle;
std::string filename;
// Flags for which data items are actually present
data_flags dataflags;
// **** Private member functions
// sort part list
void sort();
// for the organise method
void add_refl(const Hkl& hkl_red, const int& index, const Dtype& s);
void end_refl(const int& index);
void set_run(); // set all runs in part list
bool accept() const; // true if reflection(NextRefNum) is acceptable
// also counts ice ring
// private method, no counting or other internal storage
bool acceptableReflection(const int& RefNum) const;
//! Set runs
void SetUpRuns();
void CheckAllRuns();
void SetRunInput();
// Check that all batches in each run have the same or similar orientations
// Return false if different
// Store orientation in all runs
bool StoreOrientationRun();
// Are new datasets the same as any old ones?
// For each dataset from other list, store equivalent dataset
// index in present list, if it is the same dataset
void MergeDatasetLists(const std::vector<Xdataset>& otherDatasets,
const std::vector<Batch>& otherBatches);
struct ComparePartOrder
// This construct seems to be a way of getting pointer-to-function
// into the argument for sort. Copied from the Web.
{
bool operator()(const observation_part * part1,
const observation_part * part2);
};
}; // class hkl_unmerge_list
} // end namespace scala
#endif
// end hkl_unmerge
| 41.401949 | 115 | 0.667265 | [
"object",
"vector"
] |
d06af3410c4a15190f4e3cb2bc8448a1ae509d6a | 1,354 | cpp | C++ | test/test_GravityForce.cpp | ChrizZhuang/3D_particle_simulator | cc2a0c75dc67ec7e4f89a270bca736d9425dbec0 | [
"MIT"
] | null | null | null | test/test_GravityForce.cpp | ChrizZhuang/3D_particle_simulator | cc2a0c75dc67ec7e4f89a270bca736d9425dbec0 | [
"MIT"
] | null | null | null | test/test_GravityForce.cpp | ChrizZhuang/3D_particle_simulator | cc2a0c75dc67ec7e4f89a270bca736d9425dbec0 | [
"MIT"
] | null | null | null | // File to test GravityForce
#include <iostream>
#include "GravityForce.hpp"
#include "SimpleParticleList.hpp"
#include "LatticeParticleList.hpp"
void test_GravityForce()
{
std::cout << "Testing GravityForce ..." << std::endl;
const int N=27; // Number of particles, 3 in each direction
// Check for SimpleParticleList
{
std::cout << ".. GravityForce for SimpleParticleList" << std::endl;
// Construct a concrete GravityForce
double g1[3]={0., 0., -9.8};
GravityForce gf1(N, g1);
double m=.1;
SimpleParticleList spl(N, m);
const Vector3D& vec3d = gf1.calc_force(spl);
// Check that the force F=mg
for (int d=0; d < vec3d.dim(); ++d)
for (int i=0; i < vec3d.size(); ++i)
assert(vec3d[d][i] == m*g1[d]);
}
// Check for LatticeParticleList
{
std::cout << ".. GravityForce for LatticeParticleList" << std::endl;
double g2[3]={9.8, 0., 0.}; // create a different gravity vector
GravityForce gf2(N, g2);
double m2=.2;
std::vector<double> vecm(N,m2);
LatticeParticleList lpl(N, vecm);
const Vector3D& vec3d = gf2.calc_force(lpl);
// Check that the force F=mg
for (int d=0; d < vec3d.dim(); ++d)
for (int i=0; i < vec3d.size(); ++i)
assert(vec3d[d][i] == vecm[i]*g2[d]);
}
std::cout << ".. GravityForce tests passed!" << std::endl;
}
| 27.632653 | 72 | 0.61226 | [
"vector"
] |
d06de7190a562c72ba7498022895ab4e727e6faf | 3,453 | cpp | C++ | modules/stereo_camera/src/json_struct/json_detect_boxes.cpp | dzyswy/stereo-client | 2855500187047e535a6834dcad31cf3c6f2b86a3 | [
"MIT"
] | 2 | 2019-10-17T09:11:29.000Z | 2022-01-17T06:19:25.000Z | modules/stereo_camera/src/json_struct/json_detect_boxes.cpp | dzyswy/stereo-client | 2855500187047e535a6834dcad31cf3c6f2b86a3 | [
"MIT"
] | null | null | null | modules/stereo_camera/src/json_struct/json_detect_boxes.cpp | dzyswy/stereo-client | 2855500187047e535a6834dcad31cf3c6f2b86a3 | [
"MIT"
] | null | null | null | #include "json_detect_boxes.h"
#include "json/json.h"
using namespace std;
json_detect_boxes::json_detect_boxes()
{
}
json_detect_boxes::json_detect_boxes(std::vector<struct stereo_detect_box> &value)
{
detect_boxes_ = value;
}
std::vector<struct stereo_detect_box> json_detect_boxes::to_struct()
{
return detect_boxes_;
}
int json_detect_boxes::from_string(std::string &value)
{
vector<struct stereo_detect_box> detect_boxes;
try {
Json::Reader reader;
Json::Value jroot;
Json::Value jdetect_boxes;
Json::Value jdetect_box;
if (!reader.parse(value, jroot))
return -1;
if (jroot["detect_boxes"].empty())
return -1;
jdetect_boxes = jroot["detect_boxes"];
for (int i = 0; i < jdetect_boxes.size(); i++)
{
jdetect_box = jdetect_boxes[i];
struct stereo_detect_box detect_box;
detect_box.id = jdetect_box["id"].asInt();
detect_box.box_x = jdetect_box["box_x"].asInt();
detect_box.box_y = jdetect_box["box_y"].asInt();
detect_box.box_w = jdetect_box["box_w"].asInt();
detect_box.box_h = jdetect_box["box_h"].asInt();
detect_box.x = jdetect_box["x"].asInt();
detect_box.y = jdetect_box["y"].asInt();
detect_box.d = jdetect_box["d"].asInt();
detect_box.xcm = jdetect_box["xcm"].asInt();
detect_box.ycm = jdetect_box["ycm"].asInt();
detect_box.zcm = jdetect_box["zcm"].asInt();
detect_box.xtcm = jdetect_box["xtcm"].asInt();
detect_box.ytcm = jdetect_box["ytcm"].asInt();
detect_box.ztcm = jdetect_box["ztcm"].asInt();
detect_box.xa = jdetect_box["xa"].asFloat();
detect_box.ya = jdetect_box["ya"].asFloat();
detect_box.r = jdetect_box["r"].asFloat();
detect_box.pan = jdetect_box["pan"].asInt();
detect_box.tilt = jdetect_box["tilt"].asInt();
detect_box.zoom = jdetect_box["zoom"].asInt();
detect_boxes.push_back(detect_box);
}
} catch(std::exception &ex)
{
printf( "jsoncpp struct error: %s.\n", ex.what());
return -1;
}
detect_boxes_ = detect_boxes;
return 0;
}
int json_detect_boxes::to_string(std::string &value)
{
try {
Json::Value jroot;
Json::Value jdetect_boxes;
Json::Value jdetect_box;
for (int i = 0; i < detect_boxes_.size(); i++)
{
struct stereo_detect_box &detect_box = detect_boxes_[i];
jdetect_box["id"] = detect_box.id;
jdetect_box["box_x"] = detect_box.box_x;
jdetect_box["box_y"] = detect_box.box_y;
jdetect_box["box_w"] = detect_box.box_w;
jdetect_box["box_h"] = detect_box.box_h;
jdetect_box["x"] = detect_box.x;
jdetect_box["y"] = detect_box.y;
jdetect_box["d"] = detect_box.d;
jdetect_box["xcm"] = detect_box.xcm;
jdetect_box["ycm"] = detect_box.ycm;
jdetect_box["zcm"] = detect_box.zcm;
jdetect_box["xtcm"] = detect_box.xtcm;
jdetect_box["ytcm"] = detect_box.ytcm;
jdetect_box["ztcm"] = detect_box.ztcm;
jdetect_box["xa"] = detect_box.xa;
jdetect_box["ya"] = detect_box.ya;
jdetect_box["r"] = detect_box.r;
jdetect_box["pan"] = detect_box.pan;
jdetect_box["tilt"] = detect_box.tilt;
jdetect_box["zoom"] = detect_box.zoom;
jdetect_boxes.append(jdetect_box);
}
jroot["detect_boxes"] = jdetect_boxes;
// value = jroot.toStyledString();
Json::StreamWriterBuilder builder;
builder["indentation"] = "";
value = Json::writeString(builder, jroot);
}
catch(std::exception &ex)
{
printf( "jsoncpp struct error: %s.\n", ex.what());
return -1;
}
return 0;
}
| 24.316901 | 82 | 0.670432 | [
"vector"
] |
d077b9b00963bedb360d4a6b6660d4cfbefb830c | 682 | cpp | C++ | Samples/MediaPlayerCPP/FloatToDoubleConverter.cpp | tesar-tech/FFmpegInteropX | db3e24878b5a14038162b27636bd28c1c062c94c | [
"Apache-2.0"
] | 102 | 2019-03-03T03:54:30.000Z | 2022-03-12T13:08:29.000Z | Samples/MediaPlayerCPP/FloatToDoubleConverter.cpp | tesar-tech/FFmpegInteropX | db3e24878b5a14038162b27636bd28c1c062c94c | [
"Apache-2.0"
] | 149 | 2019-02-27T19:08:25.000Z | 2022-03-02T21:43:34.000Z | Samples/MediaPlayerCPP/FloatToDoubleConverter.cpp | tesar-tech/FFmpegInteropX | db3e24878b5a14038162b27636bd28c1c062c94c | [
"Apache-2.0"
] | 34 | 2019-03-17T22:32:22.000Z | 2022-01-23T10:48:52.000Z | #include "pch.h"
#include "FloatToDoubleConverter.h"
Platform::Object^ MediaPlayerCPP::FloatToDoubleConverter::Convert(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language)
{
auto box = static_cast<Platform::IBox<float>^>(value);
return ref new Platform::Box<double>(box->Value);
}
Platform::Object^ MediaPlayerCPP::FloatToDoubleConverter::ConvertBack(Platform::Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language)
{
auto box = static_cast<Platform::IBox<double>^>(value);
return ref new Platform::Box<float>((float)box->Value);
}
| 45.466667 | 200 | 0.765396 | [
"object"
] |
d07ae49f03cfe4554a617ca009d1760aa4a77c78 | 3,133 | cpp | C++ | DMOPC/dmopc15c2p6.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | DMOPC/dmopc15c2p6.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | DMOPC/dmopc15c2p6.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define gc getchar_unlocked()
#define pc(x) putchar_unlocked(x)
template<typename T> void scan(T &x){x = 0;bool _=0;T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;}
template<typename T> void printn(T n){bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=n%10+48;n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);}
template<typename First, typename ... Ints> void scan(First &arg, Ints&... rest){scan(arg);scan(rest...);}
template<typename T> void print(T n){printn(n);pc(10);}
template<typename First, typename ... Ints> void print(First arg, Ints... rest){printn(arg);pc(32);print(rest...);}
using namespace std;
const int MM = 24008, adj = 8002;
int n, m, mx[10], my[10], ans;
#define lc (rt<<1)
#define rc (rt<<1|1)
#define nm ((nl+nr)>>1)
struct st{
//1 add, -1 remove
int op, x, l, r;
bool operator <(const st &o) const{
if(x != o.x)
return x < o.x;
return op > o.op;
}
};
vector<st> q;
struct node{
int val, lp;
} tree[MM*3];
inline void push_up(int rt){
tree[rt].val = max(tree[lc].val, tree[rc].val);
}
// node with lazy val means yet to push to children (but updated itself)
inline void push_down(int rt, int nl, int nr){
int &val = tree[rt].lp;
if(val && nl^nr){
tree[lc].lp += val;
tree[lc].val += val;
tree[rc].lp += val;
tree[rc].val += val;
}
val = 0;
}
void build(int l = 1, int r = MM-1, int rt = 1){
int nl = l, nr = r;
if(l == r){
tree[rt].val = 0;
return;
}
build(l, nm, lc);
build(nm+1, r, rc);
push_up(rt);
}
void update(int l, int r, int val, int nl = 1, int nr = MM-1, int rt = 1){
if(r < nl || l > nr)
return;
if(l <= nl && r >= nr){
tree[rt].val += val;
tree[rt].lp += val;
return;
}
push_down(rt, nl, nr);
update(l, r, val, nl, nm, lc);
update(l, r, val, nm+1, nr, rc);
push_up(rt);
}
int query(int l, int r, int nl = 1, int nr = MM-1, int rt = 1){
if(r < nl || l > nr)
return 0;
if(l <= nl && r >= nr)
return tree[rt].val;
push_down(rt, nl, nr);
return max(query(l, r, nl, nm, lc), query(l, r, nm+1, nr, rc));
}
int main(){
scan(m);
for(int i = 0; i < m; i++)
scan(mx[i], my[i]);
scan(n);
for(int i = 0,x,y,nx,ny,d; i < n; i++){
scan(x, y);
d = 1e9;
for(int j = 0; j < m; j++)
d = min(d, abs(x-mx[j]) + abs(y-my[j]));
d--;
nx = y+x+adj, ny = y-x+adj;
//within [8000, 16000]
//d < 8000
//+-d, within [0, 24000]
//print(nx-d, nx+d, ny-d, ny+d);
q.push_back({1, nx-d, ny-d, ny+d});
q.push_back({-1, nx+d, ny-d, ny+d});
}
sort(q.begin(), q.end());
for(auto i: q){
update(i.l, i.r, i.op);
ans = max(ans, tree[1].val);
}
print(ans);
return 0;
} | 27.008621 | 175 | 0.48037 | [
"vector"
] |
d07b507ef176d3452d06c8177855cbe43cb51d7a | 1,956 | cpp | C++ | codes/ZJU_ICPC/fibtree.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 2 | 2021-03-07T03:34:02.000Z | 2021-03-09T01:22:21.000Z | codes/ZJU_ICPC/fibtree.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 1 | 2021-03-27T15:01:23.000Z | 2021-03-27T15:55:34.000Z | codes/ZJU_ICPC/fibtree.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 1 | 2021-03-27T05:02:33.000Z | 2021-03-27T05:02:33.000Z | #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cassert>
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
#define max_v 100100
#define int_max 0x3f3f3f3f
#define cont continue
#define pow_2(n) (1 << (n))
//tree
#define u second.first
#define v second.second
#define w first
using namespace std;
vector<pair<int, pair<int, int> > > edges;
int parent[max_v], fib[max_v];
int n, m;
bool cmp(const pair<int, pair<int, int>>& a, const pair<int, pair<int, int>>& b){
return a.w > b.w;
}
int find(int x){
if(x != parent[x]) parent[x] = find(parent[x]);
return parent[x];
}
void Union(int x, int y){
x = find(x), y = find(y);
if(x == y) return;
parent[x] = y;
}
void make_DSU(){
for(int i = 0; i <=n; i++) parent[i] = i;
}
int kruskal(){
make_DSU();
int total = 0, cnt = 0;
assert(edges.size());
for(int i = 0; i<edges.size(); i++){
auto x = edges[i];
if(find(x.u) != find(x.v)){
total += x.w;
Union(x.u, x.v);
cnt++;
}
}
//assert(cnt == n - 1);
if(cnt != n - 1){
printf("No");
exit(0);
}
return total;
}
int main(){
scanf("%d%d", &n, &m);
if(m == 0){ printf("No"); return 0;}
for(int i = 0; i<m; i++){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
edges.push_back(make_pair(c, make_pair(b, a)));
edges.push_back(make_pair(c, make_pair(a, b)));
}
sort(edges.begin(), edges.end());
int mini = kruskal();
sort(edges.begin(), edges.end(), cmp);
int maxi = kruskal();
//assert(maxi);
if(maxi == 0){
printf("No");
return 0;
}
fib[1] = 1;
fib[0] = 1;
int i = 2;
while(true){
if(fib[i - 1] + fib[i - 2] > m) break;
fib[i] = fib[i - 1] + fib[i - 2];
i++;
}
bool ans = false;
for(int j = 0; j<i; j++)
if(fib[j] >= mini && fib[j] <= maxi) ans = true;
if(ans) printf("Yes");
else printf("No");
return 0;
}
| 18.807692 | 81 | 0.546524 | [
"vector"
] |
4ee0c4fe0a1934346715b758a464a1618d979977 | 2,636 | cxx | C++ | icetray/private/modules/Keep.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 1 | 2020-12-24T22:00:01.000Z | 2020-12-24T22:00:01.000Z | icetray/private/modules/Keep.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | null | null | null | icetray/private/modules/Keep.cxx | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 3 | 2020-07-17T09:20:29.000Z | 2021-03-30T16:44:18.000Z | /**
* $Id: Keep.cxx 168867 2018-12-07 20:47:53Z mjl5147 $
*
* Copyright (C) 2007
* Dr. Torsten Schmidt <hightech-consulting@gmx.de>
* and the IceCube Collaboration <http://www.icecube.wisc.edu>
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
// class header file
#include <icetray/modules/Keep.h>
I3_MODULE(Keep);
#include <icetray/I3Context.h>
#include <icetray/I3DefaultName.h>
// namespace declarations
using namespace std;
// implementation
Keep::Keep(const I3Context& context)
: I3ConditionalModule(context)
{
keysParam_.push_back("I3Calibration");
keysParam_.push_back("I3DetectorStatus");
keysParam_.push_back("I3Geometry");
keysParam_.push_back("DrivingTime");
keysParam_.push_back("I3EventHeader");
AddParameter("Keys",
"Keep frame objects with names that match any of these keys",
keysParam_);
AddParameter("Streams",
"A list of frame types which this function should fire on. "
"By default runs only on DAQ and physics frames",
std::vector<I3Frame::Stream>{I3Frame::DAQ,I3Frame::Physics});
}
Keep::~Keep(){}
void Keep::Configure()
{
GetParameter("Keys", keysParam_);
set<string> tmp(keysParam_.begin(), keysParam_.end());
keys_.swap(tmp);
std::vector<I3Frame::Stream> svec;
GetParameter("Streams", svec);
streams_ = std::set<I3Frame::Stream>(svec.begin(), svec.end());
}
void Keep::Process()
{
log_trace("%s", "Processing");
I3FramePtr frame = PopFrame();
if(!streams_.count(frame->GetStop()))
// Don't remove anything from this frame!
PushFrame(frame);
else {
// Supposed to run here
I3FramePtr newFrame(new I3Frame(frame->GetStop()));
newFrame->drop_blobs(frame->drop_blobs());
for(set<string>::const_iterator iter = keys_.begin(); iter != keys_.end(); ++iter){
I3Frame::typename_iterator jter = frame->typename_find(*iter);
if(jter != frame->typename_end()) newFrame->take(*frame, *iter);
}
PushFrame(newFrame, "OutBox");
}
}
| 29.954545 | 87 | 0.685129 | [
"vector"
] |
4ee340b351ba490722b96067530210679a549573 | 7,038 | cpp | C++ | ssl/src/v20191205/model/DvAuths.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | ssl/src/v20191205/model/DvAuths.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | ssl/src/v20191205/model/DvAuths.cpp | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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.
*/
#include <tencentcloud/ssl/v20191205/model/DvAuths.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ssl::V20191205::Model;
using namespace rapidjson;
using namespace std;
DvAuths::DvAuths() :
m_dvAuthKeyHasBeenSet(false),
m_dvAuthValueHasBeenSet(false),
m_dvAuthDomainHasBeenSet(false),
m_dvAuthPathHasBeenSet(false),
m_dvAuthSubDomainHasBeenSet(false),
m_dvAuthVerifyTypeHasBeenSet(false)
{
}
CoreInternalOutcome DvAuths::Deserialize(const Value &value)
{
string requestId = "";
if (value.HasMember("DvAuthKey") && !value["DvAuthKey"].IsNull())
{
if (!value["DvAuthKey"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuths.DvAuthKey` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthKey = string(value["DvAuthKey"].GetString());
m_dvAuthKeyHasBeenSet = true;
}
if (value.HasMember("DvAuthValue") && !value["DvAuthValue"].IsNull())
{
if (!value["DvAuthValue"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuths.DvAuthValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthValue = string(value["DvAuthValue"].GetString());
m_dvAuthValueHasBeenSet = true;
}
if (value.HasMember("DvAuthDomain") && !value["DvAuthDomain"].IsNull())
{
if (!value["DvAuthDomain"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuths.DvAuthDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthDomain = string(value["DvAuthDomain"].GetString());
m_dvAuthDomainHasBeenSet = true;
}
if (value.HasMember("DvAuthPath") && !value["DvAuthPath"].IsNull())
{
if (!value["DvAuthPath"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuths.DvAuthPath` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthPath = string(value["DvAuthPath"].GetString());
m_dvAuthPathHasBeenSet = true;
}
if (value.HasMember("DvAuthSubDomain") && !value["DvAuthSubDomain"].IsNull())
{
if (!value["DvAuthSubDomain"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuths.DvAuthSubDomain` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthSubDomain = string(value["DvAuthSubDomain"].GetString());
m_dvAuthSubDomainHasBeenSet = true;
}
if (value.HasMember("DvAuthVerifyType") && !value["DvAuthVerifyType"].IsNull())
{
if (!value["DvAuthVerifyType"].IsString())
{
return CoreInternalOutcome(Error("response `DvAuths.DvAuthVerifyType` IsString=false incorrectly").SetRequestId(requestId));
}
m_dvAuthVerifyType = string(value["DvAuthVerifyType"].GetString());
m_dvAuthVerifyTypeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void DvAuths::ToJsonObject(Value &value, Document::AllocatorType& allocator) const
{
if (m_dvAuthKeyHasBeenSet)
{
Value iKey(kStringType);
string key = "DvAuthKey";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_dvAuthKey.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthValueHasBeenSet)
{
Value iKey(kStringType);
string key = "DvAuthValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_dvAuthValue.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthDomainHasBeenSet)
{
Value iKey(kStringType);
string key = "DvAuthDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_dvAuthDomain.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthPathHasBeenSet)
{
Value iKey(kStringType);
string key = "DvAuthPath";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_dvAuthPath.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthSubDomainHasBeenSet)
{
Value iKey(kStringType);
string key = "DvAuthSubDomain";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_dvAuthSubDomain.c_str(), allocator).Move(), allocator);
}
if (m_dvAuthVerifyTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "DvAuthVerifyType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_dvAuthVerifyType.c_str(), allocator).Move(), allocator);
}
}
string DvAuths::GetDvAuthKey() const
{
return m_dvAuthKey;
}
void DvAuths::SetDvAuthKey(const string& _dvAuthKey)
{
m_dvAuthKey = _dvAuthKey;
m_dvAuthKeyHasBeenSet = true;
}
bool DvAuths::DvAuthKeyHasBeenSet() const
{
return m_dvAuthKeyHasBeenSet;
}
string DvAuths::GetDvAuthValue() const
{
return m_dvAuthValue;
}
void DvAuths::SetDvAuthValue(const string& _dvAuthValue)
{
m_dvAuthValue = _dvAuthValue;
m_dvAuthValueHasBeenSet = true;
}
bool DvAuths::DvAuthValueHasBeenSet() const
{
return m_dvAuthValueHasBeenSet;
}
string DvAuths::GetDvAuthDomain() const
{
return m_dvAuthDomain;
}
void DvAuths::SetDvAuthDomain(const string& _dvAuthDomain)
{
m_dvAuthDomain = _dvAuthDomain;
m_dvAuthDomainHasBeenSet = true;
}
bool DvAuths::DvAuthDomainHasBeenSet() const
{
return m_dvAuthDomainHasBeenSet;
}
string DvAuths::GetDvAuthPath() const
{
return m_dvAuthPath;
}
void DvAuths::SetDvAuthPath(const string& _dvAuthPath)
{
m_dvAuthPath = _dvAuthPath;
m_dvAuthPathHasBeenSet = true;
}
bool DvAuths::DvAuthPathHasBeenSet() const
{
return m_dvAuthPathHasBeenSet;
}
string DvAuths::GetDvAuthSubDomain() const
{
return m_dvAuthSubDomain;
}
void DvAuths::SetDvAuthSubDomain(const string& _dvAuthSubDomain)
{
m_dvAuthSubDomain = _dvAuthSubDomain;
m_dvAuthSubDomainHasBeenSet = true;
}
bool DvAuths::DvAuthSubDomainHasBeenSet() const
{
return m_dvAuthSubDomainHasBeenSet;
}
string DvAuths::GetDvAuthVerifyType() const
{
return m_dvAuthVerifyType;
}
void DvAuths::SetDvAuthVerifyType(const string& _dvAuthVerifyType)
{
m_dvAuthVerifyType = _dvAuthVerifyType;
m_dvAuthVerifyTypeHasBeenSet = true;
}
bool DvAuths::DvAuthVerifyTypeHasBeenSet() const
{
return m_dvAuthVerifyTypeHasBeenSet;
}
| 27.818182 | 136 | 0.690537 | [
"model"
] |
4ee37411be1a27efef376661e2aae6a2b37a709b | 24,604 | cpp | C++ | cpp/opendnp3tests/src/TestAppLayer.cpp | tarm/dnp3_orig | 87c639b3462c980fba255e85793f6ec663abe981 | [
"Apache-2.0"
] | null | null | null | cpp/opendnp3tests/src/TestAppLayer.cpp | tarm/dnp3_orig | 87c639b3462c980fba255e85793f6ec663abe981 | [
"Apache-2.0"
] | null | null | null | cpp/opendnp3tests/src/TestAppLayer.cpp | tarm/dnp3_orig | 87c639b3462c980fba255e85793f6ec663abe981 | [
"Apache-2.0"
] | 3 | 2016-07-13T18:54:13.000Z | 2021-04-12T13:30:39.000Z | /**
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp licenses this file to you 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.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#include <catch.hpp>
#include <openpal/ToHex.h>
#include <openpal/StaticBuffer.h>
#include <opendnp3/DNPErrorCodes.h>
#include <opendnp3/LogLevels.h>
#include "Exception.h"
#include "BufferHelpers.h"
#include "AppLayerTest.h"
#include "HexConversions.h"
using namespace openpal;
using namespace opendnp3;
std::string RequestToHex(FunctionCode function, bool fir, bool fin, bool con, bool uns, uint8_t seq)
{
StaticBuffer<2> buffer;
APDURequest request(buffer.GetWriteBuffer());
request.SetFunction(function);
request.SetControl(AppControlField(fir, fin, con, uns, seq));
return toHex(request.ToReadOnly());
}
std::string ResponseToHex(FunctionCode function, bool fir, bool fin, bool con, bool uns, uint8_t seq)
{
StaticBuffer<4> buffer;
APDUResponse response(buffer.GetWriteBuffer());
response.SetFunction(function);
response.SetControl(AppControlField(fir, fin, con, uns, seq));
response.SetIIN(IINField::Empty);
return toHex(response.ToReadOnly());
}
#define SUITE(name) "AppLayerSuite - " name
// Test the accessible events to demonstrate do not work if the layer is offline
TEST_CASE(SUITE("InitialState"))
{
AppLayerTest t;
t.app.OnLowerLayerDown();
REQUIRE(t.log.PopOneEntry(opendnp3::flags::ERR));
t.app.OnLowerLayerDown();
REQUIRE(t.log.PopOneEntry(opendnp3::flags::ERR));
t.app.OnSendResult(true);
REQUIRE(t.log.PopOneEntry(opendnp3::flags::ERR));
t.app.OnSendResult(false);
REQUIRE(t.log.PopOneEntry(opendnp3::flags::ERR));
t.lower.SendUp("");
REQUIRE(t.log.PopOneEntry(opendnp3::flags::ERR));
}
// Check that Up/Down are forwarded correctly
// and that the state gets reset correctly
TEST_CASE(SUITE("LayerUpDown"))
{
AppLayerTest t(true); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
REQUIRE(t.state == t.user.mState);
t.SendRequest(FunctionCode::READ, true, true, false, false);
t.lower.ThisLayerDown(); ++t.state.NumLayerDown;
REQUIRE(t.state == t.user.mState);
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
REQUIRE(t.state == t.user.mState);
t.SendRequest(FunctionCode::READ, true, true, false, false);
}
// Malformed data should be getting logged
TEST_CASE(SUITE("ParsingErrorsCaptured"))
{
AppLayerTest t; t.lower.ThisLayerUp();
t.lower.SendUp("");
REQUIRE(t.log.NextErrorCode() == ALERR_INSUFFICIENT_DATA_FOR_FRAG);
}
// Test that the correct header validation occurs before passing up Unsol datas
TEST_CASE(SUITE("UnsolErrors"))
{
AppLayerTest t(true); // master
t.lower.ThisLayerUp();
t.SendUp(AppControlField(true, true, true, false, 0), FunctionCode::UNSOLICITED_RESPONSE, IINField()); // UNS = false
REQUIRE(t.log.NextErrorCode() == ALERR_BAD_UNSOL_BIT);
}
// Test that unsol data is correctly confirmed, passed up,
// and that flooding is logged+ignored
TEST_CASE(SUITE("UnsolSuccess"))
{
AppLayerTest t(true); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.lower.DisableAutoSendCallback();
t.SendUp(AppControlField(true, true, true, true, 0), FunctionCode::UNSOLICITED_RESPONSE, IINField()); ++t.state.NumUnsol;
REQUIRE(t.log.IsLogErrorFree());
REQUIRE(t.state == t.user.mState);
REQUIRE(RequestToHex(FunctionCode::CONFIRM, true, true, false, true, 0) == t.lower.PopWriteAsHex());
// if frame requiring confirmation is sent before confirm send success
// it gets ignored and logged
t.SendUp(AppControlField(true, true, true, true, 0), FunctionCode::UNSOLICITED_RESPONSE, IINField());
REQUIRE(t.state == t.user.mState);
REQUIRE(t.log.NextErrorCode() == ALERR_UNSOL_FLOOD);
t.app.OnSendResult(true);
}
// Test that the various send methods reject
// illegal function codes. Also check that the app layer
// is outstation/master aware with respect to send
TEST_CASE(SUITE("SendBadFuncCodeOutstation"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp();
// can't send a response until at least 1 request has been received
// to set the sequence number. Report this as a response failure
t.SendResponse(FunctionCode::RESPONSE, true, true, false, false);
REQUIRE(t.mts.DispatchOne());
REQUIRE(1 == t.user.mState.NumSolFailure);
REQUIRE(t.log.PopOneEntry(opendnp3::flags::ERR));
}
TEST_CASE(SUITE("SendExtraObjectData"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
// doesn't matter what the sequence number is
t.SendUp("C4 01 00 00 06"); ++t.state.NumRequest;
REQUIRE(t.state == t.user.mState);
t.SendResponse(FunctionCode::RESPONSE, true, true, false, false); // no confirmation
REQUIRE(ResponseToHex(FunctionCode::RESPONSE, true, true, false, false, 4) == t.lower.PopWriteAsHex()); //check correct seq
}
// Test a simple send without confirm transaction
TEST_CASE(SUITE("SendResponseWithoutConfirm"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
// doesn't matter what the sequence number is
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
REQUIRE(t.state == t.user.mState);
t.SendResponse(FunctionCode::RESPONSE, true, true, false, false); // no confirmation
REQUIRE(ResponseToHex(FunctionCode::RESPONSE, true, true, false, false, 4) == t.lower.PopWriteAsHex()); //check correct seq
++t.state.NumSolSendSuccess;
REQUIRE(t.state == t.user.mState);
}
// Test a simple send without confirm transaction
TEST_CASE(SUITE("SendResponseFailure"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.lower.EnableAutoSendCallback(false);
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.SendResponse(FunctionCode::RESPONSE, true, true, false, false); // no confirmation
++t.state.NumSolFailure;
REQUIRE(t.state == t.user.mState);
}
// Test a send with confirm
TEST_CASE(SUITE("SendResponseWithConfirm"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.SendResponse(FunctionCode::RESPONSE, true, false, true, false); // with confirmation, should start on timer
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.NumActive() == 1);
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::CONFIRM); ++t.state.NumSolSendSuccess;
REQUIRE(t.mts.NumActive() == 0);
REQUIRE(t.state == t.user.mState);
}
// Test a send with confirm
TEST_CASE(SUITE("CancelResponseWhileSending"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.lower.DisableAutoSendCallback();
t.SendResponse(FunctionCode::RESPONSE, true, false, true, false); // with confirmation
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.NumActive() == 0);
// before any send success or failure comes back, cancel the operation
t.app.CancelResponse();
REQUIRE(t.state == t.user.mState);
// now report that that the send has completed successfully, but this should cause the
// the app layer to inform the user that the send has failed
t.app.OnSendResult(true); ++t.state.NumSolFailure;
REQUIRE(t.state == t.user.mState);
}
// Test a send with confirm
TEST_CASE(SUITE("CancelResponseWhileAwaitingConfirm"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.SendResponse(FunctionCode::RESPONSE, true, false, true, false); // with confirmation
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.NumActive() == 1);
t.app.CancelResponse(); ++t.state.NumSolFailure;
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.NumActive() == 0); //the timer should get canceled
}
TEST_CASE(SUITE("NewRequestWhileAwaitingConfirm"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.SendResponse(FunctionCode::RESPONSE, true, false, true, false); // with confirmation
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.NumActive() == 1);
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.app.CancelResponse(); ++t.state.NumSolFailure;
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.NumActive() == 0); //the timer should get canceled
t.SendResponse(FunctionCode::RESPONSE, true, false, true, false); // with confirmation
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.NumActive() == 1);
}
// Test a send with confirm timeout
TEST_CASE(SUITE("SendResponseWithConfirmTimeout"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.SendResponse(FunctionCode::RESPONSE, true, false, true, false); // with confirmation
REQUIRE(t.state == t.user.mState);
REQUIRE(t.mts.DispatchOne()); ++t.state.NumSolFailure;
REQUIRE(t.state == t.user.mState);
}
// Test a non-fir send, this should
// increment the sequence number
TEST_CASE(SUITE("SendResponseNonFIR"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUp(AppControlField(true, true, false, false, 4), FunctionCode::READ); ++t.state.NumRequest;
t.SendResponse(FunctionCode::RESPONSE, false, false, true, false); //non-FIR, will increment seq number
t.SendUp(AppControlField(true, true, false, false, 2), FunctionCode::CONFIRM); //wrong seq number
REQUIRE(t.state == t.user.mState);
REQUIRE(t.log.NextErrorCode() == ALERR_UNEXPECTED_CONFIRM);
t.SendUp(AppControlField(true, true, false, false, 5), FunctionCode::CONFIRM); ++t.state.NumSolSendSuccess; // correct seq
REQUIRE(t.state == t.user.mState);
}
// Test an unsol send with confirm transaction
TEST_CASE(SUITE("SendUnsolicitedWithConfirm"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUnsolicited(FunctionCode::UNSOLICITED_RESPONSE, true, true, true, true);
REQUIRE(t.mts.NumActive() == 1);
t.SendUp(AppControlField(true, true, false, false, 0), FunctionCode::CONFIRM); // solicited confirm, should do nothing
REQUIRE(t.log.NextErrorCode() == ALERR_UNEXPECTED_CONFIRM);
REQUIRE(t.state == t.user.mState);
t.SendUp(AppControlField(true, true, false, true, 0), FunctionCode::CONFIRM); ++t.state.NumUnsolSendSuccess; // unsol confirm
REQUIRE(t.state == t.user.mState);
}
// Test an unsol send with confirm timeout
TEST_CASE(SUITE("SendUnsolicitedWithConfirmTimeout"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUnsolicited(FunctionCode::UNSOLICITED_RESPONSE, true, true, true, true);
REQUIRE(t.mts.DispatchOne()); ++t.state.NumUnsolFailure;
REQUIRE(t.state == t.user.mState);
}
// Test a single response transaction
TEST_CASE(SUITE("SendRequestSingleResponse"))
{
AppLayerTest t(true); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendRequest(FunctionCode::READ, true, true, false, false);
REQUIRE(t.mts.NumActive() == 1); //check that we're waiting for a response
t.SendUp(AppControlField(true, true, false, false, 0), FunctionCode::RESPONSE, IINField()); ++t.state.NumFinalRsp; // final response
REQUIRE(t.mts.NumActive() == 0);
REQUIRE(t.state == t.user.mState);
}
// Test a response timeout
TEST_CASE(SUITE("SendRequestResponseTimeout"))
{
AppLayerTest t(true); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendRequest(FunctionCode::READ, true, true, false, false);
REQUIRE(t.mts.DispatchOne()); ++t.state.NumSolFailure;
REQUIRE(t.state == t.user.mState);
}
// Test a multi-fragmented response transaction
TEST_CASE(SUITE("SendRequestMultiResponse"))
{
AppLayerTest t(true); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendRequest(FunctionCode::READ, true, true, false, false);
REQUIRE(t.mts.NumActive() == 1); //check that we're waiting for a response
t.SendUp(AppControlField(false, true, false, false, 0), FunctionCode::RESPONSE, IINField()); // check that bad FIR is rejected
REQUIRE(t.log.NextErrorCode() == ALERR_BAD_FIR_FIN);
REQUIRE(t.mts.NumActive() == 1);
REQUIRE(t.state == t.user.mState);
t.SendUp(AppControlField(true, false, false, false, 0), FunctionCode::RESPONSE, IINField()); ++t.state.NumPartialRsp; // partial response
REQUIRE(t.mts.NumActive() == 1);
REQUIRE(t.state == t.user.mState);
t.SendUp(AppControlField(false, false, false, false, 0), FunctionCode::RESPONSE, IINField()); // check that a bad sequence number is rejected
REQUIRE(t.state == t.user.mState);
REQUIRE(t.log.NextErrorCode() == ALERR_BAD_SEQUENCE);
t.SendUp(AppControlField(false, false, false, false, 1), FunctionCode::RESPONSE, IINField()); ++t.state.NumPartialRsp;
REQUIRE(t.mts.NumActive() == 1);
REQUIRE(t.state == t.user.mState);
t.SendUp(AppControlField(true, true, false, false, 2), FunctionCode::RESPONSE, IINField()); // check that a bad FIR bit is rejected
REQUIRE(t.log.NextErrorCode() == ALERR_BAD_FIR_FIN);
REQUIRE(t.mts.NumActive() == 1);
REQUIRE(t.state == t.user.mState);
t.SendUp(AppControlField(false, true, false, false, 2), FunctionCode::RESPONSE, IINField()); ++t.state.NumFinalRsp;
REQUIRE(t.mts.NumActive() == 0);
REQUIRE(t.state == t.user.mState);
}
// The SendRequest transaction needs to gracefully confirm and handle
// incoming unsolicited data before receiving it's response
TEST_CASE(SUITE("MasterUnsolictedDuringRequest"))
{
AppLayerTest t(true); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendRequest(FunctionCode::READ, true, true, false, false); // write a request
REQUIRE(RequestToHex(FunctionCode::READ, true, true, false, false, 0) == t.lower.PopWriteAsHex());
// this should queue a confirm and pass the data up immediately
t.SendUp(AppControlField(true, true, true, true, 5), FunctionCode::UNSOLICITED_RESPONSE, IINField()); ++t.state.NumUnsol;
REQUIRE(t.state == t.user.mState);
REQUIRE(RequestToHex(FunctionCode::CONFIRM, true, true, false, true, 5) == t.lower.PopWriteAsHex()); //verify and clear the buffer
t.SendUp(AppControlField(true, true, true, false, 0), FunctionCode::RESPONSE, IINField()); ++t.state.NumFinalRsp;
REQUIRE(t.state == t.user.mState);
REQUIRE(RequestToHex(FunctionCode::CONFIRM, true, true, false, false, 0) == t.lower.PopWriteAsHex()); // check that the response gets confirmed
}
/** The SendUnsolicited transaction needs to gracefully pass up
requests while doing an unsolicited transaction. It's up to the
outstation itself to buffer the last such request and process it
after the unsol transaction is complete. */
TEST_CASE(SUITE("OutstationRequestDuringUnsolicited"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUnsolicited(FunctionCode::UNSOLICITED_RESPONSE, true, true, true, true);
// this should queue a confirm and pass the data up immediately
t.SendUp(AppControlField(true, true, false, false, 0), FunctionCode::READ); ++t.state.NumRequest;
REQUIRE(t.state == t.user.mState);
t.SendUp(AppControlField(true, true, false, true, 0), FunctionCode::CONFIRM); ++t.state.NumUnsolSendSuccess; //confirm the unsolicited
REQUIRE(t.state == t.user.mState);
}
/** Test that no retries are performed by default */
TEST_CASE(SUITE("TestNoRetries"))
{
AppLayerTest t(false); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUnsolicited(FunctionCode::UNSOLICITED_RESPONSE, true, true, true, true);
REQUIRE(t.lower.NumWrites() == 1);
REQUIRE(t.mts.DispatchOne()); ++t.state.NumUnsolFailure;// timeout the unsol confirm
REQUIRE(t.lower.NumWrites() == 1);
REQUIRE(t.state == t.user.mState);
}
/** Test that retries are performed for unsol */
TEST_CASE(SUITE("TestUnsolRetries"))
{
const size_t RETRIES = 3;
AppLayerTest t(false, RETRIES); // outstation
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendUnsolicited(FunctionCode::UNSOLICITED_RESPONSE, true, true, true, true);
for(size_t i = 0; i < (RETRIES + 1); ++i)
{
REQUIRE(t.lower.NumWrites() == i + 1);
REQUIRE(t.mts.DispatchOne()); // timeout the confirm
}
++t.state.NumUnsolFailure;
REQUIRE(t.state == t.user.mState);
}
/** Test that retries are performed for a solicited request */
TEST_CASE(SUITE("TestOperateRetries"))
{
const size_t RETRIES = 3;
AppLayerTest t(true, RETRIES); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendRequest(FunctionCode::OPERATE, true, true, false, false);
for(size_t i = 0; i < (RETRIES + 1); ++i)
{
REQUIRE(t.lower.NumWrites() == i + 1);
REQUIRE(t.mts.DispatchOne()); // timeout the response
}
++t.state.NumSolFailure;
REQUIRE(t.state == t.user.mState);
}
/** Test that retries are performed for a solicited request */
TEST_CASE(SUITE("TestRetrieReentrancy"))
{
const size_t RETRIES = 1;
AppLayerTest t(true, RETRIES); // master
t.lower.ThisLayerUp(); ++t.state.NumLayerUp;
t.SendRequest(FunctionCode::OPERATE, true, true, false, false);
REQUIRE(t.lower.NumWrites() == 1);
REQUIRE(t.mts.DispatchOne()); // timeout the response
REQUIRE(t.lower.NumWrites() == 2);
}
TEST_CASE(SUITE("LargeFrame"))
{
AppLayerTest t(true, 1);
t.lower.ThisLayerUp();
HexSequence hex("80 81 06 00 01 01 01 00 00 FF 03 55 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A 02 01 00 00 FF 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 1E 05 01 00 00 13 01 01 63 81 D8 45 01 01 F7 5B C3 01 08 71 90 3E 01 00 00 70 42 01 00 00 80 3F 01 00 00 80 3F 01 B5 81 D8 45 01 00 00 80 3F 01 00 00 80 3F 01 B4 81 D8 45 01 00 00 80 3F 01 00 00 80 3F 01 9A 81 D8 45 01 37 B2 6F 43 01 72 6C 35 46 01 D8 CA 7A 44 01 31 B2 6F 43 01 70 E7 23 46 01 CB 7F 62 44 01 37 B2 6F 43 01 27 22 13 46 01 11 64 4B 44 01 37 B2 6F 43 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 C8 42 01 D0 2A 5F 42 01 7E 89 8C C2 01 D0 72 5D 40 01 CF 93 10 40 01 76 75 E5 42 01 43 B2 15 C3 01 E9 5E 65 42 01 4D BC 8A C2 01 99 1D 91 C2 01 B9 E7 FA 3D 01 49 00 7A 44 01 84 4E 86 C2 01 3D 8F E6 3D 01 48 00 7A 44 01 A6 C3 A0 C2 01 CD D7 F4 3D 01 2A 00 7A 44 01 31 B2 6F 43 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 C8 42 01 37 B2 6F 43 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 C8 42 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00 01 00 00 00 00");
t.SendRequest(FunctionCode::READ, true, true, false, false); //get the app layer into a mode to receive a request
t.app.OnReceive(hex.ToReadOnly());
}
| 50.834711 | 6,155 | 0.715453 | [
"3d"
] |
4eed87fe92294242f95205e75421d40b7a010bc8 | 1,225 | cpp | C++ | Scripts/443.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | 17 | 2018-08-23T08:53:56.000Z | 2021-04-17T00:06:13.000Z | Scripts/443.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | Scripts/443.cpp | zzz0906/LeetCode | cd0b4a4fd03d0dff585c9ef349984eba1922ece0 | [
"MIT"
] | null | null | null | class Solution {
public:
int compress(vector<char>& chars) {
if (chars.size() <= 1){
return chars.size();
}
int last = chars[0];
int lastCount = 1;
int index = 0;
for (int i = 1; i < chars.size(); i++){
if (chars[i] == last){
lastCount++;
}else{
if (lastCount == 1){
chars[index] = last;
index += 1;
}else{
chars[index] = last;
int start = 1;
for (auto c : to_string(lastCount)){
chars[index + start] = c;
start ++;
}
index += start;
}
lastCount = 1;
last = chars[i];
}
}
if (lastCount == 1){
chars[index] = last;
index += 1;
}else{
chars[index] = last;
int start = 1;
for (auto c : to_string(lastCount)){
chars[index + start] = c;
start ++;
}
index += start;
}
return index;
}
}; | 27.222222 | 56 | 0.337959 | [
"vector"
] |
4ef1852adeb35ce409b42ca4497187ed65e2792d | 15,401 | cpp | C++ | ds/netapi/svcdlls/lls/ccfapi32/utils.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/netapi/svcdlls/lls/ccfapi32/utils.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/netapi/svcdlls/lls/ccfapi32/utils.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1994-95 Microsoft Corporation
Module Name:
utils.cpp
Abstract:
Utiltities.
Author:
Don Ryan (donryan) 04-Jan-1995
Environment:
User Mode - Win32
Revision History:
Jeff Parham (jeffparh) 12-Nov-1995
Copied from LLSMGR, stripped Tv (Tree view) functions,
removed OLE support
--*/
#include "stdafx.h"
#include "ccfapi.h"
#include "utils.h"
#define _AFX_NO_OLE_SUPPORT
//
// List view utilities
//
void LvInitColumns(CListCtrl* pListCtrl, PLV_COLUMN_INFO plvColumnInfo)
/*++
Routine Description:
Initializes list view columns.
Arguments:
pListCtrl - list control.
plvColumnInfo - column information.
Return Values:
None.
--*/
{
ASSERT(plvColumnInfo);
VALIDATE_OBJECT(pListCtrl, CListCtrl);
int nStringId;
CString strText;
LV_COLUMN lvColumn;
int nColumns = plvColumnInfo->nColumns;
ASSERT(NULL != plvColumnInfo);
PLV_COLUMN_ENTRY plvColumnEntry = plvColumnInfo->lvColumnEntry;
lvColumn.mask = LVCF_FMT|
LVCF_TEXT|
LVCF_SUBITEM;
lvColumn.fmt = LVCFMT_LEFT;
pListCtrl->SetRedraw(FALSE); // turn off drawing...
while (nColumns--)
{
lvColumn.iSubItem = plvColumnEntry->iSubItem;
if (0 < (nStringId = plvColumnEntry->nStringId))
{
strText.LoadString(nStringId);
}
else
{
strText = _T("");
}
lvColumn.pszText = strText.GetBuffer(0);
int nColumnInserted = pListCtrl->InsertColumn( lvColumn.iSubItem, &lvColumn );
ASSERT( -1 != nColumnInserted );
plvColumnEntry++;
strText.ReleaseBuffer();
}
SetDefaultFont(pListCtrl);
LvResizeColumns(pListCtrl, plvColumnInfo);
pListCtrl->SetRedraw(TRUE); // turn on drawing...
}
void LvResizeColumns(CListCtrl* pListCtrl, PLV_COLUMN_INFO plvColumnInfo)
/*++
Routine Description:
Resizes list view columns.
Arguments:
pListCtrl - list control.
plvColumnInfo - column information.
Return Values:
None.
--*/
{
ASSERT(plvColumnInfo);
VALIDATE_OBJECT(pListCtrl, CListCtrl);
int nColumnWidth;
int nRelativeWidth;
int nEntireWidthSoFar = 0;
int nColumns = plvColumnInfo->nColumns;
PLV_COLUMN_ENTRY plvColumnEntry = plvColumnInfo->lvColumnEntry;
CRect clientRect;
ASSERT(NULL != pListCtrl);
pListCtrl->GetClientRect(clientRect);
pListCtrl->SetRedraw(FALSE); // turn off drawing...
while ((nRelativeWidth = plvColumnEntry->nRelativeWidth) != -1)
{
nColumnWidth = (nRelativeWidth * clientRect.Width()) / 100;
pListCtrl->SetColumnWidth(plvColumnEntry->iSubItem, nColumnWidth);
nEntireWidthSoFar += nColumnWidth;
plvColumnEntry++;
}
nColumnWidth = clientRect.Width() - nEntireWidthSoFar;
pListCtrl->SetColumnWidth(plvColumnEntry->iSubItem, nColumnWidth);
pListCtrl->SetRedraw(TRUE); // turn on drawing...
}
void LvChangeFormat(CListCtrl* pListCtrl, UINT nFormatId)
/*++
Routine Description:
Changes window style of list view.
Arguments:
pListCtrl - list control.
nFormatId - format specification.
Return Values:
None.
--*/
{
VALIDATE_OBJECT(pListCtrl, CListCtrl);
DWORD dwStyle = ::GetWindowLong(pListCtrl->GetSafeHwnd(), GWL_STYLE);
ASSERT(NULL != pListCtrl);
pListCtrl->BeginWaitCursor();
pListCtrl->SetRedraw(FALSE); // turn off drawing...
if ((dwStyle & LVS_TYPEMASK) != nFormatId)
{
::SetWindowLong(
pListCtrl->GetSafeHwnd(),
GWL_STYLE,
(dwStyle & ~LVS_TYPEMASK) | nFormatId
);
}
pListCtrl->SetRedraw(TRUE); // turn on drawing...
pListCtrl->EndWaitCursor();
}
LPVOID LvGetSelObj(CListCtrl* pListCtrl)
/*++
Routine Description:
Retrieves the object selected (assumes one) from list view.
Arguments:
pListCtrl - list control.
Return Values:
Same as LvGetNextObj.
--*/
{
int iItem = -1;
return LvGetNextObj(pListCtrl, &iItem);
}
LPVOID LvGetNextObj(CListCtrl* pListCtrl, LPINT piItem, int nType)
/*++
Routine Description:
Retrieves the next object selected from list view.
Arguments:
pListCtrl - list control.
piItem - starting index (updated).
nType - specifies search criteria.
Return Values:
Returns object pointer or null.
--*/
{
ASSERT(piItem);
VALIDATE_OBJECT(pListCtrl, CListCtrl);
LV_ITEM lvItem;
ASSERT(NULL != pListCtrl);
if ((lvItem.iItem = pListCtrl->GetNextItem(*piItem, nType)) != -1)
{
lvItem.mask = LVIF_PARAM;
lvItem.iSubItem = 0;
if (pListCtrl->GetItem(&lvItem))
{
*piItem = lvItem.iItem;
return (LPVOID)lvItem.lParam;
}
}
return NULL;
}
BOOL LvInsertObArray(CListCtrl* pListCtrl, PLV_COLUMN_INFO plvColumnInfo, CObArray* pObArray)
/*++
Routine Description:
Insert object array into list view.
Note list view must be unsorted and support LVN_GETDISPINFO.
Arguments:
pListCtrl - list control.
plvColumnInfo - column info.
pObArray - object array.
Return Values:
VT_BOOL.
--*/
{
VALIDATE_OBJECT(pObArray, CObArray);
VALIDATE_OBJECT(pListCtrl, CListCtrl);
ASSERT(plvColumnInfo);
ASSERT(NULL != pListCtrl);
ASSERT(pListCtrl->GetItemCount() == 0);
BOOL bItemsInserted = FALSE;
LV_ITEM lvItem;
lvItem.mask = LVIF_TEXT|
LVIF_PARAM|
LVIF_IMAGE;
lvItem.pszText = LPSTR_TEXTCALLBACK;
lvItem.cchTextMax = LPSTR_TEXTCALLBACK_MAX;
lvItem.iImage = I_IMAGECALLBACK;
lvItem.iSubItem = 0;
int iItem;
int iSubItem;
int nItems = (int)pObArray->GetSize();
ASSERT(nItems != -1); // iItem is -1 if error...
pListCtrl->SetRedraw(FALSE); // turn off drawing...
pListCtrl->SetItemCount(nItems);
CObject* pObject = NULL;
for (iItem = 0; (-1 != iItem) && (iItem < nItems) && (NULL != (pObject = pObArray->GetAt(iItem))); iItem++)
{
VALIDATE_OBJECT(pObject, CObject);
lvItem.iItem = iItem;
lvItem.lParam = (LPARAM)(LPVOID)pObject;
iItem = pListCtrl->InsertItem(&lvItem);
ASSERT((iItem == lvItem.iItem) || (iItem == -1));
if ( -1 != iItem )
{
for (iSubItem = 1; iSubItem < plvColumnInfo->nColumns; iSubItem++)
{
BOOL ok = pListCtrl->SetItemText(iItem, iSubItem, LPSTR_TEXTCALLBACK);
ASSERT( ok );
}
}
}
if (iItem == nItems)
{
bItemsInserted = TRUE;
VERIFY(pListCtrl->SetItemState(
0,
LVIS_FOCUSED|
LVIS_SELECTED,
LVIS_FOCUSED|
LVIS_SELECTED
));
}
else
{
theApp.SetLastError(ERROR_OUTOFMEMORY);
VERIFY(pListCtrl->DeleteAllItems());
}
LvResizeColumns(pListCtrl, plvColumnInfo);
pListCtrl->SetRedraw(TRUE); // turn on drawing...
return bItemsInserted;
}
BOOL
LvRefreshObArray(
CListCtrl* pListCtrl,
PLV_COLUMN_INFO plvColumnInfo,
CObArray* pObArray
)
/*++
Routine Description:
Refresh object array in list view.
Arguments:
pListCtrl - list control.
plvColumnInfo - column info.
pObArray - object array.
Return Values:
VT_BOOL.
--*/
{
ASSERT(plvColumnInfo);
VALIDATE_OBJECT(pObArray, CObArray);
VALIDATE_OBJECT(pListCtrl, CListCtrl);
long nObjects = (long)pObArray->GetSize();
long nObjectsInList = pListCtrl->GetItemCount();
if (!nObjects)
{
LvReleaseObArray(pListCtrl);
return TRUE;
}
else if (!nObjectsInList)
{
return LvInsertObArray(
pListCtrl,
plvColumnInfo,
pObArray
);
}
CObject* pObject;
int iObject = 0;
int iObjectInList = 0;
LV_ITEM lvItem;
ASSERT(NULL != pListCtrl);
pListCtrl->SetRedraw(FALSE); // turn off drawing...
while (nObjectsInList--)
{
lvItem.mask = LVIF_PARAM;
lvItem.iItem = iObjectInList;
lvItem.iSubItem = 0;
VERIFY(pListCtrl->GetItem(&lvItem));
pObject = (CObject*)lvItem.lParam;
VALIDATE_OBJECT(pObject, CObject);
if (iObject < nObjects)
{
pObject = pObArray->GetAt(iObject++);
VALIDATE_OBJECT(pObject, CObject);
lvItem.mask = LVIF_TEXT|LVIF_PARAM;
lvItem.pszText = LPSTR_TEXTCALLBACK;
lvItem.cchTextMax = LPSTR_TEXTCALLBACK_MAX;
lvItem.lParam = (LPARAM)(LPVOID)pObject;
VERIFY(pListCtrl->SetItem(&lvItem)); // overwrite...
iObjectInList++; // increment count...
}
else
{
VERIFY(pListCtrl->DeleteItem(iObjectInList));
}
}
lvItem.mask = LVIF_TEXT|
LVIF_PARAM|
LVIF_IMAGE;
lvItem.pszText = LPSTR_TEXTCALLBACK;
lvItem.cchTextMax = LPSTR_TEXTCALLBACK_MAX;
lvItem.iImage = I_IMAGECALLBACK;
lvItem.iSubItem = 0;
int iItem;
int iSubItem;
while (iObject < nObjects)
{
lvItem.iItem = iObject;
pObject = pObArray->GetAt(iObject++);
VALIDATE_OBJECT(pObject, CObject);
lvItem.lParam = (LPARAM)(LPVOID)pObject;
iItem = pListCtrl->InsertItem(&lvItem);
ASSERT((iItem == lvItem.iItem) && (iItem != -1));
for (iSubItem = 1; iSubItem < plvColumnInfo->nColumns; iSubItem++)
{
VERIFY(pListCtrl->SetItemText(iItem, iSubItem, LPSTR_TEXTCALLBACK));
}
}
LvResizeColumns(pListCtrl, plvColumnInfo);
pListCtrl->SetRedraw(TRUE); // turn on drawing...
return TRUE;
}
void LvReleaseObArray(CListCtrl* pListCtrl)
/*++
Routine Description:
Release objects inserted into list view.
Arguments:
pListCtrl - list control.
Return Values:
None.
--*/
{
VALIDATE_OBJECT(pListCtrl, CListCtrl);
LV_ITEM lvItem;
CObject* pObject;
lvItem.mask = LVIF_PARAM;
lvItem.iItem = 0;
lvItem.iSubItem = 0;
ASSERT(NULL != pListCtrl);
int nObjectsInList = pListCtrl->GetItemCount();
pListCtrl->BeginWaitCursor();
pListCtrl->SetRedraw(FALSE); // turn off drawing...
while (nObjectsInList--)
{
VERIFY(pListCtrl->GetItem(&lvItem));
pObject = (CObject*)lvItem.lParam;
VALIDATE_OBJECT(pObject, CObject);
VERIFY(pListCtrl->DeleteItem(lvItem.iItem));
}
pListCtrl->SetRedraw(TRUE); // turn on drawing...
pListCtrl->EndWaitCursor();
}
void LvReleaseSelObjs(CListCtrl* pListCtrl)
/*++
Routine Description:
Release selected objects in list view.
Arguments:
pListCtrl - list control.
Return Values:
None.
--*/
{
VALIDATE_OBJECT(pListCtrl, CListCtrl);
LV_ITEM lvItem;
lvItem.mask = LVIF_PARAM;
lvItem.iSubItem = 0;
CObject* pObject;
ASSERT(NULL != pListCtrl);
pListCtrl->SetRedraw(FALSE); // turn off drawing...
int iItem = pListCtrl->GetNextItem(-1, LVNI_ALL|LVNI_SELECTED);
while (iItem != -1)
{
lvItem.iItem = iItem;
VERIFY(pListCtrl->GetItem(&lvItem));
pObject = (CObject*)lvItem.lParam;
VALIDATE_OBJECT(pObject, CObject);
iItem = pListCtrl->GetNextItem(lvItem.iItem, LVNI_ALL|LVNI_SELECTED);
VERIFY(pListCtrl->DeleteItem(lvItem.iItem));
}
LvSelObjIfNecessary(pListCtrl);
pListCtrl->SetRedraw(TRUE); // turn on drawing...
}
void LvSelObjIfNecessary(CListCtrl* pListCtrl, BOOL bSetFocus)
/*++
Routine Description:
Ensure that object selected.
Arguments:
pListCtrl - list control.
bSetFocus - true if focus to be set focus as well.
Return Values:
None.
--*/
{
VALIDATE_OBJECT(pListCtrl, CListCtrl);
if (!IsItemSelectedInList(pListCtrl) && pListCtrl->GetItemCount())
{
pListCtrl->SendMessage(WM_KEYDOWN, VK_RIGHT); // HACKHACK...
int iItem = pListCtrl->GetNextItem(-1, LVNI_FOCUSED|LVNI_ALL);
int nState = bSetFocus ? (LVIS_SELECTED|LVIS_FOCUSED) : LVIS_SELECTED;
VERIFY(pListCtrl->SetItemState((iItem == -1) ? 0 : iItem, nState, nState));
}
}
#ifdef _DEBUG
void LvDumpObArray(CListCtrl* pListCtrl)
/*++
Routine Description:
Release objects inserted into list view.
Arguments:
pListCtrl - list control.
Return Values:
None.
--*/
{
VALIDATE_OBJECT(pListCtrl, CListCtrl);
LV_ITEM lvItem;
CString strDump;
CObject* pObject;
lvItem.mask = LVIF_STATE|LVIF_PARAM;
lvItem.stateMask = (DWORD)-1;
lvItem.iSubItem = 0;
ASSERT(NULL != pListCtrl);
int nObjectsInList = pListCtrl->GetItemCount();
pListCtrl->SetRedraw(FALSE); // turn off drawing...
while (nObjectsInList--)
{
lvItem.iItem = nObjectsInList;
VERIFY(pListCtrl->GetItem(&lvItem));
pObject = (CObject*)lvItem.lParam;
VALIDATE_OBJECT(pObject, CObject);
strDump.Format(_T("iItem %d"), lvItem.iItem);
strDump += (lvItem.state & LVIS_CUT) ? _T(" LVIS_CUT ") : _T("");
strDump += (lvItem.state & LVIS_FOCUSED) ? _T(" LVIS_FOCUSED ") : _T("");
strDump += (lvItem.state & LVIS_SELECTED) ? _T(" LVIS_SELECTED ") : _T("");
strDump += _T("\r\n");
afxDump << strDump;
}
pListCtrl->SetRedraw(TRUE); // turn on drawing...
}
#endif
void SetDefaultFont(CWnd* pWnd)
/*++
Routine Description:
Set default font.
Arguments:
pWnd - window to change font.
Return Values:
None.
--*/
{
VALIDATE_OBJECT(pWnd, CWnd);
HFONT hFont;
LOGFONT lFont;
CHARSETINFO csi;
DWORD dw = ::GetACP();
TCHAR szData[7] ;
LANGID wLang = GetUserDefaultUILanguage();
csi.ciCharset = DEFAULT_CHARSET;
if( GetLocaleInfo(MAKELCID(wLang, SORT_DEFAULT), LOCALE_IDEFAULTANSICODEPAGE, szData, (sizeof( szData ) / sizeof( TCHAR ))) > 0)
{
UINT uiCp = _ttoi(szData);
TranslateCharsetInfo((DWORD*) (DWORD_PTR)uiCp, &csi, TCI_SRCCODEPAGE);
}
ZeroMemory(&lFont, sizeof(lFont)); // initialize
//
// Merged from FE NT 4.0.
//
// if (!::TranslateCharsetInfo((DWORD*)dw, &csi, TCI_SRCCODEPAGE))
// csi.ciCharset = DEFAULT_CHARSET;
lFont.lfCharSet = (BYTE)csi.ciCharset;
lFont.lfHeight = 13;
lFont.lfWeight = 200; // non-bold
hFont = ::CreateFontIndirect(&lFont);
pWnd->SetFont(CFont::FromHandle(hFont));
}
| 20.728129 | 133 | 0.590676 | [
"object"
] |
4ef8b6f346be196e9778d2ded5f92abca14ae5cd | 30,008 | cpp | C++ | previz.cpp | murtaza64/code_samples | 31503beb36c85aec05d273290b71a8112c46f143 | [
"MTLL"
] | null | null | null | previz.cpp | murtaza64/code_samples | 31503beb36c85aec05d273290b71a8112c46f143 | [
"MTLL"
] | null | null | null | previz.cpp | murtaza64/code_samples | 31503beb36c85aec05d273290b71a8112c46f143 | [
"MTLL"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <float.h>
#include "SETTINGS.h"
#include "skeleton.h"
#include "displaySkeleton.h"
#include "motion.h"
using namespace std;
#define PLASTIC 0
#define MIRROR 1
#define GLASS 2
#define SS_GRID_SIZE 0.005
typedef struct cylinderInfo {
Matrix3d R;
VEC3 translation;
} cylinderInfo;
typedef struct cylinder {
VEC3 leftVertex;
VEC3 rightVertex;
float radius;
VEC3 color;
cylinderInfo info;
} cylinder;
typedef struct {
VEC3 origin;
VEC3 dir;
int in_glass;
} ray;
typedef struct {
VEC3 center;
VEC3 color;
float radius;
int material;
} sphere;
typedef struct {
VEC3 pos;
VEC3 color;
} light;
typedef struct {
VEC3 a;
VEC3 b;
VEC3 c;
int material;
VEC3 color;
} triangle;
typedef enum {NONE, SPHERE, CYLINDER, TRIANGLE} intersectType;
// Stick-man classes
DisplaySkeleton displayer;
Skeleton* skeleton;
Motion* motion;
int windowWidth = 640;
int windowHeight = 480;
VEC3 eye(-6, 0.5, 1);
VEC3 lookingAt(5, 0.5, 1);
VEC3 up(0,1,0);
// scene geometry
vector<VEC3> sphereCenters;
vector<float> sphereRadii;
vector<VEC3> sphereColors;
vector<cylinder> cylinders;
vector<sphere> spheres;
vector<triangle> tris;
light lights[2];
int nlights;
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void writePPM(const string& filename, int& xRes, int& yRes, const float* values)
{
int totalCells = xRes * yRes;
unsigned char* pixels = new unsigned char[3 * totalCells];
for (int i = 0; i < 3 * totalCells; i++)
pixels[i] = values[i];
FILE *fp;
fp = fopen(filename.c_str(), "wb");
if (fp == NULL)
{
cout << " Could not open file \"" << filename.c_str() << "\" for writing." << endl;
cout << " Make sure you're not trying to write from a weird location or with a " << endl;
cout << " strange filename. Bailing ... " << endl;
exit(0);
}
fprintf(fp, "P6\n%d %d\n255\n", xRes, yRes);
fwrite(pixels, 1, totalCells * 3, fp);
fclose(fp);
delete[] pixels;
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void calculateCylinderInfo(){
for (int i = 0; i < cylinders.size(); i++) {
cylinder cyl = cylinders[i];
VEC3 translation = (cyl.leftVertex + cyl.rightVertex) / 2;
VEC3 z = {0,0,1};
VEC3 rotAxisDir = -(cyl.leftVertex - cyl.rightVertex).cross(z);
rotAxisDir = rotAxisDir/rotAxisDir.norm();
// std::cout << "rotAxisDir:\n" << rotAxisDir << endl;
float a = rotAxisDir[0];
float b = rotAxisDir[1];
float c = rotAxisDir[2];
float d = sqrt(b*b + c*c);
Matrix3d Rx;
Matrix3d Rx_inv;
if (d == 0) {
Rx << 1, 0, 0, 0, 1, 0, 0, 0, 1;
Rx_inv << 1, 0, 0, 0, 1, 0, 0, 0, 1;
}
else {
Rx << 1, 0, 0, 0, c/d, -b/d, 0, b/d, c/d;
Rx_inv << 1, 0, 0, 0, c/d, b/d, 0, -b/d, c/d;
}
Matrix3d Ry;
Ry << d, 0, -a, 0, 1, 0, a, 0, d;
Matrix3d Ry_inv;
Ry_inv << d, 0, a, 0, 1, 0, -a, 0, d;
float acos_arg = (cyl.leftVertex - cyl.rightVertex).dot(z)/(cyl.leftVertex - cyl.rightVertex).norm();
float theta = acos((cyl.leftVertex - cyl.rightVertex).dot(z)/(cyl.leftVertex - cyl.rightVertex).norm());
// printf("theta = %f\n", theta);
// cout << "acos arg = " << acos_arg << endl;
Matrix3d Rz;
Rz << cos(theta), -sin(theta), 0, sin(theta), cos(theta), 0, 0, 0, 1;
Matrix3d R = Rx_inv * Ry_inv * Rz * Ry * Rx;
cylinders[i].info.R = R;
cylinders[i].info.translation = translation;
}
}
// bool raySphereIntersect(const VEC3& center,
// const float radius,
// const VEC3& rayPos,
// const VEC3& rayDir,
// float& t)
// {
// const VEC3 op = center - rayPos;
// const float eps = 1e-8;
// const float b = op.dot(rayDir);
// float det = b * b - op.dot(op) + radius * radius;
// // determinant check
// if (det < 0)
// return false;
// det = sqrt(det);
// t = b - det;
// if (t <= eps)
// {
// t = b + det;
// if (t <= eps)
// t = -1;
// }
// if (t < 0) return false;
// return true;
// }
bool rayCylinderIntersect(ray r, cylinder cyl, float& t, VEC3& p, VEC3& n) {
VEC3 translation = cyl.info.translation;
Matrix3d R = cyl.info.R;
VEC3 o_new = R.transpose() * (r.origin - translation);
VEC3 dir_new = R.transpose() * r.dir;
// printf("GOT TO HERE!\n");
// std::cout << "o_new:\n" << o_new << endl;
// std::cout << "dir_new:\n" << dir_new << endl;
float qa = dir_new[0]*dir_new[0] + dir_new[1]*dir_new[1];
float qb = 2*(dir_new[0]*o_new[0] + dir_new[1]*o_new[1]);
float qc = o_new[0]*o_new[0] + o_new[1]*o_new[1] - cyl.radius*cyl.radius;
float det = qb*qb - 4*qa*qc;
// printf("GOT TO HERE 2\n");
if (det < 0) {
// printf("no intersect\n");
return false;
}
else {
// printf("det > 0\n");
float t1 = (-qb - sqrt(qb*qb - 4*qa*qc)) / (2 * qa);
float t2 = (-qb + sqrt(qb*qb - 4*qa*qc)) / (2 * qa);
// std::cout << "o_new:\n" << o_new << endl;
// std::cout << "dir_new:\n" << dir_new << endl;
VEC3 p1 = o_new + t1*dir_new;
VEC3 p2 = o_new + t2*dir_new;
VEC3 lv_new = (R.transpose() * (cyl.leftVertex - translation));
VEC3 rv_new = (R.transpose() * (cyl.rightVertex - translation));
float z_min = lv_new[2];
float z_max = rv_new[2];
// cout << "R:\n" << R << endl;
// printf("z_min = %f, z_max = %f\n", z_min, z_max);
// cout << "p1 = " << p1 << endl;
if (z_min > z_max) {
float temp = z_min;
z_min = z_max;
z_max = temp;
}
if (p1[2] < z_max && p1[2] > z_min && t1 > 0.001) {
t = t1;
p = R*p1 + translation;
n = (R*(p1 - VEC3(0, 0, p1[2]))).normalized();
// printf("true\n");
return true;
}
else if (p2[2] < z_max && p2[2] > z_min && t2 > 0.001) {
t = t2;
p = R*p2 + translation;
n = (R*(p2 - VEC3(0, 0, p2[2]))).normalized();
// printf("true\n");
return true;
}
else {
return false;
}
}
}
bool rayTriangleIntersect(ray r, triangle tri, float& t_out) {
float x_a = tri.a[0];
float y_a = tri.a[1];
float z_a = tri.a[2];
float x_b = tri.b[0];
float y_b = tri.b[1];
float z_b = tri.b[2];
float x_c = tri.c[0];
float y_c = tri.c[1];
float z_c = tri.c[2];
float x_e = r.origin[0];
float y_e = r.origin[1];
float z_e = r.origin[2];
float x_d = r.dir[0];
float y_d = r.dir[1];
float z_d = r.dir[2];
float M = (x_a-x_b)*((y_a-y_c)*z_d - y_d*(z_a-z_c))
+ (y_a-y_b)*(x_d*(z_a-z_c) - (x_a-x_c)*z_d)
+ (z_a-z_b)*((x_a-x_c)*y_d - (y_a-y_c)*x_d);
float t = -((z_a-z_c)*((x_a-x_b)*(y_a-y_e) - (x_a-x_e)*(y_a-y_b))
+ (y_a-y_c)*((x_a-x_e)*(z_a-z_b) - (x_a-x_b)*(z_a-z_e))
+ (x_a-x_c)*((y_a-y_b)*(z_a-z_e) - (y_a-y_e)*(z_a-z_b)))/M;
// printf("t for triangle %i = %f", i, t);
if (t <= 0) {
return false;
}
float gamma =(z_d*((x_a-x_b)*(y_a-y_e) - (x_a-x_e)*(y_a-y_b))
+ y_d*((x_a-x_e)*(z_a-z_b) - (x_a-x_b)*(z_a-z_e))
+ x_d*((y_a-y_b)*(z_a-z_e) - (y_a-y_e)*(z_a-z_b)))/M;
if (gamma < 0 || gamma > 1) {
return false;
}
float beta =((x_a-x_e)*((y_a-y_c)*z_d - y_d*(z_a-z_c))
+ (y_a-y_e)*(x_d*(z_a-z_c) - (x_a-x_c)*z_d)
+ (z_a-z_e)*((x_a-x_c)*y_d - (y_a-y_c)*x_d))/M;
if (beta < 0 || beta > 1 - gamma) {
return false;
}
if (t > 0.00001) {
t_out = t;
return true;
}
}
bool raySphereIntersect(ray r, sphere s, float& t_out) {
float a = r.dir.dot(r.dir);
float b = 2 * r.dir.dot(r.origin - s.center);
float c = (r.origin - s.center).dot(r.origin - s.center) - s.radius*s.radius;
float t, t1, t2;
if (b*b >= 4*a*c) {
t1 = (-b - sqrt(b*b - 4*a*c)) / (2 * a);
t2 = (-b + sqrt(b*b - 4*a*c)) / (2 * a);
if (t1 <= 0.00001) {
t = t2;
}
else {
t = fmin(t1, t2);
}
if (t > 0.0001) {
t_out = t;
return true;
}
else {
return false;
}
}
else {
return false;
}
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// void rayColor(ray r, VEC3& pixelColor)
// {
// pixelColor = VEC3(1,1,1);
// // look for intersections
// int hitID = -1;
// intersectType hitType;
// float tMinFound = FLT_MAX;
// for (int y = 0; y < sphereCenters.size(); y++) {
// float tMin = FLT_MAX;
// if (raySphereIntersect(sphereCenters[y], sphereRadii[y], r.origin, r.dir, tMin)) {
// // is the closest so far?
// if (tMin < tMinFound) {
// tMinFound = tMin;
// hitID = y;
// hitType = SPHERE;
// }
// }
// }
// for (int i = 0; i < cylinders.size(); i++) {
// float tMin = FLT_MAX;
// if (rayCylinderIntersect(r, cylinders[i], tMin)) {
// if (tMin < tMinFound) {
// tMinFound = tMin;
// hitID = i;
// hitType = CYLINDER;
// }
// }
// }
// // No intersection, return white
// if (hitID == -1)
// return;
// // set to the sphere color
// pixelColor = VEC3(1, 0, 0);
// }
bool shadow_ray_intersect_tri(ray r, light li) {
//o + td = li.pos
//o[0] + td[0] = li.pos[0]
float t_min = (li.pos[0] - r.origin[0])/r.dir[0];
int hitID = -1;
intersectType hitType;
float tMinFound = FLT_MAX;
for (int i = 0; i < spheres.size(); i++) {
float tMin = FLT_MAX;
if (raySphereIntersect(r, spheres[i], tMin)) {
// is the closest so far?
if (tMin < tMinFound) {
tMinFound = tMin;
hitID = i;
hitType = SPHERE;
}
}
}
for (int i = 0; i < cylinders.size(); i++) {
float tMin = FLT_MAX;
VEC3 p;
VEC3 n;
if (rayCylinderIntersect(r, cylinders[i], tMin, p, n)) {
if (tMin < tMinFound) {
tMinFound = tMin;
hitID = i;
hitType = CYLINDER;
}
}
}
for (int i = 0; i < tris.size(); i++) {
float tMin = FLT_MAX;
if (rayTriangleIntersect(r, tris[i], tMin)) {
if (tMin < tMinFound) {
tMinFound = tMin;
hitID = i;
hitType = TRIANGLE;
}
}
}
if (hitID != -1) {
return true;
}
return false;
}
float fresnel(float costheta, float cosphi, int into_glass) {
float alpha_1 = 1.5;
float alpha_2 = 1;
if (into_glass) {
alpha_1 = 1;
alpha_2 = 1.5;
}
// float p_par = (alpha_2*costheta - alpha_1*cosphi)/(alpha_2*costheta + alpha_1*cosphi);
// float p_perp = (alpha_1*costheta - alpha_2*cosphi)/(alpha_2*costheta + alpha_1*cosphi);
// return 0.5 * (p_par*p_par + p_perp*p_perp);
float R_0 = pow(((alpha_2 -1)/(alpha_2 + 1)), 2);
float R = R_0 + (1-R_0)*pow((1-costheta), 5);
return R;
}
VEC3 rayColor(ray r, int nlights, light* lights, int depth) {
// printf("r\n");
float t_min = INFINITY;
VEC3 color = {0,0,0};
if (depth == 10) {
return color;
}
int hitID = -1;
intersectType hitType;
float tMinFound = FLT_MAX;
for (int i = 0; i < spheres.size(); i++) {
float tMin = FLT_MAX;
if (raySphereIntersect(r, spheres[i], tMin)) {
// is the closest so far?
if (tMin < tMinFound) {
tMinFound = tMin;
hitID = i;
hitType = SPHERE;
}
}
}
VEC3 p_found;
VEC3 n_found;
VEC3 p_cyl;
VEC3 n_cyl;
for (int i = 0; i < cylinders.size(); i++) {
float tMin = FLT_MAX;
if (rayCylinderIntersect(r, cylinders[i], tMin, p_cyl, n_cyl)) {
if (tMin < tMinFound) {
tMinFound = tMin;
hitID = i;
hitType = CYLINDER;
p_found = p_cyl;
n_found = n_cyl;
}
}
}
for (int i = 0; i < tris.size(); i++) {
float tMin = FLT_MAX;
if (rayTriangleIntersect(r, tris[i], tMin)) {
if (tMin < tMinFound) {
tMinFound = tMin;
hitID = i;
hitType = TRIANGLE;
}
}
}
// printf("done intersections\n");
// printf("hitID = %i\n", hitID);
if (hitID == -1) {
return color;
}
float t = tMinFound;
if (hitType == CYLINDER) {
cylinder cyl = cylinders[hitID];
VEC3 p = p_found;
VEC3 n = n_found;
color = {0,0,0};
VEC3 e = (r.origin-p)/(r.origin-p).norm();
for (int j = 0; j < nlights; j++) {
light li = lights[j];
ray shadowray;
// shadowray.origin = p;
// shadowray.dir = (li.pos - p)/(li.pos - p).norm();
VEC3 surface1 = n.cross(e);
VEC3 surface2 = surface1.cross(n);
int shadowrays_blocked = 0;
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
shadowray.origin = p + x*SS_GRID_SIZE*surface1 + y*SS_GRID_SIZE*surface2
+ (((float) rand()/(float) RAND_MAX)*SS_GRID_SIZE - SS_GRID_SIZE/2)*surface1
+ (((float) rand()/(float) RAND_MAX)*SS_GRID_SIZE - SS_GRID_SIZE/2)*surface2;
shadowray.dir = (li.pos - shadowray.origin).normalized();
if (shadow_ray_intersect_tri(shadowray, li)) {
shadowrays_blocked++;
}
}
}
// printf("shadowrays blocked: %d\n", shadowrays_blocked);
float shadow_ratio = ((float) (25 - shadowrays_blocked)) / ((float) 25);
// shadow_ratio = 1;
VEC3 l = (li.pos - p)/(li.pos - p).norm();
color += shadow_ratio * cyl.color.cwiseProduct(li.color * fmax(0, n.dot(l)));
VEC3 refl = -l + 2*(n.dot(l))*n;
color += shadow_ratio * cyl.color.cwiseProduct(li.color * pow(fmax(0, refl.dot(e)), 10));
}
}
if (hitType == SPHERE) {
sphere s = spheres[hitID];
VEC3 p = r.origin + t * r.dir;
VEC3 n = (p - s.center)/(p - s.center).norm();
if (s.material == PLASTIC) {
color = {0,0,0};
VEC3 e = (r.origin-p)/(r.origin-p).norm();
for (int j = 0; j < nlights; j++) {
light li = lights[j];
ray shadowray;
// shadowray.origin = p;
// shadowray.dir = (li.pos - p)/(li.pos - p).norm();
VEC3 surface1 = n.cross(e);
VEC3 surface2 = surface1.cross(n);
int shadowrays_blocked = 0;
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
shadowray.origin = p + x*SS_GRID_SIZE*surface1 + y*SS_GRID_SIZE*surface2
+ (((float) rand()/(float) RAND_MAX)*SS_GRID_SIZE - SS_GRID_SIZE/2)*surface1
+ (((float) rand()/(float) RAND_MAX)*SS_GRID_SIZE - SS_GRID_SIZE/2)*surface2;
shadowray.dir = (li.pos - shadowray.origin).normalized();
if (shadow_ray_intersect_tri(shadowray, li)) {
shadowrays_blocked++;
}
}
}
// if (shadowrays_blocked > 0 && shadowrays_blocked < 25) {
// printf("shadowrays blocked: %d\n", shadowrays_blocked);
// }
float shadow_ratio = ((float) (25 - shadowrays_blocked)) / ((float) 25);
VEC3 l = (li.pos - p)/(li.pos - p).norm();
color += shadow_ratio * s.color.cwiseProduct(li.color * fmax(0, n.dot(l)));
VEC3 refl = -l + 2*(n.dot(l))*n;
color += shadow_ratio * s.color.cwiseProduct(li.color * pow(fmax(0, refl.dot(e)), 10));
}
}
else if (s.material == MIRROR) {
ray reflect;
VEC3 e = (r.origin-p)/(r.origin-p).norm();
reflect.origin = p;
reflect.dir = (-e + 2*(n.dot(e))*n)/(-e + 2*(n.dot(e))*n).norm();
color = rayColor(reflect, nlights, lights, depth+1);
}
else if (s.material == GLASS) {
ray refract;
refract.origin = p;
VEC3 in = (p - r.origin)/(p - r.origin).norm();
float costheta;
float cosphi;
float k_reflect;
if (r.in_glass) {
// printf("in glass\n");
n = -n;
// printf("%f\n", n[2]);
VEC3 dir1 = (1.5/1) * (in - n * in.dot(n));
VEC3 dir2 = sqrt(1 - pow(1.5/1, 2) * (1 - pow(in.dot(n), 2))) * n;
refract.dir = (dir1 - dir2)/(dir1 - dir2).norm();
refract.in_glass = 0;
costheta = -in.dot(n);
cosphi = sqrt(1 - pow((1.5/1 * sqrt(1 - costheta*costheta)), 2));
k_reflect = fresnel(costheta, cosphi, 0);
}
else {
// printf("hit glass\n");
VEC3 dir1 = (1/1.5) * (in - n * in.dot(n));
VEC3 dir2 = sqrt(1 - pow(1/1.5, 2) * (1 - pow(in.dot(n), 2))) * n;
refract.dir = (dir1 - dir2)/(dir1 - dir2).norm();
refract.in_glass = 1;
costheta = -in.dot(n);
cosphi = sqrt(1 - pow((1/1.5 * sqrt(1 - costheta*costheta)), 2));
k_reflect = fresnel(costheta, cosphi, 1);
}
ray reflect;
VEC3 e = (r.origin-p)/(r.origin-p).norm();
reflect.origin = p;
reflect.dir = (-e + 2*(n.dot(e))*n)/(-e + 2*(n.dot(e))*n).norm();
VEC3 refract_color = rayColor(refract, nlights, lights, depth+1);
VEC3 reflect_color = rayColor(reflect, nlights, lights, depth+1);
color = k_reflect*reflect_color + (1-k_reflect)*refract_color;
}
}
// printf("t_min = %f\n", t_min);
if (hitType == TRIANGLE) {
triangle tri = tris[hitID];
VEC3 p = r.origin + t * r.dir;
VEC3 n = -(tri.c-tri.a).cross(tri.b-tri.a)/((tri.c-tri.a).cross(tri.b-tri.a)).norm();
if (tri.material == PLASTIC) {
color = {0,0,0};
VEC3 e = (r.origin-p)/(r.origin-p).norm();
for (int j = 0; j < nlights; j++) {
light li = lights[j];
ray shadowray;
// shadowray.origin = p;
// shadowray.dir = (li.pos - p)/(li.pos - p).norm();
VEC3 surface1 = n.cross(e);
VEC3 surface2 = surface1.cross(n);
int shadowrays_blocked = 0;
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
shadowray.origin = p + x*SS_GRID_SIZE*surface1 + y*SS_GRID_SIZE*surface2
+ (((float) rand()/(float) RAND_MAX)*SS_GRID_SIZE - SS_GRID_SIZE/2)*surface1
+ (((float) rand()/(float) RAND_MAX)*SS_GRID_SIZE - SS_GRID_SIZE/2)*surface2;
shadowray.dir = (li.pos - shadowray.origin).normalized();
if (shadow_ray_intersect_tri(shadowray, li)) {
shadowrays_blocked++;
}
}
}
float shadow_ratio = ((float) (25 - shadowrays_blocked)) / ((float) 25);
VEC3 l = (li.pos - p)/(li.pos - p).norm();
color += shadow_ratio * tri.color.cwiseProduct(li.color * fmax(0, n.dot(l)));
VEC3 refl = -l + 2*(n.dot(l))*n;
color += shadow_ratio * tri.color.cwiseProduct(li.color * pow(fmax(0, refl.dot(e)), 10));
}
}
else if (tri.material == MIRROR) {
ray reflect;
VEC3 e = (r.origin-p)/(r.origin-p).norm();
reflect.origin = p;
reflect.dir = (-e + 2*(n.dot(e))*n)/(-e + 2*(n.dot(e))*n).norm();
color = rayColor(reflect, nlights, lights, depth+1);
}
// color = tri.color;
}
color[0] = fmin(color[0], 1.0);
color[1] = fmin(color[1], 1.0);
color[2] = fmin(color[2], 1.0);
return color;
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
float clamp(float value)
{
if (value < 0.0) return 0.0;
else if (value > 1.0) return 1.0;
return value;
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
void renderImage(int& xRes, int& yRes, const string& filename, VEC3** prev_frames)
{
// allocate the final image
const int totalCells = xRes * yRes;
float* ppmOut = new float[3 * totalCells];
// compute image plane
const float halfY = (lookingAt - eye).norm() * tan(45.0f / 360.0f * M_PI);
const float halfX = halfY * 4.0f / 3.0f;
const VEC3 cameraZ = (lookingAt - eye).normalized();
const VEC3 cameraX = up.cross(cameraZ).normalized();
const VEC3 cameraY = cameraZ.cross(cameraX).normalized();
VEC3* curr_frame = (VEC3*) malloc(sizeof(VEC3) * xRes * yRes);
// int n_prev_frames = 0;
// n_prev_frames += prev_frames[0] != NULL;
// n_prev_frames += prev_frames[1] != NULL;
// n_prev_frames += prev_frames[2] != NULL;
// n_prev_frames += prev_frames[3] != NULL;
// printf("n_prev_frames = %d\n", n_prev_frames);
for (int y = 0; y < yRes; y++)
for (int x = 0; x < xRes; x++)
{
// generate the ray, making x-axis go left to right
const float ratioX = 1.0f - ((xRes - 1) - x) / float(xRes) * 2.0f;
const float ratioY = 1.0f - y / float(yRes) * 2.0f;
const VEC3 rayHitImage = lookingAt +
ratioX * halfX * cameraX +
ratioY * halfY * cameraY;
const VEC3 rayDir = (rayHitImage - eye).normalized();
// get the color
ray r;
r.origin = eye;
r.dir = rayDir;
VEC3 color = {0,0,0};
if (prev_frames[3] == NULL) {
color = rayColor(r, nlights, lights, 0);
}
else {
color += 0.5 * rayColor(r, nlights, lights, 0);
color += 0.25 * prev_frames[0][y * xRes + x];
color += 0.125 * prev_frames[1][y * xRes + x];
color += 0.0625 * prev_frames[2][y * xRes + x];
color += 0.0625 * prev_frames[3][y * xRes + x];
}
// VEC3 color = rayColor(r, nlights, lights, 0);
curr_frame[y * xRes + x] = color;
// set, in final image
ppmOut[3 * (y * xRes + x)] = clamp(color[0]) * 255.0f;
ppmOut[3 * (y * xRes + x) + 1] = clamp(color[1]) * 255.0f;
ppmOut[3 * (y * xRes + x) + 2] = clamp(color[2]) * 255.0f;
}
free(prev_frames[3]);
prev_frames[3] = prev_frames[2];
prev_frames[2] = prev_frames[1];
prev_frames[1] = prev_frames[0];
prev_frames[0] = curr_frame;
writePPM(filename, xRes, yRes, ppmOut);
delete[] ppmOut;
}
//////////////////////////////////////////////////////////////////////////////////
// Load up a new motion captured frame
//////////////////////////////////////////////////////////////////////////////////
void setSkeletonsToSpecifiedFrame(int frameIndex)
{
if (frameIndex < 0)
{
printf("Error in SetSkeletonsToSpecifiedFrame: frameIndex %d is illegal.\n", frameIndex);
exit(0);
}
if (displayer.GetSkeletonMotion(0) != NULL)
{
int postureID;
if (frameIndex >= displayer.GetSkeletonMotion(0)->GetNumFrames())
{
cout << " We hit the last frame! You might want to pick a different sequence. " << endl;
postureID = displayer.GetSkeletonMotion(0)->GetNumFrames() - 1;
}
else
postureID = frameIndex;
displayer.GetSkeleton(0)->setPosture(* (displayer.GetSkeletonMotion(0)->GetPosture(postureID)));
}
}
//////////////////////////////////////////////////////////////////////////////////
// Build a list of spheres in the scene
//////////////////////////////////////////////////////////////////////////////////
void buildScene()
{
sphereCenters.clear();
sphereRadii.clear();
sphereColors.clear();
// spheres.clear();
displayer.ComputeBonePositions(DisplaySkeleton::BONES_AND_LOCAL_FRAMES);
cylinders.clear();
// lights[0].color = VEC3(1, 0.3, 1);
// lights[0].pos = VEC3(0, 12, -3);
lights[0].color = VEC3(1, 1, 1);
lights[0].pos = VEC3(-10, 10, 0);
nlights = 1;
// 1.4, 0, 0.7
cylinder c0;
c0.leftVertex = VEC3(1.3, 0, 1.8);
c0.rightVertex = VEC3(1.4, 0, 0.7);
c0.radius = 0.35;
c0.color = VEC3(0.7,0.25,0.5);
cylinders.push_back(c0);
// sphereCenters.push_back(VEC3(5, 0.5, 1));
// sphereRadii.push_back(2);
sphere s0;
s0.center = VEC3(5, -1, 2);
s0.radius = 4;
s0.material = PLASTIC;
s0.color = VEC3{0, 1, 0};
// spheres.push_back(s0);
// retrieve all the bones of the skeleton
vector<MATRIX4>& rotations = displayer.rotations();
vector<MATRIX4>& scalings = displayer.scalings();
vector<VEC4>& translations = displayer.translations();
vector<float>& lengths = displayer.lengths();
// build a sphere list, but skip the first bone,
// it's just the origin
int totalBones = rotations.size();
for (int x = 1; x < totalBones; x++)
{
MATRIX4& rotation = rotations[x];
MATRIX4& scaling = scalings[x];
VEC4& translation = translations[x];
// get the endpoints of the cylinder
VEC4 leftVertex(0,0,0,1);
VEC4 rightVertex(0,0,lengths[x],1);
leftVertex = rotation * scaling * leftVertex + translation;
rightVertex = rotation * scaling * rightVertex + translation;
// get the direction vector
VEC3 direction = (rightVertex - leftVertex).head<3>();
const float magnitude = direction.norm();
direction *= 1.0 / magnitude;
// how many spheres?
const float sphereRadius = 0.05;
const int totalSpheres = magnitude / (2.0 * sphereRadius);
const float rayIncrement = magnitude / (float)totalSpheres;
// store the spheres
// sphereCenters.push_back(leftVertex.head<3>());
// sphereRadii.push_back(0.05);
// sphereColors.push_back(VEC3(1,0,0));
// sphereCenters.push_back(rightVertex.head<3>());
// sphereRadii.push_back(0.05);
// sphereColors.push_back(VEC3(1,0,0));
// for (int y = 0; y < totalSpheres; y++)
// {
// VEC3 center = ((float)y + 0.5) * rayIncrement * direction + leftVertex.head<3>();
// sphereCenters.push_back(center);
// sphereRadii.push_back(0.05);
// sphereColors.push_back(VEC3(1,0,0));
// }
cylinder c;
c.leftVertex = leftVertex.head<3>();
c.rightVertex = rightVertex.head<3>();
c.color = VEC3(0.9, 0.7, 0.5);
c.radius = 0.05;
cylinders.push_back(c);
}
calculateCylinderInfo();
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
string skeletonFilename("36.asf");
string motionFilename("36_24.amc");
// load up skeleton stuff
skeleton = new Skeleton(skeletonFilename.c_str(), MOCAP_SCALE);
skeleton->setBasePosture();
displayer.LoadSkeleton(skeleton);
// load up the motion
motion = new Motion(motionFilename.c_str(), MOCAP_SCALE, skeleton);
displayer.LoadMotion(motion);
skeleton->setPosture(*(displayer.GetSkeletonMotion(0)->GetPosture(0)));
// Note we're going 8 frames at a time, otherwise the animation
// is really slow.
// for (int x = -6; x < 8; x++) {
// for (int z = -4; z < 4; z++) {
// triangle t0;
// t0.a = VEC3(2*x, 0, 2*z);
// t0.b = VEC3(2*x, 0, 2*(z+1));
// t0.c = VEC3(2*(x+1), 0, 2*z);
// t0.color = VEC3(0.25, 0.25, 0.4);
// t0.material = PLASTIC;
// tris.push_back(t0);
// triangle t1;
// t1.a = VEC3(2*(x+1), 0, 2*(z+1));
// t1.c = VEC3(2*x, 0, 2*(z+1));
// t1.b = VEC3(2*(x+1), 0, 2*z);
// t1.color = VEC3(0.1, 0.1, 0.1);
// t1.material = PLASTIC;
// tris.push_back(t1);
// }
// }
triangle t0;
t0.a = VEC3(-12, 0, -8);
t0.b = VEC3(-12, 0, 8);
t0.c = VEC3(16, 0, -8);
t0.color = VEC3(0.25, 0.25, 0.4);
t0.material = PLASTIC;
tris.push_back(t0);
triangle t1;
t1.a = VEC3(16, 0, 8);
t1.c = VEC3(-12, 0, 8);
t1.b = VEC3(16, 0, -8);
t1.color = VEC3(0.25, 0.25, 0.4);
t1.material = PLASTIC;
tris.push_back(t1);
//LEFT Z IS POSITIVE
sphere s0;
s0.center = VEC3(1.4, 0, 0.7);
s0.radius = 0.45;
s0.material = MIRROR;
s0.color = VEC3(0, 1, 0);
spheres.push_back(s0);
sphere s1;
s1.center = VEC3(0.5, 0, 0.7);
s1.radius = 0.25;
s1.material = PLASTIC;
s1.color = VEC3(0, 0.75, 0.25);
spheres.push_back(s1);
sphere s2;
s2.center = VEC3(1, 0, -0.17);
s2.radius = 0.33;
s2.material = PLASTIC;
s2.color = VEC3(0, 0.75, 0.75);
spheres.push_back(s2);
sphere s3;
s3.center = VEC3(0.8, -0.1, -1);
s3.radius = 0.28;
s3.material = MIRROR;
s3.color = VEC3(0, 1, 0);
spheres.push_back(s3);
s3.center = VEC3(1.4, -0.2, -0.8);
s3.radius = 0.35;
s3.material = PLASTIC;
s3.color = VEC3(0.8, 0.2, 0);
spheres.push_back(s3);
VEC3** prev_frames = (VEC3**) malloc(4 * sizeof(VEC3*));
prev_frames[0] = NULL;
prev_frames[1] = NULL;
prev_frames[2] = NULL;
prev_frames[3] = NULL;
for (int x = 0; x < 2400; x += 8)
{
setSkeletonsToSpecifiedFrame(x);
buildScene();
// VEC3 lookingAt(5, 0.5, 1);
if (x > 400 && x <= 750) {
lookingAt = VEC3(5, 0.5, 1-(((float) x-400)/350)*2.3);
}
if (x > 1200 && x < 1800) {
lookingAt = VEC3(5, 0.5, -1.3+(((float) x-1200)/600)*2.3);
}
char buffer[256];
sprintf(buffer, "./frames/frame.%04i.ppm", x / 8);
renderImage(windowWidth, windowHeight, buffer, prev_frames);
cout << "Rendered " + to_string(x / 8) + " frames" << endl;
}
free(prev_frames[0]);
free(prev_frames[1]);
free(prev_frames[2]);
free(prev_frames[3]);
free(prev_frames);
return 0;
}
| 31.587368 | 109 | 0.510564 | [
"geometry",
"vector"
] |
4efffc5542f3d9c200c3b1fc39d18539eb23b69d | 2,782 | cc | C++ | components/service/ucloud/linkface/src/model/QueryFaceResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | components/service/ucloud/linkface/src/model/QueryFaceResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | components/service/ucloud/linkface/src/model/QueryFaceResult.cc | wanguojian/AliOS-Things | 47fce29d4dd39d124f0bfead27998ad7beea8441 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#include <alibabacloud/linkface/model/QueryFaceResult.h>
#include <json/json.h>
using namespace AlibabaCloud::LinkFace;
using namespace AlibabaCloud::LinkFace::Model;
QueryFaceResult::QueryFaceResult() :
ServiceResult()
{}
QueryFaceResult::QueryFaceResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
QueryFaceResult::~QueryFaceResult()
{}
void QueryFaceResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
auto allUserFaceMetasNode = dataNode["UserFaceMetas"]["UserFaceMetasItem"];
for (auto dataNodeUserFaceMetasUserFaceMetasItem : allUserFaceMetasNode)
{
Data::UserFaceMetasItem userFaceMetasItemObject;
if(!dataNodeUserFaceMetasUserFaceMetasItem["ClientTag"].isNull())
userFaceMetasItemObject.clientTag = dataNodeUserFaceMetasUserFaceMetasItem["ClientTag"].asString();
if(!dataNodeUserFaceMetasUserFaceMetasItem["Index"].isNull())
userFaceMetasItemObject.index = std::stoi(dataNodeUserFaceMetasUserFaceMetasItem["Index"].asString());
if(!dataNodeUserFaceMetasUserFaceMetasItem["FaceUrl"].isNull())
userFaceMetasItemObject.faceUrl = dataNodeUserFaceMetasUserFaceMetasItem["FaceUrl"].asString();
if(!dataNodeUserFaceMetasUserFaceMetasItem["UserInfo"].isNull())
userFaceMetasItemObject.userInfo = dataNodeUserFaceMetasUserFaceMetasItem["UserInfo"].asString();
data_.userFaceMetas.push_back(userFaceMetasItemObject);
}
auto allGroupIds = dataNode["GroupIds"]["GroupIds"];
for (auto value : allGroupIds)
data_.groupIds.push_back(value.asString());
if(!value["Code"].isNull())
code_ = std::stoi(value["Code"].asString());
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
}
std::string QueryFaceResult::getMessage()const
{
return message_;
}
QueryFaceResult::Data QueryFaceResult::getData()const
{
return data_;
}
int QueryFaceResult::getCode()const
{
return code_;
}
bool QueryFaceResult::getSuccess()const
{
return success_;
}
| 31.258427 | 105 | 0.761323 | [
"model"
] |
f607878badf9fed14e5ce81a79f3c163045e3174 | 3,181 | hpp | C++ | include/UnityEngine/EventSystems/PhysicsRaycaster_RaycastHitComparer.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/EventSystems/PhysicsRaycaster_RaycastHitComparer.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/UnityEngine/EventSystems/PhysicsRaycaster_RaycastHitComparer.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.EventSystems.PhysicsRaycaster
#include "UnityEngine/EventSystems/PhysicsRaycaster.hpp"
// Including type: System.Collections.Generic.IComparer`1
#include "System/Collections/Generic/IComparer_1.hpp"
// Including type: UnityEngine.RaycastHit
#include "UnityEngine/RaycastHit.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Type namespace: UnityEngine.EventSystems
namespace UnityEngine::EventSystems {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.EventSystems.PhysicsRaycaster/RaycastHitComparer
class PhysicsRaycaster::RaycastHitComparer : public ::Il2CppObject/*, public System::Collections::Generic::IComparer_1<UnityEngine::RaycastHit>*/ {
public:
// Creating value type constructor for type: RaycastHitComparer
RaycastHitComparer() noexcept {}
// Creating interface conversion operator: operator System::Collections::Generic::IComparer_1<UnityEngine::RaycastHit>
operator System::Collections::Generic::IComparer_1<UnityEngine::RaycastHit>() noexcept {
return *reinterpret_cast<System::Collections::Generic::IComparer_1<UnityEngine::RaycastHit>*>(this);
}
// Get static field: static public UnityEngine.EventSystems.PhysicsRaycaster/RaycastHitComparer instance
static UnityEngine::EventSystems::PhysicsRaycaster::RaycastHitComparer* _get_instance();
// Set static field: static public UnityEngine.EventSystems.PhysicsRaycaster/RaycastHitComparer instance
static void _set_instance(UnityEngine::EventSystems::PhysicsRaycaster::RaycastHitComparer* value);
// public System.Int32 Compare(UnityEngine.RaycastHit x, UnityEngine.RaycastHit y)
// Offset: 0x1417C18
int Compare(UnityEngine::RaycastHit x, UnityEngine::RaycastHit y);
// static private System.Void .cctor()
// Offset: 0x1417C64
static void _cctor();
// public System.Void .ctor()
// Offset: 0x1417C5C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static PhysicsRaycaster::RaycastHitComparer* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::EventSystems::PhysicsRaycaster::RaycastHitComparer::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<PhysicsRaycaster::RaycastHitComparer*, creationType>()));
}
}; // UnityEngine.EventSystems.PhysicsRaycaster/RaycastHitComparer
#pragma pack(pop)
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::EventSystems::PhysicsRaycaster::RaycastHitComparer*, "UnityEngine.EventSystems", "PhysicsRaycaster/RaycastHitComparer");
| 58.907407 | 157 | 0.749135 | [
"object"
] |
f60958682c725781b0788940a554008b8c2890da | 20,199 | cc | C++ | src/translator.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | src/translator.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | src/translator.cc | aj7tesh/CTranslate2 | 8e424efdbcf40c89dca7e237a249464a95eeaf74 | [
"MIT"
] | null | null | null | #include "ctranslate2/translator.h"
#include <algorithm>
#include <numeric>
#include "ctranslate2/decoding.h"
#include "ctranslate2/ops/ops.h"
#include "ctranslate2/profiler.h"
namespace ctranslate2 {
static std::vector<size_t>
tokens_to_ids(const std::vector<std::string>& tokens,
const Vocabulary& vocab) {
std::vector<size_t> ids;
ids.reserve(tokens.size());
for (const auto& token : tokens)
ids.push_back(vocab.to_id(token));
return ids;
}
static std::vector<std::vector<size_t>>
tokens_to_ids(const std::vector<std::vector<std::string>>& batch_tokens,
const Vocabulary& vocab) {
std::vector<std::vector<size_t>> batch_ids;
batch_ids.reserve(batch_tokens.size());
for (const auto& tokens : batch_tokens)
batch_ids.emplace_back(tokens_to_ids(tokens, vocab));
return batch_ids;
}
template <typename T>
static std::vector<std::vector<T>>
sort_from_longest_to_shortest(const std::vector<std::vector<T>>& ids,
std::vector<size_t>& original_to_sorted_index) {
std::vector<size_t> sorted_to_original_index(ids.size());
std::iota(sorted_to_original_index.begin(), sorted_to_original_index.end(), 0);
std::sort(sorted_to_original_index.begin(), sorted_to_original_index.end(),
[&ids](size_t i1, size_t i2) { return ids[i1].size() > ids[i2].size(); });
original_to_sorted_index.resize(ids.size());
std::vector<std::vector<T>> new_ids;
new_ids.reserve(ids.size());
for (size_t i = 0; i < ids.size(); ++i) {
size_t original_index = sorted_to_original_index[i];
original_to_sorted_index[original_index] = i;
new_ids.emplace_back(ids[original_index]);
}
return new_ids;
}
static std::pair<StorageView, StorageView>
make_inputs(const std::vector<std::vector<size_t>>& ids,
const Device device,
const dim_t length_multiple_of = 1) {
const dim_t batch_size = ids.size();
// Record lengths and maximum length.
dim_t max_length = 0;
StorageView lengths({batch_size}, DataType::INT32);
for (dim_t i = 0; i < batch_size; ++i) {
const dim_t length = ids[i].size();
lengths.at<int32_t>(i) = length;
max_length = std::max(max_length, length);
}
if (max_length % length_multiple_of != 0) {
max_length += (length_multiple_of - max_length % length_multiple_of);
}
// Make 2D input.
StorageView input({batch_size, max_length}, int32_t(0));
for (dim_t i = 0; i < batch_size; ++i) {
const dim_t length = ids[i].size();
for (dim_t t = 0; t < length; ++t)
input.at<int32_t>({i, t}) = ids[i][t];
}
return std::make_pair(input.to(device), lengths.to(device));
}
static std::unique_ptr<const Sampler> make_sampler(const TranslationOptions& options) {
const Sampler* sampler = nullptr;
if (options.sampling_topk != 1)
sampler = new RandomSampler(options.sampling_topk, options.sampling_temperature);
else
sampler = new BestSampler();
return std::unique_ptr<const Sampler>(sampler);
}
static std::unique_ptr<const SearchStrategy>
make_search_strategy(const TranslationOptions& options) {
const SearchStrategy* strategy = nullptr;
if (options.beam_size == 1)
strategy = new GreedySearch();
else
strategy = new BeamSearch(options.beam_size, options.length_penalty, options.coverage_penalty);
return std::unique_ptr<const SearchStrategy>(strategy);
}
Translator::Translator(const std::string& model_dir,
Device device,
int device_index,
ComputeType compute_type) {
set_model(models::Model::load(model_dir, device, device_index, compute_type));
}
Translator::Translator(const std::shared_ptr<const models::Model>& model) {
set_model(model);
}
Translator::Translator(const Translator& other) {
if (other._model)
set_model(other._model);
}
TranslationResult
Translator::translate(const std::vector<std::string>& tokens) {
TranslationOptions options;
return translate(tokens, options);
}
TranslationResult
Translator::translate(const std::vector<std::string>& tokens,
const TranslationOptions& options) {
std::vector<std::vector<std::string>> batch_tokens(1, tokens);
return translate_batch(batch_tokens, options)[0];
}
TranslationResult
Translator::translate_with_prefix(const std::vector<std::string>& source,
const std::vector<std::string>& target_prefix,
const TranslationOptions& options) {
std::vector<std::vector<std::string>> batch_source(1, source);
std::vector<std::vector<std::string>> batch_target_prefix(1, target_prefix);
return translate_batch_with_prefix(batch_source, batch_target_prefix, options)[0];
}
std::vector<TranslationResult>
Translator::translate_batch(const std::vector<std::vector<std::string>>& batch_tokens) {
TranslationOptions options;
return translate_batch(batch_tokens, options);
}
std::vector<TranslationResult>
Translator::translate_batch(const std::vector<std::vector<std::string>>& batch_tokens,
const TranslationOptions& options) {
std::vector<std::vector<std::string>> target_prefix;
return translate_batch_with_prefix(batch_tokens, target_prefix, options);
}
std::vector<TranslationResult>
Translator::translate_batch_with_prefix(const std::vector<std::vector<std::string>>& source,
const std::vector<std::vector<std::string>>& target_prefix,
const TranslationOptions& options) {
assert_has_model();
const size_t batch_size = source.size();
// Check options and inputs.
if (options.num_hypotheses == 0)
throw std::invalid_argument("num_hypotheses must be > 0");
if (options.beam_size == 0)
throw std::invalid_argument("beam_size must be > 0");
if (options.num_hypotheses > options.beam_size && !options.return_alternatives)
throw std::invalid_argument("The number of hypotheses can not be greater than the beam size");
if (options.sampling_topk != 1 && options.beam_size != 1)
throw std::invalid_argument("Random sampling should be used with beam_size = 1");
if (options.min_decoding_length > options.max_decoding_length)
throw std::invalid_argument("min_decoding_length is greater than max_decoding_length");
if (!target_prefix.empty() && target_prefix.size() != batch_size)
throw std::invalid_argument("Batch size mismatch: got "
+ std::to_string(batch_size) + " for source and "
+ std::to_string(target_prefix.size()) + " for target prefix");
if (batch_size == 0)
return std::vector<TranslationResult>();
const auto is_empty = [](const std::vector<std::string>& tokens) { return tokens.empty(); };
const bool no_source_is_empty = std::none_of(source.begin(), source.end(), is_empty);
const bool with_prefix = !std::all_of(target_prefix.begin(), target_prefix.end(), is_empty);
const bool allow_batch_prefix = !options.return_alternatives;
// Fast path for the common case.
if (no_source_is_empty && (!with_prefix || allow_batch_prefix))
return run_batch_translation_sorted(source, with_prefix ? &target_prefix : nullptr, options);
std::vector<TranslationResult> with_prefix_results;
std::vector<std::vector<std::string>> non_empty_source;
std::vector<std::vector<std::string>> prefix;
non_empty_source.reserve(batch_size);
if (with_prefix) {
prefix.reserve(batch_size);
if (!allow_batch_prefix) {
with_prefix_results.reserve(batch_size);
}
}
for (size_t i = 0; i < batch_size; ++i) {
if (source[i].empty())
continue;
if (with_prefix) {
if (allow_batch_prefix) {
non_empty_source.emplace_back(source[i]);
prefix.emplace_back(target_prefix[i]);
} else if (!target_prefix.empty()) {
with_prefix_results.emplace_back(run_translation(source[i], &target_prefix[i], options));
}
} else {
non_empty_source.emplace_back(source[i]);
}
}
// Run batch translation of all other non empty examples.
std::vector<TranslationResult> results;
if (!non_empty_source.empty())
results = run_batch_translation_sorted(non_empty_source,
with_prefix && allow_batch_prefix ? &prefix : nullptr,
options);
std::vector<TranslationResult> final_results;
final_results.reserve(batch_size);
// Build the final results vector.
for (size_t i = 0, non_empty_index = 0, with_prefix_index = 0; i < batch_size; ++i) {
if (source[i].empty())
final_results.emplace_back(options.num_hypotheses, options.return_attention);
else if (with_prefix && !allow_batch_prefix && !target_prefix[i].empty())
final_results.emplace_back(std::move(with_prefix_results[with_prefix_index++]));
else
final_results.emplace_back(std::move(results[non_empty_index++]));
}
return final_results;
}
std::vector<TranslationResult>
Translator::run_batch_translation_sorted(const std::vector<std::vector<std::string>>& source,
const std::vector<std::vector<std::string>>* target_prefix,
const TranslationOptions& options) {
// Sorting the source input has 2 benefits:
//
// 1. When max_batch_size is smaller that the number of inputs, we prefer translating
// together sentences that have a similar length for improved efficiency.
// 2. Decoding functions remove finished translations from the batch. On CPU, arrays are
// updated in place so it is more efficient to remove content at the end. Shorter sentences
// are more likely to finish first so we sort the batch accordingly.
std::vector<size_t> sorted_index;
auto sorted_source = sort_from_longest_to_shortest(source, sorted_index);
std::vector<std::vector<std::string>> sorted_target_prefix;
if (target_prefix) {
sorted_target_prefix.resize(target_prefix->size());
for (size_t i = 0; i < target_prefix->size(); ++i)
sorted_target_prefix[sorted_index[i]] = target_prefix->at(i);
}
std::vector<TranslationResult> results;
if (options.max_batch_size == 0
|| get_batch_size(source, options.batch_type) <= options.max_batch_size)
results = run_batch_translation(sorted_source,
target_prefix ? &sorted_target_prefix : nullptr,
options);
else {
// Translate by batch of size options.max_batch_size.
results.reserve(source.size());
std::vector<std::vector<std::string>> partial_source;
std::vector<std::vector<std::string>> partial_target_prefix;
partial_source.reserve(source.size());
if (target_prefix)
partial_target_prefix.reserve(target_prefix->size());
size_t partial_batch_size = 0;
for (size_t i = 0; i < sorted_source.size(); ++i) {
const auto& tokens = sorted_source[i];
const size_t batch_size_increment = get_batch_size_increment(tokens, options.batch_type);
if (partial_batch_size > 0
&& partial_batch_size + batch_size_increment > options.max_batch_size) {
auto partial_results = run_batch_translation(partial_source,
target_prefix
? &partial_target_prefix
: nullptr,
options);
results.insert(results.end(),
std::make_move_iterator(partial_results.begin()),
std::make_move_iterator(partial_results.end()));
partial_source.clear();
partial_batch_size = 0;
if (target_prefix)
partial_target_prefix.clear();
}
partial_source.emplace_back(std::move(tokens));
partial_batch_size += batch_size_increment;
if (target_prefix)
partial_target_prefix.emplace_back(std::move(sorted_target_prefix[i]));
}
if (!partial_source.empty()) {
auto partial_results = run_batch_translation(partial_source,
target_prefix
? &partial_target_prefix
: nullptr,
options);
results.insert(results.end(),
std::make_move_iterator(partial_results.begin()),
std::make_move_iterator(partial_results.end()));
}
}
// Reorder results based on original batch index.
std::vector<TranslationResult> final_results;
final_results.reserve(results.size());
for (auto index : sorted_index)
final_results.emplace_back(std::move(results[index]));
return final_results;
}
std::vector<TranslationResult>
Translator::run_batch_translation(const std::vector<std::vector<std::string>>& source,
const std::vector<std::vector<std::string>>* target_prefix,
const TranslationOptions& options) {
PROFILE("run_batch_translation");
auto scoped_device_setter = _model->get_scoped_device_setter();
std::vector<std::vector<size_t>> source_ids = tokens_to_ids(source, *_source_vocabulary);
std::vector<std::vector<size_t>> target_prefix_ids;
if (target_prefix)
target_prefix_ids = tokens_to_ids(*target_prefix, *_target_vocabulary);
const Device device = _model->device();
const DataType dtype = _encoder->output_type();
std::pair<StorageView, StorageView> inputs = make_inputs(source_ids,
device,
dtype == DataType::FLOAT16 ? 8 : 1);
StorageView& ids = inputs.first;
StorageView& lengths = inputs.second;
// Encode sequence.
StorageView encoded(dtype, device);
(*_encoder)(ids, lengths, encoded);
// If set, extract the subset of candidates to generate.
std::vector<size_t> output_ids_map;
if (options.use_vmap && _vocabulary_map && !_vocabulary_map->empty()) {
output_ids_map = _vocabulary_map->get_candidates(source);
} else if (dtype == DataType::FLOAT16 && _target_vocabulary->size() % 8 != 0) {
// Pad vocabulary size to a multiple of 8 to enable Tensor Cores.
// Note that get_candidates above already returns a multiple of 8.
const size_t vocab_size = _target_vocabulary->size();
const size_t padded_size = vocab_size + (8 - vocab_size % 8);
output_ids_map.resize(padded_size);
for (size_t i = 0; i < padded_size; ++i) {
output_ids_map[i] = i < vocab_size ? i : 0;
}
}
if (!output_ids_map.empty()) {
_decoder->set_vocabulary_mask(
StorageView({static_cast<dim_t>(output_ids_map.size())},
std::vector<int32_t>(output_ids_map.begin(), output_ids_map.end()),
device));
} else {
_decoder->reset_vocabulary_mask();
}
// Decode.
layers::DecoderState state = _decoder->initial_state();
state.emplace(std::string("memory"), std::move(encoded));
state.emplace(std::string("memory_lengths"), std::move(lengths));
const size_t start_id = _target_vocabulary->to_id(Vocabulary::bos_token);
const size_t end_id = _target_vocabulary->to_id(Vocabulary::eos_token);
const size_t batch_size = source.size();
const std::vector<size_t> start_ids(batch_size, start_id);
std::vector<GenerationResult<size_t>> results = decode(
*_decoder,
state,
*make_search_strategy(options),
*make_sampler(options),
start_ids,
target_prefix ? &target_prefix_ids : nullptr,
!output_ids_map.empty() ? &output_ids_map : nullptr,
end_id,
options.max_decoding_length,
options.min_decoding_length,
options.num_hypotheses,
options.return_alternatives,
options.return_scores,
options.return_attention);
// Convert generated ids to tokens.
std::vector<TranslationResult> final_results;
final_results.reserve(results.size());
for (size_t i = 0; i < batch_size; ++i) {
GenerationResult<size_t>& result = results[i];
// Remove padding in attention vectors.
if (result.has_attention()) {
const size_t source_length = source[i].size();
auto all_attention = result.attention();
for (auto& attention : all_attention) {
for (auto& vector : attention) {
vector.resize(source_length);
}
}
result.set_attention(std::move(all_attention));
}
final_results.emplace_back(make_translation_result(std::move(result), *_target_vocabulary));
}
return final_results;
}
TranslationResult
Translator::run_translation(const std::vector<std::string>& source,
const std::vector<std::string>* target_prefix,
const TranslationOptions& options) {
if (!target_prefix)
return run_batch_translation({source}, nullptr, options)[0];
else {
std::vector<std::vector<std::string>> batch_target_prefix(1, *target_prefix);
return run_batch_translation({source}, &batch_target_prefix, options)[0];
}
}
Device Translator::device() const {
assert_has_model();
return _model->device();
}
int Translator::device_index() const {
assert_has_model();
return _model->device_index();
}
ComputeType Translator::compute_type() const {
assert_has_model();
return _model->compute_type();
}
void Translator::set_model(const std::string& model_dir) {
models::ModelFileReader model_reader(model_dir);
set_model(model_reader);
}
void Translator::set_model(models::ModelReader& model_reader) {
Device device = Device::CPU;
int device_index = 0;
ComputeType compute_type = ComputeType::DEFAULT;
if (_model) {
device = _model->device();
device_index = _model->device_index();
compute_type = _model->compute_type();
}
set_model(models::Model::load(model_reader, device, device_index, compute_type));
}
void Translator::set_model(const std::shared_ptr<const models::Model>& model) {
const auto* seq2seq_model = dynamic_cast<const models::SequenceToSequenceModel*>(model.get());
if (!seq2seq_model)
throw std::invalid_argument("Translator expects a model of type SequenceToSequenceModel");
_model = model;
auto scoped_device_setter = _model->get_scoped_device_setter();
_encoder = seq2seq_model->make_encoder();
_decoder = seq2seq_model->make_decoder();
_vocabulary_map = seq2seq_model->get_vocabulary_map();
_source_vocabulary = &seq2seq_model->get_source_vocabulary();
_target_vocabulary = &seq2seq_model->get_target_vocabulary();
}
void Translator::detach_model() {
if (!_model)
return;
auto scoped_device_setter = _model->get_scoped_device_setter();
_vocabulary_map = nullptr;
_source_vocabulary = nullptr;
_target_vocabulary = nullptr;
_encoder.reset();
_decoder.reset();
_model.reset();
}
void Translator::assert_has_model() const {
if (!_model)
throw std::runtime_error("No model is attached to this translator");
}
BatchType str_to_batch_type(const std::string& batch_type) {
if (batch_type == "examples")
return BatchType::Examples;
else if (batch_type == "tokens")
return BatchType::Tokens;
throw std::invalid_argument("Invalid batch type: " + batch_type);
}
}
| 40.157058 | 102 | 0.644982 | [
"vector",
"model"
] |
f60bab54626bd17e155a80f451fe7409b8884349 | 5,877 | cpp | C++ | cpp/depends/igl/headers/igl/min_quad_with_fixed_solve.cpp | GitZHCODE/zspace_modules | 2264cb837d2f05184a51b7b453c7e24288e88ee1 | [
"MIT"
] | 2 | 2022-03-28T14:10:50.000Z | 2022-03-28T14:10:51.000Z | cpp/depends/igl/headers/igl/min_quad_with_fixed_solve.cpp | GitZHCODE/zspace_modules | 2264cb837d2f05184a51b7b453c7e24288e88ee1 | [
"MIT"
] | null | null | null | cpp/depends/igl/headers/igl/min_quad_with_fixed_solve.cpp | GitZHCODE/zspace_modules | 2264cb837d2f05184a51b7b453c7e24288e88ee1 | [
"MIT"
] | 2 | 2022-03-23T10:33:10.000Z | 2022-03-28T14:09:55.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2016 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "min_quad_with_fixed.impl.h"
#ifdef IGL_STATIC_LIBRARY
#if EIGEN_VERSION_AT_LEAST(3,3,0)
#else
template bool igl::min_quad_with_fixed_solve<double, Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> const>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::CwiseUnaryOp<Eigen::internal::scalar_multiple_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> const> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, Eigen::Matrix<double, -1, 1, 0, -1, 1> > > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
#endif
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> >&);
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
template bool igl::min_quad_with_fixed_solve<double, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(igl::min_quad_with_fixed_data<double> const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
#endif
| 244.875 | 671 | 0.650502 | [
"geometry"
] |
f61414c5d7839aba1b5f5387a0e8d66cd810f6e3 | 2,186 | cpp | C++ | lib/year2020/src/Day08Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | lib/year2020/src/Day08Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | lib/year2020/src/Day08Puzzle.cpp | MarkRDavison/AdventOfCode | 640ae6de76709367be8dfeb86b9f1f7d21908946 | [
"MIT"
] | null | null | null | #include <2020/Day08Puzzle.hpp>
#include <zeno-engine/Utility/StringExtensions.hpp>
#include <2020/HandheldConsole.hpp>
#include <set>
namespace TwentyTwenty {
Day08Puzzle::Day08Puzzle() :
core::PuzzleBase("Handheld Halting", 2020, 8) {
}
void Day08Puzzle::initialise(const core::InitialisationInfo& _initialisationInfo) {
setInputLines(ze::StringExtensions::splitStringByDelimeter(ze::StringExtensions::loadFileToString(_initialisationInfo.parameters[0]), "\n"));
}
void Day08Puzzle::setInputLines(const std::vector<std::string>& _inputLines) {
m_InputLines = std::vector<std::string>(_inputLines);
}
std::pair<std::string, std::string> Day08Puzzle::fastSolve() {
HandheldConsole console(m_InputLines);
std::set<HandheldConsoleValue> visitedProgramCounters;
while (visitedProgramCounters.find(console.programCounter) == visitedProgramCounters.end()) {
visitedProgramCounters.insert(console.programCounter);
console.runOperationAtProgramCounter();
}
const auto part1 = console.registers[HandheldConsole::AccumulatorName];
for (unsigned i = 0; i < console.originalOperations.size(); ++i) {
const auto currentOpCode = console.originalOperations[i].type;
if (currentOpCode != ConsoleOperation::OpType::NOP &&
currentOpCode != ConsoleOperation::OpType::JMP) {
continue;
}
visitedProgramCounters = std::set<HandheldConsoleValue>();
auto newOperations(console.originalOperations);
newOperations[i].type = (currentOpCode == ConsoleOperation::OpType::NOP
? ConsoleOperation::OpType::JMP
: ConsoleOperation::OpType::NOP
);
HandheldConsole modifiedConsole(newOperations);
while (visitedProgramCounters.find(modifiedConsole.programCounter) == visitedProgramCounters.end()) {
visitedProgramCounters.insert(modifiedConsole.programCounter);
modifiedConsole.runOperationAtProgramCounter();
if (0 > modifiedConsole.programCounter || modifiedConsole.programCounter >= modifiedConsole.originalOperations.size()) {
return { std::to_string(part1), std::to_string(modifiedConsole.registers[HandheldConsole::AccumulatorName]) };
}
}
}
return { std::to_string(part1), "Part 2 failed." };
}
}
| 35.836066 | 143 | 0.755261 | [
"vector"
] |
f61a9a17237393f94c45cefd6a6de8d40662c432 | 1,330 | hpp | C++ | qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/fixPermissions.hpp | largeriver/twrp | 767b63ed5e0763538466569984cf7930d9c59921 | [
"MIT"
] | null | null | null | qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/fixPermissions.hpp | largeriver/twrp | 767b63ed5e0763538466569984cf7930d9c59921 | [
"MIT"
] | null | null | null | qcom_msm8916_64_android5.0/sources/twrp/bootable/recovery/fixPermissions.hpp | largeriver/twrp | 767b63ed5e0763538466569984cf7930d9c59921 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <string.h>
#include <libgen.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include "gui/rapidxml.hpp"
#include "twrp-functions.hpp"
using namespace std;
class fixPermissions {
public:
fixPermissions();
~fixPermissions();
int fixPerms(bool enable_debug, bool remove_data_for_missing_apps);
int fixContexts();
int fixDataInternalContexts(void);
private:
int pchown(string fn, int puid, int pgid);
int pchmod(string fn, mode_t mode);
vector <string> listAllDirectories(string path);
vector <string> listAllFiles(string path);
void deletePackages();
int getPackages(const string& packageFile);
int fixApps();
int fixAllFiles(string directory, int uid, int gid, mode_t file_perms);
int fixDir(const string& dir, int diruid, int dirgid, mode_t dirmode, int fileuid, int filegid, mode_t filemode);
int fixDataData(string dataDir);
int restorecon(string entry, struct stat *sb);
int fixDataDataContexts(void);
int fixContextsRecursively(string path, int level);
struct package {
string pkgName;
string codePath;
string appDir;
string dDir;
int gid;
int uid;
package *next;
};
bool debug;
bool remove_data;
package* head;
};
| 25.09434 | 115 | 0.729323 | [
"vector"
] |
f622d93a1f4006f94b1b67c18c018a8709572ae6 | 9,940 | cc | C++ | code/foundation/threading/linux/linuxthread.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | code/foundation/threading/linux/linuxthread.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | code/foundation/threading/linux/linuxthread.cc | Nechrito/nebula | 6c7ef27ab1374d3f751d866500729524f72a0c87 | [
"BSD-2-Clause"
] | null | null | null | //-------------------------------------------------------------------------------
// linuxthread.cc
// (C) 2010 Radon Labs GmbH
// (C) 2013-2018 Individual contributors, see AUTHORS file
//-------------------------------------------------------------------------------
#include "foundation/stdneb.h"
#include "linuxthread.h"
#if !(__OSX__ || __NACL__)
#include <sched.h>
#include <sys/prctl.h>
#endif
#if NEBULA_ENABLE_THREADLOCAL_STRINGATOM_TABLES
#include "util/localstringatomtable.h"
#endif
#if __ANDROID__
#include "nvidia/nv_thread/nv_thread.h"
#endif
namespace Linux
{
__ImplementClass(Linux::LinuxThread, 'THRD', Core::RefCounted);
using namespace System;
using namespace Util;
#if NEBULA_DEBUG
Threading::CriticalSection LinuxThread::criticalSection;
List<LinuxThread*> LinuxThread::ThreadList;
#endif
//------------------------------------------------------------------------------
/**
*/
LinuxThread::LinuxThread() :
priority(Normal),
stackSize(0),
coreId(System::Cpu::Core0),
threadState(Initial),
thread(0)
{
CPU_ZERO(&this->affinity);
// register with thread list
#if NEBULA_DEBUG
LinuxThread::criticalSection.Enter();
this->threadListIterator = ThreadList.AddBack(this);
LinuxThread::criticalSection.Leave();
#endif
}
//------------------------------------------------------------------------------
/**
*/
LinuxThread::~LinuxThread()
{
if (this->IsRunning())
{
this->Stop();
}
// unregister from thread list
#if NEBULA_DEBUG
n_assert(0 != this->threadListIterator);
LinuxThread::criticalSection.Enter();
ThreadList.Remove(this->threadListIterator);
LinuxThread::criticalSection.Leave();
this->threadListIterator = 0;
#endif
}
//------------------------------------------------------------------------------
/**
*/
void
LinuxThread::Start()
{
n_assert(!this->IsRunning());
pthread_attr_t attr;
pthread_attr_init(&attr);
// set priority
#if !__NACL__
/*
NOTE: don't mess around with thread priorities (at least for now)
struct sched_param schedParam;
pthread_attr_getschedparam(&attr, &schedParam);
switch (this->priority)
{
case Low: schedParam.sched_priority = 24; break;
case Normal: break;
case High: schedParam.sched_priority = 16; break;
}
pthread_attr_setschedparam(&attr, &schedParam);
*/
#endif
// dont mess with pthreads stack size if you dont know what you are doing.
if(this->stackSize != 0)
{
pthread_attr_setstacksize(&attr, this->stackSize);
}
// start thread
#if __ANDROID__
// on Android, native threads must be registered with the Java runtime
NVThreadSpawnJNIThread(&this->thread, &attr, ThreadProc, (void*)this);
#else
pthread_create(&this->thread, &attr, ThreadProc, (void*)this);
#endif
pthread_attr_destroy(&attr);
// FIXME: on NACL, use pthread_setschedprio() to set the
// thread priority (-> what are valid prio values?)
// FIXME: thread stack size isn't set?
// if affinity is set apply it
if(CPU_COUNT(&this->affinity))
{
pthread_setaffinity_np(this->thread, sizeof(cpu_set_t), &this->affinity);
}
// wait for thread to run
this->threadStartedEvent.Wait();
}
//------------------------------------------------------------------------------
/**
This method is called by Thread::Stop() after setting the
stopRequest event and before waiting for the thread to stop. If your
thread runs a loop and waits for jobs it may need an extra wakeup
signal to stop waiting and check for the ThreadStopRequested() event. In
this case, override this method and signal your event object.
*/
void
LinuxThread::EmitWakeupSignal()
{
// empty, override in subclass!
}
//------------------------------------------------------------------------------
/**
This stops the thread by signalling the stopRequestEvent and waits for the
thread to actually quit. If the thread code runs in a loop it should use the
IsStopRequested() method to see if the thread object wants it to shutdown.
If so DoWork() should simply return.
*/
void
LinuxThread::Stop()
{
n_assert(this->IsRunning());
// signal the thread to stop
this->stopRequestEvent.Signal();
// call the wakeup-thread method, may be derived in a subclass
// if the threads needs to be woken up, it is important that this
// method is called AFTER the stopRequestEvent is signalled!
this->EmitWakeupSignal();
// wait for the thread to terminate
pthread_join(this->thread, 0);
this->threadState = Stopped;
}
//------------------------------------------------------------------------------
/**
Internal static helper method. This is called by pthread_create() and
simply calls the virtual DoWork() method on the thread object.
*/
void *
LinuxThread::ThreadProc(void *self)
{
n_assert(0 != self);
n_dbgout("LinuxThread::ThreadProc(): thread started!\n");
#if NEBULA_ENABLE_THREADLOCAL_STRINGATOM_TABLES
// setup thread-local string atom table (will be discarded when thread terminates)
LocalStringAtomTable* localStringAtomTable = n_new(LocalStringAtomTable);
#endif
LinuxThread* threadObj = static_cast<LinuxThread*>(self);
LinuxThread::SetMyThreadName(threadObj->GetName());
threadObj->threadState = Running;
threadObj->threadStartedEvent.Signal();
threadObj->DoWork();
threadObj->threadState = Stopped;
// discard local string atom table
#if NEBULA_ENABLE_THREADLOCAL_STRINGATOM_TABLES
n_delete(localStringAtomTable);
#endif
// tell memory system that a thread is ending
// FIXME, currently not implemented or used
// Memory::OnExitThread();
return 0;
}
//------------------------------------------------------------------------------
/**
Returns true if the thread is currently running.
*/
bool
LinuxThread::IsRunning() const
{
return (Running == this->threadState);
}
//------------------------------------------------------------------------------
/**
This method should be derived in a Thread subclass and contains the
actual code which is run in the thread. The method must not call
C-Lib functions under Win32. To terminate the thread, just return from
this function. If DoWork() runs in an infinite loop, call ThreadStopRequested()
to check whether the Thread object wants the thread code to quit.
*/
void
LinuxThread::DoWork()
{
// empty
}
//------------------------------------------------------------------------------
/**
Static method which returns the ThreadId of this thread.
*/
Threading::ThreadId
LinuxThread::GetMyThreadId()
{
return (pthread_t) pthread_self();
}
//------------------------------------------------------------------------------
/**
Static method which returns the stop-requested state of this
thread. Not yet implemented in Linux (see improvements to thread-local-
data system under Linux in the Nebula mobile thread).
*/
bool
LinuxThread::GetMyThreadStopRequested()
{
// FIXME! see Windows implementation for details
return false;
}
//------------------------------------------------------------------------------
/**
Give up time slice.
*/
void
LinuxThread::YieldThread()
{
sched_yield();
}
//------------------------------------------------------------------------------
/**
Returns an array with infos about all currently existing thread objects.
*/
#if NEBULA_DEBUG
Array<LinuxThread::ThreadDebugInfo>
LinuxThread::GetRunningThreadDebugInfos()
{
// NOTE: Portions of this loop aren't completely thread-safe
// (getting the thread-name for instance), but since those
// attributes don't change when the thread has been started
// this shouldn't be a problem.
Array<ThreadDebugInfo> infos;
LinuxThread::criticalSection.Enter();
List<LinuxThread*>::Iterator iter;
for (iter = ThreadList.Begin(); iter != ThreadList.End(); iter++)
{
LinuxThread* cur = *iter;
if (cur->IsRunning())
{
ThreadDebugInfo info;
info.threadName = cur->GetName();
info.threadPriority = cur->GetPriority();
info.threadCoreId = cur->GetCoreId();
info.threadStackSize = cur->GetStackSize();
infos.Append(info);
}
}
LinuxThread::criticalSection.Leave();
return infos;
}
#endif
//------------------------------------------------------------------------------
/**
*/
void
LinuxThread::SetMyThreadName(const String& n)
{
#if __OSX__
// OSX is BSD style UNIX and has pthread_np functions
pthread_setname_np(n.AsCharPtr());
#elif __NACL__
// FIXME: can't set thread name in NACL?
#else
// Linux is a bit more complicated...
String cappedName = n;
if (cappedName.Length() > 15)
{
cappedName.TerminateAtIndex(15);
}
prctl(PR_SET_NAME, (unsigned long) cappedName.AsCharPtr(), 0, 0, 0);
#endif
}
//------------------------------------------------------------------------------
/**
*/
const char *
LinuxThread::GetMyThreadName()
{
#if __OSX__
// OSX is BSD style UNIX and has pthread_np functions
return "<FIXME>";
#else
static char buffer[16];
prctl(PR_GET_NAME, buffer,0,0,0,0);
return buffer;
#endif
}
//------------------------------------------------------------------------------
/**
*/
int
LinuxThread::GetMyThreadPriority()
{
sched_param param;
int policy;
pthread_getschedparam(pthread_self(), &policy, ¶m);
return param.sched_priority;
}
//------------------------------------------------------------------------------
/**
*/
void
LinuxThread::SetThreadAffinity(uint mask)
{
CPU_SET(mask, &this->affinity);
if(this->thread != 0)
{
pthread_setaffinity_np(this->thread, sizeof(cpu_set_t), &this->affinity);
}
}
} // namespace Linux
| 28.079096 | 89 | 0.583602 | [
"object"
] |
f6326b44fddb1707ca06b1c6f85726000efc2906 | 26,611 | cpp | C++ | Source/AllProjects/CIDBuild/CIDBuild_FileDepend.cpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | 1 | 2019-05-28T06:33:01.000Z | 2019-05-28T06:33:01.000Z | Source/AllProjects/CIDBuild/CIDBuild_FileDepend.cpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | Source/AllProjects/CIDBuild/CIDBuild_FileDepend.cpp | eudora-jia/CIDLib | 02795d283d95f8a5a4fafa401b6189851901b81b | [
"MIT"
] | null | null | null | //
// FILE NAME: CIDBuild_Depend.Cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 08/22/1998
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the dependency analysis method of the TFacCIDBuld
// class. Its big enough that we don't want to put it in the same file as
// the rest of the class.
//
// We are passed the name of the project for which we should do the
// dependency analysis for. We have to create the .Depend file for the
// project and add to it all the dependencies for all of the Cpp files
// of that project.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CIDBuild.hpp"
// ---------------------------------------------------------------------------
// CLASS: TTokenInfo
// PREFIX: toki
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TTokenInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
TTokenInfo::TTokenInfo() :
m_eType(tCIDBuild::ETokens::None)
{
}
TTokenInfo::TTokenInfo( const TBldStr& strTokenName
, const tCIDBuild::ETokens eType) :
m_eType(eType)
, m_strTokenName(strTokenName)
{
}
TTokenInfo::~TTokenInfo()
{
}
// ---------------------------------------------------------------------------
// TTokenInfo: Public, non-virtual methods
// ---------------------------------------------------------------------------
const TBldStr& TTokenInfo::strTokenName() const
{
return m_strTokenName;
}
// ---------------------------------------------------------------------------
// CLASS: THeaderInfo
// PREFIX: hdri
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// THeaderInfo: Constructors and Destructor
// ---------------------------------------------------------------------------
THeaderInfo::THeaderInfo() :
m_bGenerated(kCIDLib::False)
, m_bSearched(kCIDLib::False)
{
//
// We default the bool flags to cause any initial work to be done.
// By saying its not searched yet, it will have to be searched. By
// saying it has includes, it will be searched for includes and the
// flag turned off if none are found.
//
}
THeaderInfo::THeaderInfo(const TBldStr& strFileName
, const TBldStr& strPath) :
m_bGenerated(kCIDLib::False)
, m_bSearched(kCIDLib::False)
, m_strFileName(strFileName)
, m_strPath(strPath)
{
}
THeaderInfo::~THeaderInfo()
{
}
// ---------------------------------------------------------------------------
// THeaderInfo: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid THeaderInfo::AddHeader(const TBldStr& strToAdd)
{
m_listIncluded.Add(new TBldStr(strToAdd));
}
tCIDLib::TBoolean THeaderInfo::bGenerated() const
{
return m_bGenerated;
}
tCIDLib::TBoolean THeaderInfo::bGenerated(const tCIDLib::TBoolean bToSet)
{
m_bGenerated = bToSet;
return m_bGenerated;
}
tCIDLib::TBoolean THeaderInfo::bSearched() const
{
return m_bSearched;
}
tCIDLib::TBoolean THeaderInfo::bSearched(const tCIDLib::TBoolean bToSet)
{
m_bSearched = bToSet;
return m_bSearched;
}
TList<TBldStr>& THeaderInfo::listIncluded()
{
return m_listIncluded;
}
const TBldStr& THeaderInfo::strFileName() const
{
return m_strFileName;
}
const TBldStr& THeaderInfo::strPath() const
{
return m_strPath;
}
// ---------------------------------------------------------------------------
// CLASS: TFileDepAnalyzer
// PREFIX: fda
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TFileDepAnalyzer: Static data members
// ---------------------------------------------------------------------------
TList<THeaderInfo> TFileDepAnalyzer::s_listHeaders;
// ---------------------------------------------------------------------------
// TFileDepAnalyzer: Constructors and Destructor
// ---------------------------------------------------------------------------
TFileDepAnalyzer::TFileDepAnalyzer(const TProjectInfo& projiTarget) :
m_projiTarget(projiTarget)
{
// Build up the path to the dependency file
m_strDepFile = m_projiTarget.strOutDir();
m_strDepFile.Append(m_projiTarget.strProjectName(), L".Depend");
//
// Build up all of the include paths we have to search for files. We
// know that we have the two standard output paths and their per-
// platform subdirectories, plus we have to deal with the one that
// the project can optionally provide.
//
TBldStr* pstrNew;
m_listIncludes.Add(new TBldStr(facCIDBuild.strIncludeDir()));
pstrNew = new TBldStr(facCIDBuild.strIncludeDir());
pstrNew->Append(kCIDBuild::pszPlatformDir);
m_listIncludes.Add(pstrNew);
m_listIncludes.Add(new TBldStr(facCIDBuild.strPrivIncludeDir()));
pstrNew = new TBldStr(facCIDBuild.strPrivIncludeDir());
pstrNew->Append(kCIDBuild::pszPlatformDir);
m_listIncludes.Add(pstrNew);
// Add in the include paths that are specific to this project
TList<TBldStr>::TCursor cursIncludePaths(&projiTarget.listIncludePaths());
if (cursIncludePaths.bResetIter())
{
do
{
m_listIncludes.Add(new TBldStr(cursIncludePaths.tCurElement()));
} while (cursIncludePaths.bNext());
}
// And the ones that are system wide
TList<TBldStr>::TCursor cursExtIncludePaths(&facCIDBuild.listExtIncludePaths());
if (cursExtIncludePaths.bResetIter())
{
do
{
m_listIncludes.Add(new TBldStr(cursExtIncludePaths.tCurElement()));
} while (cursExtIncludePaths.bNext());
}
}
TFileDepAnalyzer::~TFileDepAnalyzer()
{
}
// ---------------------------------------------------------------------------
// TFileDepAnalyzer: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TFileDepAnalyzer::MakeDeps()
{
// Try to change to the project directory
if (!TUtils::bChangeDir(m_projiTarget.strProjectDir()))
{
stdOut << L"Could not change to project directory: "
<< m_projiTarget.strProjectDir() << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::NotFound;
}
tCIDLib::TBoolean bOpened = kCIDLib::False;
try
{
// Create the output file (truncating any existing contents)
TTextFile tflOut
(
m_strDepFile.pszBuffer()
, tCIDBuild::EEncodings::UTF16
, tCIDLib::EAccessModes::Write
, tCIDLib::ECreateActs::CreateAlways
);
// Indicate we got the file opened
bOpened = kCIDLib::True;
// Put out the Unicode byte order mark
tflOut << kCIDLib::chUniBOM;
// Write out the simple header
tflOut << L";\n; CIDDep Dependency Output File\n;\n";
//
// Lets run through each of the Cpp files that belong to this
// project and output its dependencies to the file we just opened.
//
TList<TFindInfo>::TCursor cursCpps(&m_projiTarget.listCpps());
// Remember if we've done a header dump so far
tCIDLib::TBoolean bHdrDumpDone = kCIDLib::False;
// Return if there aren't any Cpps to do
if (cursCpps.bResetIter())
{
TBldStr strPath;
do
{
// Get a short cut to the file info for this file
const TFindInfo& fndiCur = cursCpps.tCurElement();
// Output the FILE= part for this file
tflOut << L"FILE=" << fndiCur.strFileName().pszBuffer() << L"\n";
//
// Reset the list for this cpp file, and mark all of the
// existing items in the cache as not having been generated
// yet.
//
ClearCacheGenMarks();
//
// Create a header info object for the Cpp file itself. This
// will serve as the root of the final search tree. Using
// one of these for the cpp file allows us to do a simper
// recursive processing of it later.
//
strPath = m_projiTarget.strProjectDir();
strPath.Append(fndiCur.strFileName());
THeaderInfo hdriCpp(fndiCur.strFileName(), strPath);
//
// And now lets do the analysis for this file. This will
// fill in the listCurHdrs list with pointers to the header
// info items for any headers that this Cpp file includes,
// directly or indirectly.
//
DoFile(hdriCpp);
//
// Output the list of headers for this file. We call a
// helper that has to do a transitive closure of the list
// of lists, insuring that it only outputs each header once,
// so the helper is recursive.
//
WriteHeaders(0, tflOut, hdriCpp);
// And cap off this file's section
tflOut << L"END FILE\n\n\n";
//
// If doing header dependency dumps, then handle that. If
// standard mode, then just done one file for a project,
// since mostly they never change. If full, do it for every
// file.
//
if (facCIDBuild.eHdrDumpMode() != tCIDBuild::EHdrDmpModes::None)
{
if (facCIDBuild.eHdrDumpMode() == tCIDBuild::EHdrDmpModes::Full)
{
stdOut << L"\nFILE: " << fndiCur.strFileName() << L"\n";
DumpDeps(hdriCpp, 1);
}
else if (!bHdrDumpDone)
{
stdOut << L"\nPROJECT: "
<< m_projiTarget.strProjectName() << L"\n";
DumpDeps(hdriCpp, 1);
bHdrDumpDone = kCIDLib::True;
}
}
// Flush the tokens for the next round
m_listTokens.RemoveAll();
} while (cursCpps.bNext());
}
}
catch(...)
{
if (!bOpened)
{
stdOut << L"Failed to create dependency file: "
<< m_strDepFile << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::CreateError;
}
//
// Any failure means that the file might be messed up, so we
// delete it to be sure.
//
stdOut << L"Dependency analysis failed on project '"
<< m_projiTarget.strProjectName() << L"'. " << kCIDBuild::EndLn;
if (TUtils::bDeleteFile(m_strDepFile))
{
stdOut << L" Dependency file was deleted" << kCIDBuild::EndLn;
}
else
{
stdOut << L" Could not delete target file: "
<< m_strDepFile << kCIDBuild::EndLn;
}
throw;
}
}
// ---------------------------------------------------------------------------
// TFileDepAnalyzer: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TVoid TFileDepAnalyzer::DoFile(THeaderInfo& hdriCur)
{
// Lets create a spooler for this file
TLineSpooler lsplInput(hdriCur.strPath());
// Disable macro expansion on this one, since its not a CIDBuild file
lsplInput.bDisableMacros(kCIDLib::True);
// We got the file opened, so lets go for it
tCIDBuild::ETokens eToken;
TBldStr strBuf;
TBldStr strPath;
//
// This loop will get the next token that we are interested in. The
// returned token will be the contents of an include statement or or
// a defined/undef statement.
//
// "#if defined()" and "#if !defined()" statements are handled in
// eNextToken(). It will automatically skip areas that are
// conditionally turned off and track nested #if/#if! statements.
//
eToken = eNextToken(lsplInput, strBuf);
while (eToken != tCIDBuild::ETokens::None)
{
if (eToken == tCIDBuild::ETokens::Include)
{
//
// Try to find this include in the internal include path. This
// will give us the full path to it.
//
if (bSearchInclude(strBuf, strPath))
{
// Add this guy as a header in our current file
hdriCur.AddHeader(strBuf);
//
// See if this guy is in our cache. If so, then don't
// search it again.
//
THeaderInfo* phdriChild = phdriFind(strBuf);
//
// Didn't find it, so add it to our our cache. This will
// default the new header info to indicate that headers are
// present in order to force the initial processing.
//
if (!phdriChild)
{
phdriChild = new THeaderInfo(strBuf, strPath);
s_listHeaders.Add(phdriChild);
DoFile(*phdriChild);
}
}
else
{
stdOut << L" File '" << strBuf
<< L"' was not found, used in file: "
<< hdriCur.strPath() << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileNotFound;
}
}
else if (eToken == tCIDBuild::ETokens::Define)
{
// It is a token so add it to list of not already
m_listTokens.Add(new TTokenInfo(strBuf, tCIDBuild::ETokens::Define));
}
else if (eToken == tCIDBuild::ETokens::UnDef)
{
//
// Try to undefine the token. If we don't find it in our list,
// that's ok because they could be undefining something defined
// in a system header.
//
UnDefToken(strBuf);
}
// Get the next token
eToken = eNextToken(lsplInput, strBuf);
}
}
tCIDLib::TBoolean
TFileDepAnalyzer::bSearchInclude(const TBldStr& strToFind
, TBldStr& strToFill) const
{
// Assume not found
strToFill.Clear();
//
// Loop through the include path parts and search each one for the
// file in question.
//
TList<TBldStr>::TCursor cursIncls(&m_listIncludes);
if (!cursIncls.bResetIter())
return kCIDLib::False;
do
{
TBldStr strTmp = cursIncls.tCurElement();
// Add the separator if not there
if (strTmp.chLast() != L'\\')
strTmp.Append(L"\\");
strTmp.Append(strToFind);
if (TUtils::bExists(strTmp))
{
strToFill = strTmp;
return kCIDLib::True;
}
} while (cursIncls.bNext());
return kCIDLib::False;
}
tCIDLib::TVoid TFileDepAnalyzer::ClearCacheGenMarks()
{
TList<THeaderInfo>::TCursor cursHdrs(&s_listHeaders);
if (!cursHdrs.bResetIter())
return;
do
{
cursHdrs.tCurElement().bGenerated(kCIDLib::False);
} while (cursHdrs.bNext());
}
tCIDLib::TVoid
TFileDepAnalyzer::DumpDeps( THeaderInfo& hdriCur
, const tCIDLib::TCard4 c4Depth)
{
TList<TBldStr>::TCursor cursHdrs(&hdriCur.listIncluded());
if (cursHdrs.bResetIter())
{
do
{
// Dump out the file name for this level
const TBldStr& strName = cursHdrs.tCurElement();
stdOut.ConIndent(c4Depth);
stdOut << strName << L"\n";
// And if any info is available for, dump that
THeaderInfo* phdriChild = phdriFind(strName);
if (phdriChild)
{
DumpDeps(*phdriChild, c4Depth + 1);
}
else
{
stdOut.ConIndent(c4Depth + 1);
stdOut << L"<No Info>" << L"\n";
}
} while (cursHdrs.bNext());
}
}
tCIDBuild::ETokens
TFileDepAnalyzer::eNextToken(TLineSpooler& lsplInput, TBldStr& strBuf)
{
const tCIDLib::TCard4 c4LineSz = 2048;
// Assume the worst
strBuf.Clear();
tCIDLib::TCh* pszTmp;
tCIDBuild::ETokens eRet = tCIDBuild::ETokens::None;
TBldStr strReadBuf;
tCIDLib::TCh szReadBuf[c4LineSz+1];
tCIDLib::TCard4 c4NestCount = 0;
while (lsplInput.bReadLine(strReadBuf))
{
// Get a copy of the string that we can tokenize
TRawStr::CopyStrN(szReadBuf, strReadBuf.pszBuffer(), c4LineSz);
//
// Strip out the first token in the list. Use whitespace to break
// out the tokens.
//
pszTmp = TRawStr::pszStrTok(szReadBuf, L" \t\n\r");
// If no token, then an empty line so do next line
if (!pszTmp)
continue;
// If the first character is not #, then not one of ours
if (pszTmp[0] != L'#')
continue;
//
// Find out what type of token it is. If not one of the ones we
// want, then do next line.
//
if (!TRawStr::iCompStr(pszTmp, L"#if"))
{
// Get the next token
pszTmp = TRawStr::pszStrTok(0, L" \t\n\t(");
//
// We look for defined or !defined, and set the return value
// appropriately. If neither, then skip it.
//
if (!TRawStr::iCompStr(pszTmp, L"defined"))
eRet = tCIDBuild::ETokens::IfDef;
else if (!TRawStr::iCompStr(pszTmp, L"!defined"))
eRet = tCIDBuild::ETokens::IfNotDef;
else
continue;
}
else if (!TRawStr::iCompStr(pszTmp, L"#define"))
{
eRet = tCIDBuild::ETokens::Define;
}
else if (!TRawStr::iCompStr(pszTmp, L"#undef"))
{
eRet = tCIDBuild::ETokens::UnDef;
}
else if (!TRawStr::iCompStr(pszTmp, L"#include"))
{
eRet = tCIDBuild::ETokens::Include;
}
else if (!TRawStr::iCompStr(pszTmp, L"#endif"))
{
eRet = tCIDBuild::ETokens::EndIf;
}
else
{
continue;
}
//
// If we are in a kCIDLib::False conditional section and the token is not
// something that might affect that, then just skip it.
//
if (c4NestCount
&& (eRet != tCIDBuild::ETokens::EndIf)
&& (eRet != tCIDBuild::ETokens::IfDef)
&& (eRet != tCIDBuild::ETokens::IfNotDef))
{
continue;
}
//
// If we are in a kCIDLib::False conditional section, and it is one of the
// tokens that we must track in that situation, then check it out.
//
if (c4NestCount)
{
//
// If another define, then just bump up the nesting count so
// that we can track down to the last endif to get out of the
// kCIDLib::False section, then get another line.
//
// If an endif, then bump down the count. If it hits 0, then we
// are out of the kCIDLib::False section
//
if ((eRet == tCIDBuild::ETokens::IfDef) || (eRet == tCIDBuild::ETokens::IfNotDef))
c4NestCount++;
else if (eRet == tCIDBuild::ETokens::EndIf)
c4NestCount--;
continue;
}
if (eRet == tCIDBuild::ETokens::Include)
{
//
// It is an include statement. First make sure that it is not
// a system header because we don't do them. If not, then return
// the next token to the caller.
//
pszTmp = TRawStr::pszStrTok(0, L" \t\n\r\"");
if (pszTmp[0] == L'<')
{
eRet = tCIDBuild::ETokens::None;
continue;
}
// Copy the file name ot the caller's buffer
strBuf = pszTmp;
break;
}
else if (eRet == tCIDBuild::ETokens::EndIf)
{
// Nothing to do
}
else if ((eRet == tCIDBuild::ETokens::Define)
|| (eRet == tCIDBuild::ETokens::UnDef))
{
// The next token is the defined value
pszTmp = TRawStr::pszStrTok(0, L" \t\n\r");
strBuf = pszTmp;
break;
}
else if ((eRet == tCIDBuild::ETokens::IfDef)
|| (eRet == tCIDBuild::ETokens::IfNotDef))
{
//
// This one can be complex with multiple target tokens OR'd
// together, and can be across multiple lines. So we need
// to check the last character to see if it is a continuation.
// If so, read that line in as well, appending it to the
// current line (overlapping the continuation line.
//
tCIDLib::TCard4 bState = 0;
while (pszTmp = TRawStr::pszStrTok(0, L" \t\n\r()"))
{
// If we hit the continuation, read the next line
if (!TRawStr::iCompStr(pszTmp, L"\\"))
{
if (!lsplInput.bReadLine(strReadBuf))
{
stdOut << L" Unexpected EOF after continuation at "
<< lsplInput.strFileName()
<< L"." << lsplInput.c4CurLine() << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::FileFormat;
}
TRawStr::CopyStrN(szReadBuf, strReadBuf.pszBuffer(), c4LineSz);
pszTmp = TRawStr::pszStrTok(szReadBuf, L" \t\n\r()");
}
if (!TRawStr::iCompStr(pszTmp, L"||"))
{
// This is the TBoolean operator
}
else
{
//
// This has to be the token so decide whether it is
// defined. Use this and the IF/IFNOT to decide wether
// the statement is kCIDLib::False. If so, clear the state flag
// otherwise leave it kCIDLib::True.
//
if (ptokiFind(pszTmp))
{
if (eRet == tCIDBuild::ETokens::IfDef)
bState = 1;
}
else
{
if (eRet == tCIDBuild::ETokens::IfNotDef)
bState = 1;
}
}
}
//
// If we got a kCIDLib::False result, then bump up the nest count which
// which start us searching for the end of the kCIDLib::False section.
//
if (!bState)
c4NestCount++;
// Reset the token and continue
eRet = tCIDBuild::ETokens::None;
}
else
{
stdOut << L" Unknown token: " << pszTmp << kCIDBuild::EndLn;
throw tCIDBuild::EErrors::Internal;
}
}
return eRet;
}
THeaderInfo* TFileDepAnalyzer::phdriFind(const TBldStr& strName) const
{
TList<THeaderInfo>::TCursor cursHdrs(&s_listHeaders);
if (!cursHdrs.bResetIter())
return 0;
do
{
if (cursHdrs.tCurElement().strFileName() == strName)
return &cursHdrs.tCurElement();
} while (cursHdrs.bNext());
return 0;
}
TTokenInfo* TFileDepAnalyzer::ptokiFind(const TBldStr& strName) const
{
TList<TTokenInfo>::TCursor cursToks(&m_listTokens);
if (!cursToks.bResetIter())
return 0;
do
{
if (cursToks.tCurElement().strTokenName() == strName)
return &cursToks.tCurElement();
} while (cursToks.bNext());
return 0;
}
void TFileDepAnalyzer::UnDefToken(const TBldStr& strName)
{
// If no tokens, then obviously not defined
if (!m_listTokens.c4ElemCount())
return;
//
// Look it up in the current list. If we find it, then remove it from
// out list.
//
TTokenInfo* ptokiUndef = ptokiFind(strName);
if (ptokiUndef)
m_listTokens.Remove(ptokiUndef);
}
tCIDLib::TVoid
TFileDepAnalyzer::WriteHeaders( const tCIDLib::TCard4 c4Level
, TTextFile& tflOut
, THeaderInfo& hdriCur)
{
// If this guy is not generated yet, then put it out. Else, just return
if (!hdriCur.bGenerated())
{
// Only do this if not the 0th level (which is the cpp file itself)
if (c4Level)
{
tflOut << L" "
<< hdriCur.strPath()
<< L"\n";
}
hdriCur.bGenerated(kCIDLib::True);
//
// Loop through all of the headers that this guy includes. If one is
// not marked as having been generated yet, then put it out and recurse
// on it, after marking it.
//
TList<TBldStr>::TCursor cursHdrs(&hdriCur.listIncluded());
if (cursHdrs.bResetIter())
{
do
{
const TBldStr& strName = cursHdrs.tCurElement();
THeaderInfo* phdriChild = phdriFind(strName);
if (phdriChild && !phdriChild->bGenerated())
WriteHeaders(c4Level + 1, tflOut, *phdriChild);
} while (cursHdrs.bNext());
}
}
}
| 31.869461 | 94 | 0.501973 | [
"object"
] |
f63b37a0774dd0c4a28bbfb4a10d4464090d9967 | 1,473 | hpp | C++ | Crocus/BoxCollider.hpp | ChunChunMorning/CrocusEngine | a93a7f813b60bf6f221abaf6b9d580263e708900 | [
"Unlicense"
] | null | null | null | Crocus/BoxCollider.hpp | ChunChunMorning/CrocusEngine | a93a7f813b60bf6f221abaf6b9d580263e708900 | [
"Unlicense"
] | null | null | null | Crocus/BoxCollider.hpp | ChunChunMorning/CrocusEngine | a93a7f813b60bf6f221abaf6b9d580263e708900 | [
"Unlicense"
] | null | null | null | # pragma once
# include "Assets.hpp"
# include "Collider.hpp"
# include "Transform.hpp"
namespace cre
{
using namespace s3d;
class BoxCollider : public Collider
{
private:
Vec3 m_offset;
Vec3 m_size;
stupid_ptr<Transform> m_transform;
public:
BoxCollider() = default;
explicit BoxCollider(const Vec3& size, Physics::Group group = Physics:: Groups::Environment);
BoxCollider(const Vec3& offset, const Vec3& size, Physics::Group group = Physics::Groups::Environment);
void init() override;
Vec3 setOffset(const Vec3& offset) { return m_offset = offset; }
Vec3 setPosition(const Vec3& position);
Vec3 setCenter(const Vec3& center);
Vec3 moveBy(const Vec3& v)
{
return m_transform->moveBy(v);
}
Vec3 offset() const { return m_offset; }
Vec3 position() const override;
Box box() const { return{ center(), m_size }; }
Vec3 size() const override { return m_size; }
Vec3 groundNormal() const override { return Vec3::Up; }
bool intersects(const Box& other) const override;
bool intersects(const Ray& other) const override;
Optional<Vec3> intersectsAt(const Ray& other) const override;
bool detectWall(const Box& body, const Vec3& direction) const override;
void extrude(const stupid_ptr<Rigidbody>& rigidbody) const override;
# ifdef _DEBUG
void draw(double thickness, const Color& color) const override;
# endif
static unique_ptr<Component> Create(const XMLElement& element, const Assets&);
};
}
| 21.661765 | 105 | 0.718262 | [
"transform"
] |
f63c47d77abf323fe45fa9405bd3782dc54df049 | 10,372 | cpp | C++ | applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_RLE_FACE_SCALAR_FIELD_3D.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 20 | 2017-07-03T19:09:09.000Z | 2021-09-10T02:53:56.000Z | applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_RLE_FACE_SCALAR_FIELD_3D.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | null | null | null | applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_RLE_FACE_SCALAR_FIELD_3D.cpp | schinmayee/nimbus | 170cd15e24a7a88243a6ea80aabadc0fc0e6e177 | [
"BSD-3-Clause"
] | 9 | 2017-09-17T02:05:06.000Z | 2020-01-31T00:12:01.000Z | #ifndef COMPILE_WITHOUT_RLE_SUPPORT
//#####################################################################
// Copyright 2005, Eran Guendelman, Geoffrey Irving.
// This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt.
//#####################################################################
#include <PhysBAM_Tools/Grids_RLE/RLE_GRID_ITERATOR_FACE_HORIZONTAL.h>
#include <PhysBAM_Tools/Grids_RLE/RLE_GRID_ITERATOR_FACE_Y.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_RLE_FACE_SCALAR_FIELD_3D.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_RLE_GRID_3D.h>
#include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_RLE_SLICE.h>
using namespace PhysBAM;
//#####################################################################
// Function Display
//#####################################################################
template<class T,class T2> void Compute_Maximum_Norm(const OPENGL_RLE_FACE_SCALAR_FIELD_3D<T,T2>& field,const RANGE<VECTOR<int,2> >& region)
{
field.max_norm=0;field.max_norm_cell=0;field.max_norm_I=VECTOR<int,3>();
for(typename RLE_GRID_3D<T>::CELL_ITERATOR cell(field.grid,region);cell;cell++){
T2 local_norm=0;
for(int axis=1;axis<=RLE_GRID_3D<T>::dimension;axis++)local_norm+=maxabs(field.value(cell.First_Face_Index(axis)),field.value(cell.Second_Face_Index(axis)));
if(field.max_norm<local_norm){field.max_norm=local_norm;field.max_norm_cell=cell.Cell();field.max_norm_I=cell.I();}}
}
template<class T> void Compute_Maximum_Norm(const OPENGL_RLE_FACE_SCALAR_FIELD_3D<T,bool>& field,const RANGE<VECTOR<int,2> >& region)
{}
template<class T,class T2> void OPENGL_RLE_FACE_SCALAR_FIELD_3D<T,T2>::
Display(const int in_color) const
{
OPENGL_RLE_SLICE* slice=(OPENGL_RLE_SLICE*)this->slice;
PHYSBAM_ASSERT(grid.long_run_cells==2);
glPushAttrib(GL_LIGHTING_BIT | GL_TEXTURE_BIT | GL_POINT_BIT);
glPointSize(point_size);glDisable(GL_LIGHTING);
RANGE<VECTOR<int,2> > region(grid.columns.domain.min_corner.x+1,grid.columns.domain.max_corner.x-1,grid.columns.domain.min_corner.y+1,grid.columns.domain.max_corner.y-1);
if(slice && slice->mode==OPENGL_SLICE::CELL_SLICE){
switch(slice->axis){
case 1: region.min_corner.x=region.max_corner.x=slice->index;break;
case 2: break; // TODO: deal with y slices
case 3: region.min_corner.y=region.max_corner.y=slice->index;break;}}
Compute_Maximum_Norm(*this,region);
RANGE<VECTOR<int,2> > xregion(region.min_corner.x,region.max_corner.x+1,region.min_corner.y,region.max_corner.y),zregion(region.min_corner.x,region.max_corner.x,region.min_corner.y,region.max_corner.y+1);
if(draw_points){
OpenGL_Begin(GL_POINTS);
if(grid.long_run_faces_horizontal==1){
for(FACE_X_ITERATOR face(grid,xregion);face;face++){int f=face.Face();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();OpenGL_Vertex(face.X());}}
for(FACE_Z_ITERATOR face(grid,zregion);face;face++){int f=face.Face();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();OpenGL_Vertex(face.X());}}}
else{
for(FACE_X_ITERATOR face(grid,xregion);face;face++){int f=face.Face();VECTOR<T,3> X=face.X();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.j(),2);OpenGL_Vertex(X);}
if(face.Long() && value(f+1)){color_map->Lookup(value(f+1)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.jmax()-1,2);OpenGL_Vertex(X);}}
for(FACE_Z_ITERATOR face(grid,zregion);face;face++){int f=face.Face();VECTOR<T,3> X=face.X();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.j(),2);OpenGL_Vertex(face.X());}
if(face.Long() && value(f+1)){color_map->Lookup(value(f+1)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.jmax()-1,2);OpenGL_Vertex(X);}}}
for(FACE_Y_ITERATOR face(grid,region,true);face;face++){int f=face.Face();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();OpenGL_Vertex(face.X());}
if(face.Long() && value(f+1)){color_map->Lookup(value(f+1)).Send_To_GL_Pipeline();
OpenGL_Vertex(face.cell2.Center());}}
OpenGL_End();}
else{
OpenGL_Begin(GL_LINES);
if(grid.long_run_faces_horizontal==1){
for(FACE_X_ITERATOR face(grid,xregion);face;face++){int f=face.Face();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();VECTOR<T,3> X=face.X(),Y=X;X.x+=value(f)*line_size;OpenGL_Vertex(Y,X);}}
for(FACE_Z_ITERATOR face(grid,zregion);face;face++){int f=face.Face();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();VECTOR<T,3> X=face.X(),Y=X;X.z+=value(f)*line_size;OpenGL_Vertex(Y,X);}}}
else{
for(FACE_X_ITERATOR face(grid,xregion);face;face++){int f=face.Face();VECTOR<T,3> X=face.X();
if(value(f)){
color_map->Lookup(value(f)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.j(),2);
OpenGL_Line(X,VECTOR<T,3>(X.x+value(f)*line_size,X.y,X.z));}
if(face.Long() && value(f+1)){
color_map->Lookup(value(f+1)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.jmax()-1,2);
OpenGL_Line(X,VECTOR<T,3>(X.x+value(f+1)*line_size,X.y,X.z));}}
for(FACE_Z_ITERATOR face(grid,zregion);face;face++){int f=face.Face();VECTOR<T,3> X=face.X();
if(value(f)){
color_map->Lookup(value(f)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.j(),2);
OpenGL_Line(X,VECTOR<T,3>(X.x,X.y,X.z+value(f)*line_size));}
if(face.Long() && value(f+1)){
color_map->Lookup(value(f+1)).Send_To_GL_Pipeline();X.y=grid.uniform_grid.Axis_X_plus_half(face.jmax()-1,2);
OpenGL_Line(X,VECTOR<T,3>(X.x,X.y,X.z+value(f+1)*line_size));}}}
for(FACE_Y_ITERATOR face(grid,region,true);face;face++){int f=face.Face();
if(value(f)){color_map->Lookup(value(f)).Send_To_GL_Pipeline();VECTOR<T,3> X=face.X();OpenGL_Vertex(X);X.y+=value(f)*line_size;OpenGL_Vertex(X);}
if(face.Long() && value(f+1)){color_map->Lookup(value(f+1)).Send_To_GL_Pipeline();
VECTOR<T,3> X=face.cell2.Center();
OpenGL_Vertex(X);X.y+=value(f+1)*line_size;OpenGL_Vertex(X);}}
OpenGL_End();}
glPopAttrib();
}
//#####################################################################
// Function Bounding_Box
//#####################################################################
template<class T,class T2> RANGE<VECTOR<float,3> > OPENGL_RLE_FACE_SCALAR_FIELD_3D<T,T2>::
Bounding_Box() const
{
return (RANGE<VECTOR<float,3> >)grid.uniform_grid.domain;
}
//#####################################################################
// Function Print_Selection_Info
//#####################################################################
template<class T,class T2> void OPENGL_RLE_FACE_SCALAR_FIELD_3D<T,T2>::
Print_Selection_Info(std::ostream& output_stream,OPENGL_SELECTION* current_selection) const
{
if(current_selection && current_selection->type==OPENGL_SELECTION::RLE_CELL_3D){
OPENGL_SELECTION_RLE_CELL_3D<T>* selection=(OPENGL_SELECTION_RLE_CELL_3D<T>*)current_selection;
const RLE_RUN_3D* run=selection->run;int dj=selection->I.y-run->jmin,cell=run->cell+dj;
int fx1=run->faces[0]+dj,fx2=run->faces[1]+dj,fy1=cell,fy2=fy1+(run->is_long?2:1),fz1=run->faces[4]+dj,fz2=run->faces[5]+dj;
bool left_face_long=false,right_face_long=false,front_face_long=false,back_face_long=false;
if(run->is_long && grid.long_run_faces_horizontal==2){ // TODO: make more efficient (maybe store some extra data in selection object to avoid this lookup)
const RLE_RUN_3D* left_run=grid.Clamped_Run_In_Column(selection->I.x-1,selection->I.y,selection->I.z);
if(left_run->is_long && (left_run+1)->jmin>selection->I.y+1) left_face_long=true;
const RLE_RUN_3D* right_run=grid.Clamped_Run_In_Column(selection->I.x+1,selection->I.y,selection->I.z);
if(right_run->is_long && (right_run+1)->jmin>selection->I.y+1) right_face_long=true;
const RLE_RUN_3D* front_run=grid.Clamped_Run_In_Column(selection->I.x,selection->I.y,selection->I.z-1);
if(front_run->is_long && (front_run+1)->jmin>selection->I.y+1) front_face_long=true;
const RLE_RUN_3D* back_run=grid.Clamped_Run_In_Column(selection->I.x,selection->I.y,selection->I.z+1);
if(back_run->is_long && (back_run+1)->jmin>selection->I.y+1) back_face_long=true;}
ARRAY<T2>& V=value;
output_stream<<"u left = "<<V(fx1);if(left_face_long) output_stream<<" "<<V(fx1+1);output_stream<<", ";
output_stream<<"right = "<<V(fx2);if(right_face_long) output_stream<<" "<<V(fx2+1);output_stream<<std::endl;
output_stream<<"v bottom = "<<V(fy1);if(run->is_long) output_stream<<", mid = "<<V(fy1+1);output_stream<<", top = "<<V(fy2)<<std::endl;
output_stream<<"w front = "<<V(fz1);if(front_face_long) output_stream<<" "<<V(fz1+1);output_stream<<", ";
output_stream<<"back = "<<V(fz2);if(back_face_long) output_stream<<" "<<V(fz2+1);output_stream<<std::endl;
if(!run->is_long){
T ux=(V(fx2)-V(fx1))*grid.uniform_grid.one_over_dX.x,vy=(V(fy2)-V(fy1))*grid.uniform_grid.one_over_dX.y,wz=(V(fz2)-V(fz1))*grid.uniform_grid.one_over_dX.z;
output_stream<<"divergence = "<<ux+vy+wz<<" (ux="<<ux<<", vy="<<vy<<", wz="<<wz<<")"<<std::endl;}}
}
//#####################################################################
template class OPENGL_RLE_FACE_SCALAR_FIELD_3D<float>;
template class OPENGL_RLE_FACE_SCALAR_FIELD_3D<float,int>;
template class OPENGL_RLE_FACE_SCALAR_FIELD_3D<float,bool>;
#ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT
template class OPENGL_RLE_FACE_SCALAR_FIELD_3D<double>;
template class OPENGL_RLE_FACE_SCALAR_FIELD_3D<double,int>;
template class OPENGL_RLE_FACE_SCALAR_FIELD_3D<double,bool>;
#endif
#endif
| 73.560284 | 208 | 0.643367 | [
"object",
"vector"
] |
f648f857dc88995645d2c36e2f0ed097d52b89cd | 3,375 | cpp | C++ | TerrainGenerator/src/terrain_generator/World.cpp | LucidSigma/vulkan-terrain-generator | 532530331d988dbd2c4e9ae382812d28fabbd5e8 | [
"MIT"
] | 2 | 2020-04-14T01:54:54.000Z | 2020-04-14T08:30:21.000Z | TerrainGenerator/src/terrain_generator/World.cpp | LucidSigma/vulkan-terrain-generator | 532530331d988dbd2c4e9ae382812d28fabbd5e8 | [
"MIT"
] | null | null | null | TerrainGenerator/src/terrain_generator/World.cpp | LucidSigma/vulkan-terrain-generator | 532530331d988dbd2c4e9ae382812d28fabbd5e8 | [
"MIT"
] | null | null | null | #include "World.h"
#include <array>
#define GLM_FORCE_RADIANS
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/gtc/matrix_transform.hpp>
World::World(Renderer& renderer, const Window& window)
: m_renderer(renderer)
{
Initialise(window);
for (int i = -s_RenderDistance; i <= s_RenderDistance; ++i)
{
for (int j = -s_RenderDistance; j <= s_RenderDistance; ++j)
{
m_chunks.emplace_back(std::make_unique<Chunk>(m_renderer, glm::ivec2{ i, j }));
}
}
}
World::~World() noexcept
{
m_chunks.clear();
m_terrainPipeline->Destroy();
}
void World::ProcessInput()
{
m_camera.ProcessInput();
}
void World::Update(const float deltaTime)
{
m_camera.Update(deltaTime);
static glm::ivec2 previousChunk{ 0, 0 };
const glm::ivec2 currentChunk = glm::ivec2{ glm::round(m_camera.GetPosition().x / Chunk::GetChunkLength()), glm::round(m_camera.GetPosition().z / Chunk::GetChunkWidth()) };
if (currentChunk != previousChunk)
{
for (auto& chunk : m_chunks)
{
const float xDistanceFromCamera = chunk->GetPosition().x - (m_camera.GetPosition().x / Chunk::GetChunkLength());
const float zDistanceFromCamera = chunk->GetPosition().y - (m_camera.GetPosition().z / Chunk::GetChunkWidth());
if (xDistanceFromCamera > s_RenderDistance)
{
chunk = std::make_unique<Chunk>(m_renderer, glm::ivec2{ chunk->GetPosition().x - (s_RenderDistance * 2.0f), chunk->GetPosition().y });
}
else if (xDistanceFromCamera < -s_RenderDistance)
{
chunk = std::make_unique<Chunk>(m_renderer, glm::ivec2{ chunk->GetPosition().x + (s_RenderDistance * 2.0f), chunk->GetPosition().y });
}
else if (zDistanceFromCamera > s_RenderDistance)
{
chunk = std::make_unique<Chunk>(m_renderer, glm::ivec2{ chunk->GetPosition().x, chunk->GetPosition().y - (s_RenderDistance * 2.0f) });
}
else if (zDistanceFromCamera < -s_RenderDistance)
{
chunk = std::make_unique<Chunk>(m_renderer, glm::ivec2{ chunk->GetPosition().x, chunk->GetPosition().y + (s_RenderDistance * 2.0f) });
}
}
}
previousChunk = currentChunk;
}
void World::Render()
{
m_renderer.BindPipeline(*m_terrainPipeline);
const std::array<glm::mat4, 2> viewProjection{ m_camera.GetViewMatrix(), m_projection };
m_terrainPipeline->SetUniform(0, viewProjection);
m_renderer.BindDescriptorSet(*m_terrainPipeline);
for (const auto& chunk : m_chunks)
{
chunk->Render(m_renderer, *m_terrainPipeline);
}
}
void World::ProcessWindowResize(const Window& window)
{
m_terrainPipeline->RefreshUniformBuffers();
m_projection = glm::perspectiveLH(glm::radians(60.0f), static_cast<float>(window.GetDrawableSize().x) / static_cast<float>(window.GetDrawableSize().y), 0.1f, 2500.0f);
m_projection[1][1] *= -1.0f;
}
void World::Initialise(const Window& window)
{
const GraphicsPipeline::Config terrainPipelineConfig{
.shaderInfo{
{ "assets/shaders/terrain.vert.spv", ShaderModule::Stage::Vertex },
{ "assets/shaders/terrain.frag.spv", ShaderModule::Stage::Fragment }
},
.enableDepthTest = true,
.drawWireframe = false,
.enableCullFace = true,
.enableBlending = true
};
m_terrainPipeline = std::make_unique<GraphicsPipeline>(m_renderer, terrainPipelineConfig);
m_projection = glm::perspectiveLH(glm::radians(60.0f), static_cast<float>(window.GetDrawableSize().x) / static_cast<float>(window.GetDrawableSize().y), 0.1f, 2500.0f);
m_projection[1][1] *= -1.0f;
} | 30.405405 | 173 | 0.713778 | [
"render"
] |
f64b7678e64ca7589187016dbc4bfe350c8ee1ee | 1,189 | hpp | C++ | include/pcl_utils/camera.hpp | yamaha-bps/ros2_pcl_utils | 513615ac1b6b251a39f29eb7ff03f307747b8aa3 | [
"MIT"
] | 1 | 2021-07-05T14:35:35.000Z | 2021-07-05T14:35:35.000Z | include/pcl_utils/camera.hpp | yamaha-bps/ros2_pcl_utils | 513615ac1b6b251a39f29eb7ff03f307747b8aa3 | [
"MIT"
] | null | null | null | include/pcl_utils/camera.hpp | yamaha-bps/ros2_pcl_utils | 513615ac1b6b251a39f29eb7ff03f307747b8aa3 | [
"MIT"
] | 1 | 2022-03-31T01:35:07.000Z | 2022-03-31T01:35:07.000Z | // Copyright Yamaha 2021
// MIT License
// https://github.com/yamaha-bps/ros2_pcl_utils/blob/master/LICENSE
#ifndef PCL_UTILS__CAMERA_HPP_
#define PCL_UTILS__CAMERA_HPP_
#include <Eigen/Core>
#include <sensor_msgs/msg/camera_info.hpp>
/**
* @brief Camera projection with OpenCV model
*
* https://docs.opencv.org/4.2.0/d9/d0c/group__calib3d.html
*
* @tparam T scalar data type
* @param pt_CAM 3D point in camera frame
* @param cam camera information
* @return Eigen::Matrix<T, 2, 1> pixel coordinates
*/
template<typename T>
Eigen::Matrix<T, 2, 1> cameraProject(
const Eigen::Matrix<T, 3, 1> & pt_CAM,
const sensor_msgs::msg::CameraInfo & cam)
{
const T xp = pt_CAM.x() / pt_CAM.z();
const T yp = pt_CAM.y() / pt_CAM.z();
const T r2 = xp * xp + yp * yp;
const T r4 = r2 * r2;
const T ratio = 1. + cam.d[0] * r2 + cam.d[1] * r4 + cam.d[4] * (r2 * r4);
const T xpp =
xp * ratio + 2 * cam.d[2] * xp * yp + cam.d[3] * (r2 + 2 * xp * xp);
const T ypp =
yp * ratio + cam.d[2] * (r2 + 2 * yp * yp) + 2 * cam.d[3] * xp * yp;
return Eigen::Matrix<T, 2, 1>(
cam.k[0] * xpp + cam.k[2],
cam.k[4] * ypp + cam.k[5]);
}
#endif // PCL_UTILS__CAMERA_HPP_
| 27.651163 | 76 | 0.622372 | [
"model",
"3d"
] |
f64f7d3292f5271d3bfb0190ea1b89416e053bcf | 26,698 | cpp | C++ | src/Utils/ConfigurationUtils.cpp | Gigahawk/cli-visualizer | 52eb54efdac2ebe9ecdb5ababc7518f09421c917 | [
"MIT"
] | 2 | 2020-11-06T02:07:08.000Z | 2021-05-06T00:53:41.000Z | src/Utils/ConfigurationUtils.cpp | Gigahawk/cli-visualizer | 52eb54efdac2ebe9ecdb5ababc7518f09421c917 | [
"MIT"
] | null | null | null | src/Utils/ConfigurationUtils.cpp | Gigahawk/cli-visualizer | 52eb54efdac2ebe9ecdb5ababc7518f09421c917 | [
"MIT"
] | 1 | 2021-01-26T15:17:14.000Z | 2021-01-26T15:17:14.000Z | /*
* ConfigurationUtils.cpp
*
* Created on: Jul 30, 2015
* Author: dpayne
*/
#include <cmath>
#include <fstream>
#include <set>
#include <string>
#include <unordered_map>
#include "Domain/VisException.h"
#include "Utils/ConfigurationUtils.h"
#include "Utils/Logger.h"
#include "Utils/NcursesUtils.h"
#include "Utils/Utils.h"
namespace
{
const std::string k_audio_sources_setting{"audio.sources"}; // mpd,alsa
const std::string k_mpd_fifo_path_setting{"mpd.fifo.path"};
const std::string k_stereo_enabled_setting{"audio.stereo.enabled"};
const std::string k_override_terminal_colors_setting{
"colors.override.terminal"};
const std::string k_rotation_interval_setting{"visualizer.rotation.secs"};
const std::string k_vis_pulse_audio_source_setting{"audio.pulse.source"};
const std::string k_visualizers_setting{"visualizers"};
const std::string k_fps_setting{"visualizer.fps"};
const std::string k_color_scheme_path_setting{"colors.scheme"};
const std::string k_sampling_frequency_setting{"audio.sampling.frequency"};
const std::string k_low_cutoff_frequency_setting{"audio.low.cutoff.frequency"};
const std::string k_high_cutoff_frequency_setting{
"audio.high.cutoff.frequency"};
const std::string k_scaling_multiplier_setting{"visualizer.scaling.multiplier"};
const std::string k_lorenz_character_setting{"visualizer.lorenz.character"};
const std::string k_ellipse_character_setting{"visualizer.ellipse.character"};
const std::string k_ellipse_radius_setting{"visualizer.ellipse.radius"};
// Spectrum settings
const std::string k_spectrum_character_setting{"visualizer.spectrum.character"};
const std::string k_spectrum_bar_width_setting{"visualizer.spectrum.bar.width"};
const std::string k_spectrum_bar_spacing_setting{
"visualizer.spectrum.bar.spacing"};
const std::string k_spectrum_smoothing_mode_setting{
"visualizer.spectrum.smoothing.mode"};
const std::string k_spectrum_falloff_mode_setting{
"visualizer.spectrum.falloff.mode"};
const std::string k_spectrum_falloff_weight_setting{
"visualizer.spectrum.falloff.weight"};
const std::string k_spectrum_top_margin_setting{
"visualizer.spectrum.top.margin"};
const std::string k_spectrum_bottom_margin_setting{
"visualizer.spectrum.bottom.margin"};
const std::string k_spectrum_right_margin_setting{
"visualizer.spectrum.right.margin"};
const std::string k_spectrum_left_margin_setting{
"visualizer.spectrum.left.margin"};
const std::string k_spectrum_reversed_setting{"visualizer.spectrum.reversed"};
const std::string k_monstercat_smoothing_factor_setting{
"visualizer.monstercat.smoothing.factor"};
const std::string k_sgs_smoothing_points_setting{
"visualizer.sgs.smoothing.points"};
const std::string k_sgs_smoothing_passes_setting{
"visualizer.sgs.smoothing.passes"};
} // namespace
std::unordered_map<std::string, std::wstring>
vis::ConfigurationUtils::read_config(const std::string &config_path,
const std::locale &loc)
{
std::unordered_map<std::string, std::wstring> properties_map;
std::wifstream file(config_path.c_str(), std::wifstream::in);
std::wstring line;
file.imbue(loc);
if (!file.good())
{
VIS_LOG(vis::LogLevel::WARN, "Configuration not found at %s",
config_path.c_str());
return properties_map;
}
std::pair<std::wstring, std::wstring> split_line{L"", L""};
while (file.good() && std::getline(file, line))
{
if (!line.empty() && line[0] != L'#')
{
vis::Utils::split_first(line, L'=', &split_line);
if (!split_line.first.empty())
{
properties_map[Utils::wstring_to_string(split_line.first)] =
split_line.second;
}
else
{
VIS_LOG(vis::LogLevel::WARN,
"Configuration line was not valid at %s", line.c_str());
}
}
}
return properties_map;
}
void vis::ConfigurationUtils::add_color_gradients(
bool is_override_terminal_colors, const vis::ColorDefinition &color,
const double gradient_interval, std::vector<vis::ColorDefinition> *colors)
{
if (colors->empty() || gradient_interval <= 0)
{
colors->push_back(color);
return;
}
vis::ColorDefinition previous_color = colors->back();
auto start_color = previous_color;
const double red_diff =
(color.get_red() - previous_color.get_red()) / gradient_interval;
const double green_diff =
(color.get_green() - previous_color.get_green()) / gradient_interval;
const double blue_diff =
(color.get_blue() - previous_color.get_blue()) / gradient_interval;
for (auto i = 0u; i < std::round(gradient_interval - 1.0); ++i)
{
const auto red = static_cast<int16_t>(
std::round(start_color.get_red() + (red_diff * i)));
const auto green = static_cast<int16_t>(
std::round(start_color.get_green() + (green_diff * i)));
const auto blue = static_cast<int16_t>(
std::round(start_color.get_blue() + (blue_diff * i)));
if (is_override_terminal_colors)
{
const auto gradient_color = vis::ColorDefinition{
static_cast<ColorIndex>(colors->size() + 1), red, green, blue};
if (previous_color != gradient_color)
{
previous_color = gradient_color;
colors->push_back(previous_color);
}
}
else
{
const auto color_index =
NcursesUtils::to_ansi_color(red, green, blue);
// gradients will generally result in a lot of duplicates
if (previous_color.get_color_index() != color_index)
{
previous_color =
vis::ColorDefinition{color_index, red, green, blue};
colors->push_back(previous_color);
}
}
}
if (is_override_terminal_colors)
{
colors->emplace_back(vis::ColorDefinition{
static_cast<ColorIndex>(colors->size() + 1), color.get_red(),
color.get_green(), color.get_blue()});
}
else
{
colors->push_back(color);
}
}
double vis::ConfigurationUtils::get_gradient_interval(
int32_t number_of_colors, int32_t number_of_colors_supported)
{
double gradient_interval = 0.0;
if (number_of_colors >= number_of_colors_supported)
{
gradient_interval = 0.0;
}
else if (number_of_colors <= 1)
{
gradient_interval = number_of_colors_supported - 1;
}
else
{
// Subtract 1 from the number of colors supported since color 0 is
// reserved
gradient_interval =
static_cast<double>(number_of_colors_supported - 1) /
static_cast<double>(number_of_colors - 1);
}
return gradient_interval;
}
std::vector<vis::ColorDefinition>
vis::ConfigurationUtils::read_color_lines(bool is_override_terminal_colors,
const std::vector<std::string> &lines)
{
std::vector<vis::ColorDefinition> colors;
for (const auto &color_line : lines)
{
const auto next_color_index = static_cast<int16_t>(colors.size() + 1);
if (color_line.size() >= 7)
{
VIS_LOG(vis::LogLevel::DEBUG, "Reading hex color line %s",
color_line.c_str());
const auto hex_color =
vis::Utils::hex_to_int(color_line.substr(1, 6));
// ncurses uses colors between 0-1000, so scale from 0-256 to 0-1000
const auto red = static_cast<int16_t>(
std::round((static_cast<double>((hex_color >> 16) % 256)) *
(1000.0 / 255.0)));
const auto green = static_cast<int16_t>(
std::round((static_cast<double>((hex_color >> 8) % 256)) *
(1000.0 / 255.0)));
const auto blue = static_cast<int16_t>(std::round(
(static_cast<double>(hex_color % 256)) * (1000.0 / 255.0)));
// skip color 0, since it is reserved by the terminal for
// white/black
vis::ColorDefinition color =
vis::ColorDefinition{next_color_index, red, green, blue};
if (!is_override_terminal_colors)
{
color = vis::ColorDefinition{
NcursesUtils::to_ansi_color(red, green, blue), red, green,
blue};
}
colors.push_back(color);
}
else
{
VIS_LOG(vis::LogLevel::DEBUG, "Reading basic color line %s",
color_line.c_str());
const auto basic_color = NcursesUtils::to_basic_color(color_line);
if (basic_color.get_color_index() >= 0)
{
if (is_override_terminal_colors)
{
colors.emplace_back(vis::ColorDefinition{
next_color_index, basic_color.get_red(),
basic_color.get_green(), basic_color.get_blue()});
}
else
{
colors.push_back(basic_color);
}
}
else
{
VIS_LOG(vis::LogLevel::WARN,
"Configuration color "
"definition line was not "
"valid at %s",
color_line.c_str());
}
}
}
return colors;
}
std::vector<vis::ColorDefinition>
vis::ConfigurationUtils::colors_with_gradients(
bool is_override_terminal_colors,
const std::vector<vis::ColorDefinition> &colors)
{
const auto gradient_interval =
get_gradient_interval(static_cast<int32_t>(colors.size()),
NcursesUtils::number_of_colors_supported());
std::vector<vis::ColorDefinition> gradients;
gradients.reserve(
static_cast<size_t>(NcursesUtils::number_of_colors_supported()));
for (const auto &color : colors)
{
add_color_gradients(is_override_terminal_colors, color,
gradient_interval, &gradients);
}
return gradients;
}
std::vector<vis::ColorDefinition>
vis::ConfigurationUtils::read_colors(bool is_override_terminal_colors,
const std::string &colors_path)
{
std::vector<vis::ColorDefinition> colors;
std::ifstream file(colors_path.c_str(), std::ifstream::in);
std::string line;
if (!file.good())
{
VIS_LOG(vis::LogLevel::WARN, "Colors configuration not found at %s",
colors_path.c_str());
throw vis::VisException("Colors configuration not found at %s",
colors_path.c_str());
}
std::vector<std::string> lines;
bool is_gradient_enabled = true;
while (file.good() && std::getline(file, line))
{
if (!line.empty())
{
// first line, check for disabling gradient
if (lines.empty() &&
line == VisConstants::k_disabled_gradient_color_config)
{
is_gradient_enabled = false;
}
else if (lines.empty() &&
line == VisConstants::k_enabled_gradient_color_config)
{
is_gradient_enabled = true;
}
else
{
lines.push_back(line);
}
}
}
const auto color_from_lines =
read_color_lines(is_override_terminal_colors, lines);
if (is_gradient_enabled)
{
return colors_with_gradients(is_override_terminal_colors,
color_from_lines);
}
return color_from_lines;
}
vis::FalloffMode vis::ConfigurationUtils::read_falloff_mode(
const std::unordered_map<std::string, std::wstring> &properties,
const std::string &config_param,
const vis::FalloffMode default_falloff_mode)
{
auto falloff_mode_str = vis::Utils::get(
properties, k_spectrum_falloff_mode_setting, std::string{""});
vis::FalloffMode falloff_mode = default_falloff_mode;
if (!falloff_mode_str.empty())
{
std::transform(falloff_mode_str.begin(), falloff_mode_str.end(),
falloff_mode_str.begin(), ::tolower);
if (falloff_mode_str == "none")
{
falloff_mode = vis::FalloffMode::None;
}
else if (falloff_mode_str == "fill")
{
falloff_mode = vis::FalloffMode::Fill;
}
else if (falloff_mode_str == "top")
{
falloff_mode = vis::FalloffMode::Top;
}
else
{
VIS_LOG(vis::LogLevel::ERROR, "Invalid falloff mode %s for %s",
falloff_mode_str.c_str(), config_param.c_str());
}
}
return falloff_mode;
}
vis::SmoothingMode vis::ConfigurationUtils::read_smoothing_mode(
const std::unordered_map<std::string, std::wstring> &properties,
const std::string &config_param,
const vis::SmoothingMode default_smoothing_mode)
{
auto smoothing_mode_str = vis::Utils::get(
properties, k_spectrum_smoothing_mode_setting, std::string{""});
vis::SmoothingMode smoothing_mode = default_smoothing_mode;
if (!smoothing_mode_str.empty())
{
std::transform(smoothing_mode_str.begin(), smoothing_mode_str.end(),
smoothing_mode_str.begin(), ::tolower);
if (smoothing_mode_str == "none")
{
smoothing_mode = vis::SmoothingMode::None;
}
else if (smoothing_mode_str == "monstercat")
{
smoothing_mode = vis::SmoothingMode::MonsterCat;
}
else if (smoothing_mode_str == "sgs")
{
smoothing_mode = vis::SmoothingMode::Sgs;
}
else
{
VIS_LOG(vis::LogLevel::ERROR, "Invalid spectrum mode %s for %s",
smoothing_mode_str.c_str(), config_param.c_str());
}
}
return smoothing_mode;
}
void vis::ConfigurationUtils::load_settings(
const std::shared_ptr<Settings> settings, const std::locale &loc)
{
const auto config_path = VisConstants::k_default_config_path;
load_settings(settings, config_path, loc);
}
void vis::ConfigurationUtils::setup_default_colors(
const std::shared_ptr<Settings> settings)
{
const auto max_color =
static_cast<double>(NcursesUtils::number_of_colors_supported()) - 1;
const double frequency = (M_PI * 2.0) / max_color;
// used to remove duplicates
std::set<int16_t> colors_uniq;
std::vector<vis::ColorDefinition> colors;
const auto width = 127.0;
const auto center = 128.0;
for (int16_t i = 0; i < static_cast<int16_t>(max_color); ++i)
{
// https://www.wolframalpha.com/input/?i=graph+sin((pi+*+2.0%2F256)*x+%2B++(3.0+*+pi+%2F+3)),++sin((pi+*+2.0%2F256)*x+%2B++(-1.0*+pi+%2F+3)),+sin((pi+*+2.0%2F256)*x+%2B++(1.0+*+pi+%2F+3))+from+x%3D0+to+256
const auto red = static_cast<int16_t>(
std::sin(frequency * i + 3.0) * width + center);
const auto green = static_cast<int16_t>(
std::sin(frequency * i + -1 * M_PI / 3.0) * width + center);
const auto blue = static_cast<int16_t>(
std::sin(frequency * i + 1 * M_PI / 3.0) * width + center);
if (settings->is_override_terminal_colors())
{
colors.emplace_back(i + 1, red, green, blue);
}
else
{
const vis::ColorIndex color_index =
NcursesUtils::to_ansi_color(red, green, blue);
if (colors_uniq.find(color_index) == colors_uniq.end())
{
colors.emplace_back(color_index, red, green, blue);
colors_uniq.insert(color_index);
}
}
}
settings->set_colors(colors);
}
void vis::ConfigurationUtils::load_color_settings_from_color_scheme(
const std::string &color_scheme, const std::shared_ptr<Settings> settings)
{
if (!color_scheme.empty())
{
const auto colors_config_path =
VisConstants::k_colors_directory + color_scheme;
if (!colors_config_path.empty())
{
settings->set_colors(vis::ConfigurationUtils::read_colors(
settings->is_override_terminal_colors(), colors_config_path));
}
VIS_LOG(vis::LogLevel::DEBUG, "Read %lld colors from %s",
settings->get_colors().size(), color_scheme.c_str());
}
if (settings->get_colors().empty())
{
int32_t number_of_colors_supported =
NcursesUtils::number_of_colors_supported();
VIS_LOG(vis::LogLevel::DEBUG, "%d colors supported",
NcursesUtils::number_of_colors_supported());
if (number_of_colors_supported <= 0)
{
setup_default_colors(settings);
}
else if (number_of_colors_supported <= 8)
{
settings->set_colors(VisConstants::k_default_8_colors);
}
else if (number_of_colors_supported <= 16)
{
settings->set_colors(VisConstants::k_default_16_colors);
}
else
{
setup_default_colors(settings);
}
}
for (const auto &color : settings->get_colors())
{
VIS_LOG(vis::LogLevel::DEBUG, "Added color: %02x %02x %02x at index %d",
color.get_red(), color.get_green(), color.get_blue(),
color.get_color_index());
}
}
void vis::ConfigurationUtils::load_color_settings(
const std::shared_ptr<Settings> settings)
{
if (!settings->get_color_schemes().empty())
{
load_color_settings_from_color_scheme(settings->get_color_schemes()[0],
settings);
}
else
{
load_color_settings_from_color_scheme("", settings);
}
}
void vis::ConfigurationUtils::validate_setting_is_not_negative(
const double t, const std::string &setting)
{
if (t < 0.0)
{
throw vis::VisException("Invalid settings %s=%d", setting.c_str(), t);
}
}
void vis::ConfigurationUtils::validate_setting_is_greater_than_zero(
const double t, const std::string &setting)
{
if (t <= 0.0)
{
throw vis::VisException("Invalid settings %s=%d", setting.c_str(), t);
}
}
void vis::ConfigurationUtils::load_settings(
const std::shared_ptr<Settings> settings, const std::string &config_path,
const std::locale &loc)
{
const auto properties =
vis::ConfigurationUtils::read_config(config_path, loc);
// setup mpd
settings->set_mpd_fifo_path(
Utils::get(properties, k_mpd_fifo_path_setting,
VisConstants::k_default_mpd_fifo_path));
// enable pulse audio by default if available
#ifdef _ENABLE_PULSE
const std::string default_audio_source =
VisConstants::k_pulse_audio_source_name;
#else
const std::string default_audio_source =
VisConstants::k_mpd_audio_source_name;
#endif
// setup audio sources
settings->set_audio_source(
Utils::get(properties, k_audio_sources_setting, default_audio_source));
settings->set_scaling_multiplier(
Utils::get(properties, k_scaling_multiplier_setting,
VisConstants::k_default_scaling_multiplier));
settings->set_fps(
Utils::get(properties, k_fps_setting, VisConstants::k_default_fps));
validate_setting_is_greater_than_zero(settings->get_fps(), k_fps_setting);
settings->set_sampling_frequency(
Utils::get(properties, k_sampling_frequency_setting,
VisConstants::k_default_sampling_frequency));
validate_setting_is_greater_than_zero(settings->get_sampling_frequency(),
k_sampling_frequency_setting);
settings->set_low_cutoff_frequency(
Utils::get(properties, k_low_cutoff_frequency_setting,
VisConstants::k_default_low_cutoff_frequency));
validate_setting_is_greater_than_zero(settings->get_low_cutoff_frequency(),
k_low_cutoff_frequency_setting);
settings->set_high_cutoff_frequency(
Utils::get(properties, k_high_cutoff_frequency_setting,
VisConstants::k_default_high_cutoff_frequency));
validate_setting_is_greater_than_zero(settings->get_high_cutoff_frequency(),
k_high_cutoff_frequency_setting);
settings->set_spectrum_character(
Utils::get(properties, k_spectrum_character_setting,
VisConstants::k_default_spectrum_character));
settings->set_spectrum_bar_width(
Utils::get(properties, k_spectrum_bar_width_setting,
VisConstants::k_default_spectrum_bar_width));
validate_setting_is_greater_than_zero(settings->get_spectrum_bar_width(),
k_spectrum_bar_width_setting);
settings->set_spectrum_bar_spacing(
Utils::get(properties, k_spectrum_bar_spacing_setting,
VisConstants::k_default_spectrum_bar_spacing));
validate_setting_is_not_negative(settings->get_spectrum_bar_spacing(),
k_spectrum_bar_spacing_setting);
settings->set_spectrum_smoothing_mode(
read_smoothing_mode(properties, k_spectrum_smoothing_mode_setting,
VisConstants::k_default_spectrum_smoothing_mode));
settings->set_spectrum_falloff_mode(
read_falloff_mode(properties, k_spectrum_falloff_mode_setting,
VisConstants::k_default_spectrum_falloff_mode));
settings->set_spectrum_falloff_weight(
Utils::get(properties, k_spectrum_falloff_weight_setting,
VisConstants::k_default_spectrum_falloff_weight));
validate_setting_is_greater_than_zero(
settings->get_spectrum_falloff_weight(),
k_spectrum_falloff_weight_setting);
settings->set_spectrum_top_margin(
Utils::get(properties, k_spectrum_top_margin_setting,
VisConstants::k_default_spectrum_top_margin));
validate_setting_is_not_negative(settings->get_spectrum_top_margin(),
k_spectrum_top_margin_setting);
settings->set_spectrum_bottom_margin(
Utils::get(properties, k_spectrum_bottom_margin_setting,
VisConstants::k_default_spectrum_bottom_margin));
validate_setting_is_not_negative(settings->get_spectrum_bottom_margin(),
k_spectrum_bottom_margin_setting);
settings->set_spectrum_right_margin(
Utils::get(properties, k_spectrum_right_margin_setting,
VisConstants::k_default_spectrum_right_margin));
validate_setting_is_not_negative(settings->get_spectrum_right_margin(),
k_spectrum_right_margin_setting);
settings->set_spectrum_left_margin(
Utils::get(properties, k_spectrum_left_margin_setting,
VisConstants::k_default_spectrum_left_margin));
validate_setting_is_not_negative(settings->get_spectrum_left_margin(),
k_spectrum_left_margin_setting);
settings->set_is_spectrum_reversed(
Utils::get(properties, k_spectrum_reversed_setting,
VisConstants::k_default_spectrum_reversed));
settings->set_monstercat_smoothing_factor(
Utils::get(properties, k_monstercat_smoothing_factor_setting,
VisConstants::k_default_monstercat_smoothing_factor));
validate_setting_is_greater_than_zero(
settings->get_monstercat_smoothing_factor(),
k_monstercat_smoothing_factor_setting);
settings->set_sgs_smoothing_points(
Utils::get(properties, k_sgs_smoothing_points_setting,
VisConstants::k_default_sgs_smoothing_points));
validate_setting_is_greater_than_zero(settings->get_sgs_smoothing_points(),
k_sgs_smoothing_points_setting);
settings->set_sgs_smoothing_passes(
Utils::get(properties, k_sgs_smoothing_passes_setting,
VisConstants::k_default_sgs_smoothing_passes));
validate_setting_is_greater_than_zero(settings->get_sgs_smoothing_passes(),
k_sgs_smoothing_passes_setting);
#ifdef _OS_OSX
// ncurses on Mac OS X doesn't support wide chars by default, so use a
// non-wide character for the default
wchar_t default_lorenz_char = VisConstants::k_default_lorenz_character_osx;
wchar_t default_ellipse_char =
VisConstants::k_default_ellipse_character_osx;
#else
wchar_t default_lorenz_char = VisConstants::k_default_lorenz_character;
wchar_t default_ellipse_char = VisConstants::k_default_ellipse_character;
#endif
settings->set_lorenz_character(Utils::get(
properties, k_lorenz_character_setting, default_lorenz_char));
settings->set_ellipse_character(Utils::get(
properties, k_ellipse_character_setting, default_ellipse_char));
settings->set_ellipse_radius(
Utils::get(properties, k_ellipse_radius_setting,
VisConstants::k_default_ellipse_radius));
validate_setting_is_greater_than_zero(settings->get_ellipse_radius(),
k_ellipse_radius_setting);
settings->set_rotation_interval(
Utils::get(properties, k_rotation_interval_setting,
VisConstants::k_default_visualizer_rotation_interval));
validate_setting_is_not_negative(settings->get_rotation_interval(),
k_rotation_interval_setting);
settings->set_pulse_audio_source(
Utils::get(properties, k_vis_pulse_audio_source_setting,
VisConstants::k_default_visualizer_pulse_audio_source));
settings->set_is_stereo_enabled(
Utils::get(properties, k_stereo_enabled_setting, true));
settings->set_is_override_terminal_colors(
Utils::get(properties, k_override_terminal_colors_setting, true));
settings->set_color_schemes(Utils::split(
Utils::get(properties, k_color_scheme_path_setting, std::string{""}),
','));
const auto visualizers =
Utils::split(Utils::get(properties, k_visualizers_setting,
VisConstants::k_default_visualizers),
',');
settings->set_visualizers(visualizers);
}
| 35.740295 | 213 | 0.637875 | [
"vector",
"transform"
] |
f653388c8109bdaf4453d3481851668f5ac46940 | 3,181 | cpp | C++ | ABC/110/C.cpp | BaseOutside/AtCoder-Solved | 7b7b6c53332881e550aaa0755f298fcdeae3824a | [
"MIT"
] | null | null | null | ABC/110/C.cpp | BaseOutside/AtCoder-Solved | 7b7b6c53332881e550aaa0755f298fcdeae3824a | [
"MIT"
] | null | null | null | ABC/110/C.cpp | BaseOutside/AtCoder-Solved | 7b7b6c53332881e550aaa0755f298fcdeae3824a | [
"MIT"
] | null | null | null | //include
//------------------------------------------
#include <algorithm>
#include <bitset>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
//conversion
//------------------------------------------
inline int toInt(string s) {
int v;
istringstream sin(s);
sin >> v;
return v;
}
template <class T>
inline string toString(T x) {
ostringstream sout;
sout << x;
return sout.str();
}
//math
//-------------------------------------------
template <class T>
inline T sqr(T x) { return x * x; }
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;
//container util
//------------------------------------------
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i, c) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define SORT(c) sort((c).begin(), (c).end())
#define RSORT(c) sort((c).begin(), (c).end(), std::greater<decltype((c).front())>())
#define SUM(c) accumulate((c).begin(), (c).end(), 0LL)
template <class T>
inline T max_V(vector<T> &vec) {
auto maxVal = vec[0];
for (const auto &i : vec)
if (i > maxVal) maxVal = i;
return maxVal;
}
template <class T>
inline size_t max_I(vector<T> &vec) {
size_t maxIndex = 0;
for (size_t i = 0; i != vec.size(); ++i)
if (vec[i] > vec[maxIndex]) maxIndex = i;
return maxIndex;
}
//repetition
//------------------------------------------
#define FOR(i, a, b) for (long long i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)
//constant
//--------------------------------------------
constexpr double EPS = 1e-10;
constexpr double PI = 3.141592653589793;
//clear memory
#define CLR(a) memset((a), 0, sizeof(a))
//debug
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" \
<< " " << __FILE__ << endl;
int main() {
string s, t; cin >> s >> t;
VI taiou(26, 100);
REP (i, s.size()) {
if (taiou.at(s.at(i) - 'a') == 100) {
taiou.at(s.at(i) - 'a') = s.at(i) - t.at(i);
}
else {
if (taiou.at(s.at(i) - 'a') != s.at(i) - t.at(i)) {
cout << "No\n";
return 0;
}
}
}
VI taiou_v(26, 100);
REP (i, t.size()) {
if (taiou_v.at(t.at(i) - 'a') == 100) {
taiou_v.at(t.at(i) - 'a') = s.at(i) - t.at(i);
}
else {
if (taiou_v.at(t.at(i) - 'a') != s.at(i) - t.at(i)) {
cout << "No\n";
return 0;
}
}
}
cout << "Yes\n";
}
| 24.469231 | 84 | 0.479723 | [
"vector"
] |
f657cbba74d52ddd8d3d4234cd06c54cbf3c6129 | 3,464 | cpp | C++ | Programs/QuickEd/Classes/UI/Properties/BindingPropertyDelegate.cpp | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Programs/QuickEd/Classes/UI/Properties/BindingPropertyDelegate.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Programs/QuickEd/Classes/UI/Properties/BindingPropertyDelegate.cpp | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z |
#include "UI/DataBinding/UIDataBindingComponent.h"
#include "PropertiesModel.h"
#include "Utils/QtDavaConvertion.h"
#include "PropertiesTreeItemDelegate.h"
#include "BindingPropertyDelegate.h"
#include <TArc/Utils/Utils.h>
#include <QLineEdit>
#include <QComboBox>
#include <QHBoxLayout>
BindingPropertyDelegate::BindingPropertyDelegate(PropertiesTreeItemDelegate* delegate)
: BasePropertyDelegate(delegate)
{
}
QWidget* BindingPropertyDelegate::createEditor(QWidget* parent, const PropertiesContext& context, const QStyleOptionViewItem& option, const QModelIndex& index)
{
QWidget* lineWidget = new QWidget(parent);
QHBoxLayout* horizontalLayout = new QHBoxLayout(lineWidget);
horizontalLayout->setSpacing(1);
horizontalLayout->setContentsMargins(0, 0, 0, 0);
horizontalLayout->setObjectName("horizontalLayout");
lineWidget->setLayout(horizontalLayout);
QLineEdit* lineEdit = new QLineEdit();
lineEdit->setObjectName("lineEdit");
connect(lineEdit, &QLineEdit::editingFinished, [this, parent, lineEdit]() {
BasePropertyDelegate::SetValueModified(parent, lineEdit->isModified());
itemDelegate->emitCommitData(parent);
});
QComboBox* comboBox = new QComboBox();
comboBox->addItems(QStringList() << "r"
<< "w"
<< "rw"); // sync with UIDataBindingComponent::UpdateMode
comboBox->setObjectName("comboBox");
connect(comboBox, static_cast<void (QComboBox::*)(const QString&)>(&QComboBox::activated), [this, parent](const QString&) {
BasePropertyDelegate::SetValueModified(parent, true);
itemDelegate->emitCommitData(parent);
});
lineWidget->layout()->addWidget(comboBox);
lineWidget->layout()->addWidget(lineEdit);
return lineWidget;
}
void BindingPropertyDelegate::setEditorData(QWidget* rawEditor, const QModelIndex& index) const
{
QLineEdit* lineEdit = rawEditor->findChild<QLineEdit*>("lineEdit");
QComboBox* comboBox = rawEditor->findChild<QComboBox*>("comboBox");
QMap<QString, QVariant> map = index.data(PropertiesModel::BindingRole).toMap();
auto modeIt = map.find("mode");
auto valueIt = map.find("value");
if (modeIt != map.end() && valueIt != map.end())
{
QString value = DAVA::UnescapeString((*valueIt).toString());
lineEdit->blockSignals(true);
lineEdit->setText(value);
lineEdit->blockSignals(false);
comboBox->blockSignals(true);
comboBox->setCurrentIndex((*modeIt).toInt());
comboBox->blockSignals(false);
}
}
bool BindingPropertyDelegate::setModelData(QWidget* rawEditor, QAbstractItemModel* model, const QModelIndex& index) const
{
if (BasePropertyDelegate::setModelData(rawEditor, model, index))
return true;
QLineEdit* lineEditor = rawEditor->findChild<QLineEdit*>("lineEdit");
QComboBox* comboEditor = rawEditor->findChild<QComboBox*>("comboBox");
DAVA::int32 bindingMode = 0;
if (comboEditor != nullptr)
{
bindingMode = comboEditor->currentIndex();
}
QString text = "";
if (lineEditor != nullptr)
{
text = lineEditor->text();
}
QMap<QString, QVariant> map;
map.insert("value", DAVA::EscapeString(text));
map.insert("mode", bindingMode);
BasePropertyDelegate::SetValueModified(rawEditor, false);
return model->setData(index, QVariant(map), PropertiesModel::BindingRole);
}
| 34.64 | 159 | 0.691975 | [
"model"
] |
2cec9249d05036d64be8208172cfd2fa886507e4 | 1,364 | hpp | C++ | hexl/eltwise/eltwise-add-mod-internal.hpp | tgonzalez89-intel/hexl | 352e9ed14cb615defa33e4768d156eea3413361a | [
"Apache-2.0"
] | 136 | 2021-03-26T15:24:31.000Z | 2022-03-30T07:50:15.000Z | hexl/eltwise/eltwise-add-mod-internal.hpp | tgonzalez89-intel/hexl | 352e9ed14cb615defa33e4768d156eea3413361a | [
"Apache-2.0"
] | 24 | 2021-04-03T06:10:47.000Z | 2022-03-24T03:34:50.000Z | hexl/eltwise/eltwise-add-mod-internal.hpp | tgonzalez89-intel/hexl | 352e9ed14cb615defa33e4768d156eea3413361a | [
"Apache-2.0"
] | 27 | 2021-04-01T07:50:11.000Z | 2022-03-22T00:54:23.000Z | // Copyright (C) 2020-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
namespace intel {
namespace hexl {
/// @brief Adds two vectors elementwise with modular reduction
/// @param[out] result Stores result
/// @param[in] operand1 Vector of elements to add
/// @param[in] operand2 Vector of elements to add
/// @param[in] n Number of elements in each vector
/// @param[in] modulus Modulus with which to perform modular reduction
/// @details Computes \f$ operand1[i] = (operand1[i] + operand2[i]) \mod modulus
/// \f$ for \f$ i=0, ..., n-1\f$.
void EltwiseAddModNative(uint64_t* result, const uint64_t* operand1,
const uint64_t* operand2, uint64_t n,
uint64_t modulus);
/// @brief Adds a vector and scalar elementwise with modular reduction
/// @param[out] result Stores result
/// @param[in] operand1 Vector of elements to add
/// @param[in] operand2 Scalar add
/// @param[in] n Number of elements in each vector
/// @param[in] modulus Modulus with which to perform modular reduction
/// @details Computes \f$ operand1[i] = (operand1[i] + operand2) \mod modulus
/// \f$ for \f$ i=0, ..., n-1\f$.
void EltwiseAddModNative(uint64_t* result, const uint64_t* operand1,
uint64_t operand2, uint64_t n, uint64_t modulus);
} // namespace hexl
} // namespace intel
| 40.117647 | 80 | 0.678152 | [
"vector"
] |
2cf0fa6e377668d52c483e3722faf46394e75ade | 272 | cpp | C++ | Main.cpp | pasaunders/rayTracer | 9c16ebd92d2f6f520a7a9055fe51153bbcaf9021 | [
"MIT"
] | null | null | null | Main.cpp | pasaunders/rayTracer | 9c16ebd92d2f6f520a7a9055fe51153bbcaf9021 | [
"MIT"
] | null | null | null | Main.cpp | pasaunders/rayTracer | 9c16ebd92d2f6f520a7a9055fe51153bbcaf9021 | [
"MIT"
] | null | null | null | #include <vector>
#include "View/write.h"
int main(int argc, char const *argv[])
{
std::vector<unsigned char> rows;
for(size_t i = 0; i < 100; i++)
{
rows.push_back(50);
}
write_png_file("defaultName.png", rows, 10);
return 0;
}
| 17 | 48 | 0.566176 | [
"vector"
] |
2cfbb0a0230503ca4eaf8c9ddd742b5da2229d11 | 5,611 | cpp | C++ | Source/ImGui/Private/ImGuiContextProxy.cpp | CoconutLizard/UnrealImGui | 00a13a6fa935a02f59449d563086f32413255acd | [
"MIT"
] | null | null | null | Source/ImGui/Private/ImGuiContextProxy.cpp | CoconutLizard/UnrealImGui | 00a13a6fa935a02f59449d563086f32413255acd | [
"MIT"
] | 2 | 2021-06-24T09:21:21.000Z | 2021-09-16T13:39:35.000Z | Source/ImGui/Private/ImGuiContextProxy.cpp | CoconutLizard/UnrealImGui | 00a13a6fa935a02f59449d563086f32413255acd | [
"MIT"
] | null | null | null | // Distributed under the MIT License (MIT) (see accompanying LICENSE file)
#include "ImGuiContextProxy.h"
#include "ImGuiPrivatePCH.h"
#include "ImGuiImplementation.h"
#include "ImGuiInteroperability.h"
#include <Runtime/Launch/Resources/Version.h>
static constexpr float DEFAULT_CANVAS_WIDTH = 3840.f;
static constexpr float DEFAULT_CANVAS_HEIGHT = 2160.f;
namespace CVars
{
extern TAutoConsoleVariable<int> DebugDrawOnWorldTick;
}
namespace
{
FString GetSaveDirectory()
{
#if (ENGINE_MAJOR_VERSION > 4 || (ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 18))
const FString SavedDir = FPaths::ProjectSavedDir();
#else
const FString SavedDir = FPaths::GameSavedDir();
#endif
FString Directory = FPaths::Combine(*SavedDir, TEXT("ImGui"));
// Make sure that directory is created.
IPlatformFile::GetPlatformPhysical().CreateDirectory(*Directory);
return Directory;
}
FString GetIniFile(const FString& Name)
{
static FString SaveDirectory = GetSaveDirectory();
return FPaths::Combine(SaveDirectory, Name + TEXT(".ini"));
}
}
FImGuiContextProxy::FImGuiContextProxy(const FString& InName, FSimpleMulticastDelegate* InSharedDrawEvent)
: Name(InName)
, SharedDrawEvent(InSharedDrawEvent)
, IniFilename(TCHAR_TO_ANSI(*GetIniFile(InName)))
{
// Create context.
Context = TUniquePtr<ImGuiContext>(ImGui::CreateContext());
// Set this context in ImGui for initialization (any allocations will be tracked in this context).
SetAsCurrent();
// Start initialization.
ImGuiIO& IO = ImGui::GetIO();
// Set session data storage.
IO.IniFilename = IniFilename.c_str();
// Use pre-defined canvas size.
IO.DisplaySize = { DEFAULT_CANVAS_WIDTH, DEFAULT_CANVAS_HEIGHT };
// When GetTexData is called for the first time it builds atlas texture and copies mouse cursor data to context.
// When multiple contexts share atlas then only the first one will get mouse data. A simple workaround is to use
// a temporary atlas if shared one is already built.
unsigned char* Pixels;
const bool bIsAltasBuilt = IO.Fonts->TexPixelsAlpha8 != nullptr;
if (bIsAltasBuilt)
{
ImFontAtlas().GetTexDataAsRGBA32(&Pixels, nullptr, nullptr);
}
else
{
IO.Fonts->GetTexDataAsRGBA32(&Pixels, nullptr, nullptr);
}
// Initialize key mapping, so context can correctly interpret input state.
ImGuiInterops::SetUnrealKeyMap(IO);
// Begin frame to complete context initialization (this is to avoid problems with other systems calling to ImGui
// during startup).
BeginFrame();
}
FImGuiContextProxy::~FImGuiContextProxy()
{
if (Context)
{
// Set this context in ImGui for de-initialization (any de-allocations will be tracked in this context).
SetAsCurrent();
// Save context data and destroy.
ImGuiImplementation::SaveCurrentContextIniSettings(IniFilename.c_str());
ImGui::DestroyContext(Context.Release());
// Set default context in ImGui to keep global context pointer valid.
ImGui::SetCurrentContext(&ImGuiImplementation::GetDefaultContext());
}
}
void FImGuiContextProxy::Draw()
{
if (bIsFrameStarted && !bIsDrawCalled)
{
bIsDrawCalled = true;
SetAsCurrent();
const bool bSharedFirst = (CVars::DebugDrawOnWorldTick.GetValueOnGameThread() > 0);
// Broadcast draw event to allow listeners to draw their controls to this context.
if (bSharedFirst && SharedDrawEvent && SharedDrawEvent->IsBound())
{
SharedDrawEvent->Broadcast();
}
if (DrawEvent.IsBound())
{
DrawEvent.Broadcast();
}
if (!bSharedFirst && SharedDrawEvent && SharedDrawEvent->IsBound())
{
SharedDrawEvent->Broadcast();
}
}
}
void FImGuiContextProxy::Tick(float DeltaSeconds)
{
// Making sure that we tick only once per frame.
if (LastFrameNumber < GFrameNumber)
{
LastFrameNumber = GFrameNumber;
SetAsCurrent();
if (bIsFrameStarted)
{
// Make sure that draw events are called before the end of the frame.
Draw();
// Ending frame will produce render output that we capture and store for later use. This also puts context to
// state in which it does not allow to draw controls, so we want to immediately start a new frame.
EndFrame();
}
// Update context information (some data, like mouse cursor, may be cleaned in new frame, so we should collect it
// beforehand).
bHasActiveItem = ImGui::IsAnyItemActive();
MouseCursor = ImGuiInterops::ToSlateMouseCursor(ImGui::GetMouseCursor());
// Begin a new frame and set the context back to a state in which it allows to draw controls.
BeginFrame(DeltaSeconds);
}
}
void FImGuiContextProxy::BeginFrame(float DeltaTime)
{
if (!bIsFrameStarted)
{
ImGuiIO& IO = ImGui::GetIO();
IO.DeltaTime = DeltaTime;
if (InputState)
{
ImGuiInterops::CopyInput(IO, *InputState);
}
ImGui::NewFrame();
bIsFrameStarted = true;
bIsDrawCalled = false;
}
}
void FImGuiContextProxy::EndFrame()
{
if (bIsFrameStarted)
{
// Prepare draw data (after this call we cannot draw to this context until we start a new frame).
ImGui::Render();
// Update our draw data, so we can use them later during Slate rendering while ImGui is in the middle of the
// next frame.
UpdateDrawData(ImGui::GetDrawData());
bIsFrameStarted = false;
}
}
void FImGuiContextProxy::UpdateDrawData(ImDrawData* DrawData)
{
if (DrawData && DrawData->CmdListsCount > 0)
{
DrawLists.SetNum(DrawData->CmdListsCount, false);
for (int Index = 0; Index < DrawData->CmdListsCount; Index++)
{
DrawLists[Index].TransferDrawData(*DrawData->CmdLists[Index]);
}
}
else
{
// If we are not rendering then this might be a good moment to empty the array.
DrawLists.Empty();
}
}
| 26.592417 | 115 | 0.735876 | [
"render"
] |
2cfc870bd2bcf51f2dba6347d82664c360f70e93 | 3,267 | cpp | C++ | Server/relatko-ba-graph-52fc092b557e/test/sat/test_factors.cpp | RadoslavSmarzik/graph-editor | 7441f4768269131e5e9636819f1bf27ae9d6013d | [
"MIT"
] | null | null | null | Server/relatko-ba-graph-52fc092b557e/test/sat/test_factors.cpp | RadoslavSmarzik/graph-editor | 7441f4768269131e5e9636819f1bf27ae9d6013d | [
"MIT"
] | null | null | null | Server/relatko-ba-graph-52fc092b557e/test/sat/test_factors.cpp | RadoslavSmarzik/graph-editor | 7441f4768269131e5e9636819f1bf27ae9d6013d | [
"MIT"
] | null | null | null | #include "implementation.h"
#include <io/print_nice.hpp>
#include <graphs.hpp>
#include <sat/solver_cmsat.hpp>
#include <sat/exec_factors.hpp>
#include <cassert>
using namespace ba_graph;
bool cb(std::vector<Edge> &, int *count) {
(*count)++;
return true;
}
int main() {
CMSatSolver solver;
CMAllSatSolver allSolver;
auto s = std::set({0, 1, 2, 3, 4, 5});
auto subsets = all_subsets(s, 1);
assert(subsets.size() == 6);
for (auto set : subsets)
assert(set.size() == 1);
subsets = all_subsets(s, 4);
assert(subsets.size() == 15);
for (auto set : subsets)
assert(set.size() == 4);
Graph g = std::move(empty_graph(4));
addE(g, Location(0, 1));
addE(g, Location(1, 2));
addE(g, Location(1, 3));
addE(g, Location(2, 3));
assert(has_perfect_matching_sat(solver, g));
int c = 0;
assert(perfect_matchings_enumerate_sat(allSolver, g, cb, &c));
assert(c == 1);
assert(perfect_matchings_list_sat(allSolver, g).size() == 1);
deleteV(g, 0);
assert(!has_perfect_matching_sat(solver, g));
g = std::move(circuit(11));
assert(!has_perfect_matching_sat(solver, g));
c = 0;
assert(!perfect_matchings_enumerate_sat(allSolver, g, cb, &c));
assert(c == 0);
g = std::move(circuit(8));
assert(has_perfect_matching_sat(solver, g));
c = 0;
assert(perfect_matchings_enumerate_sat(allSolver, g, cb, &c));
assert(c == 2);
g = std::move(complete_graph(4));
assert(has_perfect_matching_sat(solver, g));
c = 0;
assert(perfect_matchings_enumerate_sat(allSolver, g, cb, &c));
assert(c == 3);
g = std::move(create_petersen());
assert(has_perfect_matching_sat(solver, g));
c = 0;
assert(perfect_matchings_enumerate_sat(allSolver, g, cb, &c));
assert(c == 6);
assert(perfect_matchings_list_sat(allSolver, g).size() == 6);
deleteV(g, 0);
assert(!has_perfect_matching_sat(solver, g));
assert(perfect_matchings_list_sat(allSolver, g).size() == 0);
g = std::move(complete_graph(5));
assert(!has_kfactor_sat(solver, g, 1));
assert(has_kfactor_sat(solver, g, 2));
assert(!has_kfactor_sat(solver, g, 3));
assert(has_kfactor_sat(solver, g, 4));
assert(!has_kfactor_sat(solver, g, 5));
assert(kfactors_list_sat(allSolver, g, 1, static_factory).size() == 0);
assert(kfactors_list_sat(allSolver, g, 2, static_factory).size() == 12);
assert(kfactors_list_sat(allSolver, g, 3, static_factory).size() == 0);
assert(kfactors_list_sat(allSolver, g, 4, static_factory).size() == 1);
assert(kfactors_list_sat(allSolver, g, 5, static_factory).size() == 0);
g = std::move(create_petersen());
assert(has_kfactor_sat(solver, g, 1));
assert(has_kfactor_sat(solver, g, 2));
assert(has_kfactor_sat(solver, g, 3));
assert(!has_kfactor_sat(solver, g, 4));
assert(kfactors_list_sat(allSolver, g, 1, static_factory).size() == 6);
assert(kfactors_list_sat(allSolver, g, 2, static_factory).size() == 6);
assert(kfactors_list_sat(allSolver, g, 3, static_factory).size() == 1);
assert(kfactors_list_sat(allSolver, g, 4, static_factory).size() == 0);
assert(kfactors_list_sat(allSolver, g, 5, static_factory).size() == 0);
return 0;
}
| 33.336735 | 76 | 0.650444 | [
"vector"
] |
2cff4e631af4495e4e37653d0db5a82fa492f99d | 659 | cpp | C++ | OIandACM/OJ/LeetCode/first/easy-136-只出现一次的数字.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | 8 | 2019-08-09T14:28:13.000Z | 2021-02-23T03:22:15.000Z | OIandACM/OJ/LeetCode/first/easy-136-只出现一次的数字.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | null | null | null | OIandACM/OJ/LeetCode/first/easy-136-只出现一次的数字.cpp | ASC8384/MyCodeSnippets | aa74afa85672601bd25bf625590f26ac909b2042 | [
"CC0-1.0"
] | 4 | 2019-08-16T12:00:41.000Z | 2019-11-29T12:01:17.000Z | /*
* @lc app=leetcode.cn id=136 lang=cpp
*
* [136] 只出现一次的数字
*
* https://leetcode-cn.com/problems/single-number/description/
*
* algorithms
* Easy (66.43%)
* Likes: 1291
* Dislikes: 0
* Total Accepted: 218.4K
* Total Submissions: 317.9K
* Testcase Example: '[2,2,1]'
*
* 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
*
* 说明:
*
* 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
*
* 示例 1:
*
* 输入: [2,2,1]
* 输出: 1
*
*
* 示例 2:
*
* 输入: [4,1,2,1,2]
* 输出: 4
*
*/
// @lc code=start
class Solution {
public:
int singleNumber(vector<int> &nums) {
int ret = 0;
for(auto i : nums) {
ret ^= i;
}
return ret;
}
};
// @lc code=end
| 14.021277 | 62 | 0.578149 | [
"vector"
] |
fa06effa5105570933bf2d0eada7e45a35a5a51d | 2,628 | cpp | C++ | test/test_multi_plots.cpp | jleben/datavis | 579eec88816ea45f04baf9890e11445a6bb98425 | [
"MIT"
] | 1 | 2022-03-17T08:05:19.000Z | 2022-03-17T08:05:19.000Z | test/test_multi_plots.cpp | jleben/datavis | 579eec88816ea45f04baf9890e11445a6bb98425 | [
"MIT"
] | 9 | 2018-01-09T03:25:51.000Z | 2018-01-09T03:54:01.000Z | test/test_multi_plots.cpp | jleben/ren | 579eec88816ea45f04baf9890e11445a6bb98425 | [
"MIT"
] | null | null | null | #include "../plot/plot_view.hpp"
#include "../plot/line_plot.hpp"
#include "../plot/heat_map.hpp"
#include "../data/array.hpp"
#include "../data/data_set.hpp"
#include <QApplication>
#include <QDebug>
#include <QWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QCheckBox>
#include <cmath>
using namespace datavis;
static double pi = std::atan(1.0) * 4.0;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
int data_size = 200;
double base_freq = 1.0/200.0;
auto source1 = make_shared<DataSet>(vector<int>({data_size}));
{
//cout << "Generating data:" << endl;
auto region = get_all(*source1->data());
for (auto & i : region)
{
auto loc = i.location()[0];
i.value() = std::sin(2.0 * loc / data_size * 2 * pi) ;
//cout << i.value() << endl;
}
}
auto source2 = make_shared<DataSet>(vector<int>({data_size}));
DataSet::Dimension dim;
dim.map.offset = 100;
dim.map.scale = 0.5;
source2->setDimension(0, dim);
{
//cout << "Generating data:" << endl;
auto region = get_all(*source2->data());
for (auto & i : region)
{
auto loc = i.location()[0];
i.value() = 0.5 * std::sin((0.5 + 2.0 * loc / data_size) * 2 * pi) ;
//cout << i.value() << endl;
}
}
auto plot_view = new PlotView;
{
auto plot = new LinePlot;
plot->setDataSet(source1);
plot_view->addPlot(plot);
}
{
auto plot = new LinePlot;
plot->setDataSet(source2);
plot_view->addPlot(plot);
}
auto win = new QWidget;
auto stacked_option = new QCheckBox("Stacked");
stacked_option->setChecked(plot_view->isStacked());
auto common_x_option = new QCheckBox("Common X");
common_x_option->setChecked(plot_view->hasCommonX());
auto common_y_option = new QCheckBox("Common Y");
common_y_option->setChecked(plot_view->hasCommonY());
auto layout = new QVBoxLayout(win);
layout->addWidget(stacked_option);
layout->addWidget(common_x_option);
layout->addWidget(common_y_option);
layout->addWidget(plot_view);
QObject::connect(stacked_option, &QCheckBox::clicked,
plot_view, &PlotView::setStacked);
QObject::connect(common_x_option, &QCheckBox::clicked,
plot_view, &PlotView::setCommonX);
QObject::connect(common_y_option, &QCheckBox::clicked,
plot_view, &PlotView::setCommonY);
win->resize(600,600);
win->show();
return app.exec();
}
| 25.514563 | 80 | 0.592085 | [
"vector"
] |
fa090410e9d3f275076e17ce7458a5627f43f275 | 14,574 | cpp | C++ | snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleElement/cpp/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 834 | 2017-06-24T10:40:36.000Z | 2022-03-31T19:48:51.000Z | snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleElement/cpp/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 7,042 | 2017-06-23T22:34:47.000Z | 2022-03-31T23:05:23.000Z | snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.VisualStyles.VisualStyleElement/cpp/form1.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 1,640 | 2017-06-23T22:31:39.000Z | 2022-03-31T02:45:37.000Z | // This sample can go in the VisualStyleElement class overview or a conceptual
// topic to give the new user a chance to view what each of the defined
// elements looks like. This sample also gives them the ability to preview each
// element at three different sizes.
// <Snippet0>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>
#using <System.dll>
using namespace System;
using namespace System::Text;
using namespace System::Drawing;
using namespace System::Collections::Generic;
using namespace System::Reflection;
using namespace System::Windows::Forms;
using namespace System::Windows::Forms::VisualStyles;
namespace VisualStyleElementViewer
{
public ref class ElementViewer : public UserControl
{
private:
VisualStyleElement^ element;
VisualStyleRenderer^ renderer;
Dictionary<String^, VisualStyleElement^>^ elementDictionary;
Rectangle descriptionRect;
Rectangle displayRect;
Rectangle displayRectFull;
System::Drawing::Size currentTrueSize;
StringBuilder^ elementDescription;
Label^ infoLabel;
TreeView^ treeView;
DomainUpDown^ domainUpDown;
bool drawElement;
public:
ElementViewer():UserControl()
{
elementDictionary =
gcnew Dictionary<String^, VisualStyleElement^>();
currentTrueSize = System::Drawing::Size();
elementDescription = gcnew StringBuilder();
infoLabel = gcnew Label();
treeView = gcnew TreeView();
domainUpDown = gcnew DomainUpDown();
this->Location = Point(10, 10);
this->Size = System::Drawing::Size(650, 500);
this->Text = "VisualStyleElement Viewer";
this->Font = SystemFonts::IconTitleFont;
this->BackColor = Color::White;
this->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
this->AutoSize = true;
this->Load += gcnew EventHandler(this,
&ElementViewer::ElementViewer_Load);
}
private:
void ElementViewer_Load(Object^ sender, EventArgs^ e)
{
// Make sure the visual styles are enabled before
// going any further.
if (!Application::RenderWithVisualStyles)
{
return;
}
infoLabel->Location = Point(320, 10);
infoLabel->Size = System::Drawing::Size(300, 60);
infoLabel->Text = "Expand the element class nodes " +
"in the tree view to access visual style elements. " +
"Click an element name to draw the element below. To " +
"change the size of a resizable element, use the " +
"spin control.";
domainUpDown->Location = Point(320, 80);
domainUpDown->Size = System::Drawing::Size(70, 30);
domainUpDown->ReadOnly = true;
domainUpDown->Items->Add(elementSizes::Large);
domainUpDown->Items->Add(elementSizes::Medium);
domainUpDown->Items->Add(elementSizes::TrueSize);
domainUpDown->SelectedIndex = 2;
domainUpDown->SelectedItemChanged +=
gcnew EventHandler(this,
&ElementViewer::DomainUpDown_SelectedItemChanged);
domainUpDown->DownButton();
descriptionRect = Rectangle(320, 120, 250, 50);
displayRect = Rectangle(320, 160, 0, 0);
displayRectFull = Rectangle(320, 160, 300, 200);
// Initialize the element and renderer to known good values.
element = VisualStyleElement::Button::PushButton::Normal;
renderer = gcnew VisualStyleRenderer(element);
SetupElementCollection();
SetupTreeView();
this->Controls->AddRange(gcnew array<Control^>{treeView,
domainUpDown, infoLabel });
}
// Use reflection to build a Dictionary of all
// VisualStyleElement objects exposed in the
// System.Windows.Forms.VisualStyles namespace.
private:
void SetupElementCollection()
{
StringBuilder^ elementName = gcnew StringBuilder();
VisualStyleElement^ currentElement;
int plusSignIndex = 0;
// Get array of first-level nested types within
// VisualStyleElement; these are the element classes.
array<Type^>^ elementClasses =
VisualStyleElement::typeid->GetNestedTypes();
for each (Type^ elementClass in elementClasses)
{
// Get an array of second-level nested types within
// VisualStyleElement; these are the element parts.
array<Type^>^ elementParts = elementClass->GetNestedTypes();
// Get the index of the first '+' character in
// the full element class name.
plusSignIndex = elementClass->FullName->IndexOf('+');
for each (Type^ elementPart in elementParts)
{
// Get an array of static property details
// for the current type. Each of these types have
// properties that return VisualStyleElement objects.
array<PropertyInfo^>^ elementProperties =
elementPart->GetProperties(BindingFlags::Static |
BindingFlags::Public);
// For each property, insert the unique full element
// name and the element into the collection.
for each(PropertyInfo^ elementProperty in
elementProperties)
{
// Get the element.
currentElement =
(VisualStyleElement^)elementProperty->
GetValue(nullptr, BindingFlags::Static, nullptr,
nullptr, nullptr);
// Append the full element name.
elementName->Append(elementClass->FullName,
plusSignIndex + 1,
elementClass->FullName->Length -
plusSignIndex - 1);
elementName->Append("." +
elementPart->Name + "." +
elementProperty->Name);
// Add the element and element name to
// the Dictionary.
elementDictionary->Add(elementName->ToString(),
currentElement);
// Clear the element name for the
// next iteration.
elementName->Remove(0, elementName->Length);
}
}
}
}
// Initialize the tree view with the element names.
private:
void SetupTreeView()
{
treeView->Location = Point(10, 10);
treeView->Size = System::Drawing::Size(300, 450);
// treeView->BorderStyle = BorderStyle.FixedSingle;
treeView->BackColor = Color::WhiteSmoke;
treeView->SelectedNode = nullptr;
treeView->AfterSelect +=
gcnew TreeViewEventHandler(this,
&ElementViewer::TreeView_AfterSelect);
treeView->BeginUpdate();
// An index into the top-level tree nodes.
int nodeIndex = 0;
// An index into the first '.' character in an element name.
int firstDotIndex = 0;
// Initialize the element class name to compare
// with the class name of the first element
// in the Dictionary, and set this name to the first
// top-level node.
StringBuilder^ compareClassName =
gcnew StringBuilder("Button");
treeView->Nodes->Add(
gcnew TreeNode(compareClassName->ToString()));
// The current element class name.
StringBuilder^ currentClassName = gcnew StringBuilder();
// The text for each second-level node.
StringBuilder^ nodeText = gcnew StringBuilder();
for each(KeyValuePair<String^, VisualStyleElement^>^ entry
in elementDictionary)
{
// Isolate the class name of the current element.
firstDotIndex = entry->Key->IndexOf('.');
currentClassName->Append(entry->Key, 0, firstDotIndex);
// Determine whether we need to increment to the next
// element class.
if (currentClassName->ToString() !=
compareClassName->ToString())
{
// Increment the index to the next top-level node
// in the tree view.
nodeIndex++;
// Get the new class name to compare with.
compareClassName->Remove(0, compareClassName->Length);
compareClassName->Append(entry->Key);
compareClassName->Remove(firstDotIndex,
compareClassName->Length - firstDotIndex);
// Add a new top-level node to the tree view.
treeView->Nodes->Add(
gcnew TreeNode(compareClassName->ToString()));
}
// Get the text for the new second-level node.
nodeText->Append(entry->Key, firstDotIndex + 1,
entry->Key->Length - firstDotIndex - 1);
// Create and insert the new second-level node.
TreeNode^ newNode = gcnew TreeNode(nodeText->ToString());
newNode->Name = entry->Key;
treeView->Nodes[nodeIndex]->Nodes->Add(newNode);
currentClassName->Remove(0, currentClassName->Length);
nodeText->Remove(0, nodeText->Length);
}
treeView->EndUpdate();
}
protected:
virtual void OnPaint(PaintEventArgs^ e) override
{
__super::OnPaint(e);
// Do nothing further if visual styles are disabled.
if (!Application::RenderWithVisualStyles)
{
this->Text = "Visual styles are disabled.";
TextRenderer::DrawText(e->Graphics, this->Text, this->Font,
this->Location, this->ForeColor);
return;
}
// Draw the element description.
TextRenderer::DrawText(e->Graphics, elementDescription->ToString(),
this->Font, descriptionRect, this->ForeColor,
TextFormatFlags::WordBreak);
// Draw the element, if an element is selected.
if (drawElement)
{
renderer->DrawBackground(e->Graphics, this->displayRect);
}
}
// Set the element to draw.
private:
void TreeView_AfterSelect(Object^ sender, TreeViewEventArgs^ e)
{
// Clear the element description.
elementDescription->Remove(0, elementDescription->Length);
// If the user clicked a first-level node, disable drawing.
if (e->Node->Nodes->Count > 0)
{
drawElement = false;
elementDescription->Append("No element is selected");
domainUpDown->Enabled = false;
}
// The user clicked an element node.
else
{
// Add the element name to the description.
elementDescription->Append(e->Node->Text);
// Get the element that corresponds to the selected
// node's name.
String^ key = e->Node->Name;
element = elementDictionary[key];
// Disable resizing if the element is not defined.
if (!VisualStyleRenderer::IsElementDefined(element))
{
drawElement = false;
elementDescription->Append(" is not defined.");
domainUpDown->Enabled = false;
}
else
{
// Set the element to the renderer.
drawElement = true;
renderer->SetParameters(element);
elementDescription->Append(" is defined.");
// Get the system-defined size of the element.
Graphics^ g = this->CreateGraphics();
currentTrueSize = renderer->GetPartSize(g,
ThemeSizeType::True);
delete g;
displayRect.Size = currentTrueSize;
domainUpDown->Enabled = true;
domainUpDown->SelectedIndex = 2;
}
}
Invalidate();
}
// Resize the element display area.
private:
void DomainUpDown_SelectedItemChanged(Object^ sender,
EventArgs^ e)
{
switch ((int)domainUpDown->SelectedItem)
{
case this->elementSizes::TrueSize:
displayRect.Size = currentTrueSize;
break;
case this->elementSizes::Medium:
displayRect.Size =
System::Drawing::Size(displayRectFull.Width / 2,
displayRectFull.Height / 2);
break;
case this->elementSizes::Large:
displayRect.Size = displayRectFull.Size;
break;
}
Invalidate();
}
// These values represent the options in the UpDown control.
private:
enum class elementSizes
{
TrueSize,
Medium,
Large
};
};
public ref class ElementViewerForm : public Form
{
public:
ElementViewerForm()
{
ElementViewer^ elementViewer = gcnew ElementViewer();
this->Controls->Add(elementViewer);
this->Text = elementViewer->Text;
this->Size = System::Drawing::Size(700, 550);
}
};
}
using namespace VisualStyleElementViewer;
[STAThread]
int main()
{
Application::EnableVisualStyles();
Application::Run(gcnew ElementViewerForm());
}
// </Snippet0>
| 37.854545 | 79 | 0.538425 | [
"object"
] |
fa0ff9771652f48cb388c271de30aa6b31659969 | 552 | cpp | C++ | cpp/digit_number.cpp | ysoftman/test_code | 4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8 | [
"MIT"
] | 3 | 2017-12-07T04:29:36.000Z | 2022-01-11T10:58:14.000Z | cpp/digit_number.cpp | ysoftman/test_code | 4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8 | [
"MIT"
] | 14 | 2018-07-17T05:16:42.000Z | 2022-03-22T00:43:47.000Z | cpp/digit_number.cpp | ysoftman/test_code | 4c71cc7c6a17d73cc84298e3a44051d3ab9d40f8 | [
"MIT"
] | null | null | null |
// ysoftman
// 자리수 숫자 파싱
#include <stdio.h>
#include <vector>
using namespace std;
void parseDigitNumber(int n)
{
printf("n = %d\n", n);
vector<int> vec;
while (n >= 1)
{
vec.push_back(n % 10);
n /= 10;
}
vector<int>::reverse_iterator iter;
for (iter = vec.rbegin(); iter != vec.rend(); ++iter)
{
printf("%d ", *iter);
}
printf(" digit cnt(%ld)\n", vec.size());
}
int main()
{
parseDigitNumber(228);
parseDigitNumber(1230560);
parseDigitNumber(78984568);
return 0;
}
| 16.727273 | 57 | 0.550725 | [
"vector"
] |
fa11de275b15ee0ce9596ead32bd17b6e192a3e1 | 726 | cc | C++ | cpp/cuts/DK_length_plus/create_cut.cc | michieluithetbroek/A-MDVRP | fe7739f3961ddb25db8f64ec20472915d3c95168 | [
"MIT"
] | 23 | 2020-04-09T16:33:23.000Z | 2022-03-21T16:41:11.000Z | cpp/cuts/DK_length_plus/create_cut.cc | michieluithetbroek/A-MDVRP | fe7739f3961ddb25db8f64ec20472915d3c95168 | [
"MIT"
] | 2 | 2020-04-10T11:55:28.000Z | 2020-04-10T12:11:51.000Z | cpp/cuts/DK_length_plus/create_cut.cc | michieluithetbroek/A-MDVRP | fe7739f3961ddb25db8f64ec20472915d3c95168 | [
"MIT"
] | 10 | 2020-05-28T18:59:52.000Z | 2022-03-10T13:32:44.000Z | #include "./DK_length_plus.ih"
/*
*
*/
CutReturn DK_length_plus::create_cut(vector<int> const &seq, size_t n, int l) const
{
CutReturn cut;
cut.rhs = n + 1;
size_t const i = seq[0];
size_t const k = seq[n - 1];
cut.add(2, i, l);
cut.add(1, l, k);
for (size_t h = 1; h < n; ++h)
cut.add(2, i, seq[h]);
for (size_t h = 1; h < n; ++h)
cut.add(1, seq[h], seq[h - 1]);
for (size_t h = 1; h < n - 1; ++h)
for (size_t h2 = h + 1; h2 < n; ++h2)
cut.add(1, seq[h], seq[h2]);
for (size_t h = 1; h < n; ++h)
cut.add(1, seq[h], l);
// Add depots
for (size_t idx = 0; idx < d_nDepots; ++idx)
{
cut.add(1, i, idx);
cut.add(1, idx, l);
}
return cut;
}
| 18.15 | 83 | 0.49449 | [
"vector"
] |
fa1c46c9d000b1b61325ae2cf999a73173d1c3c7 | 573 | cpp | C++ | Youtube/Unions.cpp | lance-lh/learning-c-plusplus | 90342cc5d26a5adb87aa3e97795d4bbfca7bef52 | [
"MIT"
] | 1 | 2019-03-27T13:00:02.000Z | 2019-03-27T13:00:02.000Z | Youtube/Unions.cpp | lance-lh/learning-c-plusplus | 90342cc5d26a5adb87aa3e97795d4bbfca7bef52 | [
"MIT"
] | null | null | null | Youtube/Unions.cpp | lance-lh/learning-c-plusplus | 90342cc5d26a5adb87aa3e97795d4bbfca7bef52 | [
"MIT"
] | 1 | 2021-01-12T22:01:28.000Z | 2021-01-12T22:01:28.000Z | // union is like class or struct, a union can only have one member
#include<iostream>
struct Vector2
{
float x, y;
};
struct Vector4
{
union
{
struct
{
float x, y, z, w;
};
struct
{
Vector2 a, b;
};
};
};
void PrintVector2(const Vector2& vector)
{
std::cout << vector.x << ", " << vector.y << std::endl;
}
int main()
{
Vector4 vector = { 1.0f, 2.0f, 3.0f, 4.0f };
PrintVector2(vector.a);
PrintVector2(vector.b);
vector.z = 500.0f;
std::cout << "-----------" << std::endl;
PrintVector2(vector.a);
PrintVector2(vector.b);
std::cin.get();
} | 14.325 | 66 | 0.589878 | [
"vector"
] |
fa26e5b2dcacfc02b4fceb32e63473f957a6117f | 75,810 | cpp | C++ | TOMB5/game/newinv2.cpp | walkawayy/TOMB5 | cc33d5147ed21c8db123a72f4acdc9241e3ed73c | [
"MIT"
] | null | null | null | TOMB5/game/newinv2.cpp | walkawayy/TOMB5 | cc33d5147ed21c8db123a72f4acdc9241e3ed73c | [
"MIT"
] | null | null | null | TOMB5/game/newinv2.cpp | walkawayy/TOMB5 | cc33d5147ed21c8db123a72f4acdc9241e3ed73c | [
"MIT"
] | null | null | null | #include "../tomb5/pch.h"
#include "newinv2.h"
#include "gameflow.h"
#include "effects.h"
#include "../specific/d3dmatrix.h"
#include "sound.h"
#include "objects.h"
#include "lara1gun.h"
#include "lara2gun.h"
#include "camera.h"
#include "control.h"
#include "xatracks.h"
#include "lara.h"
#include "larafire.h"
#include "lara_states.h"
#include "../specific/LoadSave.h"
#include "../specific/input.h"
#include "../specific/output.h"
#include "health.h"
#include "../specific/3dmath.h"
#include "draw.h"
#include "subsuit.h"
#include "../specific/specificfx.h"
#include "../specific/polyinsert.h"
#include "text.h"
#include "../specific/audio.h"
#ifdef GENERAL_FIXES
#include "savegame.h"
#endif
short optmessages[11] =
{
STR_USE, STR_CHOOSE_AMMO, STR_COMBINE, STR_SEPARATE, STR_EQUIP, STR_COMBINE_WITH, STR_LOAD_GAME, STR_SAVE_GAME, STR_EXAMINE, STR_STATISTICS, STR_CHOOSE_WEAPON_MODE
};
uchar wanky_secrets_table[18] =
{
0, 3, 3, 3, 3, 3, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
};
ushort options_table[99] =
{
0x020A, 0x040A, 0x004A, 0x080A, 0x0812, 0x008A, 0x0092, 0x010A, 0x0112, 0x0004,
0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004,
0x000C, 0x000C, 0x0004, 0x0004, 0x0004, 0x0004, 0x8000, 0x1000, 0x2000, 0x0004,
0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x000C, 0x000C, 0x000C,
0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C,
0x000C, 0x000C, 0x000C, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004,
0x0004, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C,
0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x0004, 0x0004, 0x0004,
0x0004, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x000C, 0x0004,
0x0004, 0x0020, 0x0020, 0x0020, 0x0004, 0x4002, 0x0004, 0x000C, 0x000C
};
COMBINELIST dels_handy_combine_table[24] =
{
{combine_revolver_lasersight, INV_REVOLVER_ITEM1, INV_LASERSIGHT_ITEM, INV_REVOLVER_ITEM2},
{combine_crossbow_lasersight, INV_CROSSBOW_AMMO2_ITEM1, INV_LASERSIGHT_ITEM, INV_CROSSBOW_AMMO2_ITEM2},
{combine_HK_SILENCER, INV_HK_ITEM1, INV_SILENCER_ITEM, INV_HK_ITEM2},
{combine_PuzzleItem1, INV_PUZZLE_ITEM1_COMBO1, INV_PUZZLE_ITEM1_COMBO2, INV_PUZZLE_ITEM1},
{combine_PuzzleItem2, INV_PUZZLE_ITEM2_COMBO1, INV_PUZZLE_ITEM2_COMBO2, INV_PUZZLE_ITEM2},
{combine_PuzzleItem3, INV_PUZZLE_ITEM3_COMBO1, INV_PUZZLE_ITEM3_COMBO2, INV_PUZZLE_ITEM3},
{combine_PuzzleItem4, INV_PUZZLE_ITEM4_COMBO1, INV_PUZZLE_ITEM4_COMBO2, INV_PUZZLE_ITEM4},
{combine_PuzzleItem5, INV_PUZZLE_ITEM5_COMBO1, INV_PUZZLE_ITEM5_COMBO2, INV_PUZZLE_ITEM5},
{combine_PuzzleItem6, INV_PUZZLE_ITEM6_COMBO1, INV_PUZZLE_ITEM6_COMBO2, INV_PUZZLE_ITEM6},
{combine_PuzzleItem7, INV_PUZZLE_ITEM7_COMBO1, INV_PUZZLE_ITEM7_COMBO2, INV_PUZZLE_ITEM7},
{combine_PuzzleItem8, INV_PUZZLE_ITEM8_COMBO1, INV_PUZZLE_ITEM8_COMBO2, INV_PUZZLE_ITEM8},
{combine_KeyItem1, INV_KEY_ITEM1_COMBO1, INV_KEY_ITEM1_COMBO2, INV_KEY_ITEM1},
{combine_KeyItem2, INV_KEY_ITEM2_COMBO1, INV_KEY_ITEM2_COMBO2, INV_KEY_ITEM2},
{combine_KeyItem3, INV_KEY_ITEM3_COMBO1, INV_KEY_ITEM3_COMBO2, INV_KEY_ITEM3},
{combine_KeyItem4, INV_KEY_ITEM4_COMBO1, INV_KEY_ITEM4_COMBO2, INV_KEY_ITEM4},
{combine_KeyItem5, INV_KEY_ITEM5_COMBO1, INV_KEY_ITEM5_COMBO2, INV_KEY_ITEM5},
{combine_KeyItem6, INV_KEY_ITEM6_COMBO1, INV_KEY_ITEM6_COMBO2, INV_KEY_ITEM6},
{combine_KeyItem7, INV_KEY_ITEM7_COMBO1, INV_KEY_ITEM7_COMBO2, INV_KEY_ITEM7},
{combine_KeyItem8, INV_KEY_ITEM8_COMBO1, INV_KEY_ITEM8_COMBO2, INV_KEY_ITEM8},
{combine_PickupItem1, INV_PICKUP_ITEM1_COMBO1, INV_PICKUP_ITEM1_COMBO2, INV_PICKUP_ITEM1},
{combine_PickupItem2, INV_PICKUP_ITEM2_COMBO1, INV_PICKUP_ITEM2_COMBO2, INV_PICKUP_ITEM2},
{combine_PickupItem3, INV_PICKUP_ITEM3_COMBO1, INV_PICKUP_ITEM3_COMBO2, INV_PICKUP_ITEM3},
{combine_PickupItem4, INV_PICKUP_ITEM4_COMBO1, INV_PICKUP_ITEM4_COMBO2, INV_PICKUP_ITEM4},
{combine_clothbottle, INV_CLOTH, INV_BOTTLE, INV_WET_CLOTH}
};
int S_CallInventory2()
{
ITEM_INFO* item;
long return_value, val;
short room_number;
if (gfCurrentLevel < LVL5_BASE || gfCurrentLevel > LVL5_SINKING_SUBMARINE)
{
inventry_objects_list[INV_REVOLVER_ITEM1].objname = STR_REVOLVER;
inventry_objects_list[INV_REVOLVER_ITEM2].objname = STR_REVOLVER_LASERSIGHT;
inventry_objects_list[INV_REVOLVER_AMMO_ITEM].objname = STR_REVOLVER_AMMO;
}
else
{
inventry_objects_list[INV_REVOLVER_ITEM1].objname = STR_DESERTEAGLE;
inventry_objects_list[INV_REVOLVER_ITEM2].objname = STR_DESERTEAGLE_LASERSIGHT;
inventry_objects_list[INV_REVOLVER_AMMO_ITEM].objname = STR_DESERTEAGLE_AMMO;
}
if (gfCurrentLevel > LVL5_THIRTEENTH_FLOOR && gfCurrentLevel < LVL5_RED_ALERT)
inventry_objects_list[INV_BINOCULARS_ITEM].objname = STR_HEADSET;
else
inventry_objects_list[INV_BINOCULARS_ITEM].objname = STR_BINOCULARS;
#ifdef GENERAL_FIXES//restore HK tip, and properly align HK in iris
inventry_objects_list[INV_HK_ITEM1].meshbits = -1;
if (gfCurrentLevel == LVL5_ESCAPE_WITH_THE_IRIS)
{//fucked up inv HK in this level why core
inventry_objects_list[INV_HK_ITEM1].xrot = 8448;
inventry_objects_list[INV_HK_ITEM1].yrot = 16384;
inventry_objects_list[INV_HK_ITEM1].zrot = 16384;
inventry_objects_list[INV_HK_ITEM1].flags = 10;
inventry_objects_list[INV_HK_ITEM1].yoff = -40;
}
else//original values, for 13th floor and Red Alert
{
inventry_objects_list[INV_HK_ITEM1].xrot = -16384;
inventry_objects_list[INV_HK_ITEM1].yrot = 0;
inventry_objects_list[INV_HK_ITEM1].zrot = 0;
inventry_objects_list[INV_HK_ITEM1].flags = 2;
inventry_objects_list[INV_HK_ITEM1].yoff = 0;
}
#endif
friggrimmer = 0;
oldLaraBusy = lara.Busy != 0;
if (input & IN_SELECT)
friggrimmer = 1;
rings[RING_INVENTORY] = &pcring1;
rings[RING_AMMO] = &pcring2;
CreateMonoScreen();
InventoryActive = 1;
init_new_inventry();
camera.number_frames = 2;
while (!reset_flag)
{
val = 0;
OBJLIST_SPACING = phd_centerx >> 1;
S_InitialisePolyList();
SetDebounce = 1;
S_UpdateInput();
input = inputBusy;
UpdatePulseColour();
GameTimer++;
if (dbinput & IN_OPTION)
{
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
val = 1;
}
return_value = thread_started;
if (return_value)
return return_value;
S_DisplayMonoScreen();
if (GlobalSoftReset)
{
GlobalSoftReset = 0;
val = 1;
}
do_debounced_joystick_poo();
if (rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem == INV_COMPASS_ITEM &&
keymap[DIK_G] && keymap[DIK_U] && keymap[DIK_N] && keymap[DIK_S])//GUNS
dels_give_lara_guns_cheat();
if (rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem == INV_COMPASS_ITEM &&
keymap[DIK_B] && keymap[DIK_I] && keymap[DIK_T] && keymap[DIK_S])//BITS
{
#ifndef GENERAL_FIXES //no items with BITS
dels_give_lara_items_cheat();
#endif
savegame.CampaignSecrets[0] = 9;
savegame.CampaignSecrets[1] = 9;
savegame.CampaignSecrets[2] = 9;
savegame.CampaignSecrets[3] = 9;
}
#ifndef _DEBUG
if (rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem == INV_COMPASS_ITEM &&
keymap[DIK_I] && keymap[DIK_T] && keymap[DIK_E] && keymap[DIK_M]) //ITEM
dels_give_lara_items_cheat();
if (rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem == INV_COMPASS_ITEM &&
keymap[DIK_S] && keymap[DIK_K] && keymap[DIK_I] && keymap[DIK_P]) //SKIP
{
gfLevelComplete = gfCurrentLevel + 1;
SCNoDrawLara = 0;
bDisableLaraControl = 0;
}
if (rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem == INV_COMPASS_ITEM &&
keymap[DIK_H] && keymap[DIK_E] && keymap[DIK_A] && keymap[DIK_L]) //heal
lara_item->hit_points = 1000;
#endif
if (GLOBAL_invkeypadmode)
do_keypad_mode();
else if (examine_mode)
do_examine_mode();
else if (stats_mode)
do_stats_mode();
else
{
draw_current_object_list(RING_INVENTORY);
handle_inventry_menu();
if (rings[RING_AMMO]->ringactive)
draw_current_object_list(RING_AMMO);
draw_ammo_selector();
fade_ammo_selector();
}
if (use_the_bitch && !input)
val = 1;
S_OutputPolyList();
camera.number_frames = S_DumpScreen();
if (loading_or_saving)
{
do
{
S_InitialisePolyList();
SetDebounce = 1;
S_UpdateInput();
input = inputBusy;
UpdatePulseColour();
if (loading_or_saving == 1)
val = go_and_load_game();
else if (go_and_save_game())
val = 1;
} while (!val);
if (val == 1 && loading_or_saving == val)
{
return_value = 1;
val = 1;
}
friggrimmer2 = 1;
friggrimmer = 1;
deselect_debounce = 0;
go_deselect = 0;
loading_or_saving = 0;
}
if (val)
break;
}
InitialisePickUpDisplay();
GLOBAL_lastinvitem = rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem;
update_laras_weapons_status();
if (use_the_bitch && !GLOBAL_invkeypadmode)
use_current_item();
FreeMonoScreen();
lara.Busy = oldLaraBusy & 1;
InventoryActive = 0;
if (GLOBAL_invkeypadmode)
{
val = 0;
GLOBAL_invkeypadmode = 0;
if (keypadnuminputs == 4)
val = keypadinputs[3] + 10 * (keypadinputs[2] + 10 * (keypadinputs[1] + 10 * keypadinputs[0]));
if (GLOBAL_invkeypadcombination == val)
{
item = lara_item;
room_number = lara_item->room_number;
GetHeight(GetFloor(lara_item->pos.x_pos, lara_item->pos.y_pos, lara_item->pos.z_pos, &room_number), item->pos.x_pos, item->pos.y_pos, item->pos.z_pos);
TestTriggers(trigger_index, 1, 0);
}
}
return return_value;
}
void init_new_inventry()
{
examine_mode = 0;
stats_mode = 0;
AlterFOV(14560);
lara.Busy = 0;
GLOBAL_inventoryitemchosen = NO_ITEM;
left_debounce = 0;
right_debounce = 0;
up_debounce = 0;
down_debounce = 0;
go_left = 0;
go_right = 0;
go_up = 0;
go_down = 0;
select_debounce = 0;
deselect_debounce = 0;
go_select = 0;
go_deselect = 0;
left_repeat = 0;
right_repeat = 0;
loading_or_saving = 0;
use_the_bitch = 0;
if (lara.num_shotgun_ammo1 == -1)
AmountShotGunAmmo1 = -1;
else
AmountShotGunAmmo1 = lara.num_shotgun_ammo1 / 6;
if (lara.num_shotgun_ammo2 == -1)
AmountShotGunAmmo2 = -1;
else
AmountShotGunAmmo2 = lara.num_shotgun_ammo2 / 6;
AmountHKAmmo1 = lara.num_hk_ammo1;
AmountCrossBowAmmo1 = lara.num_crossbow_ammo1;
AmountCrossBowAmmo2 = lara.num_crossbow_ammo2;
AmountUziAmmo = lara.num_uzi_ammo;
AmountRevolverAmmo = lara.num_revolver_ammo;
AmountPistolsAmmo = lara.num_pistols_ammo;
construct_object_list();
if (GLOBAL_enterinventory == NO_ITEM)
{
if (GLOBAL_lastinvitem != NO_ITEM)
{
if (have_i_got_item((short)GLOBAL_lastinvitem))
setup_objectlist_startposition((short)GLOBAL_lastinvitem);
GLOBAL_lastinvitem = NO_ITEM;
}
}
else if (GLOBAL_enterinventory == 0xDEADBEEF)
{
GLOBAL_invkeypadmode = 1;
init_keypad_mode();
GLOBAL_enterinventory = NO_ITEM;
}
else
{
if (have_i_got_object(GLOBAL_enterinventory))
setup_objectlist_startposition2(GLOBAL_enterinventory);
GLOBAL_enterinventory = NO_ITEM;
}
ammo_selector_fade_val = 0;
ammo_selector_fade_dir = 0;
combine_ring_fade_val = 0;
combine_ring_fade_dir = 0;
combine_type_flag = 0;
seperate_type_flag = 0;
combine_obj1 = 0;
combine_obj2 = 0;
normal_ring_fade_val = 128;
normal_ring_fade_dir = 0;
handle_object_changeover(RING_INVENTORY);
}
void do_debounced_joystick_poo()
{
go_left = 0;
go_right = 0;
go_up = 0;
go_down = 0;
go_select = 0;
go_deselect = 0;
if (input & IN_LEFT)
{
if (left_repeat >= 8)
go_left = 1;
else
left_repeat++;
if (!left_debounce)
go_left = 1;
left_debounce = 1;
}
else
{
left_debounce = 0;
left_repeat = 0;
}
if (input & IN_RIGHT)
{
if (right_repeat >= 8)
go_right = 1;
else
right_repeat++;
if (!right_debounce)
go_right = 1;
right_debounce = 1;
}
else
{
right_debounce = 0;
right_repeat = 0;
}
if (input & IN_FORWARD)
{
if (!up_debounce)
go_up = 1;
up_debounce = 1;
}
else
up_debounce = 0;
if (input & IN_BACK)
{
if (!down_debounce)
go_down = 1;
down_debounce = 1;
}
else
down_debounce = 0;
if (input & IN_ACTION || input & IN_SELECT)
select_debounce = 1;
else
{
if (select_debounce == 1 && !friggrimmer)
go_select = 1;
select_debounce = 0;
friggrimmer = 0;
}
if (input & IN_DESELECT)
deselect_debounce = 1;
else
{
if (deselect_debounce == 1 && !friggrimmer2)
go_deselect = 1;
deselect_debounce = 0;
friggrimmer2 = 0;
}
}
void DrawThreeDeeObject2D(int x, int y, int num, int shade, int xrot, int yrot, int zrot, int bright, int overlay)
{
INVOBJ* objme;
ITEM_INFO item;
objme = &inventry_objects_list[num];
item.pos.x_rot = xrot + objme->xrot;
item.pos.y_rot = yrot + objme->yrot;
item.pos.z_rot = zrot + objme->zrot;
item.object_number = objme->object_number;
phd_LookAt(0, 1024, 0, 0, 0, 0, 0);
#ifndef GENERAL_FIXES
aLookAt(0, 1024, 0, 100, 0, 200, 0);
#endif
if (!bright)
pcbright = 0x007F7F7F;
else if (bright == 1)
pcbright = 0x002F2F2F;
else
pcbright = bright | ((bright | (bright << 8)) << 8);
SetD3DViewMatrix();
phd_PushUnitMatrix();
phd_TranslateRel(0, 0, objme->scale1);
yoffset = objme->yoff + y;
item.mesh_bits = objme->meshbits;
xoffset = x;
item.shade = -1;
item.pos.x_pos = 0;
item.pos.y_pos = 0;
item.pos.z_pos = 0;
item.room_number = 0;
item.il.nCurrentLights = 0;
item.il.nPrevLights = 0;
item.il.ambient = 0x007F7F7F;
item.anim_number = objects[item.object_number].anim_index;
if (objme->flags & 8)
DrawInventoryItemMe(&item, shade, overlay, 1);
else
DrawInventoryItemMe(&item, shade, overlay, 0);
phd_PopMatrix();
xoffset = phd_centerx;
yoffset = phd_centery;
}
void DrawInventoryItemMe(ITEM_INFO* item, long shade, int overlay, int shagflag)
{
ANIM_STRUCT* anim;
OBJECT_INFO* object;
VECTOR vec;
short** meshpp;
long* bone;
short* rotation1;
short* frmptr;
ulong bit;
long poppush, unk_bak;
anim = &anims[item->anim_number];
frmptr = anim->frame_ptr;
object = &objects[item->object_number];
phd_PushMatrix();
if ((item->object_number == PC_LOAD_INV_ITEM || item->object_number == PC_SAVE_INV_ITEM) && !IsHardware())
{
if (IsSuperLowRes())
{
if (IsSuperLowRes() == 1)
phd_TranslateRel(0, -390, 0);
else
phd_TranslateRel(0, -190, 0);
}
}
if (item->object_number == HK_ITEM && gfCurrentLevel == LVL5_ESCAPE_WITH_THE_IRIS)
phd_TranslateRel(0, 70, 0);
phd_RotYXZ(item->pos.y_rot, item->pos.x_rot, item->pos.z_rot);
if (item->object_number == PUZZLE_HOLE8 && GLOBAL_invkeypadmode)
{
vec.vx = 24576;
vec.vy = 16384;
vec.vz = 4096;
ScaleCurrentMatrix(&vec);
}
bit = 1;
meshpp = &meshes[object->mesh_index];
bone = &bones[object->bone_index];
if (!shagflag)
phd_TranslateRel(frmptr[6], frmptr[7], frmptr[8]);
rotation1 = &frmptr[9];
gar_RotYXZsuperpack(&rotation1, 0);
if (item->mesh_bits & 1)
{
if (overlay)
phd_PutPolygonsPickup(*meshpp, (float)xoffset, (float)yoffset, pcbright);
else
{
unk_bak = GlobalAlpha;
GlobalAlpha = 0xFF000000;
phd_PutPolygonsPickup(*meshpp, (float)xoffset, (float)yoffset, pcbright);
GlobalAlpha = unk_bak;
}
}
meshpp += 2;
for (int i = 0; i < object->nmeshes - 1; i++, meshpp += 2, bone += 4)
{
poppush = *bone;
if (poppush & 1)
phd_PopMatrix();
if (poppush & 2)
phd_PushMatrix();
phd_TranslateRel(bone[1], bone[2], bone[3]);
gar_RotYXZsuperpack(&rotation1, 0);
bit <<= 1;
if (bit & item->mesh_bits)
{
if (overlay)
phd_PutPolygonsPickup(*meshpp, (float)xoffset, (float)yoffset, pcbright);
else
{
unk_bak = GlobalAlpha;
GlobalAlpha = 0xFF000000;
phd_PutPolygonsPickup(*meshpp, (float)xoffset, (float)yoffset, pcbright);
GlobalAlpha = unk_bak;
}
}
}
phd_PopMatrix();
}
int go_and_load_game()
{
return LoadGame();
}
int go_and_save_game()
{
return SaveGame();
}
void construct_combine_object_list()
{
rings[RING_AMMO]->numobjectsinlist = 0;
for (int i = 0; i < 100; i++)
rings[RING_AMMO]->current_object_list[i].invitem = -1;
if (!(gfLevelFlags & GF_YOUNGLARA))
{
if (lara.sixshooter_type_carried & WTYPE_PRESENT)
{
if (lara.sixshooter_type_carried & WTYPE_LASERSIGHT)
insert_object_into_list_v2(INV_REVOLVER_ITEM2);
else
insert_object_into_list_v2(INV_REVOLVER_ITEM1);
}
#ifndef GENERAL_FIXES//stop HK from appearing in combine list
if (lara.hk_type_carried & WTYPE_PRESENT)
insert_object_into_list_v2(INV_HK_ITEM1);
#endif
if (lara.crossbow_type_carried & WTYPE_PRESENT && (gfCurrentLevel < LVL5_THIRTEENTH_FLOOR || gfCurrentLevel > LVL5_RED_ALERT))
{
if (lara.crossbow_type_carried & WTYPE_LASERSIGHT)
insert_object_into_list_v2(INV_CROSSBOW_AMMO2_ITEM2);
else
insert_object_into_list_v2(INV_CROSSBOW_AMMO2_ITEM1);
}
if (lara.lasersight)
insert_object_into_list_v2(INV_LASERSIGHT_ITEM);
if (lara.silencer)
insert_object_into_list_v2(INV_SILENCER_ITEM);
}
for (int i = 0; i < 16; i++)
if (lara.puzzleitemscombo & (1 << i))
insert_object_into_list_v2(INV_PUZZLE_ITEM1_COMBO1 + i);
for (int i = 0; i < 16; i++)
if (lara.keyitemscombo & (1 << i))
insert_object_into_list_v2(INV_KEY_ITEM1_COMBO1 + i);
for (int i = 0; i < 8; i++)
if (lara.pickupitemscombo & (1 << i))
insert_object_into_list_v2(INV_PICKUP_ITEM1_COMBO1 + i);
if (lara.wetcloth == CLOTH_DRY)
insert_object_into_list_v2(INV_CLOTH);
if (lara.bottle)
insert_object_into_list_v2(INV_BOTTLE);
rings[RING_AMMO]->objlistmovement = 0;
rings[RING_AMMO]->curobjinlist = 0;
rings[RING_AMMO]->ringactive = 0;
}
void insert_object_into_list_v2(int num)
{
if (options_table[num] & 9)
{
if (rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem != num)
{
rings[RING_AMMO]->current_object_list[rings[RING_AMMO]->numobjectsinlist].invitem = num;
rings[RING_AMMO]->current_object_list[rings[RING_AMMO]->numobjectsinlist].yrot = 0;
rings[RING_AMMO]->current_object_list[rings[RING_AMMO]->numobjectsinlist++].bright = 32;
}
}
}
void construct_object_list()
{
rings[RING_INVENTORY]->numobjectsinlist = 0;
for (int i = 0; i < 100; i++)
rings[RING_INVENTORY]->current_object_list[i].invitem = NO_ITEM;
CurrentPistolsAmmoType = 0;
CurrentUziAmmoType = 0;
CurrentRevolverAmmoType = 0;
CurrentShotGunAmmoType = 0;
CurrentGrenadeGunAmmoType = 0;
CurrentCrossBowAmmoType = 0;
if (!(gfLevelFlags & GF_YOUNGLARA))
{
if (lara.pistols_type_carried & WTYPE_PRESENT)
insert_object_into_list(INV_PISTOLS_ITEM);
if (lara.uzis_type_carried & WTYPE_PRESENT)
insert_object_into_list(INV_UZI_ITEM);
else if (AmountUziAmmo)
insert_object_into_list(INV_UZI_AMMO_ITEM);
if (lara.sixshooter_type_carried & WTYPE_PRESENT)
{
if (lara.sixshooter_type_carried & WTYPE_LASERSIGHT)
insert_object_into_list(INV_REVOLVER_ITEM2);
else
insert_object_into_list(INV_REVOLVER_ITEM1);
}
else if (AmountRevolverAmmo)
insert_object_into_list(INV_REVOLVER_AMMO_ITEM);
if (lara.shotgun_type_carried & WTYPE_PRESENT)
{
insert_object_into_list(INV_SHOTGUN_ITEM);
if (lara.shotgun_type_carried & WTYPE_AMMO_2)
CurrentShotGunAmmoType = 1;
}
else
{
if (AmountShotGunAmmo1)
insert_object_into_list(INV_SHOTGUN_AMMO1_ITEM);
if (AmountShotGunAmmo2)
insert_object_into_list(INV_SHOTGUN_AMMO2_ITEM);
}
if (lara.hk_type_carried & WTYPE_PRESENT)
{
if (lara.hk_type_carried & WTYPE_SILENCER)
insert_object_into_list(INV_HK_ITEM2);
else
insert_object_into_list(INV_HK_ITEM1);
if (lara.hk_type_carried & WTYPE_AMMO_2)
CurrentGrenadeGunAmmoType = 1;
else if (lara.hk_type_carried & WTYPE_AMMO_3)
CurrentGrenadeGunAmmoType = 2;
}
else if (AmountHKAmmo1)
insert_object_into_list(INV_HK_AMMO_ITEM4);
if (lara.crossbow_type_carried & WTYPE_PRESENT)
{
if (gfCurrentLevel < LVL5_THIRTEENTH_FLOOR || gfCurrentLevel > LVL5_RED_ALERT)
{
if (lara.crossbow_type_carried & WTYPE_LASERSIGHT)
insert_object_into_list(INV_CROSSBOW_AMMO2_ITEM2);
else
insert_object_into_list(INV_CROSSBOW_AMMO2_ITEM1);
if (lara.crossbow_type_carried & WTYPE_AMMO_2)
CurrentCrossBowAmmoType = 1;
}
else
{
insert_object_into_list(INV_CROSSBOW_ITEM);
CurrentCrossBowAmmoType = 0;
}
}
else if (gfCurrentLevel < LVL5_THIRTEENTH_FLOOR || gfCurrentLevel > LVL5_RED_ALERT)
{
if (AmountCrossBowAmmo1)
insert_object_into_list(INV_CROSSBOW_AMMO2_ITEM3);
if (AmountCrossBowAmmo2)
insert_object_into_list(INV_CROSSBOW_AMMO2_ITEM4);
}
else if (AmountCrossBowAmmo1)
insert_object_into_list(INV_CROSSBOW_AMMO1_ITEM);
if (lara.lasersight)
insert_object_into_list(INV_LASERSIGHT_ITEM);
if (lara.silencer)
insert_object_into_list(INV_SILENCER_ITEM);
if (lara.binoculars)
insert_object_into_list(INV_BINOCULARS_ITEM);
if (lara.num_flares)
insert_object_into_list(INV_FLARE_INV_ITEM);
}
insert_object_into_list(INV_COMPASS_ITEM);
if (lara.num_small_medipack)
insert_object_into_list(INV_SMALLMEDI_ITEM);
if (lara.num_large_medipack)
insert_object_into_list(INV_BIGMEDI_ITEM);
if (lara.crowbar)
insert_object_into_list(INV_CROWBAR_ITEM);
for (int i = 0; i < 8; i++)
if (lara.puzzleitems[i])
insert_object_into_list(INV_PUZZLE_ITEM1 + i);
for (int i = 0; i < 16; i++)
if (lara.puzzleitemscombo & (1 << i))
insert_object_into_list(INV_PUZZLE_ITEM1_COMBO1 + i);
for (int i = 0; i < 8; i++)
if (lara.keyitems & (1 << i))
insert_object_into_list(INV_KEY_ITEM1 + i);
for (int i = 0; i < 16; i++)
if (lara.keyitemscombo & (1 << i))
insert_object_into_list(INV_KEY_ITEM1_COMBO1 + i);
for (int i = 0; i < 4; i++)
if (lara.pickupitems & (1 << i))
insert_object_into_list(INV_PICKUP_ITEM1 + i);
for (int i = 0; i < 8; i++)
if (lara.pickupitemscombo & (1 << i))
insert_object_into_list(INV_PICKUP_ITEM1_COMBO1 + i);
if (lara.examine1)
insert_object_into_list(INV_EXAMINE1);
if (lara.examine2)
insert_object_into_list(INV_EXAMINE2);
if (lara.examine3)
insert_object_into_list(INV_EXAMINE3);
if (lara.wetcloth == CLOTH_WET)
insert_object_into_list(INV_WET_CLOTH);
if (lara.wetcloth == CLOTH_DRY)
insert_object_into_list(INV_CLOTH);
if (lara.bottle)
insert_object_into_list(INV_BOTTLE);
if (Gameflow->LoadSaveEnabled)
{
insert_object_into_list(INV_MEMCARD_LOAD_INV_ITEM);
insert_object_into_list(INV_MEMCARD_SAVE_INV_ITEM);
}
rings[RING_INVENTORY]->objlistmovement = 0;
rings[RING_INVENTORY]->curobjinlist = 0;
rings[RING_INVENTORY]->ringactive = 1;
rings[RING_AMMO]->objlistmovement = 0;
rings[RING_AMMO]->curobjinlist = 0;
rings[RING_AMMO]->ringactive = 0;
handle_object_changeover(RING_INVENTORY);
ammo_active = 0;
}
void insert_object_into_list(int num)
{
rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->numobjectsinlist].invitem = num;
rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->numobjectsinlist].yrot = 0;
rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->numobjectsinlist].bright = 32;
rings[RING_INVENTORY]->numobjectsinlist++;
}
void draw_current_object_list(int ringnum)
{
long n, maxobj, xoff, shade, minobj, objmeup, nummeup, activenum;
short ymeup, yrot;
char textbufme[128];
if (rings[ringnum]->numobjectsinlist <= 0)
return;
if (ringnum == RING_AMMO)
{
ammo_selector_fade_val = 0;
ammo_selector_fade_dir = 0;
if (combine_ring_fade_dir == 1)
{
if (combine_ring_fade_val < 128)
combine_ring_fade_val += 32;
if (combine_ring_fade_val > 128)
{
combine_ring_fade_val = 128;
combine_ring_fade_dir = 0;
}
}
else if (combine_ring_fade_dir == 2)
{
combine_ring_fade_val -= 32;
if (combine_ring_fade_val <= 0)
{
combine_ring_fade_val = 0;
combine_ring_fade_dir = 0;
if (combine_type_flag)
normal_ring_fade_dir = 2;
else
{
rings[RING_INVENTORY]->ringactive = 1;
menu_active = 1;
rings[RING_AMMO]->ringactive = 0;
handle_object_changeover(RING_INVENTORY);
}
rings[RING_AMMO]->ringactive = 0;
}
}
}
else if (normal_ring_fade_dir == 1)
{
if (normal_ring_fade_val < 128)
normal_ring_fade_val += 32;
if (normal_ring_fade_val > 128)
{
normal_ring_fade_val = 128;
normal_ring_fade_dir = 0;
rings[RING_INVENTORY]->ringactive = 1;
menu_active = 1;
}
}
else if (normal_ring_fade_dir == 2)
{
normal_ring_fade_val -= 32;
if (normal_ring_fade_val <= 0)
{
normal_ring_fade_val = 0;
normal_ring_fade_dir = 1;
if (combine_type_flag == 1)
{
combine_type_flag = 0;
combine_these_two_objects(combine_obj1, combine_obj2);
}
else if (seperate_type_flag)
seperate_object(rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem);
handle_object_changeover(RING_INVENTORY);
}
}
minobj = 0;
maxobj = 0;
xoff = 0;
n = 0;
if (rings[ringnum]->numobjectsinlist != 1)
xoff = (OBJLIST_SPACING * rings[ringnum]->objlistmovement) >> 16;
if (rings[ringnum]->numobjectsinlist == 2)
{
minobj = -1;
maxobj = 0;
n = rings[ringnum]->curobjinlist - 1;
}
if (rings[ringnum]->numobjectsinlist == 3 || rings[ringnum]->numobjectsinlist == 4)
{
minobj = -2;
maxobj = 1;
n = rings[ringnum]->curobjinlist - 2;
}
if (rings[ringnum]->numobjectsinlist >= 5)
{
minobj = -3;
maxobj = 2;
n = rings[ringnum]->curobjinlist - 3;
}
if (n < 0)
n += rings[ringnum]->numobjectsinlist;
if (rings[ringnum]->objlistmovement < 0)
maxobj++;
if (minobj <= maxobj)
{
for (int i = minobj; i <= maxobj; i++)
{
if (minobj == i)
{
if (rings[ringnum]->objlistmovement < 0)
shade = 0;
else
shade = rings[ringnum]->objlistmovement >> 9;
}
else if (i != minobj + 1 || maxobj == minobj + 1)
{
if (i != maxobj)
shade = 128;
else
{
if (rings[ringnum]->objlistmovement < 0)
shade = (-128 * rings[ringnum]->objlistmovement) >> 16;
else
shade = 128 - (short)(rings[ringnum]->objlistmovement >> 9);
}
}
else
{
if (rings[ringnum]->objlistmovement < 0)
shade = 128 - ((-128 * rings[ringnum]->objlistmovement) >> 16);
else
shade = 128;
}
if (!minobj && !maxobj)
shade = 128;
if (ringnum == RING_AMMO && combine_ring_fade_val < 128 && shade)
shade = combine_ring_fade_val;
else if (ringnum == RING_INVENTORY && normal_ring_fade_val < 128 && shade)
shade = normal_ring_fade_val;
if (!i)
{
nummeup = 0;
switch (inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number)
{
case BIGMEDI_ITEM:
nummeup = lara.num_large_medipack;
break;
case SMALLMEDI_ITEM:
nummeup = lara.num_small_medipack;
break;
case FLARE_INV_ITEM:
nummeup = lara.num_flares;
break;
default:
if (inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number < PUZZLE_ITEM1 ||
inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number > PUZZLE_ITEM8)
{
switch (inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number)
{
case SHOTGUN_AMMO1_ITEM:
nummeup = lara.num_shotgun_ammo1 == -1 ? lara.num_shotgun_ammo1 : lara.num_shotgun_ammo1 / 6;
break;
case SHOTGUN_AMMO2_ITEM:
nummeup = lara.num_crossbow_ammo2 == -1 ? lara.num_shotgun_ammo2 : lara.num_shotgun_ammo2 / 6;
break;
case HK_AMMO_ITEM:
nummeup = lara.num_hk_ammo1;
break;
case CROSSBOW_AMMO1_ITEM:
nummeup = lara.num_crossbow_ammo1;
break;
case CROSSBOW_AMMO2_ITEM:
nummeup = lara.num_crossbow_ammo2;
break;
case REVOLVER_AMMO_ITEM:
nummeup = lara.num_revolver_ammo;
break;
case UZI_AMMO_ITEM:
nummeup = lara.num_uzi_ammo;
break;
case BOTTLE:
nummeup = lara.bottle;
break;
case PICKUP_ITEM4:
nummeup = savegame.Level.Secrets;
break;
}
}
else
{
nummeup = lara.puzzleitems[inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number - PUZZLE_ITEM1];
if (nummeup <= 1)
sprintf(textbufme, SCRIPT_TEXT(inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].objname));
else
sprintf(textbufme, "%d x %s", nummeup, SCRIPT_TEXT(inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].objname));
}
break;
}
if (inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number < PUZZLE_ITEM1 ||
inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number > PUZZLE_ITEM8)
{
if (nummeup)
{
if (inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].object_number == PICKUP_ITEM4)
sprintf(textbufme, SCRIPT_TEXT_bis(STR_SECRETS_NUM), nummeup, wanky_secrets_table[gfCurrentLevel]);
else if (nummeup == -1)
sprintf(textbufme, SCRIPT_TEXT(STR_UNLIMITED), SCRIPT_TEXT(inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].objname));
else
sprintf(textbufme, "%d x %s", nummeup, SCRIPT_TEXT(inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].objname));
}
else
sprintf(textbufme, SCRIPT_TEXT(inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].objname));
}
if (ringnum == RING_INVENTORY)
objmeup = (int)(phd_centery - (phd_winymax + 1) * 0.0625 * 3.0);
else
objmeup = (int)((phd_winymax + 1) * 0.0625 * 3.0 + phd_centery);
PrintString(phd_centerx, (ushort)objmeup, 8, textbufme, FF_CENTER);
}
if (!i && !rings[ringnum]->objlistmovement)
{
if ((inventry_objects_list[rings[ringnum]->current_object_list[n].invitem].flags & 2))
rings[ringnum]->current_object_list[n].yrot += 1022;
}
else
spinback(&rings[ringnum]->current_object_list[n].yrot);
yrot = rings[ringnum]->current_object_list[n].yrot;
if (rings[ringnum]->objlistmovement)
{
if (rings[ringnum]->objlistmovement > 0)
activenum = -1;
else
activenum = 1;
}
else
activenum = 0;
if (i == activenum)
{
if (rings[ringnum]->current_object_list[n].bright < 160)
rings[ringnum]->current_object_list[n].bright += 16;
if (rings[ringnum]->current_object_list[n].bright > 160)
rings[ringnum]->current_object_list[n].bright = 160;
}
else
{
if (rings[ringnum]->current_object_list[n].bright > 32)
rings[ringnum]->current_object_list[n].bright -= 16;
if (rings[ringnum]->current_object_list[n].bright < 32)
rings[ringnum]->current_object_list[n].bright = 32;
}
if (ringnum == RING_INVENTORY)
ymeup = 42;
else
ymeup = 190;
DrawThreeDeeObject2D((long)((phd_centerx * 0.00390625 * 256.0 + inventry_xpos) + xoff + i * OBJLIST_SPACING),
(long)(phd_centery * 0.0083333338 * ymeup + inventry_ypos),
rings[ringnum]->current_object_list[n].invitem,
shade, 0, yrot, 0, rings[ringnum]->current_object_list[n].bright, 0);
if (++n >= rings[ringnum]->numobjectsinlist)
n = 0;
}
if (rings[ringnum]->ringactive)
{
if (rings[ringnum]->numobjectsinlist != 1 && (ringnum != 1 || combine_ring_fade_val == 128))
{
if (rings[ringnum]->objlistmovement > 0)
rings[ringnum]->objlistmovement += 8192;
if (rings[ringnum]->objlistmovement < 0)
rings[ringnum]->objlistmovement -= 8192;
if (go_left)
{
if (!rings[ringnum]->objlistmovement)
{
SoundEffect(SFX_MENU_ROTATE, 0, SFX_ALWAYS);
rings[ringnum]->objlistmovement += 8192;
if (ammo_selector_flag)
ammo_selector_fade_dir = 2;
}
}
if (go_right)
{
if (!rings[ringnum]->objlistmovement)
{
SoundEffect(SFX_MENU_ROTATE, 0, SFX_ALWAYS);
rings[ringnum]->objlistmovement -= 8192;
if (ammo_selector_flag)
ammo_selector_fade_dir = 2;
}
}
if (rings[ringnum]->objlistmovement < 65536)
{
if (rings[ringnum]->objlistmovement < -65535)
{
rings[ringnum]->curobjinlist++;
if (rings[ringnum]->curobjinlist >= rings[ringnum]->numobjectsinlist)
rings[ringnum]->curobjinlist = 0;
rings[ringnum]->objlistmovement = 0;
if (ringnum == RING_INVENTORY)
handle_object_changeover(0);
}
}
else
{
rings[ringnum]->curobjinlist--;
if (rings[ringnum]->curobjinlist < 0)
rings[ringnum]->curobjinlist = rings[ringnum]->numobjectsinlist - 1;
rings[ringnum]->objlistmovement = 0;
if (ringnum == RING_INVENTORY)
handle_object_changeover(0);
}
}
}
}
}
void handle_object_changeover(int ringnum)
{
current_selected_option = 0;
menu_active = 1;
setup_ammo_selector();
}
void handle_inventry_menu()
{
long n, opts, ypos, num;
if (rings[RING_AMMO]->ringactive)
{
PrintString(phd_centerx, phd_centery, 1, SCRIPT_TEXT(optmessages[5]), FF_CENTER);
if (rings[RING_INVENTORY]->objlistmovement)
return;
if (rings[RING_AMMO]->objlistmovement)
return;
if (go_select)
{
if (do_these_objects_combine(rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem, rings[RING_AMMO]->current_object_list[rings[RING_AMMO]->curobjinlist].invitem))
{
combine_ring_fade_dir = 2;
combine_type_flag = 1;
combine_obj1 = rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem;
combine_obj2 = rings[RING_AMMO]->current_object_list[rings[RING_AMMO]->curobjinlist].invitem;
SoundEffect(SFX_MENU_COMBINE, 0, SFX_ALWAYS);
}
else
{
SayNo();
combine_ring_fade_dir = 2;
}
}
if (go_deselect)
{
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
combine_ring_fade_dir = 2;
go_deselect = 0;
}
return;
}
else
{
num = rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem;
for (int i = 0; i < 3; i++)
{
current_options[i].type = 0;
current_options[i].text = 0;
}
n = 0;
if (!ammo_active)
{
opts = options_table[rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem];
if ((opts & 0x1000))
{
current_options[0].type = 9;
current_options[0].text = SCRIPT_TEXT(optmessages[6]);
n = 1;
}
if ((opts & 0x2000))
{
current_options[n].type = 10;
current_options[n].text = SCRIPT_TEXT(optmessages[7]);
n++;
}
if ((opts & 0x20))
{
current_options[n].type = 11;
current_options[n].text = SCRIPT_TEXT(optmessages[8]);
n++;
}
if ((opts & 0x8000))
{
current_options[n].type = 12;
current_options[n].text = SCRIPT_TEXT(optmessages[9]);
n++;
}
if ((opts & 0x4))
{
current_options[n].type = 1;
current_options[n].text = SCRIPT_TEXT(optmessages[0]);
n++;
}
if ((opts & 0x2))
{
current_options[n].type = 5;
current_options[n].text = SCRIPT_TEXT(optmessages[4]);
n++;
}
if ((opts & 0xC0))
{
current_options[n].type = 2;
current_options[n].text = SCRIPT_TEXT(optmessages[1]);
n++;
}
if ((opts & 0x100))
{
current_options[n].type = 2;
current_options[n].text = SCRIPT_TEXT(optmessages[10]);
n++;
}
if ((opts & 8))
{
if (is_item_currently_combinable((short)num))
{
current_options[n].type = 3;
current_options[n].text = SCRIPT_TEXT(optmessages[2]);
n++;
}
}
if ((opts & 0x1))
{
current_options[n].type = 3;
current_options[n].text = SCRIPT_TEXT(optmessages[2]);
n++;
}
if ((opts & 0x10))
{
current_options[n].type = 4;
current_options[n].text = SCRIPT_TEXT(optmessages[3]);
n++;
}
}
else
{
current_options[0].type = 6;
current_options[0].text = SCRIPT_TEXT(inventry_objects_list[ammo_object_list[0].invitem].objname);
current_options[1].type = 7;
current_options[1].text = SCRIPT_TEXT(inventry_objects_list[ammo_object_list[1].invitem].objname);
n = 2;
if ((options_table[rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem] & 0x100))
{
n = 3;
current_options[2].type = 8;
current_options[2].text = SCRIPT_TEXT(inventry_objects_list[ammo_object_list[2].invitem].objname);
}
current_selected_option = current_ammo_type[0];
}
ypos = phd_centery - font_height;
if (n == 1)
ypos += font_height;
else if (n == 2)
ypos += font_height >> 1;
if (n > 0)
{
for (int i = 0; i < n; i++)
{
if (i == current_selected_option)
{
PrintString(phd_centerx, (ushort)ypos, 1, current_options[i].text, FF_CENTER);
ypos += font_height;
}
else
{
PrintString(phd_centerx, (ushort)ypos, 5, current_options[i].text, FF_CENTER);
ypos += font_height;
}
}
}
if (menu_active && !rings[RING_INVENTORY]->objlistmovement && !rings[RING_AMMO]->objlistmovement)
{
if (go_up && current_selected_option > 0)
{
current_selected_option--;
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
}
else if (go_down && current_selected_option < n - 1)
{
current_selected_option++;
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
}
if (ammo_active)
{
if (go_left && current_selected_option > 0)
{
current_selected_option--;
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
}
if (go_right && current_selected_option < n - 1)
{
current_selected_option++;
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
}
current_ammo_type[0] = current_selected_option;
}
if (go_select)
{
if (current_options[current_selected_option].type != 5 && current_options[current_selected_option].type != 1)
SoundEffect(SFX_MENU_CHOOSE, 0, SFX_ALWAYS);
switch (current_options[current_selected_option].type)
{
case 2:
rings[RING_INVENTORY]->ringactive = 0;
ammo_active = 1;
Stashedcurrent_selected_option = current_selected_option;
StashedCurrentPistolsAmmoType = CurrentPistolsAmmoType;
StashedCurrentUziAmmoType = CurrentUziAmmoType;
StashedCurrentRevolverAmmoType = CurrentRevolverAmmoType;
StashedCurrentShotGunAmmoType = CurrentShotGunAmmoType;
StashedCurrentGrenadeGunAmmoType = CurrentGrenadeGunAmmoType;
break;
case 9:
loading_or_saving = 1;
break;
case 10:
loading_or_saving = 2;
break;
case 11:
examine_mode = 1;
break;
case 12:
stats_mode = 1;
break;
case 6:
case 7:
case 8:
ammo_active = 0;
rings[RING_INVENTORY]->ringactive = 1;
current_selected_option = 0;
break;
case 3:
construct_combine_object_list();
rings[RING_INVENTORY]->ringactive = 0;
rings[RING_AMMO]->ringactive = 1;
ammo_selector_flag = 0;
menu_active = 0;
combine_ring_fade_dir = 1;
break;
case 4:
seperate_type_flag = 1;
normal_ring_fade_dir = 2;
break;
case 5:
case 1:
menu_active = 0;
use_the_bitch = 1;
break;
}
}
if (go_deselect && ammo_active)
{
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
go_deselect = 0;
ammo_active = 0;
rings[RING_INVENTORY]->ringactive = 1;
CurrentPistolsAmmoType = StashedCurrentPistolsAmmoType;
CurrentUziAmmoType = StashedCurrentUziAmmoType;
CurrentRevolverAmmoType = StashedCurrentRevolverAmmoType;
CurrentShotGunAmmoType = StashedCurrentShotGunAmmoType;
CurrentGrenadeGunAmmoType = StashedCurrentGrenadeGunAmmoType;
CurrentCrossBowAmmoType = StashedCurrentCrossBowAmmoType;
current_selected_option = Stashedcurrent_selected_option;
}
}
}
}
void setup_ammo_selector()
{
long num, opts;
num = 0;
opts = options_table[rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem];
ammo_selector_flag = 0;
num_ammo_slots = 0;
if (!rings[RING_AMMO]->ringactive)
{
ammo_object_list[2].yrot = 0;
ammo_object_list[1].yrot = 0;
ammo_object_list[0].yrot = 0;
if (opts & 0x4FC0)
{
ammo_selector_flag = 1;
ammo_selector_fade_dir = 1;
if (opts & 0x200)
{
ammo_object_list[0].invitem = INV_UZI_AMMO_ITEM;
ammo_object_list[0].amount = AmountUziAmmo;
num = 1;
num_ammo_slots = 1;
current_ammo_type = &CurrentUziAmmoType;
}
if (opts & 0x400)
{
num = 1;
ammo_object_list[0].invitem = INV_PISTOLS_AMMO_ITEM;
ammo_object_list[0].amount = -1;
num_ammo_slots = 1;
current_ammo_type = &CurrentPistolsAmmoType;
}
if (opts & 0x800)
{
num = 1;
ammo_object_list[0].invitem = INV_REVOLVER_AMMO_ITEM;
ammo_object_list[0].amount = AmountRevolverAmmo;
num_ammo_slots = 1;
current_ammo_type = &CurrentRevolverAmmoType;
}
if (opts & 0x80)
{
current_ammo_type = &CurrentCrossBowAmmoType;
ammo_object_list[num].invitem = INV_CROSSBOW_AMMO2_ITEM3;
ammo_object_list[num].amount = AmountCrossBowAmmo1;
num++;
ammo_object_list[num].invitem = INV_CROSSBOW_AMMO2_ITEM4;
ammo_object_list[num].amount = AmountCrossBowAmmo2;
num++;
num_ammo_slots = (char)num;
}
if (opts & 0x100)
{
current_ammo_type = &CurrentGrenadeGunAmmoType;
ammo_object_list[num].invitem = INV_HK_AMMO_ITEM1;
ammo_object_list[num].amount = AmountHKAmmo1;
num++;
ammo_object_list[num].invitem = INV_HK_AMMO_ITEM2;
ammo_object_list[num].amount = AmountHKAmmo1;
num++;
ammo_object_list[num].invitem = INV_HK_AMMO_ITEM3;
ammo_object_list[num].amount = AmountHKAmmo1;
num++;
num_ammo_slots = (char)num;
}
if (opts & 0x40)
{
current_ammo_type = &CurrentShotGunAmmoType;
ammo_object_list[num].invitem = INV_SHOTGUN_AMMO1_ITEM;
ammo_object_list[num].amount = AmountShotGunAmmo1;
num++;
ammo_object_list[num].invitem = INV_SHOTGUN_AMMO2_ITEM;
ammo_object_list[num].amount = AmountShotGunAmmo2;
num++;
num_ammo_slots = (char)num;
}
if (opts & 0x4000)
{
ammo_object_list[0].invitem = INV_CROSSBOW_AMMO1_ITEM;
ammo_object_list[0].amount = AmountCrossBowAmmo1;
num_ammo_slots = 1;
current_ammo_type = &CurrentCrossBowAmmoType;
}
}
}
}
void fade_ammo_selector()
{
if (rings[RING_INVENTORY]->ringactive && (right_repeat >= 8 || left_repeat >= 8))
ammo_selector_fade_val = 0;
else if (ammo_selector_fade_dir == 1)
{
if (ammo_selector_fade_val < 128)
ammo_selector_fade_val += 32;
if (ammo_selector_fade_val > 128)
{
ammo_selector_fade_val = 128;
ammo_selector_fade_dir = 0;
}
}
else if (ammo_selector_fade_dir == 2)
{
if (ammo_selector_fade_val > 0)
ammo_selector_fade_val -= 32;
if (ammo_selector_fade_val < 0)
{
ammo_selector_fade_val = 0;
ammo_selector_fade_dir = 0;
}
}
}
void draw_ammo_selector()
{
INVOBJ* objme;
long xpos;
short yrot;
char cunter[256];
if (!ammo_selector_flag)
return;
xpos = (2 * phd_centerx - OBJLIST_SPACING) >> 1;
if (num_ammo_slots == 2)
xpos -= OBJLIST_SPACING / 2;
else if (num_ammo_slots == 3)
xpos -= OBJLIST_SPACING;
if (num_ammo_slots > 0)
{
for (int i = 0; i < num_ammo_slots; i++)
{
objme = &inventry_objects_list[ammo_object_list[i].invitem];
if (i == current_ammo_type[0])
{
if ((objme->flags & 2))
ammo_object_list[i].yrot += 1022;
}
else
spinback(&ammo_object_list[i].yrot);
yrot = ammo_object_list[i].yrot;
if (i == current_ammo_type[0])
{
if (ammo_object_list[i].amount == -1)
sprintf(cunter, SCRIPT_TEXT(STR_UNLIMITED), SCRIPT_TEXT(inventry_objects_list[ammo_object_list[i].invitem].objname));
else
sprintf(cunter, "%d x %s", ammo_object_list[i].amount, SCRIPT_TEXT(inventry_objects_list[ammo_object_list[i].invitem].objname));
if (ammo_selector_fade_val)
PrintString(phd_centerx, font_height + phd_centery + 2 * font_height - 9, 8, &cunter[0], FF_CENTER);
if (i == current_ammo_type[0])
DrawThreeDeeObject2D((int)(phd_centerx * 0.00390625 * 64.0 + inventry_xpos + xpos), (int)(phd_centery * 0.0083333338 * 190.0 + inventry_ypos), ammo_object_list[i].invitem, ammo_selector_fade_val, 0, yrot, 0, 0, 0);
else
DrawThreeDeeObject2D((int)(phd_centerx * 0.00390625 * 64.0 + inventry_xpos + xpos), (int)(phd_centery * 0.0083333338 * 190.0 + inventry_ypos), ammo_object_list[i].invitem, ammo_selector_fade_val, 0, yrot, 0, 1, 0);
}
else
DrawThreeDeeObject2D((int)(phd_centerx * 0.00390625 * 64.0 + inventry_xpos + xpos), (int)(phd_centery * 0.0083333338 * 190.0 + inventry_ypos), ammo_object_list[i].invitem, ammo_selector_fade_val, 0, yrot, 0, 1, 0);
xpos += OBJLIST_SPACING;
}
}
}
void spinback(ushort* cock)
{
ushort val, val2;
val = *cock;
if (val)
{
if (val <= 32768)
{
val2 = val;
if (val2 < 1022)
val = 1022;
else if (val2 > 16384)
val2 = 16384;
val -= (val2 >> 3);
if (val > 32768)
val = 0;
}
else
{
val2 = -val;
if (val2 < 1022)
val = 1022;
else if (val2 > 16384)
val2 = 16384;
val += (val2 >> 3);
if (val < 32768)
val = 0;
}
*cock = val;
}
}
void update_laras_weapons_status()
{
if (lara.shotgun_type_carried & WTYPE_PRESENT)
{
lara.shotgun_type_carried &= ~(WTYPE_AMMO_1 | WTYPE_AMMO_2 | WTYPE_AMMO_3);
if (CurrentShotGunAmmoType)
lara.shotgun_type_carried |= WTYPE_AMMO_2;
else
lara.shotgun_type_carried |= WTYPE_AMMO_1;
}
if (lara.hk_type_carried & WTYPE_PRESENT)
{
lara.hk_type_carried &= ~(WTYPE_AMMO_1 | WTYPE_AMMO_2 | WTYPE_AMMO_3);
if (CurrentGrenadeGunAmmoType == 0)
lara.hk_type_carried |= WTYPE_AMMO_1;
else if (CurrentGrenadeGunAmmoType == 1)
lara.hk_type_carried |= WTYPE_AMMO_2;
else if (CurrentGrenadeGunAmmoType == 2)
lara.hk_type_carried |= WTYPE_AMMO_3;
}
if (lara.crossbow_type_carried & WTYPE_PRESENT)
{
lara.crossbow_type_carried &= ~(WTYPE_AMMO_1 | WTYPE_AMMO_2 | WTYPE_AMMO_3);
if (CurrentCrossBowAmmoType)
lara.crossbow_type_carried |= WTYPE_AMMO_2;
else
lara.crossbow_type_carried |= WTYPE_AMMO_1;
}
}
int is_item_currently_combinable(short obj)
{
for (int i = 0; i < 24; i++)
{
if (dels_handy_combine_table[i].item1 == obj && have_i_got_item(dels_handy_combine_table[i].item2))
return 1;
if (dels_handy_combine_table[i].item2 == obj && have_i_got_item(dels_handy_combine_table[i].item1))
return 1;
}
return 0;
}
int have_i_got_item(short obj)
{
for (int i = 0; i < 100; i++)
if (rings[RING_INVENTORY]->current_object_list[i].invitem == obj)
return 1;
return 0;
}
int do_these_objects_combine(int obj1, int obj2)
{
for (int i = 0; i < 24; i++)
{
if (dels_handy_combine_table[i].item1 == obj1 && dels_handy_combine_table[i].item2 == obj2)
return 1;
if (dels_handy_combine_table[i].item1 == obj2 && dels_handy_combine_table[i].item2 == obj1)
return 1;
}
return 0;
}
void combine_these_two_objects(short obj1, short obj2)
{
int n;
for (n = 0; n < 24; n++)
{
if (dels_handy_combine_table[n].item1 == obj1 &&
dels_handy_combine_table[n].item2 == obj2)
break;
if (dels_handy_combine_table[n].item1 == obj2 &&
dels_handy_combine_table[n].item2 == obj1)
break;
}
dels_handy_combine_table[n].combine_routine(0);
construct_object_list();
setup_objectlist_startposition(dels_handy_combine_table[n].combined_item);
handle_object_changeover(0);
}
void seperate_object(short obj)
{
int n;
for (n = 0; n < 24; n++)
if (dels_handy_combine_table[n].combined_item == obj)
break;
dels_handy_combine_table[n].combine_routine(1);
construct_object_list();
setup_objectlist_startposition(dels_handy_combine_table[n].item1);
}
void combine_HK_SILENCER(long flag)
{
if (flag)
{
lara.silencer = 1;
lara.hk_type_carried &= ~WTYPE_SILENCER;
}
else
{
lara.silencer = 0;
lara.hk_type_carried |= WTYPE_SILENCER;
}
}
void combine_revolver_lasersight(long flag)
{
if (flag)
{
lara.lasersight = 1;
lara.sixshooter_type_carried &= ~WTYPE_LASERSIGHT;
}
else
{
lara.lasersight = 0;
lara.sixshooter_type_carried |= WTYPE_LASERSIGHT;
}
if (lara.gun_status && lara.gun_type == WEAPON_REVOLVER)
{
undraw_pistol_mesh_right(WEAPON_REVOLVER);
draw_pistol_meshes(WEAPON_REVOLVER);
}
}
void combine_crossbow_lasersight(long flag)
{
if (flag)
{
lara.lasersight = 1;
lara.crossbow_type_carried &= ~WTYPE_LASERSIGHT;
}
else
{
lara.lasersight = 0;
lara.crossbow_type_carried |= WTYPE_LASERSIGHT;
}
if (lara.gun_status && lara.gun_type == WEAPON_CROSSBOW)
{
undraw_shotgun_meshes(WEAPON_CROSSBOW);
draw_shotgun_meshes(WEAPON_CROSSBOW);
}
}
void combine_PuzzleItem1(long flag)
{
lara.puzzleitemscombo &= 0xFFFC;
lara.puzzleitems[0] = 1;
}
void combine_PuzzleItem2(long flag)
{
lara.puzzleitemscombo &= 0xFFF3;
lara.puzzleitems[1] = 1;
}
void combine_PuzzleItem3(long flag)
{
lara.puzzleitemscombo &= 0xFFCF;
lara.puzzleitems[2] = 1;
}
void combine_PuzzleItem4(long flag)
{
lara.puzzleitemscombo &= 0xFF3F;
lara.puzzleitems[3] = 1;
}
void combine_PuzzleItem5(long flag)
{
lara.puzzleitemscombo &= 0xFCFF;
lara.puzzleitems[4] = 1;
}
void combine_PuzzleItem6(long flag)
{
lara.puzzleitemscombo &= 0xF3FF;
lara.puzzleitems[5] = 1;
}
void combine_PuzzleItem7(long flag)
{
lara.puzzleitemscombo &= 0xCFFF;
lara.puzzleitems[6] = 1;
}
void combine_PuzzleItem8(long flag)
{
lara.puzzleitemscombo &= 0x3FFF;
lara.puzzleitems[7] = 1;
}
void combine_KeyItem1(long flag)
{
lara.keyitems |= 1;
lara.keyitemscombo &= 0xFFFC;
}
void combine_KeyItem2(long flag)
{
lara.keyitems |= 2;
lara.keyitemscombo &= 0xFFF3;
}
void combine_KeyItem3(long flag)
{
lara.keyitems |= 4;
lara.keyitemscombo &= 0xFFCF;
}
void combine_KeyItem4(long flag)
{
lara.keyitems |= 8;
lara.keyitemscombo &= 0xFF3F;
}
void combine_KeyItem5(long flag)
{
lara.keyitems |= 16;
lara.keyitemscombo &= 0xFCFF;
}
void combine_KeyItem6(long flag)
{
lara.keyitems |= 32;
lara.keyitemscombo &= 0xF3FF;
}
void combine_KeyItem7(long flag)
{
lara.keyitems |= 64;
lara.keyitemscombo &= 0xCFFF;
}
void combine_KeyItem8(long flag)
{
lara.keyitems |= 128;
lara.keyitemscombo &= 0x3FFF;
}
void combine_PickupItem1(long flag)
{
lara.pickupitems |= 1;
lara.pickupitemscombo &= 0xFFFC;
}
void combine_PickupItem2(long flag)
{
lara.pickupitems |= 2;
lara.pickupitemscombo &= 0xFFF3;
}
void combine_PickupItem3(long flag)
{
lara.pickupitems |= 4;
lara.pickupitemscombo &= 0xFFCF;
}
void combine_PickupItem4(long flag)
{
lara.pickupitems |= 8;
lara.pickupitemscombo &= 0xFF3F;
}
void combine_clothbottle(long flag)
{
lara.wetcloth = CLOTH_WET;
lara.bottle--;
}
void setup_objectlist_startposition(short newobj)
{
for (int i = 0; i < 100; i++)
if (rings[RING_INVENTORY]->current_object_list[i].invitem == newobj)
rings[RING_INVENTORY]->curobjinlist = i;
}
void setup_objectlist_startposition2(short newobj)
{
for (int i = 0; i < 100; i++)
if (inventry_objects_list[rings[RING_INVENTORY]->current_object_list[i].invitem].object_number == newobj)
rings[RING_INVENTORY]->curobjinlist = i;
}
void use_current_item()
{
long OldBinocular;
short invobject, gmeobject;
OldBinocular = BinocularRange;
oldLaraBusy = 0;
BinocularRange = 0;
lara_item->mesh_bits = -1;
invobject = rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem;
gmeobject = inventry_objects_list[invobject].object_number;
if (gfCurrentLevel == LVL5_DEEPSEA_DIVE && gmeobject == PUZZLE_ITEM1)
{
FireChaff();
return;
}
if (lara.water_status == LW_ABOVE_WATER || lara.water_status == LW_WADE)
{
if (gmeobject == PISTOLS_ITEM)
{
lara.request_gun_type = WEAPON_PISTOLS;
if (lara.gun_status != LG_NO_ARMS)
return;
if (lara.gun_type == WEAPON_PISTOLS)
lara.gun_status = LG_DRAW_GUNS;
return;
}
if (gmeobject == UZI_ITEM)
{
lara.request_gun_type = WEAPON_UZI;
if (lara.gun_status != LG_NO_ARMS)
return;
if (lara.gun_type == WEAPON_UZI)
lara.gun_status = LG_DRAW_GUNS;
return;
}
}
if (gmeobject != SHOTGUN_ITEM && gmeobject != REVOLVER_ITEM && gmeobject != HK_ITEM && gmeobject != CROSSBOW_ITEM)
{
if (gmeobject == FLARE_INV_ITEM)
{
if (lara.gun_status == LG_NO_ARMS)
{
if (lara_item->current_anim_state != AS_ALL4S && lara_item->current_anim_state != AS_CRAWL &&
lara_item->current_anim_state != AS_ALL4TURNL && lara_item->current_anim_state != AS_ALL4TURNR &&
lara_item->current_anim_state != AS_CRAWLBACK && lara_item->current_anim_state != AS_CRAWL2HANG)
{
if (lara.gun_type != 7)
{
input = IN_FLARE;
LaraGun();
input = 0;
}
return;
}
}
SayNo();
return;
}
switch (invobject)
{
case INV_BINOCULARS_ITEM:
if ((lara_item->current_anim_state == AS_STOP && lara_item->anim_number == ANIM_BREATH ||
lara.IsDucked && !(input & IN_DUCK)) && !SniperCamActive && !bUseSpotCam && !bTrackCamInit)
{
oldLaraBusy = 1;
BinocularRange = 128;
if (lara.gun_status != LG_NO_ARMS)
lara.gun_status = LG_UNDRAW_GUNS;
}
if (OldBinocular)
BinocularRange = OldBinocular;
else
BinocularOldCamera = camera.old_type;
return;
case INV_SMALLMEDI_ITEM:
if ((lara_item->hit_points <= 0 || lara_item->hit_points >= 1000) && !lara.poisoned)
{
SayNo();
return;
}
if (lara.num_small_medipack != -1)
lara.num_small_medipack--;
lara.dpoisoned = 0;
lara_item->hit_points += 500;
if (lara_item->hit_points > 1000)
lara_item->hit_points = 1000;
SoundEffect(SFX_MENU_MEDI, 0, SFX_ALWAYS);
savegame.Game.HealthUsed++;
return;
case INV_BIGMEDI_ITEM:
if ((lara_item->hit_points <= 0 || lara_item->hit_points >= 1000) && !lara.poisoned)
{
SayNo();
return;
}
if (lara.num_large_medipack != -1)
lara.num_large_medipack--;
lara.dpoisoned = 0;
lara_item->hit_points += 1000;
if (lara_item->hit_points > 1000)
lara_item->hit_points = 1000;
SoundEffect(SFX_MENU_MEDI, 0, SFX_ALWAYS);
savegame.Game.HealthUsed++;
return;
default:
GLOBAL_inventoryitemchosen = gmeobject;
return;
}
return;
}
if (lara.gun_status == LG_HANDS_BUSY)
{
SayNo();
return;
}
if (lara_item->current_anim_state == AS_ALL4S || lara_item->current_anim_state == AS_CRAWL || lara_item->current_anim_state == AS_ALL4TURNL ||
lara_item->current_anim_state == AS_ALL4TURNR || lara_item->current_anim_state == AS_CRAWLBACK || lara_item->current_anim_state == AS_CRAWL2HANG ||
lara_item->current_anim_state == AS_DUCK || lara_item->current_anim_state == AS_DUCKROTL || lara_item->current_anim_state == AS_DUCKROTR)
{
SayNo();
return;
}
if (gmeobject == SHOTGUN_ITEM)
{
lara.request_gun_type = WEAPON_SHOTGUN;
if (lara.gun_status != LG_NO_ARMS)
return;
if (lara.gun_type == 4)
lara.gun_status = LG_DRAW_GUNS;
return;
}
if (gmeobject == REVOLVER_ITEM)
{
lara.request_gun_type = WEAPON_REVOLVER;
if (lara.gun_status != LG_NO_ARMS)
return;
if (lara.gun_type == WEAPON_REVOLVER)
lara.gun_status = WEAPON_REVOLVER;
return;
}
else if (gmeobject == HK_ITEM)
{
lara.request_gun_type = WEAPON_HK;
if (lara.gun_status != 0)
return;
if (lara.gun_type == 5)
lara.gun_status = 2;
return;
}
else
{
lara.request_gun_type = WEAPON_CROSSBOW;
if (lara.gun_status != LG_NO_ARMS)
return;
if (lara.gun_type == WEAPON_CROSSBOW)
lara.gun_status = 2;
return;
}
}
void DEL_picked_up_object(short objnum)
{
switch (objnum)
{
case UZI_ITEM:
if (!(lara.uzis_type_carried & WTYPE_PRESENT))
lara.uzis_type_carried = WTYPE_PRESENT | WTYPE_AMMO_1;
if (lara.num_uzi_ammo != -1)
lara.num_uzi_ammo += 30;
return;
case PISTOLS_ITEM:
if (!(lara.uzis_type_carried & WTYPE_PRESENT))
lara.pistols_type_carried = WTYPE_PRESENT | WTYPE_AMMO_1;
lara.num_pistols_ammo = -1;
return;
case SHOTGUN_ITEM:
if (!(lara.shotgun_type_carried & WTYPE_PRESENT))
lara.shotgun_type_carried = WTYPE_PRESENT | WTYPE_AMMO_1;
if (lara.num_shotgun_ammo1 != -1)
lara.num_shotgun_ammo1 += 36;
return;
case REVOLVER_ITEM:
if (!(lara.sixshooter_type_carried & WTYPE_PRESENT))
lara.sixshooter_type_carried = WTYPE_PRESENT | WTYPE_AMMO_1;
if (lara.num_revolver_ammo != -1)
lara.num_revolver_ammo += 6;
return;
case CROSSBOW_ITEM:
if (gfCurrentLevel < LVL5_THIRTEENTH_FLOOR || gfCurrentLevel > LVL5_RED_ALERT)
{
if (!(lara.crossbow_type_carried & WTYPE_PRESENT))
lara.crossbow_type_carried = WTYPE_PRESENT | WTYPE_AMMO_1;
if (lara.num_crossbow_ammo1 != -1)
lara.num_crossbow_ammo1 += 10;
}
else
{
lara.crossbow_type_carried = WTYPE_PRESENT | WTYPE_LASERSIGHT | WTYPE_AMMO_1;
lara.num_crossbow_ammo2 = 0;
}
return;
case HK_ITEM:
SetCutNotPlayed(23);
if (!(lara.hk_type_carried & WTYPE_PRESENT))
lara.hk_type_carried = WTYPE_PRESENT | WTYPE_AMMO_1;
if (gfCurrentLevel != LVL5_ESCAPE_WITH_THE_IRIS)
if (lara.num_hk_ammo1 != -1)
lara.num_hk_ammo1 += 30;
return;
case SHOTGUN_AMMO1_ITEM:
if (lara.num_shotgun_ammo1 != -1)
lara.num_shotgun_ammo1 += 36;
return;
case SHOTGUN_AMMO2_ITEM:
if (lara.num_shotgun_ammo2 != -1)
lara.num_shotgun_ammo2 += 36;
return;
case HK_AMMO_ITEM:
if (lara.num_hk_ammo1 != -1)
lara.num_hk_ammo1 += 30;
return;
case CROSSBOW_AMMO1_ITEM:
if (lara.num_crossbow_ammo1 != -1)
lara.num_crossbow_ammo1++;
return;
case CROSSBOW_AMMO2_ITEM:
if (lara.num_crossbow_ammo2 != -1)
lara.num_crossbow_ammo2 += 10;
return;
case REVOLVER_AMMO_ITEM:
if (lara.num_revolver_ammo != -1)
lara.num_revolver_ammo += 6;
return;
case UZI_AMMO_ITEM:
if (lara.num_uzi_ammo != -1)
lara.num_uzi_ammo += 30;
return;
case FLARE_INV_ITEM:
if (lara.num_flares != -1)
lara.num_flares += 12;
return;
case SILENCER_ITEM:
if (!((lara.uzis_type_carried | lara.pistols_type_carried | lara.shotgun_type_carried | lara.sixshooter_type_carried |
lara.crossbow_type_carried | lara.hk_type_carried) & WTYPE_SILENCER))
lara.silencer = 1;
return;
case LASERSIGHT_ITEM:
if (!((lara.uzis_type_carried | lara.pistols_type_carried | lara.shotgun_type_carried | lara.sixshooter_type_carried |
lara.crossbow_type_carried | lara.hk_type_carried) & WTYPE_LASERSIGHT))
lara.lasersight = 1;
return;
case BIGMEDI_ITEM:
if (lara.num_large_medipack != -1)
lara.num_large_medipack++;
return;
case SMALLMEDI_ITEM:
if (lara.num_small_medipack != -1)
lara.num_small_medipack++;
return;
case BINOCULARS_ITEM:
lara.binoculars = 1;
return;
case PICKUP_ITEM4:
IsAtmospherePlaying = 0;
S_CDPlay(CDA_XA1_SECRET, 0);
lara.pickupitems |= 8;
savegame.Level.Secrets++;
savegame.Game.Secrets++;
if (gfCurrentLevel >= LVL5_THIRTEENTH_FLOOR && gfCurrentLevel <= LVL5_RED_ALERT)
savegame.CampaignSecrets[3]++;
else if (gfCurrentLevel >= LVL5_BASE && gfCurrentLevel <= LVL5_SINKING_SUBMARINE)
savegame.CampaignSecrets[2]++;
else if (gfCurrentLevel >= LVL5_STREETS_OF_ROME && gfCurrentLevel <= LVL5_COLOSSEUM)
savegame.CampaignSecrets[0]++;
else if (gfCurrentLevel >= LVL5_GALLOWS_TREE && gfCurrentLevel <= LVL5_OLD_MILL)
savegame.CampaignSecrets[1]++;
return;
case CROWBAR_ITEM:
lara.crowbar = 1;
return;
case EXAMINE1:
lara.examine1 = 1;
return;
case EXAMINE2:
lara.examine2 = 1;
return;
case EXAMINE3:
lara.examine3 = 1;
return;
case WET_CLOTH:
lara.wetcloth = CLOTH_WET;
return;
case CLOTH:
lara.wetcloth = CLOTH_DRY;
return;
case BOTTLE:
lara.bottle++;
return;
default:
if (objnum >= PICKUP_ITEM1 && objnum <= PICKUP_ITEM3)
lara.pickupitems |= 1 << (objnum - PICKUP_ITEM1);
else if (objnum >= PICKUP_ITEM1_COMBO1 && objnum <= PICKUP_ITEM4_COMBO2)
lara.pickupitemscombo |= 1 << (objnum - PICKUP_ITEM1_COMBO1);
else if (objnum >= KEY_ITEM1 && objnum <= KEY_ITEM8)
lara.keyitems |= 1 << (objnum - KEY_ITEM1);
else if (objnum >= KEY_ITEM1_COMBO1 && objnum <= KEY_ITEM8_COMBO2)
lara.keyitemscombo |= 1 << (objnum - KEY_ITEM1_COMBO1);
else if (objnum >= PUZZLE_ITEM1 && objnum <= PUZZLE_ITEM8)
lara.puzzleitems[objnum - PUZZLE_ITEM1]++;
else if (objnum >= PUZZLE_ITEM1_COMBO1 && objnum <= PUZZLE_ITEM8_COMBO2)
lara.puzzleitemscombo |= 1 << (objnum - PUZZLE_ITEM1_COMBO1);
}
}
void NailInvItem(short objnum)
{
switch (objnum)
{
case UZI_ITEM:
lara.uzis_type_carried = WTYPE_MISSING;
lara.num_uzi_ammo = 0;
break;
case PISTOLS_ITEM:
#ifdef GENERAL_FIXES
tomb5_save.LHolster = LARA_HOLSTERS;
#endif
lara.holster = LARA_HOLSTERS;
lara.pistols_type_carried = WTYPE_MISSING;
lara.gun_status = LG_NO_ARMS;
lara.last_gun_type = WEAPON_NONE;
lara.gun_type = WEAPON_NONE;
lara.request_gun_type = WEAPON_NONE;
break;
case SHOTGUN_ITEM:
lara.shotgun_type_carried = WTYPE_MISSING;
lara.num_shotgun_ammo1 = 0;
break;
case REVOLVER_ITEM:
lara.sixshooter_type_carried = WTYPE_MISSING;
lara.num_revolver_ammo = 0;
break;
case CROSSBOW_ITEM:
lara.crossbow_type_carried = WTYPE_MISSING;
lara.num_crossbow_ammo1 = 0;
break;
case HK_ITEM:
lara.hk_type_carried = WTYPE_MISSING;
lara.num_hk_ammo1 = 0;
break;
case FLARE_INV_ITEM:
lara.num_flares = 0;
break;
case SILENCER_ITEM:
lara.silencer = WTYPE_MISSING;
break;
case LASERSIGHT_ITEM:
lara.lasersight = WTYPE_MISSING;
break;
case BIGMEDI_ITEM:
lara.num_large_medipack = 0;
break;
case SMALLMEDI_ITEM:
lara.num_small_medipack = 0;
break;
case BINOCULARS_ITEM:
lara.binoculars = WTYPE_MISSING;
break;
case CROWBAR_ITEM:
lara.crowbar = 0;
break;
case EXAMINE1:
lara.examine1 = 0;
break;
case EXAMINE2:
lara.examine2 = 0;
break;
case EXAMINE3:
lara.examine3 = 0;
break;
case WET_CLOTH:
lara.wetcloth = CLOTH_MISSING;
break;
case CLOTH:
lara.wetcloth = CLOTH_MISSING;
break;
case BOTTLE:
lara.bottle = 0;
break;
default:
if (objnum >= PICKUP_ITEM1 && objnum <= PICKUP_ITEM4)
lara.pickupitems &= ~(1 << (objnum - PICKUP_ITEM1));
else if (objnum >= PICKUP_ITEM1_COMBO1 && objnum <= PICKUP_ITEM4_COMBO2)
lara.pickupitemscombo &= ~(1 << (objnum - PICKUP_ITEM1_COMBO1));
else if (objnum >= KEY_ITEM1 && objnum <= KEY_ITEM8)
lara.keyitems &= ~(1 << (objnum - KEY_ITEM1));
else if (objnum >= KEY_ITEM1_COMBO1 && objnum <= KEY_ITEM8_COMBO2)
lara.keyitemscombo &= ~(1 << (objnum - KEY_ITEM1_COMBO1));
else if (objnum >= PUZZLE_ITEM1 && objnum <= PUZZLE_ITEM8)
lara.puzzleitems[objnum - PUZZLE_ITEM1] = 0;
else if (objnum >= PUZZLE_ITEM1_COMBO1 && objnum <= PUZZLE_ITEM8_COMBO2)
lara.puzzleitemscombo &= ~(1 << (objnum - PUZZLE_ITEM1_COMBO1));
break;
}
}
int have_i_got_object(short object_number)
{
if (object_number >= PUZZLE_ITEM1_COMBO1 && object_number <= PUZZLE_ITEM8_COMBO2)
return (lara.puzzleitemscombo >> (object_number - PUZZLE_ITEM1_COMBO1)) & 1;
if (object_number >= PUZZLE_ITEM1 && object_number <= PUZZLE_ITEM8)
return lara.puzzleitems[object_number - PUZZLE_ITEM1];
if (object_number >= KEY_ITEM1_COMBO1 && object_number <= KEY_ITEM8_COMBO2)
return (lara.keyitemscombo >> (object_number - KEY_ITEM1_COMBO1)) & 1;
if (object_number >= KEY_ITEM1 && object_number <= KEY_ITEM8)
return (lara.keyitems >> (object_number - KEY_ITEM1)) & 1;
if (object_number >= PICKUP_ITEM1_COMBO1 && object_number <= PICKUP_ITEM4_COMBO2)
return (lara.pickupitemscombo >> (object_number - PICKUP_ITEM1_COMBO1)) & 1;
if (object_number >= PICKUP_ITEM1 && object_number <= PICKUP_ITEM4)
return (lara.pickupitems >> (object_number - PICKUP_ITEM1)) & 1;
if (object_number == CROWBAR_ITEM)
return lara.crowbar;
if (object_number == WET_CLOTH)
return lara.wetcloth & 2;
return 0;
}
void remove_inventory_item(short object_number)
{
if (object_number >= PUZZLE_ITEM1_COMBO1 && object_number <= PUZZLE_ITEM8_COMBO2)
lara.puzzleitemscombo &= ~(1 << (object_number + 76));
if (object_number >= PUZZLE_ITEM1 && object_number <= PUZZLE_ITEM8)
lara.puzzleitems[object_number - PUZZLE_ITEM1]--;
if (object_number >= KEY_ITEM1_COMBO1 && object_number <= KEY_ITEM8_COMBO2)
lara.keyitemscombo &= ~(1 << (object_number + 52));
if (object_number >= KEY_ITEM1 && object_number <= KEY_ITEM8)
lara.keyitems &= ~(1 << (object_number + 60));
if (object_number >= PICKUP_ITEM1_COMBO1 && object_number <= PICKUP_ITEM4_COMBO2)
lara.pickupitemscombo &= ~(1 << (object_number + 32));
if (object_number >= PICKUP_ITEM1 && object_number <= PICKUP_ITEM4)
lara.pickupitems &= ~(1 << (object_number + 36));
}
int convert_obj_to_invobj(short obj)
{
for (int i = 0; i < 100; i++)
if (inventry_objects_list[i].object_number == obj)
return i;
return 27;
}
int convert_invobj_to_obj(int obj)
{
return inventry_objects_list[obj].object_number;
}
void init_keypad_mode()
{
keypadx = 0;
keypady = 0;
keypadnuminputs = 0;
keypadpause = 0;
keypadinputs[0] = 0;
keypadinputs[1] = 0;
keypadinputs[2] = 0;
keypadinputs[3] = 0;
}
void do_keypad_mode()
{
INVOBJ* objme;
long n, val, val2;
char buf[5];
val = 0x1FFF;
if (keypadnuminputs)
{
for (int i = 0; i < (int)keypadnuminputs; i++)
{
val2 = keypadinputs[i];
if (!val2)
val2 = 11;
val = val & ~(1 << (val2 & 31)) | 1 << (val2 + 12 & 31);
}
}
objme = &inventry_objects_list[INV_PUZZLE_HOLE8];
if (!(GnFrameCounter & 2) && !keypadpause)
objme->meshbits = val & ~(1 << (((3 * keypady + keypadx) + 13) & 0x1F)) | 1 << (((3 * keypady + keypadx) + 1) & 0x1F);
else
objme->meshbits = val & ~(1 << (((keypadx + 3 * keypady) + 1) & 0x1F)) | 1 << (((keypadx + 3 * keypady) + 13) & 0x1F);
DrawThreeDeeObject2D((int)(phd_centerx * 0.00390625 * 256.0 + inventry_xpos), (int)((phd_centery * 0.0083333338 * 256.0 + inventry_ypos) / 2),
INV_PUZZLE_HOLE8, 128, 0x8000, 0x4000, 0x4000, 0, 0);
PrintString(0x100, (ushort)((phd_centery * 0.0083333338 * 256.0 + inventry_ypos) / 2 - 64), 6, SCRIPT_TEXT_bis(STR_ENTER_COMBINATION), FF_CENTER);
buf[0] = 45;
buf[1] = 45;
buf[2] = 45;
buf[3] = 45;
buf[4] = 0;
if (keypadnuminputs)
for (int i = 0; i < keypadnuminputs; i++)
buf[i] = keypadinputs[i] + 48;
PrintString(0x100, (ushort)((phd_centery * 0.0083333338 * 256.0 + inventry_ypos) / 2 + 64), 1, buf, FF_CENTER);
if (keypadpause)
{
#ifdef KEYPAD_SOUNDS
long combination;
combination = keypadinputs[3] + 10 * (keypadinputs[2] + 10 * (keypadinputs[1] + 10 * keypadinputs[0]));
if (GLOBAL_invkeypadcombination == combination)
{
if (keypadpause == 30 || keypadpause == 20 || keypadpause == 10)
SoundEffect(SFX_KEYPAD_ENTRY_YES, 0, SFX_ALWAYS);
}
else
{
if (keypadpause == 30 || keypadpause == 25 || keypadpause == 20 || keypadpause == 15 || keypadpause == 10 || keypadpause == 5)
SoundEffect(SFX_KEYPAD_ENTRY_NO, 0, SFX_ALWAYS | 0x1000 | SFX_SETVOL);
}
#endif
keypadpause--;
if (keypadpause <= 0)
{
menu_active = 0;
use_the_bitch = 1;
return;
}
}
if (go_select)
{
uchar va = keypady * 3 + keypadx + 1;
unsigned int va2 = (unsigned int)(va);
switch (va)
{
case 10://#, resets input
SoundEffect(SFX_KEYPAD_HASH, 0, SFX_ALWAYS);
keypadnuminputs = 0;
return;
case 11://zero
va = 0;
va2 = 0;
break;
case 12://*, submits input
keypadpause = 30;
SoundEffect(SFX_KEYPAD_STAR, 0, SFX_ALWAYS);
return;
}
if (keypadnuminputs == 4)
return;
n = 0;
if (keypadnuminputs)
{
do
{
if (keypadinputs[n] == va)
return;
n++;
} while (n < keypadnuminputs);
}
SoundEffect(va2 + SFX_KEYPAD_0, 0, SFX_ALWAYS);
keypadinputs[keypadnuminputs] = va;
keypadnuminputs++;
if (keypadnuminputs == 4)
{
keypadx = 2;
keypady = 3;
}
}
if (go_left && keypadx)
keypadx--;
if (go_right && keypadx < 2)
keypadx++;
if (go_up && keypady)
keypady--;
if (go_down && keypady < 3)
keypady++;
}
void do_examine_mode()
{
INVOBJ* objme;
long saved_scale;
objme = &inventry_objects_list[rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem];
saved_scale = objme->scale1;
examine_mode += 8;
if (examine_mode > 128)
examine_mode = 128;
objme->scale1 = 300;
DrawThreeDeeObject2D((int)(phd_centerx + inventry_xpos), (int)(phd_centery / 120.0 * 256.0 + inventry_xpos) / 2,
rings[RING_INVENTORY]->current_object_list[rings[RING_INVENTORY]->curobjinlist].invitem,
examine_mode, 32768, 16384, 16384, 96, 0);
objme->scale1 = (short)saved_scale;
if (go_deselect)
{
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
go_deselect = 0;
examine_mode = 0;
}
}
void do_stats_mode()
{
stats_mode += 8;
if (stats_mode > 128)
stats_mode = 128;
DisplayStatsUCunt();
if (go_deselect)
{
SoundEffect(SFX_MENU_SELECT, 0, SFX_ALWAYS);
go_deselect = 0;
stats_mode = 0;
}
}
void dels_give_lara_items_cheat()
{
#ifdef ENABLE_CHEATS
long piss;//I'll keep it for reasons
if (objects[CROWBAR_ITEM].loaded)
lara.crowbar = 1;
for (piss = 0; piss < 8; ++piss)
{
if (objects[PUZZLE_ITEM1 + piss].loaded)
lara.puzzleitems[piss] = 1;
}
for (piss = 0; piss < 8; ++piss)
{
if (objects[KEY_ITEM1 + piss].loaded)
lara.keyitems |= (1 << (piss & 0x1F));
}
for (piss = 0; piss < 3; ++piss)
{
if (objects[PICKUP_ITEM1 + piss].loaded)
lara.pickupitems |= (1 << (piss & 0x1F));
}
if (gfCurrentLevel == LVL5_SUBMARINE)
{
lara.puzzleitems[0] = 0;
lara.puzzleitemscombo = 0;
lara.keyitemscombo = 0;
lara.pickupitemscombo = 0;
}
if (gfCurrentLevel == LVL5_OLD_MILL)
{
lara.puzzleitems[2] = 0;
lara.puzzleitemscombo = 0;
lara.keyitemscombo = 0;
lara.pickupitemscombo = 0;
}
#endif
}
void dels_give_lara_guns_cheat()
{
#ifdef ENABLE_CHEATS
//actually this isn't in the JP exe either, it's taken from PSX code
if (objects[FLARE_INV_ITEM].loaded)
lara.num_flares = -1;
lara.num_small_medipack = -1;
lara.num_large_medipack = -1;
if (!(gfLevelFlags & GF_YOUNGLARA))
{
if (objects[SHOTGUN_ITEM].loaded)
{
lara.num_shotgun_ammo1 = -1;
lara.num_shotgun_ammo2 = -1;
lara.shotgun_type_carried |= -1;
}
if (objects[REVOLVER_ITEM].loaded)
{
lara.num_revolver_ammo = -1;
lara.sixshooter_type_carried |= -1;
}
if (objects[CROSSBOW_ITEM].loaded)
{
lara.num_crossbow_ammo1 = -1;
lara.num_crossbow_ammo2 = -1;
lara.crossbow_type_carried |= -1;
if (gfCurrentLevel < LVL5_GIBBY_LEVEL)
{
lara.crossbow_type_carried = WTYPE_PRESENT | WTYPE_LASERSIGHT | WTYPE_AMMO_1;
lara.num_crossbow_ammo2 = 0;
}
}
if (objects[HK_ITEM].loaded)
{
lara.num_hk_ammo1 = -1;
lara.hk_type_carried |= 1;
}
if (objects[UZI_ITEM].loaded)
{
lara.num_uzi_ammo = -1;
lara.uzis_type_carried |= 1;
}
if (objects[LASERSIGHT_ITEM].loaded)
lara.lasersight = 1;
if (objects[SILENCER_ITEM].loaded)
lara.silencer = 1;
}
#endif
}
int LoadGame()
{
return S_LoadSave(IN_LOAD, 1) < 0 ? -1 : 1;
}
int SaveGame()
{
input = 0;
dbinput = 0;
return S_LoadSave(IN_SAVE, 1) < 0 ? -1 : 1;
}
void DelDrawSprite(int x, int y, int def, int z)
{
SPRITESTRUCT* sprite;
D3DTLVERTEX v[4];
TEXTURESTRUCT Tex;
float u1, u2, v1, v2;
long x1, y1, x2, y2, x3, y3, x4, y4;
sprite = &spriteinfo[objects[DEFAULT_SPRITES].mesh_index + def];
if (z >= 200)
z = (int)(f_mzfar - 20.0);
else
z = (int)(f_mznear + 20.0);
x1 = x4 = (long)((float)x * (float)phd_centerx * (1.0f / 256.0f));
x2 = x3 = (long)(((float)((sprite->width >> 8) + x + 1)) * (float)phd_centerx * (1.0f / 256.0f));
y1 = y2 = (long)((float)y * (float)phd_centery * (1.0f / 120.0f));
y3 = y4 = (long)(((float)((sprite->height >> 8) + y + 1)) * (float)phd_centery * (1.0f / 120.0f));
setXY4(v, x1, y1, x2, y2, x3, y3, x4, y4, z, clipflags);
v[0].specular = 0xFF000000;
v[1].specular = 0xFF000000;
v[2].specular = 0xFF000000;
v[3].specular = 0xFF000000;
v[0].color = 0xFFFFFFFF;
v[1].color = 0xFFFFFFFF;
v[2].color = 0xFFFFFFFF;
v[3].color = 0xFFFFFFFF;
u1 = sprite->x1;
v1 = sprite->y1;
u2 = sprite->x2;
v2 = sprite->y2;
Tex.drawtype = 1;
Tex.flag = 0;
Tex.tpage = sprite->tpage;
Tex.u1 = u1;
Tex.v1 = v1;
Tex.u2 = u2;
Tex.v2 = v1;
Tex.u3 = u2;
Tex.v3 = v2;
Tex.u4 = u1;
Tex.v4 = v2;
AddQuadClippedSorted(v, 0, 1, 2, 3, &Tex, 0);
}
void inject_newinv2(bool replace)
{
INJECT(0x0045F9D0, S_CallInventory2, replace);
INJECT(0x0045FEF0, init_new_inventry, replace);
INJECT(0x004601A0, do_debounced_joystick_poo, replace);
INJECT(0x00460350, DrawThreeDeeObject2D, replace);
INJECT(0x00460580, DrawInventoryItemMe, replace);
INJECT(0x00460920, go_and_load_game, replace);
INJECT(0x00460940, go_and_save_game, replace);
INJECT(0x00460960, construct_combine_object_list, replace);
INJECT(0x00460B40, insert_object_into_list_v2, replace);
INJECT(0x00460BD0, construct_object_list, replace);
INJECT(0x00461120, insert_object_into_list, replace);
INJECT(0x00461190, draw_current_object_list, replace);
INJECT(0x00461D90, handle_object_changeover, replace);
INJECT(0x00461DC0, handle_inventry_menu, replace);
INJECT(0x00462740, setup_ammo_selector, replace);
INJECT(0x00462A00, fade_ammo_selector, replace);
INJECT(0x00462AD0, draw_ammo_selector, replace);
INJECT(0x00462DD0, spinback, replace);
INJECT(0x00462E60, update_laras_weapons_status, replace);
INJECT(0x00462EF0, is_item_currently_combinable, replace);
INJECT(0x00462F60, have_i_got_item, replace);
INJECT(0x00462FA0, do_these_objects_combine, replace);
INJECT(0x00462FF0, combine_these_two_objects, replace);
INJECT(0x00463080, seperate_object, replace);
INJECT(0x004630F0, combine_HK_SILENCER, replace);
INJECT(0x00463130, combine_revolver_lasersight, replace);
INJECT(0x004631B0, combine_crossbow_lasersight, replace);
INJECT(0x00463230, combine_PuzzleItem1, replace);
INJECT(0x00463260, combine_PuzzleItem2, replace);
INJECT(0x00463290, combine_PuzzleItem3, replace);
INJECT(0x004632C0, combine_PuzzleItem4, replace);
INJECT(0x004632F0, combine_PuzzleItem5, replace);
INJECT(0x00463320, combine_PuzzleItem6, replace);
INJECT(0x00463350, combine_PuzzleItem7, replace);
INJECT(0x00463380, combine_PuzzleItem8, replace);
INJECT(0x004633B0, combine_KeyItem1, replace);
INJECT(0x004633E0, combine_KeyItem2, replace);
INJECT(0x00463410, combine_KeyItem3, replace);
INJECT(0x00463440, combine_KeyItem4, replace);
INJECT(0x00463470, combine_KeyItem5, replace);
INJECT(0x004634A0, combine_KeyItem6, replace);
INJECT(0x004634D0, combine_KeyItem7, replace);
INJECT(0x00463500, combine_KeyItem8, replace);
INJECT(0x00463530, combine_PickupItem1, replace);
INJECT(0x00463560, combine_PickupItem2, replace);
INJECT(0x00463590, combine_PickupItem3, replace);
INJECT(0x004635C0, combine_PickupItem4, replace);
INJECT(0x004635F0, combine_clothbottle, replace);
INJECT(0x00463620, setup_objectlist_startposition, replace);
INJECT(0x00463660, setup_objectlist_startposition2, replace);
INJECT(0x004636B0, use_current_item, replace);
INJECT(0x00463B60, DEL_picked_up_object, replace);
INJECT(0x004640B0, NailInvItem, replace);
INJECT(0x00464360, have_i_got_object, replace);
INJECT(0x00464490, remove_inventory_item, replace);
INJECT(0x004645B0, convert_obj_to_invobj, replace);
INJECT(0x004645F0, convert_invobj_to_obj, replace);
INJECT(0x00464610, init_keypad_mode, replace);
INJECT(0x00464650, do_keypad_mode, replace);
INJECT(0x00464AB0, do_examine_mode, replace);
INJECT(0x00464BF0, do_stats_mode, replace);
INJECT(0x00464C60, dels_give_lara_items_cheat, replace);
INJECT(0x00464C80, dels_give_lara_guns_cheat, replace);
INJECT(0x00464EF0, LoadGame, replace);
INJECT(0x00464F20, SaveGame, replace);
INJECT(0x00464CA0, DelDrawSprite, replace);
}
| 24.454839 | 219 | 0.700158 | [
"object",
"vector"
] |
fa28084fb9ed36c96d90c9c927cb972eddbaf507 | 1,364 | cpp | C++ | engine/engine/alice/components/TimeOffset.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | engine/engine/alice/components/TimeOffset.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | engine/engine/alice/components/TimeOffset.cpp | ddr95070/RMIsaac | ee3918f685f0a88563248ddea11d089581077973 | [
"FSFAP"
] | 1 | 2020-07-02T11:51:17.000Z | 2020-07-02T11:51:17.000Z | /*
Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#include "TimeOffset.hpp"
#include <string>
#include <vector>
#include "engine/alice/components/MessageLedger.hpp"
#include "engine/alice/node.hpp"
namespace isaac {
namespace alice {
void TimeOffset::initialize() {
ledger_ = node()->getComponent<MessageLedger>();
ledger_->addOnConnectAsRxCallback(
[=](const MessageLedger::Endpoint& tx, const MessageLedger::Endpoint& rx) {
if (rx.tag == get_input_channel()) {
ledger_->addOnMessageCallback(rx, tx.component,
[=](ConstMessageBasePtr message) {
auto clone = Clone(message);
if (!clone) {
LOG_ERROR("Could not clone message");
return;
}
clone->acqtime += get_acqtime_offset();
ledger_->provide({this, get_output_channel()}, clone);
});
return;
}
});
}
} // namespace alice
} // namespace isaac
| 31.72093 | 81 | 0.655425 | [
"vector"
] |
fa2d74878adbfb596175c140791355aa7e1ca324 | 52,149 | cpp | C++ | gsoap/VisualStudio2005/wsdl2h/wsdl2h/schema.cpp | JinpengLI/gsoap | 58ba1cfaee90f6f018ef81e9cb63fbd8e1af4566 | [
"Zlib",
"OpenSSL",
"Unlicense"
] | null | null | null | gsoap/VisualStudio2005/wsdl2h/wsdl2h/schema.cpp | JinpengLI/gsoap | 58ba1cfaee90f6f018ef81e9cb63fbd8e1af4566 | [
"Zlib",
"OpenSSL",
"Unlicense"
] | 1 | 2017-07-17T17:30:47.000Z | 2017-07-24T21:20:44.000Z | gsoap/wsdl/schema.cpp | JinpengLI/gsoap | 58ba1cfaee90f6f018ef81e9cb63fbd8e1af4566 | [
"Zlib",
"OpenSSL",
"Unlicense"
] | null | null | null | /*
schema.cpp
XSD binding schema implementation
--------------------------------------------------------------------------------
gSOAP XML Web services tools
Copyright (C) 2001-2008, Robert van Engelen, Genivia Inc. All Rights Reserved.
This software is released under one of the following two licenses:
GPL or Genivia's license for commercial use.
--------------------------------------------------------------------------------
GPL license.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
Author contact information:
engelen@genivia.com / engelen@acm.org
--------------------------------------------------------------------------------
A commercial use license is available from Genivia, Inc., contact@genivia.com
--------------------------------------------------------------------------------
*/
#include "wsdlH.h" // cannot include "schemaH.h"
#include "includes.h"
extern struct Namespace namespaces[];
extern "C" {
extern int warn_ignore(struct soap*, const char*);
}
extern const char *qname_token(const char*, const char*);
extern int is_builtin_qname(const char*);
////////////////////////////////////////////////////////////////////////////////
//
// schema
//
////////////////////////////////////////////////////////////////////////////////
xs__schema::xs__schema()
{ soap = soap_new1(SOAP_XML_TREE | SOAP_C_UTFSTRING);
#ifdef WITH_OPENSSL
soap_ssl_client_context(soap, SOAP_SSL_NO_AUTHENTICATION, NULL, NULL, NULL, NULL, NULL);
#endif
soap_set_namespaces(soap, namespaces);
soap_default(soap);
soap->fignore = warn_ignore;
soap->encodingStyle = NULL;
soap->proxy_host = proxy_host;
soap->proxy_port = proxy_port;
soap->proxy_userid = proxy_userid;
soap->proxy_passwd = proxy_passwd;
targetNamespace = NULL;
version = NULL;
updated = false;
location = NULL;
redirs = 0;
}
xs__schema::xs__schema(struct soap *copy)
{ soap = soap_copy(copy);
soap->socket = SOAP_INVALID_SOCKET;
soap->recvfd = 0;
soap->sendfd = 1;
soap_default(soap);
soap->fignore = warn_ignore;
soap->encodingStyle = NULL;
targetNamespace = NULL;
version = NULL;
updated = false;
location = NULL;
redirs = 0;
}
xs__schema::xs__schema(struct soap *copy, const char *cwd, const char *loc)
{ soap = soap_copy(copy);
soap->socket = SOAP_INVALID_SOCKET;
soap->recvfd = 0;
soap->sendfd = 1;
/* no longer required, since we keep the host name:
strcpy(soap->host, copy->host);
*/
soap_default(soap);
soap->fignore = warn_ignore;
soap->encodingStyle = NULL;
targetNamespace = NULL;
version = NULL;
updated = false;
location = NULL;
redirs = 0;
read(cwd, loc);
}
xs__schema::~xs__schema()
{ }
int xs__schema::get(struct soap *soap)
{ return preprocess();
}
int xs__schema::preprocess()
{ // process xs:include recursively
// NOTE: includes are context sensitive (take context info), so keep including
for (vector<xs__include>::iterator in = include.begin(); in != include.end(); ++in)
{ (*in).preprocess(*this); // read schema and recurse over <include>
if ((*in).schemaPtr())
insert(*(*in).schemaPtr());
}
for (vector<xs__redefine>::iterator re = redefine.begin(); re != redefine.end(); ++re)
{ (*re).preprocess(*this); // read schema and recurse over <redefine>
if ((*re).schemaPtr())
insert(*(*re).schemaPtr());
}
return SOAP_OK;
}
int xs__schema::insert(xs__schema& schema)
{ bool found;
if (targetNamespace && schema.targetNamespace && strcmp(targetNamespace, schema.targetNamespace))
fprintf(stderr, "Warning: attempt to include schema with mismatching targetNamespace '%s' in schema '%s'\n", schema.targetNamespace, targetNamespace);
if (elementFormDefault != schema.elementFormDefault)
fprintf(stderr, "Warning: attempt to include schema with mismatching elementFormDefault in schema '%s'\n", targetNamespace?targetNamespace:"");
if (attributeFormDefault != schema.attributeFormDefault)
fprintf(stderr, "Warning: attempt to include schema with mismatching attributeFormDefault in schema '%s'\n", targetNamespace?targetNamespace:"");
// insert imports, but only add imports with new namespace
for (vector<xs__import>::const_iterator im = schema.import.begin(); im != schema.import.end(); ++im)
{ found = false;
if ((*im).namespace_)
{ for (vector<xs__import>::const_iterator i = import.begin(); i != import.end(); ++i)
{ if ((*i).namespace_ && !strcmp((*im).namespace_, (*i).namespace_))
{ found = true;
break;
}
}
}
if (!found)
import.push_back(*im);
}
// insert attributes, but only add attributes with new name (limited conflict check)
for (vector<xs__attribute>::const_iterator at = schema.attribute.begin(); at != schema.attribute.end(); ++at)
{ found = false;
if ((*at).name)
{ for (vector<xs__attribute>::const_iterator a = attribute.begin(); a != attribute.end(); ++a)
{ if ((*a).name && !strcmp((*at).name, (*a).name))
{ found = true;
if ((*at).type && (*a).type && strcmp((*at).type, (*a).type))
fprintf(stderr, "Warning: attempt to redefine attribute '%s' with type '%s' in schema '%s'\n", (*at).name, (*at).type, targetNamespace?targetNamespace:"");
break;
}
}
}
if (!found)
{ attribute.push_back(*at);
attribute.back().schemaPtr(this);
}
}
// insert elements, but only add elements with new name (limited conflict check)
for (vector<xs__element>::const_iterator el = schema.element.begin(); el != schema.element.end(); ++el)
{ found = false;
if ((*el).name)
{ for (vector<xs__element>::const_iterator e = element.begin(); e != element.end(); ++e)
{ if ((*e).name && !strcmp((*el).name, (*e).name))
{ found = true;
if ((*el).type && (*e).type && strcmp((*el).type, (*e).type))
fprintf(stderr, "Warning: attempt to redefine element '%s' with type '%s' in schema '%s'\n", (*el).name, (*el).type, targetNamespace?targetNamespace:"");
break;
}
}
}
if (!found)
{ element.push_back(*el);
element.back().schemaPtr(this);
}
}
// insert groups, but only add groups with new name (no conflict check)
for (vector<xs__group>::const_iterator gp = schema.group.begin(); gp != schema.group.end(); ++gp)
{ found = false;
if ((*gp).name)
{ for (vector<xs__group>::const_iterator g = group.begin(); g != group.end(); ++g)
{ if ((*g).name && !strcmp((*gp).name, (*g).name))
{ found = true;
break;
}
}
}
if (!found)
{ group.push_back(*gp);
group.back().schemaPtr(this);
}
}
// insert attributeGroups, but only add attributeGroups with new name (no conflict check)
for (vector<xs__attributeGroup>::const_iterator ag = schema.attributeGroup.begin(); ag != schema.attributeGroup.end(); ++ag)
{ found = false;
if ((*ag).name)
{ for (vector<xs__attributeGroup>::const_iterator g = attributeGroup.begin(); g != attributeGroup.end(); ++g)
{ if ((*g).name && !strcmp((*ag).name, (*g).name))
{ found = true;
break;
}
}
}
if (!found)
{ attributeGroup.push_back(*ag);
attributeGroup.back().schemaPtr(this);
}
}
// insert simpleTypes, but only add simpleTypes with new name (no conflict check)
for (vector<xs__simpleType>::const_iterator st = schema.simpleType.begin(); st != schema.simpleType.end(); ++st)
{ found = false;
if ((*st).name)
{ for (vector<xs__simpleType>::const_iterator s = simpleType.begin(); s != simpleType.end(); ++s)
{ if ((*s).name && !strcmp((*st).name, (*s).name))
{ found = true;
break;
}
}
}
if (!found)
{ simpleType.push_back(*st);
simpleType.back().schemaPtr(this);
}
}
// insert complexTypes, but only add complexTypes with new name (no conflict check)
for (vector<xs__complexType>::const_iterator ct = schema.complexType.begin(); ct != schema.complexType.end(); ++ct)
{ found = false;
if ((*ct).name)
{ for (vector<xs__complexType>::const_iterator c = complexType.begin(); c != complexType.end(); ++c)
{ if ((*c).name && !strcmp((*ct).name, (*c).name))
{ found = true;
break;
}
}
}
if (!found)
{ complexType.push_back(*ct);
complexType.back().schemaPtr(this);
}
}
return SOAP_OK;
}
int xs__schema::traverse()
{ if (vflag)
cerr << "Analyzing schema " << (targetNamespace?targetNamespace:"") << endl;
if (updated)
return SOAP_OK;
updated = true;
if (!targetNamespace)
{ if (vflag)
fprintf(stderr, "Warning: Schema has no targetNamespace\n");
targetNamespace = soap_strdup(soap, "");
}
else if (exturis.find(targetNamespace) != exturis.end())
{ if (vflag)
fprintf(stderr, "Warning: Built-in schema '%s' content encountered\n", targetNamespace);
}
// process import
for (vector<xs__import>::iterator im = import.begin(); im != import.end(); ++im)
(*im).traverse(*this);
// process attributes
for (vector<xs__attribute>::iterator at = attribute.begin(); at != attribute.end(); ++at)
(*at).traverse(*this);
// process elements
for (vector<xs__element>::iterator el = element.begin(); el != element.end();
++el)
(*el).traverse(*this);
// process simpleTypes, check conflicts with complexTypes
for (vector<xs__simpleType>::iterator st = simpleType.begin(); st != simpleType.end(); ++st)
{ (*st).traverse(*this);
if ((*st).name)
{ for (vector<xs__complexType>::iterator ct = complexType.begin(); ct != complexType.end(); ++ct)
if ((*ct).name && !strcmp((*st).name, (*ct).name))
fprintf(stderr, "Warning: top-level simpleType name and complexType name '%s' clash in schema '%s'\n", (*st).name, targetNamespace?targetNamespace:"");
}
}
// process complexTypes
for (vector<xs__complexType>::iterator ct = complexType.begin(); ct != complexType.end(); ++ct)
(*ct).traverse(*this);
// process groups
for (vector<xs__group>::iterator gp = group.begin(); gp != group.end(); ++gp)
(*gp).traverse(*this);
// process attributeGroups
for (vector<xs__attributeGroup>::iterator ag = attributeGroup.begin(); ag != attributeGroup.end(); ++ag)
(*ag).traverse(*this);
if (vflag)
cerr << "End of schema " << (targetNamespace?targetNamespace:"") << endl;
return SOAP_OK;
}
int xs__schema::read(const char *cwd, const char *loc)
{ const char *cwd_temp;
if (!cwd)
cwd = cwd_path;
if (vflag)
fprintf(stderr, "\nOpening schema '%s' from '%s'\n", loc?loc:"", cwd?cwd:"");
if (loc)
{
#ifdef WITH_OPENSSL
if (!strncmp(loc, "http://", 7) || !strncmp(loc, "https://", 8))
#else
if (!strncmp(loc, "https://", 8))
{ fprintf(stderr, "\nCannot connect to https site: no SSL support, please rebuild with SSL (default) or download the files and rerun wsdl2h\n");
exit(1);
}
else if (!strncmp(loc, "http://", 7))
#endif
{ fprintf(stderr, "\nConnecting to '%s' to retrieve schema...\n", loc);
location = soap_strdup(soap, loc);
if (soap_connect_command(soap, SOAP_GET, location, NULL))
{ fprintf(stderr, "\nConnection failed\n");
exit(1);
}
fprintf(stderr, "Connected, receiving...\n");
}
else if (cwd && (!strncmp(cwd, "http://", 7) || !strncmp(cwd, "https://", 8)))
{ char *s;
location = (char*)soap_malloc(soap, strlen(cwd) + strlen(loc) + 2);
strcpy(location, cwd);
s = strrchr(location, '/');
if (s)
*s = '\0';
strcat(location, "/");
strcat(location, loc);
fprintf(stderr, "\nConnecting to '%s' to retrieve relative '%s' schema...\n", location, loc);
if (soap_connect_command(soap, SOAP_GET, location, NULL))
{ fprintf(stderr, "\nConnection failed\n");
exit(1);
}
fprintf(stderr, "Connected, receiving...\n");
}
else
{ soap->recvfd = open(loc, O_RDONLY, 0);
if (soap->recvfd < 0)
{ if (cwd)
{ char *s;
location = (char*)soap_malloc(soap, strlen(cwd) + strlen(loc) + 2);
strcpy(location, cwd);
s = strrchr(location, '/');
#ifdef WIN32
if (!s)
s = strrchr(location, '\\');
#endif
if (s)
*s = '\0';
strcat(location, "/");
strcat(location, loc);
if (!strncmp(location, "file://", 7))
location += 7;
soap->recvfd = open(location, O_RDONLY, 0);
}
if (soap->recvfd < 0 && import_path)
{ location = (char*)soap_malloc(soap, strlen(import_path) + strlen(loc) + 2);
strcpy(location, import_path);
strcat(location, "/");
strcat(location, loc);
if (!strncmp(location, "file://", 7))
location += 7;
soap->recvfd = open(location, O_RDONLY, 0);
}
if (soap->recvfd < 0)
{ fprintf(stderr, "\nCannot open '%s' to retrieve schema\n", loc);
exit(1);
}
}
else
location = soap_strdup(soap, loc);
fprintf(stderr, "\nReading schema file '%s'...\n", location);
}
}
cwd_temp = cwd_path;
cwd_path = location;
if (!soap_begin_recv(soap))
this->soap_in(soap, "xs:schema", NULL);
if ((soap->error >= 301 && soap->error <= 303) || soap->error == 307) // HTTP redirect, socket was closed
{ int r = SOAP_ERR;
fprintf(stderr, "Redirected to '%s'...\n", soap->endpoint);
if (redirs++ < 10)
r = read(cwd, soap->endpoint);
else
fprintf(stderr, "\nMax redirects exceeded\n");
redirs--;
return r;
}
if (soap->error)
{ fprintf(stderr, "\nAn error occurred while parsing schema from '%s'\n", loc?loc:"");
soap_print_fault(soap, stderr);
soap_print_fault_location(soap, stderr);
fprintf(stderr, "\nIf this schema namespace is considered \"built-in\", then add\n namespaceprefix = <namespaceURI>\nto typemap.dat.\n");
exit(1);
}
fprintf(stderr, "Done reading '%s'\n", loc?loc:"");
soap_end_recv(soap);
if (soap->recvfd > 2)
{ close(soap->recvfd);
soap->recvfd = -1;
}
else
soap_closesock(soap);
cwd_path = cwd_temp;
return SOAP_OK;
}
void xs__schema::sourceLocation(const char *loc)
{ location = soap_strdup(soap, loc);
}
const char *xs__schema::sourceLocation()
{ return location;
}
int xs__schema::error()
{ return soap->error;
}
void xs__schema::print_fault()
{ soap_print_fault(soap, stderr);
soap_print_fault_location(soap, stderr);
}
void xs__schema::builtinType(const char *type)
{ builtinTypeSet.insert(type);
}
void xs__schema::builtinElement(const char *element)
{ builtinElementSet.insert(element);
}
void xs__schema::builtinAttribute(const char *attribute)
{ builtinAttributeSet.insert(attribute);
}
const SetOfString& xs__schema::builtinTypes() const
{ return builtinTypeSet;
}
const SetOfString& xs__schema::builtinElements() const
{ return builtinElementSet;
}
const SetOfString& xs__schema::builtinAttributes() const
{ return builtinAttributeSet;
}
xs__include::xs__include()
{ schemaLocation = NULL;
schemaRef = NULL;
}
int xs__include::preprocess(xs__schema &schema)
{ if (!schemaRef && schemaLocation)
{ // only read when not read already, uses global static std::map
static map<const char*, xs__schema*, ltstr> included;
map<const char*, xs__schema*, ltstr>::iterator i = included.find(schemaLocation);
if (i == included.end())
{ if (vflag)
cerr << "Preprocessing schema include " << (schemaLocation?schemaLocation:"?") << " into schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
included[schemaLocation] = schemaRef = new xs__schema(schema.soap);
schemaRef->read(schema.sourceLocation(), schemaLocation);
}
else
{ if (vflag)
cerr << "Schema " << (schemaLocation?schemaLocation:"?") << " already included into schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
schemaRef = (*i).second;
}
}
return SOAP_OK;
}
int xs__include::traverse(xs__schema &schema)
{ return SOAP_OK;
}
void xs__include::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema *xs__include::schemaPtr() const
{ return schemaRef;
}
xs__redefine::xs__redefine()
{ schemaLocation = NULL;
schemaRef = NULL;
}
int xs__redefine::preprocess(xs__schema &schema)
{ if (vflag)
cerr << "Preprocessing schema redefine " << (schemaLocation?schemaLocation:"?") << " into schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
if (!schemaRef)
{ if (schemaLocation)
{ schemaRef = new xs__schema(schema.soap, schema.sourceLocation(), schemaLocation);
for (vector<xs__group>::iterator gp = schemaRef->group.begin(); gp != schemaRef->group.end(); ++gp)
{ if ((*gp).name)
{ for (vector<xs__group>::const_iterator g = group.begin(); g != group.end(); ++g)
{ if ((*g).name && !strcmp((*gp).name, (*g).name))
{ *gp = *g;
break;
}
}
}
}
for (vector<xs__attributeGroup>::iterator ag = schemaRef->attributeGroup.begin(); ag != schemaRef->attributeGroup.end(); ++ag)
{ if ((*ag).name)
{ for (vector<xs__attributeGroup>::const_iterator g = attributeGroup.begin(); g != attributeGroup.end(); ++g)
{ if ((*g).name && !strcmp((*ag).name, (*g).name))
{ *ag = *g;
break;
}
}
}
}
for (vector<xs__simpleType>::iterator st = schemaRef->simpleType.begin(); st != schemaRef->simpleType.end(); ++st)
{ if ((*st).name)
{ for (vector<xs__simpleType>::const_iterator s = simpleType.begin(); s != simpleType.end(); ++s)
{ if ((*s).name && !strcmp((*st).name, (*s).name))
{ *st = *s;
break;
}
}
}
}
for (vector<xs__complexType>::iterator ct = schemaRef->complexType.begin(); ct != schemaRef->complexType.end(); ++ct)
{ if ((*ct).name)
{ for (vector<xs__complexType>::const_iterator c = complexType.begin(); c != complexType.end(); ++c)
{ if ((*c).name && !strcmp((*ct).name, (*c).name))
{ *ct = *c;
break;
}
}
}
}
}
}
return SOAP_OK;
}
int xs__redefine::traverse(xs__schema &schema)
{ return SOAP_OK;
}
void xs__redefine::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema *xs__redefine::schemaPtr() const
{ return schemaRef;
}
xs__import::xs__import()
{ namespace_ = NULL;
schemaLocation = NULL;
schemaRef = NULL;
}
int xs__import::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema import " << (namespace_?namespace_:"") << endl;
if (!schemaRef)
{ bool found = false;
if (namespace_)
{ for (SetOfString::const_iterator i = exturis.begin(); i != exturis.end(); ++i)
{ if (!soap_tag_cmp(namespace_, *i))
{ found = true;
break;
}
}
}
else
fprintf(stderr, "Warning: no namespace in <import>\n");
if (!found && !iflag) // don't import any of the schemas in the .nsmap table (or when -i option is used)
{ const char *s = schemaLocation;
if (!s)
s = namespace_;
// only read when not read already, uses global static std::map
static map<const char*, xs__schema*, ltstr> included;
map<const char*, xs__schema*, ltstr>::iterator i = included.find(s);
if (i == included.end())
{ included[s] = schemaRef = new xs__schema(schema.soap);
schemaRef->read(schema.sourceLocation(), s);
}
else
schemaRef = (*i).second;
if (schemaRef)
{ if (!schemaRef->targetNamespace || !*schemaRef->targetNamespace)
schemaRef->targetNamespace = namespace_;
else if (!namespace_ || strcmp(schemaRef->targetNamespace, namespace_))
fprintf(stderr, "Warning: schema import '%s' with schema targetNamespace '%s' mismatch\n", namespace_?namespace_:"", schemaRef->targetNamespace);
}
}
}
if (schemaRef)
schemaRef->traverse();
return SOAP_OK;
}
void xs__import::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema *xs__import::schemaPtr() const
{ return schemaRef;
}
xs__attribute::xs__attribute()
{ schemaRef = NULL;
attributeRef = NULL;
simpleTypeRef = NULL;
}
int xs__attribute::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema attribute " << (name?name:"") << endl;
schemaRef = &schema;
const char *token = qname_token(ref, schema.targetNamespace);
attributeRef = NULL;
if (token)
{ for (vector<xs__attribute>::iterator i = schema.attribute.begin(); i != schema.attribute.end(); ++i)
if (!strcmp((*i).name, token))
{ attributeRef = &(*i);
if (vflag)
cerr << "Found attribute " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (!attributeRef)
{ for (vector<xs__import>::iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(ref, s->targetNamespace);
if (token)
{ for (vector<xs__attribute>::iterator j = s->attribute.begin(); j != s->attribute.end(); ++j)
{ if (!strcmp((*j).name, token))
{ attributeRef = &(*j);
if (vflag)
cerr << "Found attribute " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (attributeRef)
break;
}
}
}
}
if (simpleType)
{ simpleType->traverse(schema);
simpleTypeRef = simpleType;
}
else
{ token = qname_token(type, schema.targetNamespace);
simpleTypeRef = NULL;
if (token)
{ for (vector<xs__simpleType>::iterator i = schema.simpleType.begin(); i != schema.simpleType.end(); ++i)
if (!strcmp((*i).name, token))
{ simpleTypeRef = &(*i);
if (vflag)
cerr << "Found attribute " << (name?name:"") << " type " << (token?token:"") << endl;
break;
}
}
if (!simpleTypeRef)
{ for (vector<xs__import>::iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(type, s->targetNamespace);
if (token)
{ for (vector<xs__simpleType>::iterator j = s->simpleType.begin(); j != s->simpleType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ simpleTypeRef = &(*j);
if (vflag)
cerr << "Found attribute " << (name?name:"") << " type " << (token?token:"") << endl;
break;
}
}
if (simpleTypeRef)
break;
}
}
}
}
}
if (!attributeRef && !simpleTypeRef)
{ if (ref)
{ if (is_builtin_qname(ref))
schema.builtinAttribute(ref);
else
cerr << "Warning: could not find attribute '" << (name?name:"") << "' ref '" << ref << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
else if (type)
{ if (is_builtin_qname(type))
schema.builtinType(type);
else
cerr << "Warning: could not find attribute '" << (name?name:"") << "' type '" << type << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
}
return SOAP_OK;
}
void xs__attribute::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema* xs__attribute::schemaPtr() const
{ return schemaRef;
}
void xs__attribute::attributePtr(xs__attribute *attribute)
{ attributeRef = attribute;
}
void xs__attribute::simpleTypePtr(xs__simpleType *simpleType)
{ simpleTypeRef = simpleType;
}
xs__attribute *xs__attribute::attributePtr() const
{ return attributeRef;
}
xs__simpleType *xs__attribute::simpleTypePtr() const
{ return simpleTypeRef;
}
xs__element::xs__element()
{ schemaRef = NULL;
elementRef = NULL;
simpleTypeRef = NULL;
complexTypeRef = NULL;
}
int xs__element::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema element " << (name?name:"") << endl;
schemaRef = &schema;
const char *token = qname_token(ref, schema.targetNamespace);
elementRef = NULL;
if (token)
{ for (vector<xs__element>::iterator i = schema.element.begin(); i != schema.element.end(); ++i)
if (!strcmp((*i).name, token))
{ elementRef = &(*i);
if (vflag)
cerr << "Found element " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (!elementRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(ref, s->targetNamespace);
if (token)
{ for (vector<xs__element>::iterator j = s->element.begin(); j != s->element.end(); ++j)
{ if (!strcmp((*j).name, token))
{ elementRef = &(*j);
if (vflag)
cerr << "Found element " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (elementRef)
break;
}
}
}
}
if (simpleType)
{ simpleType->traverse(schema);
simpleTypeRef = simpleType;
}
else
{ token = qname_token(type, schema.targetNamespace);
simpleTypeRef = NULL;
if (token)
{ for (vector<xs__simpleType>::iterator i = schema.simpleType.begin(); i != schema.simpleType.end(); ++i)
if (!strcmp((*i).name, token))
{ simpleTypeRef = &(*i);
if (vflag)
cerr << "Found element " << (name?name:"") << " simpleType " << (token?token:"") << endl;
break;
}
}
if (!simpleTypeRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(type, s->targetNamespace);
if (token)
{ for (vector<xs__simpleType>::iterator j = s->simpleType.begin(); j != s->simpleType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ simpleTypeRef = &(*j);
if (vflag)
cerr << "Found element " << (name?name:"") << " simpleType " << (token?token:"") << endl;
break;
}
}
if (simpleTypeRef)
break;
}
}
}
}
}
if (complexType)
{ complexType->traverse(schema);
complexTypeRef = complexType;
}
else
{ token = qname_token(type, schema.targetNamespace);
complexTypeRef = NULL;
if (token)
{ for (vector<xs__complexType>::iterator i = schema.complexType.begin(); i != schema.complexType.end(); ++i)
if (!strcmp((*i).name, token))
{ complexTypeRef = &(*i);
if (vflag)
cerr << "Found element " << (name?name:"") << " complexType " << (token?token:"") << endl;
break;
}
}
if (!complexTypeRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(type, s->targetNamespace);
if (token)
{ for (vector<xs__complexType>::iterator j = s->complexType.begin(); j != s->complexType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ complexTypeRef = &(*j);
if (vflag)
cerr << "Found element " << (name?name:"") << " complexType " << (token?token:"") << endl;
break;
}
}
if (complexTypeRef)
break;
}
}
}
}
}
token = qname_token(substitutionGroup, schema.targetNamespace);
if (token)
{ for (vector<xs__element>::iterator i = schema.element.begin(); i != schema.element.end(); ++i)
if (!strcmp((*i).name, token))
{ (*i).substitutions.push_back(this);
if (vflag)
cerr << "Found substitutionGroup element " << (name?name:"") << " for abstract element " << (token?token:"") << endl;
break;
}
}
for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(substitutionGroup, s->targetNamespace);
if (token)
{ for (vector<xs__element>::iterator j = s->element.begin(); j != s->element.end(); ++j)
{ if (!strcmp((*j).name, token))
{ (*j).substitutions.push_back(this);
if (vflag)
cerr << "Found substitutionGroup element " << (name?name:"") << " for abstract element " << (token?token:"") << endl;
break;
}
}
}
}
}
if (!elementRef && !simpleTypeRef && !complexTypeRef)
{ if (ref)
{ if (is_builtin_qname(ref))
schema.builtinElement(ref);
else
cerr << "Warning: could not find element '" << (name?name:"") << "' ref '" << ref << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
else if (type)
{ if (is_builtin_qname(type))
schema.builtinType(type);
else
cerr << "Warning: could not find element '" << (name?name:"") << "' type '" << type << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
}
return SOAP_OK;
}
void xs__element::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema* xs__element::schemaPtr() const
{ return schemaRef;
}
void xs__element::elementPtr(xs__element *element)
{ elementRef = element;
}
void xs__element::simpleTypePtr(xs__simpleType *simpleType)
{ simpleTypeRef = simpleType;
}
void xs__element::complexTypePtr(xs__complexType *complexType)
{ complexTypeRef = complexType;
}
xs__element *xs__element::elementPtr() const
{ return elementRef;
}
const std::vector<xs__element*>* xs__element::substitutionsPtr() const
{ return &substitutions;
}
xs__simpleType *xs__element::simpleTypePtr() const
{ return simpleTypeRef;
}
xs__complexType *xs__element::complexTypePtr() const
{ return complexTypeRef;
}
xs__simpleType::xs__simpleType()
{ schemaRef = NULL;
level = 0;
}
int xs__simpleType::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema simpleType " << (name?name:"") << endl;
schemaRef = &schema;
if (list)
list->traverse(schema);
else if (restriction)
restriction->traverse(schema);
else if (union_)
union_->traverse(schema);
return SOAP_OK;
}
void xs__simpleType::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema *xs__simpleType::schemaPtr() const
{ return schemaRef;
}
int xs__simpleType::baseLevel()
{ if (!level)
{ if (restriction)
{ level = -1;
if (restriction->simpleTypePtr())
level = restriction->simpleTypePtr()->baseLevel() + 1;
else
level = 2;
}
else if (list && list->restriction)
{ level = -1;
if (list->restriction->simpleTypePtr())
level = list->restriction->simpleTypePtr()->baseLevel() + 1;
else
level = 2;
}
else
level = 1;
}
else if (level < 0)
{ cerr << "Warning: cyclic simpleType restriction/extension base dependency in '" << (name?name:"") << "'" << endl;
}
return level;
}
xs__complexType::xs__complexType()
{ schemaRef = NULL;
level = 0;
}
int xs__complexType::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema complexType " << (name?name:"") << endl;
schemaRef = &schema;
if (simpleContent)
simpleContent->traverse(schema);
else if (complexContent)
complexContent->traverse(schema);
else if (all)
all->traverse(schema);
else if (choice)
choice->traverse(schema);
else if (sequence)
sequence->traverse(schema);
else if (any)
any->traverse(schema);
for (vector<xs__attribute>::iterator at = attribute.begin(); at != attribute.end(); ++at)
(*at).traverse(schema);
for (vector<xs__attributeGroup>::iterator ag = attributeGroup.begin(); ag != attributeGroup.end(); ++ag)
(*ag).traverse(schema);
return SOAP_OK;
}
void xs__complexType::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema *xs__complexType::schemaPtr() const
{ return schemaRef;
}
int xs__complexType::baseLevel()
{ if (!level)
{ if (simpleContent)
{ if (simpleContent->restriction)
{ level = -1;
if (simpleContent->restriction->simpleTypePtr())
level = simpleContent->restriction->simpleTypePtr()->baseLevel() + 1;
else if (simpleContent->restriction->complexTypePtr())
level = simpleContent->restriction->complexTypePtr()->baseLevel() + 1;
else
level = 2;
}
else if (simpleContent->extension)
{ level = -1;
if (simpleContent->extension->simpleTypePtr())
level = simpleContent->extension->simpleTypePtr()->baseLevel() + 1;
else if (simpleContent->extension->complexTypePtr())
level = simpleContent->extension->complexTypePtr()->baseLevel() + 1;
else
level = 2;
}
}
else if (complexContent)
{ if (complexContent->restriction)
{ level = -1;
if (complexContent->restriction->simpleTypePtr())
level = complexContent->restriction->simpleTypePtr()->baseLevel() + 1;
else if (complexContent->restriction->complexTypePtr())
level = complexContent->restriction->complexTypePtr()->baseLevel() + 1;
else
level = 2;
}
else if (complexContent->extension)
{ level = -1;
if (complexContent->extension->simpleTypePtr())
level = complexContent->extension->simpleTypePtr()->baseLevel() + 1;
else if (complexContent->extension->complexTypePtr())
level = complexContent->extension->complexTypePtr()->baseLevel() + 1;
else
level = 2;
}
}
else
level = 1;
}
else if (level < 0)
{ cerr << "Warning: cyclic complexType restriction/extension base dependency in '" << (name?name:"") << "'" << endl;
}
return level;
}
int xs__simpleContent::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema simpleContent" << endl;
if (extension)
extension->traverse(schema);
else if (restriction)
restriction->traverse(schema);
return SOAP_OK;
}
int xs__complexContent::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema complexContent" << endl;
if (extension)
extension->traverse(schema);
else if (restriction)
restriction->traverse(schema);
return SOAP_OK;
}
xs__extension::xs__extension()
{ simpleTypeRef = NULL;
complexTypeRef = NULL;
}
int xs__extension::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema extension " << (base?base:"") << endl;
if (group)
group->traverse(schema);
else if (all)
all->traverse(schema);
else if (choice)
choice->traverse(schema);
else if (sequence)
sequence->traverse(schema);
for (vector<xs__attribute>::iterator at = attribute.begin(); at != attribute.end(); ++at)
(*at).traverse(schema);
for (vector<xs__attributeGroup>::iterator ag = attributeGroup.begin(); ag != attributeGroup.end(); ++ag)
(*ag).traverse(schema);
const char *token = qname_token(base, schema.targetNamespace);
simpleTypeRef = NULL;
if (token)
{ for (vector<xs__simpleType>::iterator i = schema.simpleType.begin(); i != schema.simpleType.end(); ++i)
if (!strcmp((*i).name, token))
{ simpleTypeRef = &(*i);
if (vflag)
cerr << "Found extension base type " << (token?token:"") << endl;
break;
}
}
if (!simpleTypeRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(base, s->targetNamespace);
if (token)
{ for (vector<xs__simpleType>::iterator j = s->simpleType.begin(); j != s->simpleType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ simpleTypeRef = &(*j);
if (vflag)
cerr << "Found extension base type " << (token?token:"") << endl;
break;
}
}
if (simpleTypeRef)
break;
}
}
}
}
token = qname_token(base, schema.targetNamespace);
complexTypeRef = NULL;
if (token)
{ for (vector<xs__complexType>::iterator i = schema.complexType.begin(); i != schema.complexType.end(); ++i)
if (!strcmp((*i).name, token))
{ complexTypeRef = &(*i);
if (vflag)
cerr << "Found extension base type " << (token?token:"") << endl;
break;
}
}
if (!complexTypeRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(base, s->targetNamespace);
if (token)
{ for (vector<xs__complexType>::iterator j = s->complexType.begin(); j != s->complexType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ complexTypeRef = &(*j);
if (vflag)
cerr << "Found extension base type " << (token?token:"") << endl;
break;
}
}
if (complexTypeRef)
break;
}
}
}
}
if (!simpleTypeRef && !complexTypeRef)
{ if (base)
{ if (is_builtin_qname(base))
schema.builtinType(base);
else
cerr << "Warning: could not find extension base type '" << base << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
else
cerr << "Extension has no base" << endl;
}
return SOAP_OK;
}
void xs__extension::simpleTypePtr(xs__simpleType *simpleType)
{ simpleTypeRef = simpleType;
}
void xs__extension::complexTypePtr(xs__complexType *complexType)
{ complexTypeRef = complexType;
}
xs__simpleType *xs__extension::simpleTypePtr() const
{ return simpleTypeRef;
}
xs__complexType *xs__extension::complexTypePtr() const
{ return complexTypeRef;
}
xs__restriction::xs__restriction()
{ simpleTypeRef = NULL;
complexTypeRef = NULL;
}
int xs__restriction::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema restriction " << (base?base:"") << endl;
if (group)
group->traverse(schema);
else if (all)
all->traverse(schema);
else if (choice)
choice->traverse(schema);
else if (sequence)
sequence->traverse(schema);
else
{ for (vector<xs__enumeration>::iterator en = enumeration.begin(); en != enumeration.end(); ++en)
(*en).traverse(schema);
for (vector<xs__pattern>::iterator pn = pattern.begin(); pn != pattern.end(); ++pn)
(*pn).traverse(schema);
}
for (vector<xs__attribute>::iterator at = attribute.begin(); at != attribute.end(); ++at)
(*at).traverse(schema);
const char *token = qname_token(base, schema.targetNamespace);
simpleTypeRef = NULL;
if (token)
{ for (vector<xs__simpleType>::iterator i = schema.simpleType.begin(); i != schema.simpleType.end(); ++i)
if (!strcmp((*i).name, token))
{ simpleTypeRef = &(*i);
if (vflag)
cerr << "Found restriction base type " << (token?token:"") << endl;
break;
}
}
if (!simpleTypeRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(base, s->targetNamespace);
if (token)
{ for (vector<xs__simpleType>::iterator j = s->simpleType.begin(); j != s->simpleType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ simpleTypeRef = &(*j);
if (vflag)
cerr << "Found restriction base type " << (token?token:"") << endl;
break;
}
}
if (simpleTypeRef)
break;
}
}
}
}
token = qname_token(base, schema.targetNamespace);
complexTypeRef = NULL;
if (token)
{ for (vector<xs__complexType>::iterator i = schema.complexType.begin(); i != schema.complexType.end(); ++i)
if (!strcmp((*i).name, token))
{ complexTypeRef = &(*i);
if (vflag)
cerr << "Found restriction base type " << (token?token:"") << endl;
break;
}
}
if (!complexTypeRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(base, s->targetNamespace);
if (token)
{ for (vector<xs__complexType>::iterator j = s->complexType.begin(); j != s->complexType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ complexTypeRef = &(*j);
if (vflag)
cerr << "Found restriction base type " << (token?token:"") << endl;
break;
}
}
if (complexTypeRef)
break;
}
}
}
}
if (!simpleTypeRef && !complexTypeRef)
{ if (base)
{ if (is_builtin_qname(base))
schema.builtinType(base);
else
cerr << "Warning: could not find restriction base type '" << base << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
else
cerr << "Restriction has no base" << endl;
}
return SOAP_OK;
}
void xs__restriction::simpleTypePtr(xs__simpleType *simpleType)
{ simpleTypeRef = simpleType;
}
void xs__restriction::complexTypePtr(xs__complexType *complexType)
{ complexTypeRef = complexType;
}
xs__simpleType *xs__restriction::simpleTypePtr() const
{ return simpleTypeRef;
}
xs__complexType *xs__restriction::complexTypePtr() const
{ return complexTypeRef;
}
xs__list::xs__list()
{ itemTypeRef = NULL;
}
int xs__list::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema list" << endl;
if (restriction)
restriction->traverse(schema);
for (vector<xs__simpleType>::iterator i = simpleType.begin(); i != simpleType.end(); ++i)
(*i).traverse(schema);
itemTypeRef = NULL;
const char *token = qname_token(itemType, schema.targetNamespace);
if (token)
{ for (vector<xs__simpleType>::iterator i = schema.simpleType.begin(); i != schema.simpleType.end(); ++i)
if (!strcmp((*i).name, token))
{ itemTypeRef = &(*i);
if (vflag)
cerr << "Found list itemType " << (token?token:"") << endl;
break;
}
}
if (!itemTypeRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(itemType, s->targetNamespace);
if (token)
{ for (vector<xs__simpleType>::iterator j = s->simpleType.begin(); j != s->simpleType.end(); ++j)
{ if (!strcmp((*j).name, token))
{ itemTypeRef = &(*j);
if (vflag)
cerr << "Found list itemType " << (token?token:"") << endl;
break;
}
}
if (itemTypeRef)
break;
}
}
}
}
if (itemType && !itemTypeRef)
{ if (is_builtin_qname(itemType))
schema.builtinType(itemType);
else
cerr << "Warning: could not find list itemType '" << itemType << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
return SOAP_OK;
}
void xs__list::itemTypePtr(xs__simpleType *simpleType)
{ itemTypeRef = simpleType;
}
xs__simpleType *xs__list::itemTypePtr() const
{ return itemTypeRef;
}
int xs__union::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema union" << endl;
for (vector<xs__simpleType>::iterator i = simpleType.begin(); i != simpleType.end(); ++i)
(*i).traverse(schema);
return SOAP_OK;
}
int xs__all::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema all" << endl;
for (vector<xs__element>::iterator i = element.begin(); i != element.end(); ++i)
(*i).traverse(schema);
return SOAP_OK;
}
xs__choice::xs__choice()
{ schemaRef = NULL;
}
int xs__choice::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema choice" << endl;
schemaRef = &schema;
for (vector<xs__group>::iterator gp = group.begin(); gp != group.end(); ++gp)
(*gp).traverse(schema);
for (vector<xs__choice>::iterator ch = choice.begin(); ch != choice.end(); ++ch)
(*ch).traverse(schema);
for (vector<xs__sequence*>::iterator sq = sequence.begin(); sq != sequence.end(); ++sq)
(*sq)->traverse(schema);
for (vector<xs__element>::iterator el = element.begin(); el != element.end(); ++el)
(*el).traverse(schema);
for (vector<xs__any>::iterator an = any.begin(); an != any.end(); ++an)
(*an).traverse(schema);
return SOAP_OK;
}
void xs__choice::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema *xs__choice::schemaPtr() const
{ return schemaRef;
}
int xs__sequence::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema sequence" << endl;
for (vector<xs__element>::iterator el = element.begin(); el != element.end(); ++el)
(*el).traverse(schema);
for (vector<xs__group>::iterator gp = group.begin(); gp != group.end(); ++gp)
(*gp).traverse(schema);
for (vector<xs__choice>::iterator ch = choice.begin(); ch != choice.end(); ++ch)
(*ch).traverse(schema);
for (vector<xs__sequence*>::iterator sq = sequence.begin(); sq != sequence.end(); ++sq)
(*sq)->traverse(schema);
for (vector<xs__any>::iterator an = any.begin(); an != any.end(); ++an)
(*an).traverse(schema);
return SOAP_OK;
}
xs__attributeGroup::xs__attributeGroup()
{ schemaRef = NULL;
attributeGroupRef = NULL;
}
int xs__attributeGroup::traverse(xs__schema& schema)
{ if (vflag)
cerr << "attributeGroup" << endl;
schemaRef = &schema;
for (vector<xs__attribute>::iterator at = attribute.begin(); at != attribute.end(); ++at)
(*at).traverse(schema);
for (vector<xs__attributeGroup>::iterator ag = attributeGroup.begin(); ag != attributeGroup.end(); ++ag)
(*ag).traverse(schema);
attributeGroupRef = NULL;
if (ref)
{ const char *token = qname_token(ref, schema.targetNamespace);
if (token)
{ for (vector<xs__attributeGroup>::iterator i = schema.attributeGroup.begin(); i != schema.attributeGroup.end(); ++i)
if (!strcmp((*i).name, token))
{ attributeGroupRef = &(*i);
if (vflag)
cerr << "Found attributeGroup " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (!attributeGroupRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(ref, s->targetNamespace);
if (token)
{ for (vector<xs__attributeGroup>::iterator j = s->attributeGroup.begin(); j != s->attributeGroup.end(); ++j)
{ if (!strcmp((*j).name, token))
{ attributeGroupRef = &(*j);
if (vflag)
cerr << "Found attribute Group " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (attributeGroupRef)
break;
}
}
}
}
if (!attributeGroupRef)
cerr << "Warning: could not find attributeGroup '" << (name?name:"") << "' ref '" << (ref?ref:"") << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
return SOAP_OK;
}
void xs__attributeGroup::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
void xs__attributeGroup::attributeGroupPtr(xs__attributeGroup *attributeGroup)
{ attributeGroupRef = attributeGroup;
}
xs__schema *xs__attributeGroup::schemaPtr() const
{ return schemaRef;
}
xs__attributeGroup *xs__attributeGroup::attributeGroupPtr() const
{ return attributeGroupRef;
}
int xs__any::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema any" << endl;
for (vector<xs__element>::iterator i = element.begin(); i != element.end(); ++i)
(*i).traverse(schema);
return SOAP_OK;
}
xs__group::xs__group()
{ schemaRef = NULL;
groupRef = NULL;
}
int xs__group::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema group" << endl;
schemaRef = &schema;
if (all)
all->traverse(schema);
else if (choice)
choice->traverse(schema);
else if (sequence)
sequence->traverse(schema);
groupRef = NULL;
if (ref)
{ const char *token = qname_token(ref, schema.targetNamespace);
if (token)
{ for (vector<xs__group>::iterator i = schema.group.begin(); i != schema.group.end(); ++i)
if (!strcmp((*i).name, token))
{ groupRef = &(*i);
if (vflag)
cerr << "Found group " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (!groupRef)
{ for (vector<xs__import>::const_iterator i = schema.import.begin(); i != schema.import.end(); ++i)
{ xs__schema *s = (*i).schemaPtr();
if (s)
{ token = qname_token(ref, s->targetNamespace);
if (token)
{ for (vector<xs__group>::iterator j = s->group.begin(); j != s->group.end(); ++j)
{ if (!strcmp((*j).name, token))
{ groupRef = &(*j);
if (vflag)
cerr << "Found group " << (name?name:"") << " ref " << (token?token:"") << endl;
break;
}
}
if (groupRef)
break;
}
}
}
}
if (!groupRef)
cerr << "Warning: could not find group '" << (name?name:"") << "' ref '" << (ref?ref:"") << "' in schema " << (schema.targetNamespace?schema.targetNamespace:"") << endl;
}
return SOAP_OK;
}
void xs__group::schemaPtr(xs__schema *schema)
{ schemaRef = schema;
}
xs__schema* xs__group::schemaPtr() const
{ return schemaRef;
}
void xs__group::groupPtr(xs__group *group)
{ groupRef = group;
}
xs__group* xs__group::groupPtr() const
{ return groupRef;
}
int xs__enumeration::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema enumeration" << endl;
return SOAP_OK;
}
int xs__pattern::traverse(xs__schema &schema)
{ if (vflag)
cerr << "Analyzing schema pattern" << endl;
return SOAP_OK;
}
////////////////////////////////////////////////////////////////////////////////
//
// I/O
//
////////////////////////////////////////////////////////////////////////////////
ostream &operator<<(ostream &o, const xs__schema &e)
{ if (!e.soap)
{ struct soap soap;
soap_init2(&soap, SOAP_IO_DEFAULT, SOAP_XML_TREE | SOAP_C_UTFSTRING);
soap_set_namespaces(&soap, namespaces);
e.soap_serialize(&soap);
soap_begin_send(&soap);
e.soap_out(&soap, "xs:schema", 0, NULL);
soap_end_send(&soap);
soap_end(&soap);
soap_done(&soap);
}
else
{ ostream *os = e.soap->os;
e.soap->os = &o;
e.soap_serialize(e.soap);
soap_begin_send(e.soap);
e.soap_out(e.soap, "xs:schema", 0, NULL);
soap_end_send(e.soap);
e.soap->os = os;
}
return o;
}
istream &operator>>(istream &i, xs__schema &e)
{ if (!e.soap)
{ e.soap = soap_new();
soap_set_namespaces(e.soap, namespaces);
}
istream *is = e.soap->is;
e.soap->is = &i;
if (soap_begin_recv(e.soap)
|| !e.soap_in(e.soap, "xs:schema", NULL)
|| soap_end_recv(e.soap))
{ // handle error? Note: e.soap->error is set and app should check
}
e.soap->is = is;
return i;
}
| 31.856445 | 184 | 0.596502 | [
"vector"
] |
fa37ed310b1fc3a40f6c7604fb2336d77082618e | 8,505 | cpp | C++ | OAuth2CppLib/src/OAuth2AuthServer.cpp | gvaduha/OAuth2CppLib | 385a5daf51fa11ba8a596b699d58cd74575e986b | [
"MIT"
] | 1 | 2015-02-10T03:28:30.000Z | 2015-02-10T03:28:30.000Z | OAuth2CppLib/src/OAuth2AuthServer.cpp | gvaduha/OAuth2CppLib | 385a5daf51fa11ba8a596b699d58cd74575e986b | [
"MIT"
] | null | null | null | OAuth2CppLib/src/OAuth2AuthServer.cpp | gvaduha/OAuth2CppLib | 385a5daf51fa11ba8a596b699d58cd74575e986b | [
"MIT"
] | 1 | 2021-02-09T14:49:28.000Z | 2021-02-09T14:49:28.000Z | #pragma once
#include "Types.h"
#include "Constants.h"
#include "Interfaces.h"
#include "OAuth2AuthServer.h"
#include <algorithm>
#include <sstream>
#include <vector>
#include "Helpers.h"
namespace OAuth2
{
using std::vector;
using std::istringstream;
using std::istream_iterator;
using namespace Helpers;
const string IClientAuthorizationFacade::authorizationFormMarker = "AUTORIZATIONFORM";
void make_error_response(const Errors::Code error, const string &msg, const IHttpRequest &request, IHttpResponse &response)
{
typedef std::pair<string, string> jsonpair_t;
response.setStatus(400);
response.addHeader("Content-type","application/json; charset=utf-8");
std::map<string, string> map;
map.insert(jsonpair_t(Params::error,Errors::getText(error)));
map.insert(jsonpair_t(Params::error_description,msg));
response.setBody(mapToJSON(map));
};
// ----- AuthorizationException -----
AuthorizationException::AuthorizationException(string const &message)
: std::logic_error(message)
{
}
AuthorizationException::AuthorizationException(string const &message, string const &info)
: std::logic_error(message), _error_info(info)
{
}
AuthorizationException::AuthorizationException(AuthorizationException const &rhs)
: std::logic_error(rhs), _error_info(rhs._error_info)
{
}
AuthorizationException& AuthorizationException::operator=(AuthorizationException const &rhs)
{
exception::operator=(rhs);
_error_info = rhs._error_info;
return *this;
}
AuthorizationException::~AuthorizationException()
{
}
// ----- ServerEndpoint -----
ServerEndpoint::request_can_be_processed_lambda::request_can_be_processed_lambda(const IHttpRequest &request)
: _request(request)
{
};
bool ServerEndpoint::request_can_be_processed_lambda::operator()(const IRequestProcessor *filter) const
{
return filter->canProcessRequest(_request);
}
ServerEndpoint::ServerEndpoint(RequestFiltersQueueType requestFilters, RequestProcessorsQueueType requestProcessors, ResponseFiltersQueueType responseFilters)
: _requestProcessors(requestProcessors), _requestFilters(requestFilters), _responseFilters(responseFilters)
{
};
ServerEndpoint::~ServerEndpoint()
{
for( RequestFiltersQueueType::const_iterator it = _requestFilters.begin(); it != _requestFilters.end(); ++it )
delete *it;
for( ResponseFiltersQueueType::const_iterator it = _responseFilters.begin(); it != _responseFilters.end(); ++it )
delete *it;
for( RequestProcessorsQueueType::const_iterator it = _requestProcessors.begin(); it != _requestProcessors.end(); ++it )
delete *it;
};
// ----- ServerEndpoint -----
Errors::Code ServerEndpoint::processRequest(IHttpRequest &request, IHttpResponse &response) const
{
// Preprocess request with filters
//std::for_each(_requestFilters->begin(), _requestFilters->end(), std::bind2nd( std::mem_fun_ref( &IRequestFilter::filter ), request ));
for(RequestFiltersQueueType::const_iterator it = _requestFilters.begin(); it != _requestFilters.end(); ++it)
(*it)->filter(request);
// Choose request processor
RequestProcessorsQueueType::const_iterator it = find_if(_requestProcessors.begin(), _requestProcessors.end(), request_can_be_processed_lambda(request));
if (it == _requestProcessors.end()) // Didn't find filter
{
make_error_response(Errors::Code::unsupported_grant_type, "don't find appropriate request processor", request, response);
return Errors::Code::unsupported_grant_type;
}
// Only first found processor will process request
string errorMsg;
if ( !(*it)->validateParameters(request, errorMsg) )
{
make_error_response(Errors::Code::invalid_request, errorMsg, request, response);
return Errors::Code::unsupported_grant_type;
}
Errors::Code ret = (*it)->processRequest(request, response);
// Postprocess response with filters
//std::for_each(_responseFilters->begin(), _responseFilters->end(), std::bind2nd( std::mem_fun_ref( &IResponseFilter::filter ), response ));
for(ResponseFiltersQueueType::const_iterator it = _responseFilters.begin(); it != _responseFilters.end(); ++it)
(*it)->filter(request, response);
return ret;
};
// ----- AuthorizationServer -----
AuthorizationServer::AuthorizationServer(ServerEndpoint* authorizationEndpoint, ServerEndpoint* tokenEndpoint)
: _authorizationEndpoint(authorizationEndpoint), _tokenEndpoint(tokenEndpoint)
{
if (!authorizationEndpoint || !tokenEndpoint)
throw AuthorizationException("Authorization server endpoints must not be null");
}
Errors::Code AuthorizationServer::authorizationEndpoint(IHttpRequest &request, IHttpResponse &response) const
{
return _authorizationEndpoint->processRequest(request, response);
};
Errors::Code AuthorizationServer::tokenEndpoint(IHttpRequest &request, IHttpResponse &response) const
{
return _tokenEndpoint->processRequest(request, response);
};
AuthorizationServer::~AuthorizationServer()
{
delete _authorizationEndpoint;
delete _tokenEndpoint;
};
// ----- StandardAuthorizationServerPolicies -----
size_t tokenizeString(const string &in, vector<string> &out) //HACK: Common library function
{
istringstream iss(in);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(out));
return out.size();
};
bool StandardAuthorizationServerPolicies::isScopeValid(const Scope &clientScope, const Scope &requestScope) const
{
return requestScope.isSubscopeOf(clientScope);
};
bool StandardAuthorizationServerPolicies::isValidCallbackUri(const Client &client, const string &uri) const
{
if (uri.empty())
return false;
//transform(uri.begin(), uri.end(), uri.begin(), tolower);
vector<string> tokens;
tokenizeString(client.redirectUri, tokens);
for(vector<string>::const_iterator it = tokens.begin(); it != tokens.end(); ++it)
if (uri == *it)
return true;
return false;
};
unsigned int StandardAuthorizationServerPolicies::generateNewRefreshTokenAfter() const
{
return _generateNewRefreshTokenAfter;
}
string StandardAuthorizationServerPolicies::getCallbackUri(const Client &client) const
{
vector <string> tokens;
return tokenizeString(client.redirectUri, tokens) ? tokens[0] : "";
};
// ----- ServiceLocator -----
ServiceLocator::ServiceList * ServiceLocator::_impl = NULL;
ServiceLocator::ServiceList::ServiceList(IUserAuthenticationFacade *uauthn, IClientAuthorizationFacade *cauthz, IClientAuthenticationFacade *cauthn
, IAuthorizationCodeManager *acmngr, ITokenGenerator *atgen, ITokenGenerator * rtgen
, IAuthorizationServerStorage *storage, IAuthorizationServerPolicies *policies, IUriHelperFactory *urihelperfac)
: UserAuthN(uauthn), ClientAuthZ(cauthz), ClientAuthN(cauthn), AuthCodeManager(acmngr)
, AccessTokenGenerator(atgen), RefreshTokenGenerator(rtgen), Storage(storage), AuthorizationServerPolicies(policies)
, UriHelperFactory(urihelperfac)
{
}
ServiceLocator::ServiceList::~ServiceList()
{
delete UserAuthN;
delete ClientAuthZ;
delete ClientAuthN;
delete AuthCodeManager;
delete AccessTokenGenerator;
delete RefreshTokenGenerator;
delete Storage;
delete AuthorizationServerPolicies;
delete UriHelperFactory;
}
//FRAGILE CODE: Should be revised every time ServiceList changed!
bool ServiceLocator::ServiceList::hasNullPtrs()
{
if (!this->AuthCodeManager || !this->AuthorizationServerPolicies || !this->ClientAuthN
|| !this->ClientAuthZ || !this->AccessTokenGenerator || !this->RefreshTokenGenerator || !this->Storage
|| !this->UserAuthN || !this->UriHelperFactory
)
return true;
else
return false;
}
const ServiceLocator::ServiceList * ServiceLocator::instance()
{
if (!ServiceLocator::_impl)
throw AuthorizationException("Service locator for AS not initialized. Call init first.");
return ServiceLocator::_impl;
};
// Init must be called before any access to Instance
void ServiceLocator::init(ServiceList *services)
{
if (services->hasNullPtrs())
{
delete services;
throw AuthorizationException("Can't initialize ServiceLocator with null values");
}
else
{
std::swap(_impl, services);
if (services)
delete services;
}
};
ServiceLocator::~ServiceLocator()
{
if (_impl)
delete _impl;
};
}; //namespace OAuth2
| 30.703971 | 158 | 0.735215 | [
"vector",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.