hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 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 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ca5fef96d6c71e371afbac6047fcbf7d6beb5198 | 5,407 | cxx | C++ | Src/Decimation/qslim-2.1/tools/qslim/main.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Decimation/qslim-2.1/tools/qslim/main.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Src/Decimation/qslim-2.1/tools/qslim/main.cxx | AspdenGroup/PeleAnalysis_Aspden | 4259efa97a65a646a4e1bc3493cd9dae1e7024c5 | [
"BSD-3-Clause-LBNL"
] | null | null | null | /************************************************************************
Main QSlim file.
Copyright (C) 1998 Michael Garland. See "COPYING.txt" for details.
$Id: main.cxx,v 1.1.1.1 2006/09/20 01:42:05 marc Exp $
************************************************************************/
#include <stdmix.h>
#include <mixio.h>
#include "qslim.h"
// Configuration variables and initial values
//
unsigned int face_target = 0;
bool will_use_fslim = false;
int placement_policy = MX_PLACE_OPTIMAL;
double boundary_weight = 1000.0;
int weighting_policy = MX_WEIGHT_AREA;
bool will_record_history = false;
double compactness_ratio = 0.0;
double meshing_penalty = 1.0;
bool will_join_only = false;
bool be_quiet = false;
OutputFormat output_format = SMF;
char *output_filename = NULL;
// Globally visible variables
//
MxSMFReader *smf = NULL;
MxStdModel *m = NULL;
MxStdModel *m_orig = NULL;
MxQSlim *slim = NULL;
MxEdgeQSlim *eslim = NULL;
MxFaceQSlim *fslim = NULL;
QSlimLog *history = NULL;
MxDynBlock<MxEdge> *target_edges = NULL;
const char *slim_copyright_notice =
"Copyright (C) 1998-2002 Michael Garland. See \"COPYING.txt\" for details.";
const char *slim_version_string = "2.1";
static ostream *output_stream = NULL;
static
bool qslim_smf_hook(char *op, int, char *argv[], MxStdModel& m)
{
if( streq(op, "e") )
{
if( !target_edges )
target_edges = new MxDynBlock<MxEdge>(m.vert_count() * 3);
MxEdge& e = target_edges->add();
e.v1 = atoi(argv[0]) - 1;
e.v2 = atoi(argv[1]) - 1;
return true;
}
return false;
}
bool (*unparsed_hook)(char *, int, char*[], MxStdModel&) = qslim_smf_hook;
void slim_print_banner(ostream& out)
{
out << "QSlim surface simplification software." << endl
<< "Version " << slim_version_string << " "
<< "[Built " << __DATE__ << "]." << endl
<< slim_copyright_notice << endl;
}
void slim_init()
{
if( !slim )
{
if( will_use_fslim )
slim = fslim = new MxFaceQSlim(*m);
else
slim = eslim = new MxEdgeQSlim(*m);
}
else
{
if( will_use_fslim )
fslim = (MxFaceQSlim *)slim;
else
eslim = (MxEdgeQSlim *)slim;
}
slim->placement_policy = placement_policy;
slim->boundary_weight = boundary_weight;
slim->weighting_policy = weighting_policy;
slim->compactness_ratio = compactness_ratio;
slim->meshing_penalty = meshing_penalty;
slim->will_join_only = will_join_only;
if( eslim && target_edges )
{
eslim->initialize(*target_edges, target_edges->length());
}
else
slim->initialize();
if( will_record_history )
{
if( !eslim )
mxmsg_signal(MXMSG_WARN,
"History only available for edge contractions.");
else
{
history = new QSlimLog(100);
eslim->contraction_callback = slim_history_callback;
}
}
}
#define CLEANUP(x) if(x) { delete x; x=NULL; }
void slim_cleanup()
{
CLEANUP(smf);
CLEANUP(m);
CLEANUP(slim);
eslim = NULL;
fslim = NULL;
CLEANUP(history);
CLEANUP(target_edges);
if( output_stream != &cout )
CLEANUP(output_stream);
}
static
void setup_output()
{
if( !output_stream )
{
if( output_filename )
output_stream = new ofstream(output_filename);
else
output_stream = &cout;
}
}
bool select_output_format(const char *fmt)
{
bool h = false;
if ( streq(fmt, "mmf") ) { output_format = MMF; h = true; }
else if( streq(fmt, "pm") ) { output_format = PM; h = true; }
else if( streq(fmt, "log") ) { output_format = LOG; h = true; }
else if( streq(fmt, "smf") ) output_format = SMF;
else if( streq(fmt, "iv") ) output_format = IV;
else if( streq(fmt, "vrml")) output_format = VRML;
else return false;
if( h ) will_record_history = true;
return true;
}
void output_preamble()
{
if( output_format==MMF || output_format==LOG )
output_current_model();
}
void output_current_model()
{
setup_output();
MxSMFWriter writer;
writer.write(*output_stream, *m);
}
static
void cleanup_for_output()
{
// First, mark stray vertices for removal
//
for(uint i=0; i<m->vert_count(); i++)
if( m->vertex_is_valid(i) && m->neighbors(i).length() == 0 )
m->vertex_mark_invalid(i);
// Compact vertex array so only valid vertices remain
m->compact_vertices();
}
void output_final_model()
{
setup_output();
switch( output_format )
{
case MMF:
output_regressive_mmf(*output_stream);
break;
case LOG:
output_regressive_log(*output_stream);
break;
case PM:
output_progressive_pm(*output_stream);
break;
case IV:
cleanup_for_output();
output_iv(*output_stream);
break;
case VRML:
cleanup_for_output();
output_vrml(*output_stream);
break;
case SMF:
cleanup_for_output();
output_current_model();
break;
}
}
void input_file(const char *filename)
{
if( streq(filename, "-") )
smf->read(cin, m);
else
{
ifstream in(filename);
if( !in.good() )
mxmsg_signal(MXMSG_FATAL, "Failed to open input file", filename);
smf->read(in, m);
in.close();
}
}
static
MxDynBlock<char*> files_to_include(2);
void defer_file_inclusion(char *filename)
{
files_to_include.add(filename);
}
void include_deferred_files()
{
for(uint i=0; i<files_to_include.length(); i++)
input_file(files_to_include[i]);
}
void slim_history_callback(const MxPairContraction& conx, float cost)
{
history->add(conx);
}
| 20.716475 | 77 | 0.64546 | AspdenGroup |
ca6066f57caf92d7c73421cabf138b9710992ac9 | 7,134 | hpp | C++ | water/cmath.hpp | watercpp/water | 7a9a292a2513529cf5dabac1bc7a755055dac9b5 | [
"MIT"
] | 5 | 2017-04-18T18:18:50.000Z | 2018-08-03T09:13:26.000Z | water/cmath.hpp | watercpp/water | 7a9a292a2513529cf5dabac1bc7a755055dac9b5 | [
"MIT"
] | null | null | null | water/cmath.hpp | watercpp/water | 7a9a292a2513529cf5dabac1bc7a755055dac9b5 | [
"MIT"
] | null | null | null | // Copyright 2017-2018 Johan Paulsson
// This file is part of the Water C++ Library. It is licensed under the MIT License.
// See the license.txt file in this distribution or https://watercpp.com/license.txt
//\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_
#ifndef WATER_CMATH_HPP
#define WATER_CMATH_HPP
#include <water/water.hpp>
#ifndef WATER_NO_CHEADERS
#include <cmath>
namespace water {
using ::std::fmod;
using ::std::frexp;
using ::std::log;
using ::std::log10;
using ::std::pow;
using ::std::isfinite;
using ::std::isinf;
using ::std::isnan;
using ::std::isnormal;
using ::std::signbit;
using ::std::fpclassify;
// isnormal = not 0, subnormal, infinity or nan. it may not work for subnormals when building without strict IEEE compliance, like -ffast-math
// isfinite = not nan or infinity
}
#else
#include <math.h>
namespace water {
// this is not needed if the math.h header is made for c++
inline float fmod(float a, float b) { return ::fmodf(a, b); }
inline double fmod(double a, double b) { return ::fmod(a, b); }
inline long double fmod(long double a, long double b) { return ::fmodl(a, b); }
inline float frexp(float a, int* b) { return ::frexpf(a, b); }
inline double frexp(double a, int* b) { return ::frexp(a, b); }
inline long double frexp(long double a, int* b) { return ::frexpl(a, b); }
inline float log(float a) { return ::logf(a); }
inline double log(double a) { return ::log(a); }
inline long double log(long double a) { return ::logl(a); }
inline float log10(float a) { return ::log10f(a); }
inline double log10(double a) { return ::log10(a); }
inline long double log10(long double a) { return ::log10l(a); }
inline float pow(float a, float b) { return ::powf(a, b); }
inline double pow(double a, double b) { return ::pow(a, b); }
inline long double pow(long double a, long double b) { return ::powl(a, b); }
}
#endif
#if !defined(WATER_CMATH_NO_SLOW_MATH) && (((defined(WATER_COMPILER_GCC) || defined(WATER_COMPILER_CLANG)) && defined(__FAST_MATH__)) || defined(WATER_CMATH_SLOW_MATH))
// On GCC and Clang with -ffast-math (enabled with -Ofast) isinf + isnan is optimized away to always return false.
// Sometimes fpclassify seems to work, not sure if it depends on the C library or GCC/Clang version.
// slow_math below should detect NaN and infinity for all types as long as one of them is a IEEE 754 / IEC 60559 32 bit or 64 bit type.
// The motivation for this is to be able to build with -ffast-math but still be able to sanitize floating point values
#include <water/int.hpp>
#include <water/numeric_limits.hpp>
#include <water/types/types.hpp>
namespace water {
namespace _ {
template<
typename float_,
unsigned bits_ = sizeof(float_) * numeric_limits<unsigned char>::digits,
typename unsigned_ = uint_bits<bits_>,
bool = (bits_ == 32 || bits_ == 64) && !types::is_void<unsigned_>::result && numeric_limits<float_>::is_iec559
>
struct slow_math
{
static bool constexpr can = true;
bool
finite = true,
normal = true,
infinity = false,
nan = false;
slow_math(float_ f) {
// 32 bit
// exponent 8 bits, 128 = 0, range -126 - 127
// fraction 23 bits
//
// 64 bit
// exponent 11 bits, 1023 = 0, range -1022 - 1023
// fraction 52 bits
unsigned constexpr
exponent_bits = bits_ == 32 ? 8 : 11,
fraction_bits = bits_ == 32 ? 23 : 52;
unsigned_ constexpr exponent_max = (1 << exponent_bits) - 1;
unsigned_ u = 0;
auto ub = static_cast<unsigned char*>(static_cast<void*>(&u));
auto fb = static_cast<unsigned char const*>(static_cast<void const*>(&f)), fe = fb + sizeof(f);
do *ub++ = *fb++; while(fb != fe);
unsigned_ exponent = (u >> fraction_bits) & exponent_max;
if(!exponent) // subnormal or 0
normal = false;
else if(exponent == exponent_max) { // infinity or nan
if(u & ((static_cast<unsigned_>(1) << fraction_bits) - 1)) // fraction not 0 == nan
nan = true;
else
infinity = true;
finite = normal = false;
}
}
};
template<typename float_, unsigned bits_, typename unsigned_>
struct slow_math<float_, bits_, unsigned_, false>
{
static bool constexpr can = false;
bool
finite = true,
normal = true,
infinity = false,
nan = false;
slow_math(float_ f) {
auto c = fpclassify(f);
if(c == FP_NAN)
nan = true;
else if(c == FP_INFINITE)
infinity = true;
else if(other(static_cast<double>(f), f) || other(static_cast<float>(f), f) || other(static_cast<long double>(f), f))
;
else if(f < -numeric_limits<float_>::max() || numeric_limits<float_>::max() < f) // will this be optimized away?
infinity = true;
else if(f != f) // will this be optimized away?
nan = true;
if(nan || infinity)
normal = finite = false;
else if(c == FP_ZERO || c == FP_SUBNORMAL || (-numeric_limits<float_>::min() < f && f < numeric_limits<float_>::min()))
normal = false;
}
private:
bool other(float_, float_) {
return false;
}
template<typename other_>
bool other(other_ o, float_ f) {
if(!slow_math<other_>::can)
return false;
auto s = slow_math<other_>{o};
if(s.nan)
nan = true;
if(s.infinity && static_cast<float_>(o) == f)
infinity = true;
return true;
}
};
}
template<typename float_>
bool isfinite_strict(float_ a) {
return _::slow_math<float_>{a}.finite;
}
template<typename float_>
bool isinf_strict(float_ a) {
return _::slow_math<float_>{a}.infinity;
}
template<typename float_>
bool isnan_strict(float_ a) {
return _::slow_math<float_>{a}.nan;
}
template<typename float_>
bool isnormal_strict(float_ a) {
return _::slow_math<float_>{a}.normal;
}
}
#else
namespace water {
// fpclassify seems less likley to be optimized away
template<typename float_>
bool isfinite_strict(float_ a) {
auto c = fpclassify(a);
return c != FP_INFINITE && c != FP_NAN;
}
template<typename float_>
bool isinf_strict(float_ a) {
return fpclassify(a) == FP_INFINITE;
}
template<typename float_>
bool isnan_strict(float_ a) {
return fpclassify(a) == FP_NAN;
}
template<typename float_>
bool isnormal_strict(float_ a) {
auto c = fpclassify(a);
return c != FP_INFINITE && c != FP_NAN && c != FP_ZERO && c != FP_SUBNORMAL;
}
}
#endif
#endif
| 32.135135 | 168 | 0.586207 | watercpp |
ca60e53e1af9091655a0f3e5461747ad89db7587 | 54 | hpp | C++ | addons/common/ui/script_component.hpp | JeffPerk/HavocTeam | 6fb616c41da4baece79ebac941bac72a78c715f9 | [
"MIT"
] | null | null | null | addons/common/ui/script_component.hpp | JeffPerk/HavocTeam | 6fb616c41da4baece79ebac941bac72a78c715f9 | [
"MIT"
] | 7 | 2021-11-22T04:36:52.000Z | 2021-12-13T18:55:24.000Z | addons/common/ui/script_component.hpp | JeffPerk/HavocTeam | 6fb616c41da4baece79ebac941bac72a78c715f9 | [
"MIT"
] | null | null | null | #include "\z\havoc\addons\common\script_component.hpp" | 54 | 54 | 0.814815 | JeffPerk |
ca61ff9a42d7076e2baffa1e949c520814dbd950 | 1,435 | cpp | C++ | src/core/Platform.cpp | GiorgioCaculli/Sokoban-Cpp | 96447016268d1a23a9cb2291480f851d0d5b90dc | [
"BSD-3-Clause"
] | null | null | null | src/core/Platform.cpp | GiorgioCaculli/Sokoban-Cpp | 96447016268d1a23a9cb2291480f851d0d5b90dc | [
"BSD-3-Clause"
] | null | null | null | src/core/Platform.cpp | GiorgioCaculli/Sokoban-Cpp | 96447016268d1a23a9cb2291480f851d0d5b90dc | [
"BSD-3-Clause"
] | null | null | null | #include <gzc/games/sokoban/core/Platform.hpp>
#include <sstream>
#include <iostream>
using namespace sokoban::core;
/**
* Default constructor for the platforms
* @param x The X coordinates on the board
* @param y The Y coordinates on the board
*/
Platform::Platform( float x, float y )
: Actor( x, y )
{
}
/**
* Copy constructor for the platform actor
* @param platform The platform we wish to copy the information from
*/
Platform::Platform( const Platform &platform )
: Platform( platform.get_x(), platform.get_y() )
{
}
/**
* Redefinition of the = operator
* @param platform The platform we wish to copy the information from
* @return New instance of a platform with the copied information
*/
Platform &Platform::operator=( const Platform &platform )
{
if ( &platform != this )
{
set_x( platform.get_x() );
set_y( platform.get_y() );
}
return *this;
}
/**
* Default destructor for the platforms
*/
Platform::~Platform()
= default;
/**
* Getter meant to retrieve the nature of a platform actor
* @return The fact that the actor is actually a platform
*/
Actor::ID Platform::get_type() const
{
return Actor::PLATFORM;
}
/**
* Textual output containing the platform's information
* @return Text containing the info
*/
std::string Platform::to_string() const
{
std::stringstream ss;
ss << "Platform: " << Actor::to_string();
return ss.str();
}
| 21.41791 | 68 | 0.671777 | GiorgioCaculli |
ca6419b9acb25bfe19a56a39f202357d48d11cc4 | 12,028 | cpp | C++ | src/services/pcn-loadbalancer-rp/src/Lbrp.cpp | francescomessina/polycube | 38f2fb4ffa13cf51313b3cab9994be738ba367be | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-10-02T23:09:42.000Z | 2019-10-02T23:09:42.000Z | src/services/pcn-loadbalancer-rp/src/Lbrp.cpp | l1b0k/polycube | 7af919245c131fa9fe24c5d39d10039cbb81e825 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/services/pcn-loadbalancer-rp/src/Lbrp.cpp | l1b0k/polycube | 7af919245c131fa9fe24c5d39d10039cbb81e825 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-09-02T10:05:14.000Z | 2019-09-02T10:05:14.000Z | /*
* Copyright 2018 The Polycube Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Modify these methods with your own implementation
#include "Lbrp.h"
#include "Lbrp_dp.h"
#include <tins/ethernetII.h>
#include <tins/tins.h>
using namespace Tins;
Lbrp::Lbrp(const std::string name, const LbrpJsonObject &conf)
: Cube(conf.getBase(), {lbrp_code}, {}) {
logger()->set_pattern("[%Y-%m-%d %H:%M:%S.%e] [Lbrp] [%n] [%l] %v");
logger()->info("Creating Lbrp instance");
addServiceList(conf.getService());
addSrcIpRewrite(conf.getSrcIpRewrite());
addPortsList(conf.getPorts());
}
Lbrp::~Lbrp() {}
void Lbrp::update(const LbrpJsonObject &conf) {
// This method updates all the object/parameter in Lbrp object specified in
// the conf JsonObject.
// You can modify this implementation.
Cube::set_conf(conf.getBase());
if (conf.serviceIsSet()) {
for (auto &i : conf.getService()) {
auto vip = i.getVip();
auto vport = i.getVport();
auto proto = i.getProto();
auto m = getService(vip, vport, proto);
m->update(i);
}
}
if (conf.srcIpRewriteIsSet()) {
auto m = getSrcIpRewrite();
m->update(conf.getSrcIpRewrite());
}
if (conf.portsIsSet()) {
for (auto &i : conf.getPorts()) {
auto name = i.getName();
auto m = getPorts(name);
m->update(i);
}
}
}
LbrpJsonObject Lbrp::toJsonObject() {
LbrpJsonObject conf;
conf.setBase(Cube::to_json());
for (auto &i : getServiceList()) {
conf.addService(i->toJsonObject());
}
conf.setSrcIpRewrite(getSrcIpRewrite()->toJsonObject());
for (auto &i : getPortsList()) {
conf.addPorts(i->toJsonObject());
}
return conf;
}
void Lbrp::packet_in(Ports &port, polycube::service::PacketInMetadata &md,
const std::vector<uint8_t> &packet) {
EthernetII eth(&packet[0], packet.size());
auto b_port = getBackendPort();
if (!b_port)
return;
// send the original packet
logger()->debug("Sending original ARP reply to backend port: {}",
b_port->name());
b_port->send_packet_out(eth);
// send a second packet for the virtual src IPs
ARP &arp = eth.rfind_pdu<ARP>();
uint32_t ip = uint32_t(arp.sender_ip_addr());
ip &= htonl(src_ip_rewrite_->mask);
ip |= htonl(src_ip_rewrite_->net);
IPv4Address addr(ip);
arp.sender_ip_addr(addr);
logger()->debug("Sending modified ARP reply to backend port: {}",
b_port->name());
b_port->send_packet_out(eth);
}
void Lbrp::reloadCodeWithNewPorts() {
uint16_t frontend_port = 0;
uint16_t backend_port = 1;
for (auto &it : get_ports()) {
switch (it->getType()) {
case PortsTypeEnum::FRONTEND:
frontend_port = it->index();
break;
case PortsTypeEnum::BACKEND:
backend_port = it->index();
break;
}
}
logger()->debug("Reloading code with frontend port: {0} and backend port {1}",
frontend_port, backend_port);
std::string frontend_port_str("#define FRONTEND_PORT " +
std::to_string(frontend_port));
std::string backend_port_str("#define BACKEND_PORT " +
std::to_string(backend_port));
reload(frontend_port_str + "\n" + backend_port_str + "\n" + lbrp_code);
logger()->trace("New lbrp code loaded");
}
std::shared_ptr<Ports> Lbrp::getFrontendPort() {
for (auto &it : get_ports()) {
if (it->getType() == PortsTypeEnum::FRONTEND) {
return it;
}
}
return nullptr;
}
std::shared_ptr<Ports> Lbrp::getBackendPort() {
for (auto &it : get_ports()) {
if (it->getType() == PortsTypeEnum::BACKEND) {
return it;
}
}
return nullptr;
}
std::shared_ptr<Ports> Lbrp::getPorts(const std::string &name) {
return get_port(name);
}
std::vector<std::shared_ptr<Ports>> Lbrp::getPortsList() {
return get_ports();
}
void Lbrp::addPorts(const std::string &name, const PortsJsonObject &conf) {
if (get_ports().size() == 2) {
logger()->warn("Reached maximum number of ports");
throw std::runtime_error("Reached maximum number of ports");
}
try {
switch (conf.getType()) {
case PortsTypeEnum::FRONTEND:
if (getFrontendPort() != nullptr) {
logger()->warn("There is already a FRONTEND port");
throw std::runtime_error("There is already a FRONTEND port");
}
break;
case PortsTypeEnum::BACKEND:
if (getBackendPort() != nullptr) {
logger()->warn("There is already a BACKEND port");
throw std::runtime_error("There is already a BACKEND port");
}
break;
}
} catch (std::runtime_error &e) {
logger()->warn("Error when adding the port {0}", name);
logger()->warn("Error message: {0}", e.what());
throw;
}
add_port<PortsJsonObject>(name, conf);
if (get_ports().size() == 2) {
logger()->info("Reloading code because of the new port");
reloadCodeWithNewPorts();
}
logger()->info("New port created with name {0}", name);
}
void Lbrp::addPortsList(const std::vector<PortsJsonObject> &conf) {
for (auto &i : conf) {
std::string name_ = i.getName();
addPorts(name_, i);
}
}
void Lbrp::replacePorts(const std::string &name, const PortsJsonObject &conf) {
delPorts(name);
std::string name_ = conf.getName();
addPorts(name_, conf);
}
void Lbrp::delPorts(const std::string &name) {
remove_port(name);
}
void Lbrp::delPortsList() {
auto ports = get_ports();
for (auto it : ports) {
delPorts(it->name());
}
}
std::shared_ptr<SrcIpRewrite> Lbrp::getSrcIpRewrite() {
return src_ip_rewrite_;
}
void Lbrp::addSrcIpRewrite(const SrcIpRewriteJsonObject &value) {
logger()->debug(
"[SrcIpRewrite] Received request to create SrcIpRewrite range {0} , new "
"ip range {1} ",
value.getIpRange(), value.getNewIpRange());
src_ip_rewrite_ = std::make_shared<SrcIpRewrite>(*this, value);
src_ip_rewrite_->update(value);
}
void Lbrp::replaceSrcIpRewrite(const SrcIpRewriteJsonObject &conf) {
delSrcIpRewrite();
addSrcIpRewrite(conf);
}
void Lbrp::delSrcIpRewrite() {
// what the hell means to remove entry in this case?
}
std::shared_ptr<Service> Lbrp::getService(const std::string &vip,
const uint16_t &vport,
const ServiceProtoEnum &proto) {
// This method retrieves the pointer to Service object specified by its keys.
logger()->debug("[Service] Received request to read a service entry");
logger()->debug("[Service] Virtual IP: {0}, virtual port: {1}, protocol: {2}",
vip, vport,
ServiceJsonObject::ServiceProtoEnum_to_string(proto));
uint16_t vp = vport;
if (Service::convertProtoToNumber(proto) == 1)
vp = vport;
Service::ServiceKey key =
Service::ServiceKey(vip, vp, Service::convertProtoToNumber(proto));
if (service_map_.count(key) == 0) {
logger()->error("[Service] There are no entries associated with that key");
throw std::runtime_error("There are no entries associated with that key");
}
return std::shared_ptr<Service>(&service_map_.at(key), [](Service *) {});
}
std::vector<std::shared_ptr<Service>> Lbrp::getServiceList() {
std::vector<std::shared_ptr<Service>> services_vect;
for (auto &it : service_map_) {
Service::ServiceKey key = it.first;
services_vect.push_back(
getService(std::get<0>(key), std::get<1>(key),
Service::convertNumberToProto(std::get<2>(key))));
}
return services_vect;
}
void Lbrp::addService(const std::string &vip, const uint16_t &vport,
const ServiceProtoEnum &proto,
const ServiceJsonObject &conf) {
logger()->debug("[Service] Received request to create new service entry");
logger()->debug("[Service] Virtual IP: {0}, virtual port: {1}, protocol: {2}",
vip, vport,
ServiceJsonObject::ServiceProtoEnum_to_string(proto));
if (proto == ServiceProtoEnum::ALL) {
// Let's create 3 different services for TCP, UDP and ICMP
// Let's start from TCP
ServiceJsonObject new_conf(conf);
new_conf.setProto(ServiceProtoEnum::TCP);
addService(vip, vport, ServiceProtoEnum::TCP, new_conf);
// Now is the UDP turn
new_conf.setProto(ServiceProtoEnum::UDP);
addService(vip, vport, ServiceProtoEnum::UDP, new_conf);
// Finally, is ICMP turn. For ICMP we use a "special" port since this field
// is useless
new_conf.setProto(ServiceProtoEnum::ICMP);
new_conf.setVport(Service::ICMP_EBPF_PORT);
addService(vip, Service::ICMP_EBPF_PORT, ServiceProtoEnum::ICMP, new_conf);
// We completed all task, let's directly return since we do not have to
// execute the code below
return;
} else if (proto == ServiceProtoEnum::ICMP &&
conf.getVport() != Service::ICMP_EBPF_PORT) {
throw std::runtime_error(
"ICMP Service requires 0 as virtual port. Since this parameter is "
"useless for ICMP services");
}
}
void Lbrp::addServiceList(const std::vector<ServiceJsonObject> &conf) {
for (auto &i : conf) {
std::string vip_ = i.getVip();
uint16_t vport_ = i.getVport();
ServiceProtoEnum proto_ = i.getProto();
addService(vip_, vport_, proto_, i);
}
}
void Lbrp::replaceService(const std::string &vip, const uint16_t &vport,
const ServiceProtoEnum &proto,
const ServiceJsonObject &conf) {
delService(vip, vport, proto);
std::string vip_ = conf.getVip();
uint16_t vport_ = conf.getVport();
ServiceProtoEnum proto_ = conf.getProto();
addService(vip_, vport_, proto_, conf);
}
void Lbrp::delService(const std::string &vip, const uint16_t &vport,
const ServiceProtoEnum &proto) {
if (proto == ServiceProtoEnum::ALL) {
// Let's create 3 different services for TCP, UDP and ICMP
// Let's start from TCP
delService(vip, vport, ServiceProtoEnum::TCP);
// Now is the UDP turn
delService(vip, vport, ServiceProtoEnum::UDP);
// Finally, is ICMP turn. For ICMP we use a "special" port since this field
// is useless
delService(vip, Service::ICMP_EBPF_PORT, ServiceProtoEnum::ICMP);
// We completed all task, let's directly return since we do not have to
// execute the code below
return;
} else if (proto == ServiceProtoEnum::ICMP &&
vport != Service::ICMP_EBPF_PORT) {
throw std::runtime_error(
"ICMP Service requires 0 as virtual port. Since this parameter is "
"useless for ICMP services");
}
logger()->debug("[Service] Received request to delete a service entry");
logger()->debug("[Service] Virtual IP: {0}, virtual port: {1}, protocol: {2}",
vip, vport,
ServiceJsonObject::ServiceProtoEnum_to_string(proto));
Service::ServiceKey key =
Service::ServiceKey(vip, vport, Service::convertProtoToNumber(proto));
if (service_map_.count(key) == 0) {
logger()->error("[Service] There are no entries associated with that key");
throw std::runtime_error("There are no entries associated with that key");
}
auto service = getService(vip, vport, proto);
service->removeServiceFromKernelMap();
service_map_.erase(key);
}
void Lbrp::delServiceList() {
for (auto it = service_map_.begin(); it != service_map_.end();) {
auto tmp = it;
it++;
delService(tmp->second.getVip(), tmp->second.getVport(),
tmp->second.getProto());
}
} | 30.605598 | 80 | 0.647406 | francescomessina |
ca646a7722c5f56c31892659460ea273df62f7df | 12,114 | cpp | C++ | src/pk.cpp | tjahn/mbedcrypto | 23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425 | [
"MIT"
] | 40 | 2016-04-01T15:20:24.000Z | 2022-03-24T08:38:12.000Z | src/pk.cpp | tjahn/mbedcrypto | 23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425 | [
"MIT"
] | 4 | 2017-12-12T09:04:38.000Z | 2021-01-30T04:19:05.000Z | src/pk.cpp | tjahn/mbedcrypto | 23ea27d1d7602e0f2c4e8c8c148b73ca7b4f1425 | [
"MIT"
] | 15 | 2016-07-22T02:46:23.000Z | 2020-12-23T15:57:37.000Z | #include "mbedcrypto/pk.hpp"
#include "mbedcrypto/hash.hpp"
#include "./pk_private.hpp"
//-----------------------------------------------------------------------------
namespace mbedcrypto {
namespace pk {
//-----------------------------------------------------------------------------
static_assert(std::is_copy_constructible<context>::value == false, "");
static_assert(std::is_move_constructible<context>::value == true, "");
//-----------------------------------------------------------------------------
namespace {
//-----------------------------------------------------------------------------
// constants
enum K {
DefaultExportBufferSize = 16000,
};
struct larger_than_key : public exceptions::usage_error {
larger_than_key()
: exceptions::usage_error(
"the input value is larger than max_crypt_size()") {}
}; // struct larger_than_key
void
check_crypt_size_of(const context& pk, buffer_view_t in) {
if ( in.size() > max_crypt_size(pk))
throw larger_than_key{};
}
void
finalize_pem(buffer_t& pem) {
pem.push_back('\0');
}
void
reset_as_impl(context& d, pk_t ptype) {
reset(d);
mbedcrypto_c_call(mbedtls_pk_setup, &d.pk_, native_info(ptype));
}
bool
check_rsa_conversion(pk_t ptype) {
switch (ptype) {
case pk_t::rsa:
case pk_t::rsa_alt:
case pk_t::rsassa_pss:
return true;
default:
return false;
}
}
bool
check_ec_conversion(pk_t ptype) {
switch (ptype) {
case pk_t::eckey:
case pk_t::eckey_dh:
case pk_t::ecdsa:
return true;
default:
return false;
}
}
void
ensure_type_match(context& d, pk_t old_type, pk_t new_type) {
switch (old_type) {
case pk_t::rsa:
case pk_t::rsa_alt:
case pk_t::rsassa_pss:
if (!check_rsa_conversion(new_type)) {
reset_as_impl(d, old_type);
throw exceptions::type_error{};
}
break;
case pk_t::eckey:
case pk_t::eckey_dh:
case pk_t::ecdsa:
if (!check_ec_conversion(new_type)) {
reset_as_impl(d, old_type);
throw exceptions::type_error{};
}
break;
default:
break;
}
}
//-----------------------------------------------------------------------------
} // namespace anon
//-----------------------------------------------------------------------------
void
reset(context& d) noexcept {
d.key_is_private_ = false;
mbedtls_pk_free(&d.pk_);
}
void
reset_as(context& d, pk_t ptype) {
// is ptype compatible with current context?
ensure_type_match(d, type_of(d), ptype);
reset_as_impl(d, ptype);
}
pk_t
type_of(const context& d) {
return from_native(mbedtls_pk_get_type(&d.pk_));
}
const char*
name_of(const context& d) noexcept {
return mbedtls_pk_get_name(&d.pk_);
}
size_t
key_length(const context& d) noexcept {
return (size_t)mbedtls_pk_get_len(&d.pk_);
}
size_t
key_bitlen(const context& d) noexcept {
return (size_t)mbedtls_pk_get_bitlen(&d.pk_);
}
size_t
max_crypt_size(const context& d) {
// padding / header data (11 bytes for PKCS#1 v1.5 padding).
if (type_of(d) == pk_t::rsa)
return key_length(d) - 11;
#if defined(MBEDTLS_ECDSA_C)
else if (can_do(d, pk_t::ecdsa))
return (size_t)MBEDTLS_ECDSA_MAX_LEN;
#endif
throw exceptions::support_error{};
}
bool
has_private_key(const context& d) noexcept {
return d.key_is_private_;
}
bool
can_do(const context& d, pk_t ptype) {
int ret = mbedtls_pk_can_do(&d.pk_, to_native(ptype));
// refinement due to build options
if (type_of(d) == pk_t::eckey && ptype == pk_t::ecdsa) {
if (!supports(pk_t::ecdsa))
ret = 0;
}
return ret == 1;
}
action_flags
what_can_do(const context& d) {
pk::action_flags f{false, false, false, false};
if (d.pk_.pk_info != nullptr && key_bitlen(d) > 0) {
const auto* info = d.pk_.pk_info;
f.encrypt = info->encrypt_func != nullptr;
f.decrypt = info->decrypt_func != nullptr;
f.sign = info->sign_func != nullptr;
f.verify = info->verify_func != nullptr;
// refine due to pub/priv key
// pub keys can not sign, nor decrypt
switch (type_of(d)) {
case pk_t::rsa:
if (!d.key_is_private_)
f.decrypt = f.sign = false;
break;
case pk_t::eckey:
case pk_t::ecdsa:
if (!d.key_is_private_)
f.sign = false;
break;
default:
break;
}
}
return f;
}
bool
check_pair(const context& pub, const context& priv) {
int ret = mbedtls_pk_check_pair(&pub.pk_, &priv.pk_);
switch (ret) {
case 0:
return true;
case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
case MBEDTLS_ERR_PK_TYPE_MISMATCH:
throw exception{ret, __FUNCTION__};
break;
default:
return false;
break;
}
}
void
import_key(context& d, buffer_view_t priv_data, buffer_view_t pass) {
auto old_type = type_of(d);
reset(d);
mbedcrypto_c_call(
mbedtls_pk_parse_key,
&d.pk_,
priv_data.data(),
priv_data.size(),
pass.data(),
pass.size());
// check the key type
ensure_type_match(d, old_type, type_of(d));
d.key_is_private_ = true;
}
void
import_public_key(context& d, buffer_view_t pub_data) {
auto old_type = type_of(d);
reset(d);
mbedcrypto_c_call(
mbedtls_pk_parse_public_key,
&d.pk_,
pub_data.data(),
pub_data.size());
// check the key type
ensure_type_match(d, old_type, type_of(d));
d.key_is_private_ = false;
}
void
load_key(context& d, const char* fpath, const char* pass) {
auto old_type = type_of(d);
reset(d);
mbedcrypto_c_call(mbedtls_pk_parse_keyfile, &d.pk_, fpath, pass);
// check the key type
ensure_type_match(d, old_type, type_of(d));
d.key_is_private_ = true;
}
void
load_public_key(context& d, const char* fpath) {
auto old_type = type_of(d);
reset(d);
mbedcrypto_c_call(mbedtls_pk_parse_public_keyfile, &d.pk_, fpath);
// check the key type
ensure_type_match(d, old_type, type_of(d));
d.key_is_private_ = false;
}
buffer_t
export_key(context& d, key_format fmt) {
#if defined(MBEDTLS_PK_WRITE_C)
buffer_t output(K::DefaultExportBufferSize, '\0');
if (fmt == pem_format) {
mbedcrypto_c_call(
mbedtls_pk_write_key_pem,
&d.pk_,
to_ptr(output),
K::DefaultExportBufferSize);
output.resize(std::strlen(output.c_str()));
finalize_pem(output);
} else if (fmt == pk::der_format) {
int ret = mbedtls_pk_write_key_der(
&d.pk_, to_ptr(output), K::DefaultExportBufferSize);
if (ret < 0)
throw exception{ret, __FUNCTION__};
size_t length = ret;
output.erase(0, K::DefaultExportBufferSize - length);
output.resize(length);
}
return output;
#else // MBEDTLS_PK_WRITE_C
throw exceptions::pk_export_missed{};
#endif // MBEDTLS_PK_WRITE_C
}
buffer_t
export_public_key(context& d, key_format fmt) {
#if defined(MBEDTLS_PK_WRITE_C)
buffer_t output(K::DefaultExportBufferSize, '\0');
if (fmt == pk::pem_format) {
mbedcrypto_c_call(
mbedtls_pk_write_pubkey_pem,
&d.pk_,
to_ptr(output),
K::DefaultExportBufferSize);
output.resize(std::strlen(output.c_str()));
finalize_pem(output);
} else if (fmt == pk::der_format) {
int ret = mbedtls_pk_write_pubkey_der(
&d.pk_, to_ptr(output), K::DefaultExportBufferSize);
if (ret < 0)
throw exception{ret, __FUNCTION__};
size_t length = ret;
output.erase(0, K::DefaultExportBufferSize - length);
output.resize(length);
}
return output;
#else // MBEDTLS_PK_WRITE_C
throw exceptions::pk_export_missed{};
#endif // MBEDTLS_PK_WRITE_C
}
bool
supports_key_export() noexcept {
#if defined(MBEDTLS_PK_WRITE_C)
return true;
#else // MBEDTLS_PK_WRITE_C
return false;
#endif // MBEDTLS_PK_WRITE_C
}
bool
supports_rsa_keygen() noexcept {
#if defined(MBEDTLS_GENPRIME)
return true;
#else
return false;
#endif
}
bool
supports_ec_keygen() noexcept {
#if defined(MBEDTLS_ECP_C)
return true;
#else
return false;
#endif
}
void
generate_rsa_key(context& d, size_t key_bitlen, size_t exponent) {
#if defined(MBEDTLS_GENPRIME)
// resets previous states
pk::reset_as(d, pk_t::rsa);
mbedcrypto_c_call(
mbedtls_rsa_gen_key,
mbedtls_pk_rsa(d.pk_),
rnd_generator::maker,
&d.rnd_,
static_cast<unsigned int>(key_bitlen),
static_cast<int>(exponent));
// set the key type
d.key_is_private_ = true;
#else // MBEDTLS_GENPRIME
throw exceptions::rsa_keygen_missed{};
#endif // MBEDTLS_GENPRIME
}
void
generate_ec_key(context& d, curve_t ctype) {
#if defined(MBEDTLS_ECP_C)
// resets previous states
pk::reset_as(d, pk_t::eckey);
mbedcrypto_c_call(
mbedtls_ecp_gen_key,
to_native(ctype),
mbedtls_pk_ec(d.pk_),
rnd_generator::maker,
&d.rnd_);
// set the key type
d.key_is_private_ = true;
#else // MBEDTLS_ECP_C
throw exceptions::ecp_missed{};
#endif // MBEDTLS_ECP_C
}
buffer_t
sign(context& d, buffer_view_t hvalue, hash_t halgo) {
if (type_of(d) != pk_t::rsa && !can_do(d, pk_t::ecdsa))
throw exceptions::support_error{};
check_crypt_size_of(d, hvalue);
size_t olen = 32 + max_crypt_size(d);
buffer_t output(olen, '\0');
mbedcrypto_c_call(
mbedtls_pk_sign,
&d.pk_,
to_native(halgo),
hvalue.data(),
hvalue.size(),
to_ptr(output),
&olen,
rnd_generator::maker,
&d.rnd_);
output.resize(olen);
return output;
}
bool
verify(
context& d, buffer_view_t signature, buffer_view_t hvalue, hash_t halgo) {
if (type_of(d) != pk_t::rsa && !can_do(d, pk_t::ecdsa))
throw exceptions::support_error{};
check_crypt_size_of(d, hvalue);
int ret = mbedtls_pk_verify(
&d.pk_,
to_native(halgo),
hvalue.data(),
hvalue.size(),
signature.data(),
signature.size());
// TODO: check when to report other errors
switch (ret) {
case 0:
return true;
case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
case MBEDTLS_ERR_PK_TYPE_MISMATCH:
throw exception{ret, "failed to verify the signature"};
break;
default:
break;
}
return false;
}
buffer_t
encrypt(context& d, buffer_view_t source) {
if (type_of(d) != pk_t::rsa)
throw exceptions::support_error{};
check_crypt_size_of(d, source);
size_t olen = 32 + max_crypt_size(d);
buffer_t output(olen, '\0');
mbedcrypto_c_call(
mbedtls_pk_encrypt,
&d.pk_,
source.data(),
source.size(),
to_ptr(output),
&olen,
olen,
rnd_generator::maker,
&d.rnd_);
output.resize(olen);
return output;
}
buffer_t
decrypt(context& d, buffer_view_t encrypted_value) {
if (type_of(d) != pk_t::rsa)
throw exceptions::support_error{};
if ((encrypted_value.size() << 3) > key_bitlen(d))
throw larger_than_key{};
size_t olen = 32 + max_crypt_size(d);
buffer_t output(olen, '\0');
mbedcrypto_c_call(
mbedtls_pk_decrypt,
&d.pk_,
encrypted_value.data(),
encrypted_value.size(),
to_ptr(output),
&olen,
olen,
rnd_generator::maker,
&d.rnd_);
output.resize(olen);
return output;
}
//-----------------------------------------------------------------------------
rnd_generator&
pk_base::rnd() {
return context().rnd_;
}
//-----------------------------------------------------------------------------
} // namespace pk
} // namespace mbedcrypto
//-----------------------------------------------------------------------------
| 22.856604 | 79 | 0.586264 | tjahn |
ca67342f1bf4fc8fd50302e0c131e91b518a2dd6 | 1,887 | cpp | C++ | src/ScriptInterface/TitleFormat.cpp | marc2k3/foo_jscript_panel | 3bc2dedd8c0961993bd3a13ddd4e69f4c6832cdb | [
"MIT"
] | 139 | 2017-12-22T12:53:03.000Z | 2022-03-01T08:27:25.000Z | src/ScriptInterface/TitleFormat.cpp | marc2k3/foo_jscript_panel | 3bc2dedd8c0961993bd3a13ddd4e69f4c6832cdb | [
"MIT"
] | 48 | 2018-01-14T17:21:19.000Z | 2020-02-01T16:32:18.000Z | src/ScriptInterface/TitleFormat.cpp | marc2k3/foo_jscript_panel | 3bc2dedd8c0961993bd3a13ddd4e69f4c6832cdb | [
"MIT"
] | 27 | 2017-12-23T10:23:13.000Z | 2022-03-22T10:50:37.000Z | #include "stdafx.h"
#include "TitleFormat.h"
TitleFormat::TitleFormat(const std::wstring& pattern)
{
const string8 upattern = from_wide(pattern);
titleformat_compiler::get()->compile_safe(m_obj, upattern);
}
STDMETHODIMP TitleFormat::get__ptr(void** out)
{
if (!out) return E_POINTER;
*out = m_obj.get_ptr();
return S_OK;
}
STDMETHODIMP TitleFormat::Eval(BSTR* out)
{
if (m_obj.is_empty() || !out) return E_POINTER;
string8 str;
playback_control::get()->playback_format_title(nullptr, str, m_obj, nullptr, playback_control::display_level_all);
*out = to_bstr(str);
return S_OK;
}
STDMETHODIMP TitleFormat::EvalActivePlaylistItem(UINT playlistItemIndex, BSTR* out)
{
if (m_obj.is_empty() || !out) return E_POINTER;
string8 str;
Plman::theAPI()->activeplaylist_item_format_title(playlistItemIndex, nullptr, str, m_obj, nullptr, playback_control::display_level_all);
*out = to_bstr(str);
return S_OK;
}
STDMETHODIMP TitleFormat::EvalWithMetadb(IMetadbHandle* handle, BSTR* out)
{
if (m_obj.is_empty() || !out) return E_POINTER;
metadb_handle* ptr = nullptr;
GET_PTR(handle, ptr);
string8 str;
ptr->format_title(nullptr, str, m_obj, nullptr);
*out = to_bstr(str);
return S_OK;
}
STDMETHODIMP TitleFormat::EvalWithMetadbs(IMetadbHandleList* handles, VARIANT* out)
{
if (m_obj.is_empty() || !out) return E_POINTER;
metadb_handle_list* handles_ptr = nullptr;
GET_PTR(handles, handles_ptr);
const uint32_t count = handles_ptr->get_count();
ComArrayWriter writer;
if (!writer.create(count)) return E_OUTOFMEMORY;
for (const uint32_t i : std::views::iota(0U, count))
{
string8 str;
handles_ptr->get_item(i)->format_title(nullptr, str, m_obj, nullptr);
if (!writer.put_item(i, str)) return E_OUTOFMEMORY;
}
out->vt = VT_ARRAY | VT_VARIANT;
out->parray = writer.get_ptr();
return S_OK;
}
void TitleFormat::FinalRelease()
{
m_obj.release();
}
| 24.192308 | 137 | 0.738209 | marc2k3 |
ca6e22c41d1eddb977506f02d5c727cbac0634cf | 340 | cpp | C++ | luogu/P6159.cpp | wznmickey/StudyInUMSJTU-JI | d4111de5995bfae06cd606464979c52ae631b8fb | [
"MIT"
] | 1 | 2020-12-09T09:09:09.000Z | 2020-12-09T09:09:09.000Z | luogu/P6159.cpp | wznmickey/StudyInUMSJTU-JI | d4111de5995bfae06cd606464979c52ae631b8fb | [
"MIT"
] | null | null | null | luogu/P6159.cpp | wznmickey/StudyInUMSJTU-JI | d4111de5995bfae06cd606464979c52ae631b8fb | [
"MIT"
] | 1 | 2021-11-28T11:41:36.000Z | 2021-11-28T11:41:36.000Z | #include <bits/stdc++.h>
using namespace std;
long long n, p, k, now, temp;
int main()
{
scanf("%lld%lld%lld", &n, &p, &k);
/*
now = 0;
for (int i = 0; i < k; i++)
{
temp = ((p + n - now) % n + p) % n;
now = p;
p = temp;
}
printf("%d", now);
*/
printf("%d",p*k%n);
return 0;
} | 17.894737 | 43 | 0.405882 | wznmickey |
ca797b779007981051fe156c68850c3b37152ce9 | 1,379 | cpp | C++ | Source Code/05_functions_and_random/05_04.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | 2 | 2017-03-18T22:04:47.000Z | 2017-03-30T23:24:53.000Z | Source Code/05_functions_and_random/05_04.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | null | null | null | Source Code/05_functions_and_random/05_04.cpp | rushone2010/CS_A150 | 0acab19e69c051f67b8dafe904ca77de0431958d | [
"MIT"
] | null | null | null | // Computes the area of a circle with the radius given and
// the volume of a sphere with the radius given.
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 3.14159;
double area(double radius);
// area - Computes the area of a circle with the radius given.
// @param double - The radius of the circle.
// @return double - The area of the circle.
double volume(double radius);
// volume - Computes the volume of a sphere with the radius given.
// @param double - The radius of the sphere.
// @return double - The volume of the sphere.
int main()
{
double radiusOfBoth;
cout << "Enter a radius to use for both a circle\n"
<< "and a sphere (in inches): ";
cin >> radiusOfBoth;
double areaOfCircle = area(radiusOfBoth);
double volumeOfSphere = volume(radiusOfBoth);
cout << "\nRadius = " << radiusOfBoth << " inches\n"
<< "Area of circle = " << areaOfCircle
<< " square inches\n"
<< "Volume of sphere = " << volumeOfSphere
<< " cubic inches\n";
cout << endl;
cin.ignore();
cin.get();
return 0;
}
double area(double radius)
{
// formula for area of a circle: (PI * r^2)
return (PI * radius * radius);
}
double volume(double radius)
{
// formula for volume of a sphere: ((4/3) * PI * r^2)
return ((4.0/3.0) * PI * pow(radius, 3));
}
| 25.537037 | 67 | 0.622915 | rushone2010 |
ca7b6718574b0b2e80980fe993f72ae8d641c699 | 1,161 | cpp | C++ | nowcoder/contests/浙城校赛/C.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | 1 | 2020-08-10T21:40:21.000Z | 2020-08-10T21:40:21.000Z | nowcoder/contests/浙城校赛/C.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | nowcoder/contests/浙城校赛/C.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | #include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#define ll long long
#define F(i,a,b) for(int i=(a);i<=(b);i++)
#define mst(a,b) memset((a),(b),sizeof(a))
#define PII pair<int,int>
#define rep(i,x,y) for(auto i=(x);i<=(y);++i)
#define dep(i,x,y) for(auto i=(x);i>=(y);--i)
using namespace std;
template<class T>inline void rd(T &x) {
x=0; int ch=getchar(),f=0;
while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
if(f)x=-x;
}
const int inf=0x3f3f3f3f;
const int maxn=100050;
int T;
ll x,m,n,f[maxn];
int main()
{
cin>>T;
while(T--)
{
cin>>x>>m>>n;
f[0]=1;
ll tot=1;
for(int i=1;i<=n;i++)
{
f[i]=f[i-1];
if(i%7==1&&i!=1)
{
f[i]+=min(x,max(m-tot,0ll));
tot+=x;
}
else if(i>=14) f[i]-=f[i-14];
}
if(n<8) puts("0");
else if(n<14) cout<<f[n-8]<<endl;
else cout<<f[n-8]-f[n-14]<<endl;
}
return 0;
} | 23.22 | 67 | 0.485788 | songhn233 |
ca7e6735dca1ae95cec310cda7a885d1f20d74b1 | 142,444 | cpp | C++ | C10_Libraries/Plugins/VRExpansionPlugin/VRExpansionPlugin/Intermediate/Build/Win64/UE4Editor/Inc/VRExpansionPlugin/GrippableStaticMeshComponent.gen.cpp | Docdavies/Unreal-Engine-4-Virtual-Reality-Projects | 86305b7a7c8112933e73bcd95d7d33a1d6b8c210 | [
"MIT"
] | 24 | 2019-04-20T01:46:33.000Z | 2022-02-06T07:22:53.000Z | C10_Libraries/Plugins/VRExpansionPlugin/VRExpansionPlugin/Intermediate/Build/Win64/UE4Editor/Inc/VRExpansionPlugin/GrippableStaticMeshComponent.gen.cpp | Docdavies/Unreal-Engine-4-Virtual-Reality-Projects | 86305b7a7c8112933e73bcd95d7d33a1d6b8c210 | [
"MIT"
] | null | null | null | C10_Libraries/Plugins/VRExpansionPlugin/VRExpansionPlugin/Intermediate/Build/Win64/UE4Editor/Inc/VRExpansionPlugin/GrippableStaticMeshComponent.gen.cpp | Docdavies/Unreal-Engine-4-Virtual-Reality-Projects | 86305b7a7c8112933e73bcd95d7d33a1d6b8c210 | [
"MIT"
] | 16 | 2019-06-03T16:02:56.000Z | 2022-01-19T08:36:57.000Z | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "VRExpansionPlugin/Public/Grippables/GrippableStaticMeshComponent.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeGrippableStaticMeshComponent() {}
// Cross Module References
VREXPANSIONPLUGIN_API UClass* Z_Construct_UClass_UGrippableStaticMeshComponent_NoRegister();
VREXPANSIONPLUGIN_API UClass* Z_Construct_UClass_UGrippableStaticMeshComponent();
ENGINE_API UClass* Z_Construct_UClass_UStaticMeshComponent();
UPackage* Z_Construct_UPackage__Script_VRExpansionPlugin();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings();
VREXPANSIONPLUGIN_API UScriptStruct* Z_Construct_UScriptStruct_FBPAdvGripSettings();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange();
VREXPANSIONPLUGIN_API UClass* Z_Construct_UClass_UGripMotionControllerComponent_NoRegister();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FTransform();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FVector();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts();
VREXPANSIONPLUGIN_API UClass* Z_Construct_UClass_UVRGripScriptBase_NoRegister();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType();
VREXPANSIONPLUGIN_API UEnum* Z_Construct_UEnum_VRExpansionPlugin_EGripCollisionType();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting();
VREXPANSIONPLUGIN_API UEnum* Z_Construct_UEnum_VRExpansionPlugin_EGripLateUpdateSettings();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType();
VREXPANSIONPLUGIN_API UEnum* Z_Construct_UEnum_VRExpansionPlugin_EGripMovementReplicationSettings();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip();
VREXPANSIONPLUGIN_API UScriptStruct* Z_Construct_UScriptStruct_FBPActorGripInformation();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput();
ENGINE_API UEnum* Z_Construct_UEnum_Engine_EInputEvent();
INPUTCORE_API UScriptStruct* Z_Construct_UScriptStruct_FKey();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip();
ENGINE_API UClass* Z_Construct_UClass_USceneComponent_NoRegister();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing();
VREXPANSIONPLUGIN_API UScriptStruct* Z_Construct_UScriptStruct_FTransform_NetQuantize();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType();
VREXPANSIONPLUGIN_API UEnum* Z_Construct_UEnum_VRExpansionPlugin_ESecondaryGripType();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior();
VREXPANSIONPLUGIN_API UEnum* Z_Construct_UEnum_VRExpansionPlugin_EGripInterfaceTeleportBehavior();
VREXPANSIONPLUGIN_API UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip();
VREXPANSIONPLUGIN_API UScriptStruct* Z_Construct_UScriptStruct_FBPInterfaceProperties();
GAMEPLAYTAGS_API UScriptStruct* Z_Construct_UScriptStruct_FGameplayTagContainer();
VREXPANSIONPLUGIN_API UClass* Z_Construct_UClass_UVRGripInterface_NoRegister();
GAMEPLAYTAGS_API UClass* Z_Construct_UClass_UGameplayTagAssetInterface_NoRegister();
// End Cross Module References
static FName NAME_UGrippableStaticMeshComponent_AdvancedGripSettings = FName(TEXT("AdvancedGripSettings"));
FBPAdvGripSettings UGrippableStaticMeshComponent::AdvancedGripSettings()
{
GrippableStaticMeshComponent_eventAdvancedGripSettings_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_AdvancedGripSettings),&Parms);
return Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_ClosestGripSlotInRange = FName(TEXT("ClosestGripSlotInRange"));
void UGrippableStaticMeshComponent::ClosestGripSlotInRange(FVector WorldLocation, bool bSecondarySlot, bool& bHadSlotInRange, FTransform& SlotWorldTransform, UGripMotionControllerComponent* CallingController, FName OverridePrefix)
{
GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms Parms;
Parms.WorldLocation=WorldLocation;
Parms.bSecondarySlot=bSecondarySlot ? true : false;
Parms.bHadSlotInRange=bHadSlotInRange ? true : false;
Parms.SlotWorldTransform=SlotWorldTransform;
Parms.CallingController=CallingController;
Parms.OverridePrefix=OverridePrefix;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_ClosestGripSlotInRange),&Parms);
bHadSlotInRange=Parms.bHadSlotInRange;
SlotWorldTransform=Parms.SlotWorldTransform;
}
static FName NAME_UGrippableStaticMeshComponent_DenyGripping = FName(TEXT("DenyGripping"));
bool UGrippableStaticMeshComponent::DenyGripping()
{
GrippableStaticMeshComponent_eventDenyGripping_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_DenyGripping),&Parms);
return !!Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_GetGripScripts = FName(TEXT("GetGripScripts"));
bool UGrippableStaticMeshComponent::GetGripScripts(TArray<UVRGripScriptBase*>& ArrayReference)
{
GrippableStaticMeshComponent_eventGetGripScripts_Parms Parms;
Parms.ArrayReference=ArrayReference;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_GetGripScripts),&Parms);
ArrayReference=Parms.ArrayReference;
return !!Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping = FName(TEXT("GetGripStiffnessAndDamping"));
void UGrippableStaticMeshComponent::GetGripStiffnessAndDamping(float& GripStiffnessOut, float& GripDampingOut)
{
GrippableStaticMeshComponent_eventGetGripStiffnessAndDamping_Parms Parms;
Parms.GripStiffnessOut=GripStiffnessOut;
Parms.GripDampingOut=GripDampingOut;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping),&Parms);
GripStiffnessOut=Parms.GripStiffnessOut;
GripDampingOut=Parms.GripDampingOut;
}
static FName NAME_UGrippableStaticMeshComponent_GetPrimaryGripType = FName(TEXT("GetPrimaryGripType"));
EGripCollisionType UGrippableStaticMeshComponent::GetPrimaryGripType(bool bIsSlot)
{
GrippableStaticMeshComponent_eventGetPrimaryGripType_Parms Parms;
Parms.bIsSlot=bIsSlot ? true : false;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_GetPrimaryGripType),&Parms);
return Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_GripBreakDistance = FName(TEXT("GripBreakDistance"));
float UGrippableStaticMeshComponent::GripBreakDistance()
{
GrippableStaticMeshComponent_eventGripBreakDistance_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_GripBreakDistance),&Parms);
return Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_GripLateUpdateSetting = FName(TEXT("GripLateUpdateSetting"));
EGripLateUpdateSettings UGrippableStaticMeshComponent::GripLateUpdateSetting()
{
GrippableStaticMeshComponent_eventGripLateUpdateSetting_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_GripLateUpdateSetting),&Parms);
return Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_GripMovementReplicationType = FName(TEXT("GripMovementReplicationType"));
EGripMovementReplicationSettings UGrippableStaticMeshComponent::GripMovementReplicationType()
{
GrippableStaticMeshComponent_eventGripMovementReplicationType_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_GripMovementReplicationType),&Parms);
return Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_IsHeld = FName(TEXT("IsHeld"));
void UGrippableStaticMeshComponent::IsHeld(UGripMotionControllerComponent*& HoldingController, bool& bIsHeld)
{
GrippableStaticMeshComponent_eventIsHeld_Parms Parms;
Parms.HoldingController=HoldingController;
Parms.bIsHeld=bIsHeld ? true : false;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_IsHeld),&Parms);
HoldingController=Parms.HoldingController;
bIsHeld=Parms.bIsHeld;
}
static FName NAME_UGrippableStaticMeshComponent_OnChildGrip = FName(TEXT("OnChildGrip"));
void UGrippableStaticMeshComponent::OnChildGrip(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation)
{
GrippableStaticMeshComponent_eventOnChildGrip_Parms Parms;
Parms.GrippingController=GrippingController;
Parms.GripInformation=GripInformation;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnChildGrip),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_OnChildGripRelease = FName(TEXT("OnChildGripRelease"));
void UGrippableStaticMeshComponent::OnChildGripRelease(UGripMotionControllerComponent* ReleasingController, FBPActorGripInformation const& GripInformation, bool bWasSocketed)
{
GrippableStaticMeshComponent_eventOnChildGripRelease_Parms Parms;
Parms.ReleasingController=ReleasingController;
Parms.GripInformation=GripInformation;
Parms.bWasSocketed=bWasSocketed ? true : false;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnChildGripRelease),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_OnEndSecondaryUsed = FName(TEXT("OnEndSecondaryUsed"));
void UGrippableStaticMeshComponent::OnEndSecondaryUsed()
{
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnEndSecondaryUsed),NULL);
}
static FName NAME_UGrippableStaticMeshComponent_OnEndUsed = FName(TEXT("OnEndUsed"));
void UGrippableStaticMeshComponent::OnEndUsed()
{
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnEndUsed),NULL);
}
static FName NAME_UGrippableStaticMeshComponent_OnGrip = FName(TEXT("OnGrip"));
void UGrippableStaticMeshComponent::OnGrip(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation)
{
GrippableStaticMeshComponent_eventOnGrip_Parms Parms;
Parms.GrippingController=GrippingController;
Parms.GripInformation=GripInformation;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnGrip),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_OnGripRelease = FName(TEXT("OnGripRelease"));
void UGrippableStaticMeshComponent::OnGripRelease(UGripMotionControllerComponent* ReleasingController, FBPActorGripInformation const& GripInformation, bool bWasSocketed)
{
GrippableStaticMeshComponent_eventOnGripRelease_Parms Parms;
Parms.ReleasingController=ReleasingController;
Parms.GripInformation=GripInformation;
Parms.bWasSocketed=bWasSocketed ? true : false;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnGripRelease),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_OnInput = FName(TEXT("OnInput"));
void UGrippableStaticMeshComponent::OnInput(FKey Key, EInputEvent KeyEvent)
{
GrippableStaticMeshComponent_eventOnInput_Parms Parms;
Parms.Key=Key;
Parms.KeyEvent=KeyEvent;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnInput),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_OnSecondaryGrip = FName(TEXT("OnSecondaryGrip"));
void UGrippableStaticMeshComponent::OnSecondaryGrip(USceneComponent* SecondaryGripComponent, FBPActorGripInformation const& GripInformation)
{
GrippableStaticMeshComponent_eventOnSecondaryGrip_Parms Parms;
Parms.SecondaryGripComponent=SecondaryGripComponent;
Parms.GripInformation=GripInformation;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnSecondaryGrip),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_OnSecondaryGripRelease = FName(TEXT("OnSecondaryGripRelease"));
void UGrippableStaticMeshComponent::OnSecondaryGripRelease(USceneComponent* ReleasingSecondaryGripComponent, FBPActorGripInformation const& GripInformation)
{
GrippableStaticMeshComponent_eventOnSecondaryGripRelease_Parms Parms;
Parms.ReleasingSecondaryGripComponent=ReleasingSecondaryGripComponent;
Parms.GripInformation=GripInformation;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnSecondaryGripRelease),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_OnSecondaryUsed = FName(TEXT("OnSecondaryUsed"));
void UGrippableStaticMeshComponent::OnSecondaryUsed()
{
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnSecondaryUsed),NULL);
}
static FName NAME_UGrippableStaticMeshComponent_OnUsed = FName(TEXT("OnUsed"));
void UGrippableStaticMeshComponent::OnUsed()
{
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_OnUsed),NULL);
}
static FName NAME_UGrippableStaticMeshComponent_RequestsSocketing = FName(TEXT("RequestsSocketing"));
bool UGrippableStaticMeshComponent::RequestsSocketing(USceneComponent*& ParentToSocketTo, FName& OptionalSocketName, FTransform_NetQuantize& RelativeTransform)
{
GrippableStaticMeshComponent_eventRequestsSocketing_Parms Parms;
Parms.ParentToSocketTo=ParentToSocketTo;
Parms.OptionalSocketName=OptionalSocketName;
Parms.RelativeTransform=RelativeTransform;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_RequestsSocketing),&Parms);
ParentToSocketTo=Parms.ParentToSocketTo;
OptionalSocketName=Parms.OptionalSocketName;
RelativeTransform=Parms.RelativeTransform;
return !!Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_SecondaryGripType = FName(TEXT("SecondaryGripType"));
ESecondaryGripType UGrippableStaticMeshComponent::SecondaryGripType()
{
GrippableStaticMeshComponent_eventSecondaryGripType_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_SecondaryGripType),&Parms);
return Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_SetHeld = FName(TEXT("SetHeld"));
void UGrippableStaticMeshComponent::SetHeld(UGripMotionControllerComponent* HoldingController, bool bIsHeld)
{
GrippableStaticMeshComponent_eventSetHeld_Parms Parms;
Parms.HoldingController=HoldingController;
Parms.bIsHeld=bIsHeld ? true : false;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_SetHeld),&Parms);
}
static FName NAME_UGrippableStaticMeshComponent_SimulateOnDrop = FName(TEXT("SimulateOnDrop"));
bool UGrippableStaticMeshComponent::SimulateOnDrop()
{
GrippableStaticMeshComponent_eventSimulateOnDrop_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_SimulateOnDrop),&Parms);
return !!Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_TeleportBehavior = FName(TEXT("TeleportBehavior"));
EGripInterfaceTeleportBehavior UGrippableStaticMeshComponent::TeleportBehavior()
{
GrippableStaticMeshComponent_eventTeleportBehavior_Parms Parms;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_TeleportBehavior),&Parms);
return Parms.ReturnValue;
}
static FName NAME_UGrippableStaticMeshComponent_TickGrip = FName(TEXT("TickGrip"));
void UGrippableStaticMeshComponent::TickGrip(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation, float DeltaTime)
{
GrippableStaticMeshComponent_eventTickGrip_Parms Parms;
Parms.GrippingController=GrippingController;
Parms.GripInformation=GripInformation;
Parms.DeltaTime=DeltaTime;
ProcessEvent(FindFunctionChecked(NAME_UGrippableStaticMeshComponent_TickGrip),&Parms);
}
void UGrippableStaticMeshComponent::StaticRegisterNativesUGrippableStaticMeshComponent()
{
UClass* Class = UGrippableStaticMeshComponent::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "AdvancedGripSettings", &UGrippableStaticMeshComponent::execAdvancedGripSettings },
{ "ClosestGripSlotInRange", &UGrippableStaticMeshComponent::execClosestGripSlotInRange },
{ "DenyGripping", &UGrippableStaticMeshComponent::execDenyGripping },
{ "GetGripScripts", &UGrippableStaticMeshComponent::execGetGripScripts },
{ "GetGripStiffnessAndDamping", &UGrippableStaticMeshComponent::execGetGripStiffnessAndDamping },
{ "GetPrimaryGripType", &UGrippableStaticMeshComponent::execGetPrimaryGripType },
{ "GripBreakDistance", &UGrippableStaticMeshComponent::execGripBreakDistance },
{ "GripLateUpdateSetting", &UGrippableStaticMeshComponent::execGripLateUpdateSetting },
{ "GripMovementReplicationType", &UGrippableStaticMeshComponent::execGripMovementReplicationType },
{ "IsHeld", &UGrippableStaticMeshComponent::execIsHeld },
{ "OnChildGrip", &UGrippableStaticMeshComponent::execOnChildGrip },
{ "OnChildGripRelease", &UGrippableStaticMeshComponent::execOnChildGripRelease },
{ "OnEndSecondaryUsed", &UGrippableStaticMeshComponent::execOnEndSecondaryUsed },
{ "OnEndUsed", &UGrippableStaticMeshComponent::execOnEndUsed },
{ "OnGrip", &UGrippableStaticMeshComponent::execOnGrip },
{ "OnGripRelease", &UGrippableStaticMeshComponent::execOnGripRelease },
{ "OnInput", &UGrippableStaticMeshComponent::execOnInput },
{ "OnSecondaryGrip", &UGrippableStaticMeshComponent::execOnSecondaryGrip },
{ "OnSecondaryGripRelease", &UGrippableStaticMeshComponent::execOnSecondaryGripRelease },
{ "OnSecondaryUsed", &UGrippableStaticMeshComponent::execOnSecondaryUsed },
{ "OnUsed", &UGrippableStaticMeshComponent::execOnUsed },
{ "RequestsSocketing", &UGrippableStaticMeshComponent::execRequestsSocketing },
{ "SecondaryGripType", &UGrippableStaticMeshComponent::execSecondaryGripType },
{ "SetDenyGripping", &UGrippableStaticMeshComponent::execSetDenyGripping },
{ "SetHeld", &UGrippableStaticMeshComponent::execSetHeld },
{ "SimulateOnDrop", &UGrippableStaticMeshComponent::execSimulateOnDrop },
{ "TeleportBehavior", &UGrippableStaticMeshComponent::execTeleportBehavior },
{ "TickGrip", &UGrippableStaticMeshComponent::execTickGrip },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics
{
static const UE4CodeGen_Private::FStructPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventAdvancedGripSettings_Parms, ReturnValue), Z_Construct_UScriptStruct_FBPAdvGripSettings, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Get the advanced physics settings for this grip" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "AdvancedGripSettings", sizeof(GrippableStaticMeshComponent_eventAdvancedGripSettings_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics
{
static const UE4CodeGen_Private::FNamePropertyParams NewProp_OverridePrefix;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CallingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_CallingController;
static const UE4CodeGen_Private::FStructPropertyParams NewProp_SlotWorldTransform;
static void NewProp_bHadSlotInRange_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bHadSlotInRange;
static void NewProp_bSecondarySlot_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bSecondarySlot;
static const UE4CodeGen_Private::FStructPropertyParams NewProp_WorldLocation;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_OverridePrefix = { "OverridePrefix", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms, OverridePrefix), METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_CallingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_CallingController = { "CallingController", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms, CallingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_CallingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_CallingController_MetaData)) };
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_SlotWorldTransform = { "SlotWorldTransform", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms, SlotWorldTransform), Z_Construct_UScriptStruct_FTransform, METADATA_PARAMS(nullptr, 0) };
void Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bHadSlotInRange_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms*)Obj)->bHadSlotInRange = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bHadSlotInRange = { "bHadSlotInRange", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bHadSlotInRange_SetBit, METADATA_PARAMS(nullptr, 0) };
void Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bSecondarySlot_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms*)Obj)->bSecondarySlot = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bSecondarySlot = { "bSecondarySlot", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bSecondarySlot_SetBit, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_WorldLocation = { "WorldLocation", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms, WorldLocation), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_OverridePrefix,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_CallingController,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_SlotWorldTransform,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bHadSlotInRange,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_bSecondarySlot,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::NewProp_WorldLocation,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "CPP_Default_CallingController", "None" },
{ "CPP_Default_OverridePrefix", "None" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Get closest primary slot in range" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "ClosestGripSlotInRange", sizeof(GrippableStaticMeshComponent_eventClosestGripSlotInRange_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0CC20C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics
{
static void NewProp_ReturnValue_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::NewProp_ReturnValue_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventDenyGripping_Parms*)Obj)->ReturnValue = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventDenyGripping_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "DisplayName", "IsDenyingGrips" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Set up as deny instead of allow so that default allows for gripping" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "DenyGripping", sizeof(GrippableStaticMeshComponent_eventDenyGripping_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics
{
static void NewProp_ReturnValue_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ArrayReference_MetaData[];
#endif
static const UE4CodeGen_Private::FArrayPropertyParams NewProp_ArrayReference;
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ArrayReference_Inner;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ReturnValue_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventGetGripScripts_Parms*)Obj)->ReturnValue = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventGetGripScripts_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ArrayReference_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ArrayReference = { "ArrayReference", nullptr, (EPropertyFlags)0x0010008000000180, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventGetGripScripts_Parms, ArrayReference), METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ArrayReference_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ArrayReference_MetaData)) };
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ArrayReference_Inner = { "ArrayReference", nullptr, (EPropertyFlags)0x0000000000080000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UClass_UVRGripScriptBase_NoRegister, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ArrayReference,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::NewProp_ArrayReference_Inner,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Get grip scripts" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "GetGripScripts", sizeof(GrippableStaticMeshComponent_eventGetGripScripts_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics
{
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_GripDampingOut;
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_GripStiffnessOut;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::NewProp_GripDampingOut = { "GripDampingOut", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventGetGripStiffnessAndDamping_Parms, GripDampingOut), METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::NewProp_GripStiffnessOut = { "GripStiffnessOut", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventGetGripStiffnessAndDamping_Parms, GripStiffnessOut), METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::NewProp_GripDampingOut,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::NewProp_GripStiffnessOut,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "What grip stiffness and damping to use if using a physics constraint" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "GetGripStiffnessAndDamping", sizeof(GrippableStaticMeshComponent_eventGetGripStiffnessAndDamping_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics
{
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FBytePropertyParams NewProp_ReturnValue_Underlying;
static void NewProp_bIsSlot_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsSlot;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventGetPrimaryGripType_Parms, ReturnValue), Z_Construct_UEnum_VRExpansionPlugin_EGripCollisionType, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_ReturnValue_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
void Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_bIsSlot_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventGetPrimaryGripType_Parms*)Obj)->bIsSlot = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_bIsSlot = { "bIsSlot", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventGetPrimaryGripType_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_bIsSlot_SetBit, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_ReturnValue_Underlying,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::NewProp_bIsSlot,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Grip type to use" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "GetPrimaryGripType", sizeof(GrippableStaticMeshComponent_eventGetPrimaryGripType_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics
{
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventGripBreakDistance_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "What distance to break a grip at (only relevent with physics enabled grips" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "GripBreakDistance", sizeof(GrippableStaticMeshComponent_eventGripBreakDistance_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics
{
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FBytePropertyParams NewProp_ReturnValue_Underlying;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventGripLateUpdateSetting_Parms, ReturnValue), Z_Construct_UEnum_VRExpansionPlugin_EGripLateUpdateSettings, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::NewProp_ReturnValue_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::NewProp_ReturnValue_Underlying,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Define the late update setting" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "GripLateUpdateSetting", sizeof(GrippableStaticMeshComponent_eventGripLateUpdateSetting_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics
{
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FBytePropertyParams NewProp_ReturnValue_Underlying;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventGripMovementReplicationType_Parms, ReturnValue), Z_Construct_UEnum_VRExpansionPlugin_EGripMovementReplicationSettings, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::NewProp_ReturnValue_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::NewProp_ReturnValue_Underlying,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Define which movement repliation setting to use" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "GripMovementReplicationType", sizeof(GrippableStaticMeshComponent_eventGripMovementReplicationType_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics
{
static void NewProp_bIsHeld_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsHeld;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_HoldingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_HoldingController;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_bIsHeld_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventIsHeld_Parms*)Obj)->bIsHeld = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_bIsHeld = { "bIsHeld", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventIsHeld_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_bIsHeld_SetBit, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_HoldingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_HoldingController = { "HoldingController", nullptr, (EPropertyFlags)0x0010000000080180, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventIsHeld_Parms, HoldingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_HoldingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_HoldingController_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_bIsHeld,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::NewProp_HoldingController,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Returns if the object is held and if so, which pawn is holding it" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "IsHeld", sizeof(GrippableStaticMeshComponent_eventIsHeld_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripInformation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GripInformation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GrippingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_GrippingController;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GripInformation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GripInformation = { "GripInformation", nullptr, (EPropertyFlags)0x0010008008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnChildGrip_Parms, GripInformation), Z_Construct_UScriptStruct_FBPActorGripInformation, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GripInformation_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GripInformation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GrippingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GrippingController = { "GrippingController", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnChildGrip_Parms, GrippingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GrippingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GrippingController_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GripInformation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::NewProp_GrippingController,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Event triggered on the interfaced object when child component is gripped" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnChildGrip", sizeof(GrippableStaticMeshComponent_eventOnChildGrip_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics
{
static void NewProp_bWasSocketed_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bWasSocketed;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripInformation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GripInformation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ReleasingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReleasingController;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_bWasSocketed_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventOnChildGripRelease_Parms*)Obj)->bWasSocketed = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_bWasSocketed = { "bWasSocketed", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventOnChildGripRelease_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_bWasSocketed_SetBit, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_GripInformation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_GripInformation = { "GripInformation", nullptr, (EPropertyFlags)0x0010008008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnChildGripRelease_Parms, GripInformation), Z_Construct_UScriptStruct_FBPActorGripInformation, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_GripInformation_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_GripInformation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_ReleasingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_ReleasingController = { "ReleasingController", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnChildGripRelease_Parms, ReleasingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_ReleasingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_ReleasingController_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_bWasSocketed,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_GripInformation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::NewProp_ReleasingController,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Event triggered on the interfaced object when child component is released" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnChildGripRelease", sizeof(GrippableStaticMeshComponent_eventOnChildGripRelease_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Call to stop using an object" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnEndSecondaryUsed", 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Call to stop using an object" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnEndUsed", 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripInformation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GripInformation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GrippingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_GrippingController;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GripInformation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GripInformation = { "GripInformation", nullptr, (EPropertyFlags)0x0010008008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnGrip_Parms, GripInformation), Z_Construct_UScriptStruct_FBPActorGripInformation, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GripInformation_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GripInformation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GrippingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GrippingController = { "GrippingController", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnGrip_Parms, GrippingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GrippingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GrippingController_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GripInformation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::NewProp_GrippingController,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Event triggered on the interfaced object when gripped" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnGrip", sizeof(GrippableStaticMeshComponent_eventOnGrip_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics
{
static void NewProp_bWasSocketed_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bWasSocketed;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripInformation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GripInformation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ReleasingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReleasingController;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_bWasSocketed_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventOnGripRelease_Parms*)Obj)->bWasSocketed = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_bWasSocketed = { "bWasSocketed", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventOnGripRelease_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_bWasSocketed_SetBit, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_GripInformation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_GripInformation = { "GripInformation", nullptr, (EPropertyFlags)0x0010008008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnGripRelease_Parms, GripInformation), Z_Construct_UScriptStruct_FBPActorGripInformation, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_GripInformation_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_GripInformation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_ReleasingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_ReleasingController = { "ReleasingController", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnGripRelease_Parms, ReleasingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_ReleasingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_ReleasingController_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_bWasSocketed,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_GripInformation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::NewProp_ReleasingController,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Event triggered on the interfaced object when grip is released" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnGripRelease", sizeof(GrippableStaticMeshComponent_eventOnGripRelease_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics
{
static const UE4CodeGen_Private::FBytePropertyParams NewProp_KeyEvent;
static const UE4CodeGen_Private::FStructPropertyParams NewProp_Key;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::NewProp_KeyEvent = { "KeyEvent", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnInput_Parms, KeyEvent), Z_Construct_UEnum_Engine_EInputEvent, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::NewProp_Key = { "Key", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnInput_Parms, Key), Z_Construct_UScriptStruct_FKey, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::NewProp_KeyEvent,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::NewProp_Key,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Call to send an action event to the object" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnInput", sizeof(GrippableStaticMeshComponent_eventOnInput_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripInformation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GripInformation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SecondaryGripComponent_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_SecondaryGripComponent;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_GripInformation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_GripInformation = { "GripInformation", nullptr, (EPropertyFlags)0x0010008008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnSecondaryGrip_Parms, GripInformation), Z_Construct_UScriptStruct_FBPActorGripInformation, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_GripInformation_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_GripInformation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_SecondaryGripComponent_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_SecondaryGripComponent = { "SecondaryGripComponent", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnSecondaryGrip_Parms, SecondaryGripComponent), Z_Construct_UClass_USceneComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_SecondaryGripComponent_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_SecondaryGripComponent_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_GripInformation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::NewProp_SecondaryGripComponent,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Event triggered on the interfaced object when secondary gripped" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnSecondaryGrip", sizeof(GrippableStaticMeshComponent_eventOnSecondaryGrip_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripInformation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GripInformation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ReleasingSecondaryGripComponent_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReleasingSecondaryGripComponent;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_GripInformation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_GripInformation = { "GripInformation", nullptr, (EPropertyFlags)0x0010008008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnSecondaryGripRelease_Parms, GripInformation), Z_Construct_UScriptStruct_FBPActorGripInformation, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_GripInformation_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_GripInformation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_ReleasingSecondaryGripComponent_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_ReleasingSecondaryGripComponent = { "ReleasingSecondaryGripComponent", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventOnSecondaryGripRelease_Parms, ReleasingSecondaryGripComponent), Z_Construct_UClass_USceneComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_ReleasingSecondaryGripComponent_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_ReleasingSecondaryGripComponent_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_GripInformation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::NewProp_ReleasingSecondaryGripComponent,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Event triggered on the interfaced object when secondary grip is released" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnSecondaryGripRelease", sizeof(GrippableStaticMeshComponent_eventOnSecondaryGripRelease_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Call to use an object" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnSecondaryUsed", 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Call to use an object" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "OnUsed", 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics
{
static void NewProp_ReturnValue_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FStructPropertyParams NewProp_RelativeTransform;
static const UE4CodeGen_Private::FNamePropertyParams NewProp_OptionalSocketName;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ParentToSocketTo_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ParentToSocketTo;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ReturnValue_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventRequestsSocketing_Parms*)Obj)->ReturnValue = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventRequestsSocketing_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_RelativeTransform = { "RelativeTransform", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventRequestsSocketing_Parms, RelativeTransform), Z_Construct_UScriptStruct_FTransform_NetQuantize, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_OptionalSocketName = { "OptionalSocketName", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventRequestsSocketing_Parms, OptionalSocketName), METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ParentToSocketTo_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ParentToSocketTo = { "ParentToSocketTo", nullptr, (EPropertyFlags)0x0010000000080180, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventRequestsSocketing_Parms, ParentToSocketTo), Z_Construct_UClass_USceneComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ParentToSocketTo_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ParentToSocketTo_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_RelativeTransform,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_OptionalSocketName,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::NewProp_ParentToSocketTo,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Returns if the object wants to be socketed" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "RequestsSocketing", sizeof(GrippableStaticMeshComponent_eventRequestsSocketing_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics
{
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FBytePropertyParams NewProp_ReturnValue_Underlying;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventSecondaryGripType_Parms, ReturnValue), Z_Construct_UEnum_VRExpansionPlugin_ESecondaryGripType, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::NewProp_ReturnValue_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::NewProp_ReturnValue_Underlying,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Secondary grip type" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "SecondaryGripType", sizeof(GrippableStaticMeshComponent_eventSecondaryGripType_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics
{
struct GrippableStaticMeshComponent_eventSetDenyGripping_Parms
{
bool bDenyGripping;
};
static void NewProp_bDenyGripping_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bDenyGripping;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::NewProp_bDenyGripping_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventSetDenyGripping_Parms*)Obj)->bDenyGripping = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::NewProp_bDenyGripping = { "bDenyGripping", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventSetDenyGripping_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::NewProp_bDenyGripping_SetBit, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::NewProp_bDenyGripping,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Sets the Deny Gripping variable on the FBPInterfaceSettings struct" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "SetDenyGripping", sizeof(GrippableStaticMeshComponent_eventSetDenyGripping_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics
{
static void NewProp_bIsHeld_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsHeld;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_HoldingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_HoldingController;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_bIsHeld_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventSetHeld_Parms*)Obj)->bIsHeld = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_bIsHeld = { "bIsHeld", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventSetHeld_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_bIsHeld_SetBit, METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_HoldingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_HoldingController = { "HoldingController", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventSetHeld_Parms, HoldingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_HoldingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_HoldingController_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_bIsHeld,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::NewProp_HoldingController,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "BlueprintCallable," },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "SetHeld", sizeof(GrippableStaticMeshComponent_eventSetHeld_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics
{
static void NewProp_ReturnValue_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
void Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::NewProp_ReturnValue_SetBit(void* Obj)
{
((GrippableStaticMeshComponent_eventSimulateOnDrop_Parms*)Obj)->ReturnValue = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(GrippableStaticMeshComponent_eventSimulateOnDrop_Parms), &Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Should this object simulate on drop" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "SimulateOnDrop", sizeof(GrippableStaticMeshComponent_eventSimulateOnDrop_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics
{
static const UE4CodeGen_Private::FEnumPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FBytePropertyParams NewProp_ReturnValue_Underlying;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventTeleportBehavior_Parms, ReturnValue), Z_Construct_UEnum_VRExpansionPlugin_EGripInterfaceTeleportBehavior, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::NewProp_ReturnValue_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::NewProp_ReturnValue,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::NewProp_ReturnValue_Underlying,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "How an interfaced object behaves when teleporting" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "TeleportBehavior", sizeof(GrippableStaticMeshComponent_eventTeleportBehavior_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x0C020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics
{
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_DeltaTime;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripInformation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GripInformation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GrippingController_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_GrippingController;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_DeltaTime = { "DeltaTime", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventTickGrip_Parms, DeltaTime), METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GripInformation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GripInformation = { "GripInformation", nullptr, (EPropertyFlags)0x0010008008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventTickGrip_Parms, GripInformation), Z_Construct_UScriptStruct_FBPActorGripInformation, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GripInformation_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GripInformation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GrippingController_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GrippingController = { "GrippingController", nullptr, (EPropertyFlags)0x0010000000080080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(GrippableStaticMeshComponent_eventTickGrip_Parms, GrippingController), Z_Construct_UClass_UGripMotionControllerComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GrippingController_MetaData, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GrippingController_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_DeltaTime,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GripInformation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::NewProp_GrippingController,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::Function_MetaDataParams[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Event triggered each tick on the interfaced object when gripped, can be used for custom movement or grip based logic" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UGrippableStaticMeshComponent, nullptr, "TickGrip", sizeof(GrippableStaticMeshComponent_eventTickGrip_Parms), Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08420C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UGrippableStaticMeshComponent_NoRegister()
{
return UGrippableStaticMeshComponent::StaticClass();
}
struct Z_Construct_UClass_UGrippableStaticMeshComponent_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_VRGripInterfaceSettings_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_VRGripInterfaceSettings;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bReplicateMovement_MetaData[];
#endif
static void NewProp_bReplicateMovement_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bReplicateMovement;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bRepGripSettingsAndGameplayTags_MetaData[];
#endif
static void NewProp_bRepGripSettingsAndGameplayTags_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bRepGripSettingsAndGameplayTags;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GameplayTags_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_GameplayTags;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripLogicScripts_MetaData[];
#endif
static const UE4CodeGen_Private::FArrayPropertyParams NewProp_GripLogicScripts;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GripLogicScripts_Inner_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_GripLogicScripts_Inner;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const UE4CodeGen_Private::FImplementedInterfaceParams InterfaceParams[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UStaticMeshComponent,
(UObject* (*)())Z_Construct_UPackage__Script_VRExpansionPlugin,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_AdvancedGripSettings, "AdvancedGripSettings" }, // 762585886
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_ClosestGripSlotInRange, "ClosestGripSlotInRange" }, // 2272821568
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_DenyGripping, "DenyGripping" }, // 1767275283
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripScripts, "GetGripScripts" }, // 2279644934
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_GetGripStiffnessAndDamping, "GetGripStiffnessAndDamping" }, // 1500980331
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_GetPrimaryGripType, "GetPrimaryGripType" }, // 2963296902
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_GripBreakDistance, "GripBreakDistance" }, // 1478392741
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_GripLateUpdateSetting, "GripLateUpdateSetting" }, // 1324845332
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_GripMovementReplicationType, "GripMovementReplicationType" }, // 2319373172
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_IsHeld, "IsHeld" }, // 3786169678
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGrip, "OnChildGrip" }, // 767601137
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnChildGripRelease, "OnChildGripRelease" }, // 4287492726
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndSecondaryUsed, "OnEndSecondaryUsed" }, // 3833655261
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnEndUsed, "OnEndUsed" }, // 1028990552
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGrip, "OnGrip" }, // 1314697240
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnGripRelease, "OnGripRelease" }, // 387544051
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnInput, "OnInput" }, // 166655003
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGrip, "OnSecondaryGrip" }, // 935206333
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryGripRelease, "OnSecondaryGripRelease" }, // 1160525169
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnSecondaryUsed, "OnSecondaryUsed" }, // 949007931
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_OnUsed, "OnUsed" }, // 2025767282
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_RequestsSocketing, "RequestsSocketing" }, // 1815442755
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_SecondaryGripType, "SecondaryGripType" }, // 1854293530
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_SetDenyGripping, "SetDenyGripping" }, // 3496596012
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_SetHeld, "SetHeld" }, // 316638335
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_SimulateOnDrop, "SimulateOnDrop" }, // 3409704786
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_TeleportBehavior, "TeleportBehavior" }, // 19720207
{ &Z_Construct_UFunction_UGrippableStaticMeshComponent_TickGrip, "TickGrip" }, // 2703171655
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::Class_MetaDataParams[] = {
{ "BlueprintSpawnableComponent", "" },
{ "BlueprintType", "true" },
{ "ClassGroupNames", "VRExpansionPlugin" },
{ "HideCategories", "Object Activation Components|Activation Trigger" },
{ "IncludePath", "Grippables/GrippableStaticMeshComponent.h" },
{ "IsBlueprintBase", "true" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ObjectInitializerConstructorDeclared", "" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_VRGripInterfaceSettings_MetaData[] = {
{ "Category", "VRGripInterface" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_VRGripInterfaceSettings = { "VRGripInterfaceSettings", nullptr, (EPropertyFlags)0x0010008000000025, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UGrippableStaticMeshComponent, VRGripInterfaceSettings), Z_Construct_UScriptStruct_FBPInterfaceProperties, METADATA_PARAMS(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_VRGripInterfaceSettings_MetaData, ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_VRGripInterfaceSettings_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bReplicateMovement_MetaData[] = {
{ "Category", "VRGripInterface|Replication" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Overrides the default of : true and allows for controlling it like in an actor, should be default of off normally with grippable components" },
};
#endif
void Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bReplicateMovement_SetBit(void* Obj)
{
((UGrippableStaticMeshComponent*)Obj)->bReplicateMovement = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bReplicateMovement = { "bReplicateMovement", nullptr, (EPropertyFlags)0x0010000000000025, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UGrippableStaticMeshComponent), &Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bReplicateMovement_SetBit, METADATA_PARAMS(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bReplicateMovement_MetaData, ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bReplicateMovement_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bRepGripSettingsAndGameplayTags_MetaData[] = {
{ "Category", "VRGripInterface|Replication" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Requires bReplicates to be true for the component" },
};
#endif
void Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bRepGripSettingsAndGameplayTags_SetBit(void* Obj)
{
((UGrippableStaticMeshComponent*)Obj)->bRepGripSettingsAndGameplayTags = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bRepGripSettingsAndGameplayTags = { "bRepGripSettingsAndGameplayTags", nullptr, (EPropertyFlags)0x0010000000000025, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UGrippableStaticMeshComponent), &Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bRepGripSettingsAndGameplayTags_SetBit, METADATA_PARAMS(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bRepGripSettingsAndGameplayTags_MetaData, ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bRepGripSettingsAndGameplayTags_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GameplayTags_MetaData[] = {
{ "Category", "GameplayTags" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Tags that are set on this object" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GameplayTags = { "GameplayTags", nullptr, (EPropertyFlags)0x0010000000000025, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UGrippableStaticMeshComponent, GameplayTags), Z_Construct_UScriptStruct_FGameplayTagContainer, METADATA_PARAMS(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GameplayTags_MetaData, ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GameplayTags_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_MetaData[] = {
{ "Category", "VRGripInterface" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Overridden to return requirements tags" },
};
#endif
const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts = { "GripLogicScripts", nullptr, (EPropertyFlags)0x001000800000003d, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UGrippableStaticMeshComponent, GripLogicScripts), METADATA_PARAMS(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_MetaData, ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_Inner_MetaData[] = {
{ "Category", "VRGripInterface" },
{ "EditInline", "true" },
{ "ModuleRelativePath", "Public/Grippables/GrippableStaticMeshComponent.h" },
{ "ToolTip", "Overridden to return requirements tags" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_Inner = { "GripLogicScripts", nullptr, (EPropertyFlags)0x0002000000080008, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UClass_UVRGripScriptBase_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_Inner_MetaData, ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_Inner_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_VRGripInterfaceSettings,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bReplicateMovement,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_bRepGripSettingsAndGameplayTags,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GameplayTags,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::NewProp_GripLogicScripts_Inner,
};
const UE4CodeGen_Private::FImplementedInterfaceParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::InterfaceParams[] = {
{ Z_Construct_UClass_UVRGripInterface_NoRegister, (int32)VTABLE_OFFSET(UGrippableStaticMeshComponent, IVRGripInterface), false },
{ Z_Construct_UClass_UGameplayTagAssetInterface_NoRegister, (int32)VTABLE_OFFSET(UGrippableStaticMeshComponent, IGameplayTagAssetInterface), false },
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UGrippableStaticMeshComponent>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::ClassParams = {
&UGrippableStaticMeshComponent::StaticClass,
"Engine",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::PropPointers,
InterfaceParams,
ARRAY_COUNT(DependentSingletons),
ARRAY_COUNT(FuncInfo),
ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::PropPointers),
ARRAY_COUNT(InterfaceParams),
0x00B010A4u,
METADATA_PARAMS(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UGrippableStaticMeshComponent()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UGrippableStaticMeshComponent_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UGrippableStaticMeshComponent, 4292704888);
template<> VREXPANSIONPLUGIN_API UClass* StaticClass<UGrippableStaticMeshComponent>()
{
return UGrippableStaticMeshComponent::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UGrippableStaticMeshComponent(Z_Construct_UClass_UGrippableStaticMeshComponent, &UGrippableStaticMeshComponent::StaticClass, TEXT("/Script/VRExpansionPlugin"), TEXT("UGrippableStaticMeshComponent"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UGrippableStaticMeshComponent);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 86.962149 | 881 | 0.873782 | Docdavies |
ca7edf48008e93d1131ba1efae51b5ec54014aa2 | 492 | cpp | C++ | contest/AOJ/1601.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/AOJ/1601.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/AOJ/1601.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "stack.hpp"
#include "string.hpp"
int main() {
for (int n; n = in, n != 0;) {
Vector<String> w(n, in);
for (int i = 0;; ++i) {
Stack<int> s({7, 7, 5, 7, 5});
for (int j = i; j < n && !s.empty(); ++j) {
int k = s.top() - w[j].size();
if (k == 0) {
continue;
}
s.emplace(k);
if (k < 0) {
break;
}
}
if (s.empty()) {
cout << i + 1 << endl;
break;
}
}
}
}
| 18.923077 | 49 | 0.351626 | not522 |
ca7f1e2fbfa8165834f1e421e1ce74cd2225376f | 40,099 | hpp | C++ | 1/Code/Source/Engine/Math.hpp | Zakhar-V/Prototypes | 413a7ce9fdb2a6f3ba97a041f798c71351efc855 | [
"MIT"
] | null | null | null | 1/Code/Source/Engine/Math.hpp | Zakhar-V/Prototypes | 413a7ce9fdb2a6f3ba97a041f798c71351efc855 | [
"MIT"
] | null | null | null | 1/Code/Source/Engine/Math.hpp | Zakhar-V/Prototypes | 413a7ce9fdb2a6f3ba97a041f798c71351efc855 | [
"MIT"
] | null | null | null | #pragma once
#include "Common.hpp"
#include "String.hpp"
namespace ge
{
//----------------------------------------------------------------------------//
// Defs
//----------------------------------------------------------------------------//
#ifdef _FAST_HALF_FLOAT
# define FAST_HALF_FLOAT
#endif
typedef float float32;
typedef struct half float16;
typedef double float64;
static const float Epsilon = 1e-6f;
static const float Epsilon2 = 1e-12f;
static const float Pi = 3.1415926535897932384626433832795f;
static const float Rad2Deg = 57.295779513082320876798154814105f;
static const float Deg2Rad = 0.01745329251994329576923690768489f;
//----------------------------------------------------------------------------//
// Math funcs
//----------------------------------------------------------------------------//
template <typename T> const T& Min(const T& _a, const T& _b) { return _a < _b ? _a : _b; }
template <typename T> const T& Min(const T& _a, const T& _b, const T& _c) { return _a < _b ? (_a < _c ? _a : _c) : (_b < _c ? _b : _c); }
template <typename T> const T& Max(const T& _a, const T& _b) { return _a > _b ? _a : _b; }
template <typename T> const T& Max(const T& _a, const T& _b, const T& _c) { return _a > _b ? (_a > _c ? _a : _c) : (_b > _c ? _b : _c); }
template <typename T> const T Clamp(T _x, T _l, T _u) { return _x > _l ? (_x < _u ? _x : _u) : _l; }
template <typename T> T Mix(const T& _a, const T& _b, float _t) { return _a + (_b - _a) * _t; }
template <typename T> T Abs(T _x) { return abs(_x); }
template <typename T> T Radians(T _val) { return _val * Deg2Rad; }
template <typename T> T Degrees(T _val) { return _val * Rad2Deg; }
template <typename T> T Sqr(T _x) { return _x * _x; }
inline float Sqrt(float _x) { return sqrt(_x); }
inline float RSqrt(float _x) { return 1 / sqrt(_x); }
inline float Sin(float _x) { return sin(_x); }
inline float Cos(float _x) { return cos(_x); }
inline void SinCos(float _a, float& _s, float& _c) { _s = sin(_a), _c = cos(_a); }
inline float Tan(float _x) { return tan(_x); }
inline float ASin(float _x) { return asin(_x); }
inline float ACos(float _x) { return acos(_x); }
inline float ATan2(float _y, float _x) { return atan2(_y, _x); }
inline float Log2(float _x) { return log2(_x); }
inline int Log2i(int _x) { return (int)log2f((float)_x); }
//----------------------------------------------------------------------------//
// Bitwise
//----------------------------------------------------------------------------//
inline uint32 FirstPow2(uint32 _val)
{
--_val |= _val >> 16;
_val |= _val >> 8;
_val |= _val >> 4;
_val |= _val >> 2;
_val |= _val >> 1;
return ++_val;
}
inline bool IsPow2(uint32 _val) { return (_val & (_val - 1)) == 0; }
inline uint8 FloatToByte(float _value) { return (uint8)(_value * 0xff); }
inline float ByteToFloat(uint8 _value) { return (float)(_value * (1 / 255.0f)); }
inline uint16 FloatToHalf(float _value)
{
union { float f; uint32 i; }_fb = { _value };
# ifdef FAST_HALF_FLOAT
return (uint16)((_fb.i >> 16) & 0x8000) | ((((_fb.i & 0x7f800000) - 0x38000000) >> 13) & 0x7c00) | ((_fb.i >> 13) & 0x03ff);
# else
uint32 _s = (_fb.i >> 16) & 0x00008000; // sign
int32 _e = ((_fb.i >> 23) & 0x000000ff) - 0x00000070; // exponent
uint32 _r = _fb.i & 0x007fffff; // mantissa
if (_e < 1)
{
if (_e < -10)
return 0;
_r = (_r | 0x00800000) >> (14 - _e);
return (uint16)(_s | _r);
}
else if (_e == 0x00000071)
{
if (_r == 0)
return (uint16)(_s | 0x7c00); // Inf
else
return (uint16)(((_s | 0x7c00) | (_r >>= 13)) | (_r == 0)); // NaN
}
if (_e > 30)
return (uint16)(_s | 0x7c00); // Overflow
return (uint16)((_s | (_e << 10)) | (_r >> 13));
# endif
}
inline float HalfToFloat(uint16 _value)
{
union { uint32 i; float f; }_fb;
# ifdef FAST_HALF_FLOAT
_fb.i = ((_value & 0x8000) << 16) | (((_value & 0x7c00) + 0x1C000) << 13) | ((_value & 0x03FF) << 13);
# else
register int32 _s = (_value >> 15) & 0x00000001; // sign
register int32 _e = (_value >> 10) & 0x0000001f; // exponent
register int32 _r = _value & 0x000003ff; // mantissa
if (_e == 0)
{
if (_r == 0) // Plus or minus zero
{
_fb.i = _s << 31;
return _fb.f;
}
else // Denormalized number -- renormalize it
{
for (; !(_r & 0x00000400); _r <<= 1, _e -= 1);
_e += 1;
_r &= ~0x00000400;
}
}
else if (_e == 31)
{
if (_r == 0) // Inf
{
_fb.i = (_s << 31) | 0x7f800000;
return _fb.f;
}
else // NaN
{
_fb.i = ((_s << 31) | 0x7f800000) | (_r << 13);
return _fb.f;
}
}
_e = (_e + 112) << 23;
_r = _r << 13;
_fb.i = ((_s << 31) | _e) | _r;
# endif
return _fb.f;
}
inline float FixedToFloat(uint32 _value, uint32 _bits, float _default = 0)
{
if (_bits > 31)
_bits = 31;
return _bits ? ((float)_value) / ((float)((1u << _bits) - 1u)) : _default;
}
inline uint32 FloatToFixed(float _value, uint32 _bits)
{
if (_bits > 31)
_bits = 31;
if (_value <= 0)
return 0;
if (_value >= 1)
return (1u << _bits) - 1u;
return (uint32)(_value * (float)(1u << _bits));
}
inline uint32 FixedToFixed(uint32 _value, uint32 _from, uint32 _to)
{
if (_from > 31)
_from = 31;
if (_to > 31)
_to = 31;
if (_from > _to)
_value >>= _from - _to;
else if (_from < _to && _value != 0)
{
uint32 _max = (1u << _from) - 1u;
if (_value == _max) _value = (1u << _to) - 1u;
else if (_max > 0) _value *= (1u << _to) / _max;
else _value = 0;
}
return _value;
}
//----------------------------------------------------------------------------//
// CheckSum
//----------------------------------------------------------------------------//
ENGINE_API uint32 Crc32(uint32 _crc, const void* _buf, uint _size);
inline uint32 Crc32(const void* _buf, uint _size) { return Crc32(0, _buf, _size); }
inline uint32 Crc32(const char* _str, int _length = -1, uint32 _crc = 0) { return _str ? Crc32(_crc, _str, _length < 0 ? (uint)strlen(_str) : _length) : _crc; }
inline uint32 Crc32(const String& _str, uint32 _crc = 0) { return Crc32(_crc, _str, _str.Length()); }
template <typename T> uint32 Crc32(const T& _obj, uint32 _crc = 0) { return Crc32(_crc, &_obj, sizeof(_obj)); }
//----------------------------------------------------------------------------//
// half
//----------------------------------------------------------------------------//
struct half
{
half(void) { }
half(float _value) { Pack(_value); }
half& operator = (float _value) { return Pack(_value); }
operator const float(void) const { return Unpack(); }
half operator ++ (int) { half _tmp(*this); Pack(Unpack() + 1); return _tmp; }
half& operator ++ (void) { return Pack(Unpack() + 1); }
half operator -- (int) { half _tmp(*this); Pack(Unpack() - 1); return _tmp; }
half& operator -- (void) { return Pack(Unpack() - 1); }
half& operator += (float _rhs) { return Pack(Unpack() + _rhs); }
half& operator -= (float _rhs) { return Pack(Unpack() - _rhs); }
half& operator *= (float _rhs) { return Pack(Unpack() * _rhs); }
half& operator /= (float _rhs) { return Pack(Unpack() / _rhs); }
half& Pack(float _value) { value = FloatToHalf(_value); return *this; }
const float Unpack(void) const { return HalfToFloat(value); }
uint16 value;
};
//----------------------------------------------------------------------------//
// Vec2T
//----------------------------------------------------------------------------//
template <typename T> struct Vec2T
{
Vec2T(void) { }
Vec2T(T _xy) : x(_xy), y(_xy) { }
Vec2T(T _x, T _y) : x(_x), y(_y) { }
Vec2T Copy(void) const { return *this; }
template <typename X> Vec2T(const Vec2T<X>& _v) : x(static_cast<T>(_v.x)), y(static_cast<T>(_v.y)) { }
template <typename X> explicit Vec2T(X _x, X _y) : x(static_cast<T>(_x)), y(static_cast<T>(_y)) { }
template <typename X> X Cast(void) const { return X(x, y); }
const T operator [] (uint _index) const { return (&x)[_index]; }
T& operator [] (uint _index) { return (&x)[_index]; }
const T* operator * (void) const { return &x; }
T* operator * (void) { return &x; }
Vec2T operator - (void) const { return Vec2T(-x, -y); }
Vec2T operator + (const Vec2T& _rhs) const { return Vec2T(x + _rhs.x, y + _rhs.y); }
Vec2T operator - (const Vec2T& _rhs) const { return Vec2T(x - _rhs.x, y - _rhs.y); }
Vec2T operator * (T _rhs) const { return Vec2T(x * _rhs, y * _rhs); }
Vec2T operator / (T _rhs) const { return Vec2T(x / _rhs, y / _rhs); }
Vec2T& operator += (const Vec2T& _rhs) { x += _rhs.x, y += _rhs.y; return *this; }
Vec2T& operator -= (const Vec2T& _rhs) { x -= _rhs.x, y -= _rhs.y; return *this; }
Vec2T& operator *= (T _rhs) { x *= _rhs, y *= _rhs; return *this; }
Vec2T& operator /= (T _rhs) { x /= _rhs, y /= _rhs; return *this; }
bool operator == (const Vec2T& _rhs) const { return x == _rhs.x && y == _rhs.y; }
bool operator != (const Vec2T& _rhs) const { return x != _rhs.x || y != _rhs.y; }
Vec2T& Set(T _xy) { x = _xy, y = _xy; return *this; }
Vec2T& Set(T _x, T _y) { x = _x, y = _y; return *this; }
Vec2T& Set(const Vec2T& _other) { return *this = _other; }
T x, y;
static const Vec2T Zero;
static const Vec2T One;
static const Vec2T UnitX;
static const Vec2T UnitY;
};
template <typename T> const Vec2T<T> Vec2T<T>::Zero(0);
template <typename T> const Vec2T<T> Vec2T<T>::One(1);
template <typename T> const Vec2T<T> Vec2T<T>::UnitX(1, 0);
template <typename T> const Vec2T<T> Vec2T<T>::UnitY(0, 1);
typedef Vec2T<float> Vec2;
typedef Vec2T<half> Vec2h;
typedef Vec2T<int> Vec2i;
typedef Vec2T<uint> Vec2ui;
//----------------------------------------------------------------------------//
// Vec3T
//----------------------------------------------------------------------------//
template <typename T> struct Vec3T
{
Vec3T(void) { }
Vec3T(T _xyz) : x(_xyz), y(_xyz), z(_xyz) { }
Vec3T(T _x, T _y, T _z) : x(_x), y(_y), z(_z) { }
template <typename X> Vec3T(const Vec3T<X>& _v) : x(static_cast<T>(_v.x)), y(static_cast<T>(_v.y)), z(static_cast<T>(_v.z)) { }
template <typename X> explicit Vec3T(X _x, X _y, X _z) : x(static_cast<T>(_x)), y(static_cast<T>(_y)), z(static_cast<T>(_z)) { }
Vec3T Copy(void) const { return *this; }
template <typename X> X Cast(void) const { return X(x, y, z); }
const T operator [] (uint _index) const { return (&x)[_index]; }
T& operator [] (uint _index) { return (&x)[_index]; }
const T* operator * (void) const { return &x; }
T* operator * (void) { return &x; }
Vec3T operator - (void) const { return Vec3T(-x, -y, -z); }
Vec3T operator + (const Vec3T& _rhs) const { return Vec3T(x + _rhs.x, y + _rhs.y, z + _rhs.z); }
Vec3T operator - (const Vec3T& _rhs) const { return Vec3T(x - _rhs.x, y - _rhs.y, z - _rhs.z); }
Vec3T operator * (const Vec3T& _rhs) const { return Vec3T(x * _rhs.x, y * _rhs.y, z * _rhs.z); }
Vec3T operator / (const Vec3T& _rhs) const { return Vec3T(x / _rhs.x, y / _rhs.y, z / _rhs.z); }
Vec3T operator * (T _rhs) const { return Vec3T(x * _rhs, y * _rhs, z * _rhs); }
Vec3T operator / (T _rhs) const { return Vec3T(x / _rhs, y / _rhs, z / _rhs); }
Vec3T& operator += (const Vec3T& _rhs) { x += _rhs.x, y += _rhs.y, z += _rhs.z; return *this; }
Vec3T& operator -= (const Vec3T& _rhs) { x -= _rhs.x, y -= _rhs.y, z -= _rhs.z; return *this; }
Vec3T& operator *= (const Vec3T& _rhs) { x *= _rhs.x, y *= _rhs.y, z *= _rhs.z; return *this; }
Vec3T& operator /= (const Vec3T& _rhs) { x /= _rhs.x, y /= _rhs.y, z /= _rhs.z; return *this; }
Vec3T& operator *= (T _rhs) { x *= _rhs, y *= _rhs, z *= _rhs; return *this; }
Vec3T& operator /= (T _rhs) { x /= _rhs, y /= _rhs, z /= _rhs; return *this; }
friend Vec3T operator / (T _lhs, const Vec3T& _rhs) { return Vec3T(_lhs / _rhs.x, _lhs / _rhs.y, _lhs / _rhs.z); }
friend Vec3T operator * (T _lhs, const Vec3T& _rhs) { return Vec3T(_lhs * _rhs.x, _lhs * _rhs.y, _lhs * _rhs.z); }
bool operator == (const Vec3T& _rhs) const { return x == _rhs.x && y == _rhs.y && z == _rhs.z; }
bool operator != (const Vec3T& _rhs) const { return x != _rhs.x || y != _rhs.y || z != _rhs.z; }
Vec3T& Set(T _xyz) { x = _xyz, y = _xyz, z = _xyz; return *this; }
Vec3T& Set(T _x, T _y, T _z) { x = _x, y = _y, z = _z; return *this; }
Vec3T& Set(const Vec3T& _other) { return *this = _other; }
// [for Vec3T<float>]
Vec3T<float>& SetMin(const Vec3T<float>& _a, const Vec3T<float>& _b) { x = Min(_a.x, _b.x), y = Min(_a.y, _b.y), z = Min(_a.z, _b.z); return *this; }
Vec3T<float>& SetMin(const Vec3T<float>& _other) { return SetMin(*this, _other); }
Vec3T<float>& SetMax(const Vec3T<float>& _a, const Vec3T<float>& _b) { x = Max(_a.x, _b.x), y = Max(_a.y, _b.y), z = Max(_a.z, _b.z); return *this; }
Vec3T<float>& SetMax(const Vec3T<float>& _other) { return SetMax(*this, _other); }
Vec3T<float>& Normalize(void)
{
float _l = LengthSq();
if (_l > Epsilon2)
*this *= RSqrt(_l);
return *this;
}
Vec3T<float>& NormalizeFast(void) { return *this *= LengthInv(); }
float LengthSq(void) const { return x * x + y * y + z * z; }
float Length(void) const { return Sqrt(x * x + y * y + z * z); }
float LengthInv(void) const { return Sqrt(x * x + y * y + z * z); }
float Dot(const Vec3T<float>& _rhs) const { return x * _rhs.x + y * _rhs.y + z * _rhs.z; }
float AbsDot(const Vec3T<float>& _rhs) const { return Abs(x * _rhs.x) + Abs(y * _rhs.y) + Abs(z * _rhs.z); }
Vec3T<float> Cross(const Vec3T<float>& _rhs) const { return Vec3T<float>(y * _rhs.z - z * _rhs.y, z * _rhs.x - x * _rhs.z, x * _rhs.y - y * _rhs.x); }
float Distance(const Vec3T<float>& _v) const { return (*this - _v).Length(); }
float DistanceSq(const Vec3T<float>& _v) const { return (*this - _v).LengthSq(); }
Vec3T<float> MidPoint(const Vec3T<float>& _v) const { return (*this + _v) * 0.5f; }
Vec3T<float> Reflect(const Vec3T<float>& _n) const { return Vec3T<float>(*this - (2 * Dot(_n) * _n)); }
Vec3T<float> Perpendicular(void) const
{
Vec3T<float> _perp = Cross(UNIT_X);
if (_perp.LengthSq() <= EPSILON2)
_perp = Cross(UNIT_Y);
return _perp.Normalize();
}
float Angle(const Vec3T<float>& _v) const
{
float _lp = LengthSq() * _v.LengthSq();
if (_lp > EPSILON2)
_lp = RSqrt(_lp);
return ACos(Clamp<float>(Dot(_v) * _lp, -1, 1));
}
T x, y, z;
static const Vec3T Zero;
static const Vec3T One;
static const Vec3T UnitX;
static const Vec3T UnitY;
static const Vec3T UnitZ;
};
template <typename T> const Vec3T<T> Vec3T<T>::Zero(0);
template <typename T> const Vec3T<T> Vec3T<T>::One(1);
template <typename T> const Vec3T<T> Vec3T<T>::UnitX(1, 0, 0);
template <typename T> const Vec3T<T> Vec3T<T>::UnitY(0, 1, 0);
template <typename T> const Vec3T<T> Vec3T<T>::UnitZ(0, 0, 1);
typedef Vec3T<float> Vec3;
typedef Vec3T<half> Vec3h;
typedef Vec3T<int> Vec3i;
typedef Vec3T<uint> Vec3ui;
//----------------------------------------------------------------------------//
// Vec4T
//----------------------------------------------------------------------------//
template <typename T> struct Vec4T
{
Vec4T(void) { }
Vec4T(T _xyzw) : x(_xyzw), y(_xyzw), z(_xyzw), w(_xyzw) { }
Vec4T(T _x, T _y, T _z, T _w) : x(_x), y(_y), z(_z), w(_w) { }
template <typename X> Vec4T(const Vec4T<X>& _v) : x(static_cast<T>(_v.x)), y(static_cast<T>(_v.y)), z(static_cast<T>(_v.z)), w(static_cast<T>(_v.w)) { }
template <typename X> explicit Vec4T(X _x, X _y, X _z, X _w) : x(static_cast<T>(_x)), y(static_cast<T>(_y)), z(static_cast<T>(_z)), w(static_cast<T>(_w)) { }
Vec4T Copy(void) const { return *this; }
template <typename X> X Cast(void) const { return X(x, y, z, w); }
const T operator [] (uint _index) const { return (&x)[_index]; }
T& operator [] (uint _index) { return (&x)[_index]; }
const T* operator * (void) const { return &x; }
T* operator * (void) { return &x; }
Vec4T operator - (void) const { return Vec4T(-x, -y, -z, -w); }
Vec4T operator + (const Vec4T& _rhs) const { return Vec4T(x + _rhs.x, y + _rhs.y, z + _rhs.z, w + _rhs.w); }
Vec4T operator - (const Vec4T& _rhs) const { return Vec4T(x - _rhs.x, y - _rhs.y, z - _rhs.z, w - _rhs.w); }
Vec4T operator * (T _rhs) const { return Vec4T(x * _rhs, y * _rhs, z * _rhs, w * _rhs); }
Vec4T operator / (T _rhs) const { return Vec4T(x / _rhs, y / _rhs, z / _rhs, w / _rhs); }
Vec4T& operator += (const Vec4T& _rhs) { x += _rhs.x, y += _rhs.y, z += _rhs.z, w += _rhs.w; return *this; }
Vec4T& operator -= (const Vec4T& _rhs) { x -= _rhs.x, y -= _rhs.y, z -= _rhs.z, w -= _rhs.w; return *this; }
Vec4T& operator *= (T _rhs) { x *= _rhs, y *= _rhs, z *= _rhs, w *= _rhs; return *this; }
Vec4T& operator /= (T _rhs) { x /= _rhs, y /= _rhs, z /= _rhs, w /= _rhs; return *this; }
Vec4T& Set(T _xyzw) { x = _xyzw, y = _xyzw, z = _xyzw, w = _xyzw; return *this; }
Vec4T& Set(T _x, T _y, T _z, T _w) { x = _x, y = _y, z = _z, w = _w; return *this; }
Vec4T& Set(const Vec4T& _other) { return *this = _other; }
T x, y, z, w;
static const Vec4T Zero;
static const Vec4T One;
static const Vec4T Identity;
};
template <typename T> const Vec4T<T> Vec4T<T>::Zero(0);
template <typename T> const Vec4T<T> Vec4T<T>::One(1);
template <typename T> const Vec4T<T> Vec4T<T>::Identity(0, 0, 0, 1);
typedef Vec4T<float> Vec4;
typedef Vec4T<half> Vec4h;
typedef Vec4T<int> Vec4i;
typedef Vec4T<int8> Vec4b;
typedef Vec4T<uint8> Vec4ub;
//----------------------------------------------------------------------------//
// Quat
//----------------------------------------------------------------------------//
struct Quat
{
Quat(void) { }
Quat(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { }
Quat Copy(void) const { return *this; }
template <typename X> X Cast(void) const { return X(x, y, z, w); }
const float operator [] (uint _index) const { return v[_index]; }
float& operator [] (uint _index) { return v[_index]; }
const float* operator * (void) const { return v; }
float* operator * (void) { return v; }
Quat operator - (void) const { return Quat(-x, -y, -z, -w); }
Quat operator + (const Quat& _rhs) const { return Quat(x + _rhs.x, y + _rhs.y, z + _rhs.z, w + _rhs.w); }
Quat operator - (const Quat& _rhs) const { return Quat(x - _rhs.x, y - _rhs.y, z - _rhs.z, w - _rhs.w); }
Quat operator * (const Quat& _rhs) const
{
return Quat(w * _rhs.x + x * _rhs.w + y * _rhs.z - z * _rhs.y,
w * _rhs.y + y * _rhs.w + z * _rhs.x - x * _rhs.z,
w * _rhs.z + z * _rhs.w + x * _rhs.y - y * _rhs.x,
w * _rhs.w - x * _rhs.x - y * _rhs.y - z * _rhs.z);
}
Quat operator * (float _rhs) const { return Quat(x * _rhs, y * _rhs, z * _rhs, w * _rhs); }
Quat operator / (float _rhs) const { return Quat(x / _rhs, y / _rhs, z / _rhs, w / _rhs); }
Quat& operator += (const Quat& _rhs) { x += _rhs.x, y += _rhs.y, z += _rhs.z, w += _rhs.w; return *this; }
Quat& operator -= (const Quat& _rhs) { x -= _rhs.x, y -= _rhs.y, z -= _rhs.z, w -= _rhs.w; return *this; }
Quat& operator *= (const Quat& _rhs) { return *this = *this * _rhs; }
Quat& operator *= (float _rhs) { x += _rhs, y += _rhs, z += _rhs, w += _rhs; return *this; }
Quat& operator /= (float _rhs) { x += _rhs, y += _rhs, z += _rhs, w += _rhs; return *this; }
friend Quat operator * (float _lhs, const Quat& _rhs) { return Quat(_lhs * _rhs.x, _lhs * _rhs.y, _lhs * _rhs.z, _lhs * _rhs.w); }
friend Vec3 operator * (const Vec3& _lhs, const Quat& _rhs)
{
const Vec3& _q = *(Vec3*)_rhs.v;
Vec3 _uv(_q.Cross(_lhs));
return _lhs + _uv * 2 * _rhs.w + _q.Cross(_uv) * 2;
}
Quat& Set(float _x, float _y, float _z, float _w) { x = _x, y = _y, z = _z, w = _w; return *this; }
Quat& Set(const Quat& _other) { return *this = _other; }
float Dot(const Quat& _q) const
{
return x * _q.x + y * _q.y + z * _q.z + w * _q.w;
}
Quat& Normalize(void)
{
float _l = x * x + y * y + z * z + w * w;
if (_l > Epsilon2)
*this *= RSqrt(_l);
return *this;
}
Quat& Inverse(void)
{
float _d = x * x + y * y + z * z + w * w;
if (_d > 0)
x *= -_d, y *= -_d, z *= -_d, w *= _d;
else
x = 0, y = 0, z = 0, w = 1;
return *this;
}
Quat& UnitInverse(void)
{
x = -x, y = -y, z = -z;
return *this;
}
Quat Nlerp(const Quat& _q, float _t, bool _shortestPath = false) const
{
const Quat& _p = *this;
float _c = _p.Dot(_q);
Quat _result;
if (_c < 0 && _shortestPath)
_result = _p + _t * ((-_q) - _p);
else
_result = _p + _t * (_q - _p);
return _result.Normalize();
}
Quat Slerp(const Quat& _q, float _t, bool _shortestPath = false) const
{
const Quat& _p = *this;
float _c = _p.Dot(_q);
Quat _tmp;
if (_c < 0 && _shortestPath)
_c = -_c, _tmp = -_q;
else
_tmp = _q;
if (Abs(_c) < 1 - Epsilon)
{
float _s = Sqrt(1 - _c * _c);
float _angle = ATan2(_s, _c);
float _invs = 1 / _s;
float _coeff0 = Sin((1 - _t) * _angle) * _invs;
float _coeff1 = Sin(_t * _angle) * _invs;
return _coeff0 * _p + _coeff1 * _tmp;
}
return Quat((1 - _t) * _p + _t * _tmp).Normalize();
}
void ToMatrixRows(float* _r0, float* _r1, float* _r2) const
{
float _x2 = x + x, _y2 = y + y, _z2 = z + z;
float _wx = _x2 * w, _wy = _y2 * w, _wz = _z2 * w, _xx = _x2 * x, _xy = _y2 * x, _xz = _z2 * x, _yy = _y2 * y, _yz = _z2 * y, _zz = _z2 * z;
_r0[0] = 1 - (_yy + _zz), _r0[1] = _xy + _wz, _r0[2] = _xz - _wy;
_r1[0] = _xy - _wz, _r1[1] = 1 - (_xx + _zz), _r1[2] = _yz + _wx;
_r2[0] = _xz + _wy, _r2[1] = _yz - _wx, _r2[2] = 1 - (_xx + _yy);
}
Quat& FromMatrixRows(const float* _r0, const float* _r1, const float* _r2)
{
float _invr, _root = _r0[0] + _r1[1] + _r2[2];
if (_root > 0)
{
_root = Sqrt(_root + 1);
_invr = 0.5f / _root;
return Set((_r1[2] - _r2[1]) * _invr, (_r2[0] - _r0[2]) * _invr, (_r0[1] - _r1[0]) * _invr, _root * 0.5f);
}
if (_r0[0] > _r1[1] && _r0[0] > _r2[2])
{
_root = Sqrt(_r0[0] - _r1[1] - _r2[2] + 1);
_invr = 0.5f / _root;
return Set(_root * 0.5f, (_r0[1] + _r1[0]) * _invr, (_r0[2] + _r2[0]) * _invr, (_r1[2] - _r2[1]) * _invr);
}
else if (_r1[1] > _r0[0] && _r1[1] > _r2[2])
{
_root = Sqrt(_r1[1] - _r2[2] - _r0[0] + 1);
_invr = 0.5f / _root;
return Set((_r1[0] + _r0[1]) * _invr, _root * 0.5f, (_r1[2] + _r2[1]) * _invr, (_r2[0] - _r0[2]) * _invr);
}
_root = Sqrt(_r2[2] - _r0[0] - _r1[1] + 1);
_invr = 0.5f / _root;
return Set((_r2[0] + _r0[2]) * _invr, (_r2[1] + _r1[2]) * _invr, _root * 0.5f, (_r0[1] - _r1[0]) * _invr);
}
Quat& FromAxisAngle(const Vec3& _axis, float _angle)
{
float _s, _c;
SinCos(_angle*0.5f, _s, _c);
return Set(_axis.x * _s, _axis.y * _s, _axis.z * _s, _c);
}
union
{
struct { float x, y, z, w; };
float v[4];
};
ENGINE_API static const Quat Zero;
ENGINE_API static const Quat Identity;
};
inline Quat Mix(const Quat& _a, const Quat& _b, float _t)
{
return _a.Slerp(_b, _t);
}
//----------------------------------------------------------------------------//
// Mat34
//----------------------------------------------------------------------------//
struct Mat34
{
Mat34(void) { }
Mat34(float _val) { *this = Zero; m[0][0] = _val; m[1][1] = _val; m[2][2] = _val; }
Mat34(float _00, float _01, float _02, float _03, float _10, float _11, float _12, float _13, float _20, float _21, float _22, float _23) :
m00(_00), m01(_01), m02(_02), m03(_03), m10(_10), m11(_11), m12(_12), m13(_13), m20(_20), m21(_21), m22(_22), m23(_23) { }
explicit Mat34(const float* _m34) { memcpy(v, _m34, 12 * sizeof(float)); }
Mat34 Copy(void) const { return *this; }
const float* operator [] (int _row) const { return m[_row]; }
float* operator [] (int _row) { return m[_row]; }
const float* operator * (void) const { return v; }
float* operator * (void) { return v; }
float& operator () (uint _row, uint _col) { return m[_row][_col]; }
const float operator () (uint _row, uint _col) const { return m[_row][_col]; }
const Vec3& Row(uint _row) const { return *(Vec3*)(m[_row]); }
Vec3& Row(uint _row) { return *(Vec3*)(m[_row]); }
Mat34 operator + (const Mat34& _rhs) const { return Copy().Add(_rhs); }
Mat34 operator * (const Mat34& _rhs) const { return Copy().Multiply(_rhs); }
Mat34 operator * (float _rhs) const{ return Copy().Multiply(_rhs); }
friend Vec3 operator * (const Vec3& _lhs, const Mat34& _rhs) { return _rhs.Transform(_lhs); } // Vec3 = Vec3 * Mat34
Mat34& operator += (const Mat34& _rhs) { return Add(_rhs); }
Mat34& operator *= (const Mat34& _rhs) { return Multiply(_rhs); }
Mat34& operator *= (float _rhs) { return Multiply(_rhs); }
Mat34& Add(const Mat34& _rhs)
{
for (int i = 0; i < 12; ++i) v[i] += v[i];
return *this;
}
Mat34& Multiply(float _rhs)
{
for (int i = 0; i < 12; ++i)
v[i] *= _rhs;
return *this;
}
Mat34& Multiply(const Mat34& _rhs)
{
return *this = Mat34(m00 * _rhs.m00 + m01 * _rhs.m10 + m02 * _rhs.m20,
m00 * _rhs.m01 + m01 * _rhs.m11 + m02 * _rhs.m21,
m00 * _rhs.m02 + m01 * _rhs.m12 + m02 * _rhs.m22,
m00 * _rhs.m03 + m01 * _rhs.m13 + m02 * _rhs.m23 + m03,
m10 * _rhs.m00 + m11 * _rhs.m10 + m12 * _rhs.m20,
m10 * _rhs.m01 + m11 * _rhs.m11 + m12 * _rhs.m21,
m10 * _rhs.m02 + m11 * _rhs.m12 + m12 * _rhs.m22,
m10 * _rhs.m03 + m11 * _rhs.m13 + m12 * _rhs.m23 + m13,
m20 * _rhs.m00 + m21 * _rhs.m10 + m22 * _rhs.m20,
m20 * _rhs.m01 + m21 * _rhs.m11 + m22 * _rhs.m21,
m20 * _rhs.m02 + m21 * _rhs.m12 + m22 * _rhs.m22,
m20 * _rhs.m03 + m21 * _rhs.m13 + m22 * _rhs.m23 + m23);
}
float Determinant(void) const
{
return m00 * m11 * m22 + m01 * m12 * m20 + m02 * m10 * m21 - m02 * m11 * m20 - m00 * m12 * m21 - m01 * m10 * m22;
}
Mat34& Inverse(void)
{
float _m00 = m00, _m01 = m01, _m02 = m02, _m03 = m03, _m10 = m10, _m11 = m11, _m12 = m12, _m13 = m13, _m20 = m20, _m21 = m21, _m22 = m22, _m23 = m23;
float _v0 = (_m23 * _m10 - _m20 * _m13), _v1 = (_m23 * _m11 - _m21 * _m13), _v2 = (_m23 * _m12 - _m22 * _m13);
float _t00 = +(_m22 * _m11 - _m21 * _m12), _t10 = -(_m22 * _m10 - _m20 * _m12), _t20 = +(_m21 * _m10 - _m20 * _m11);
float _invdet = 1 / (_t00 * _m00 + _t10 * _m01 + _t20 * _m02);
m00 = _t00 * _invdet;
m10 = _t10 * _invdet;
m20 = _t20 * _invdet;
m01 = -(_m22 * _m01 - _m21 * _m02) * _invdet;
m11 = +(_m22 * _m00 - _m20 * _m02) * _invdet;
m21 = -(_m21 * _m00 - _m20 * _m01) * _invdet;
m02 = +(_m12 * _m01 - _m11 * _m02) * _invdet;
m12 = -(_m12 * _m00 - _m10 * _m02) * _invdet;
m22 = +(_m11 * _m00 - _m10 * _m01) * _invdet;
m03 = -(_v2 * _m01 - _v1 * _m02 + (_m22 * _m11 - _m21 * _m12) * _m03) * _invdet;
m13 = +(_v2 * _m00 - _v0 * _m02 + (_m22 * _m10 - _m20 * _m12) * _m03) * _invdet;
m23 = -(_v1 * _m00 - _v0 * _m01 + (_m21 * _m10 - _m20 * _m11) * _m03) * _invdet;
return *this;
}
Vec3 Translate(const Vec3& _v) const
{
return Vec3(_v.x + m03, _v.y + m13, _v.z + m23);
}
Vec3 Transform(const Vec3& _v) const
{
return Vec3(
m00 * _v.x + m01 * _v.y + m02 * _v.z + m03,
m10 * _v.x + m11 * _v.y + m12 * _v.z + m13,
m20 * _v.x + m21 * _v.y + m22 * _v.z + m23);
}
Vec3 TransformVectorAbs(const Vec3& _v) const
{
return Vec3(
Abs(m00) * _v.x + Abs(m01) * _v.y + Abs(m02) * _v.z,
Abs(m10) * _v.x + Abs(m11) * _v.y + Abs(m12) * _v.z,
Abs(m20) * _v.x + Abs(m21) * _v.y + Abs(m22) * _v.z);
}
Vec3 TransformVector(const Vec3& _v) const
{
return Vec3(m00 * _v.x + m01 * _v.y + m02 * _v.z, m10 * _v.x + m11 * _v.y + m12 * _v.z, m20 * _v.x + m21 * _v.y + m22 * _v.z);
}
Mat34& SetTranslation(const Vec3& _translation)
{
m03 = _translation.x, m13 = _translation.y, m23 = _translation.z;
return *this;
}
Vec3 GetTranslation(void) const
{
return Vec3(m03, m12, m23);
}
Mat34& CreateTranslation(const Vec3& _translation)
{
return (*this = Identity).SetTranslation(_translation);
}
Mat34& SetRotation(const Quat& _rotation)
{
Vec3 _scale = GetScale();
_rotation.ToMatrixRows(m[0], m[1], m[2]);
Row(0) *= _scale, Row(1) *= _scale, Row(2) *= _scale;
return *this;
}
Quat GetRotation(void) const
{
Vec3 _m0(m00, m10, m20);
Vec3 _m1(m01, m11, m21);
Vec3 _m2(m02, m12, m22);
Vec3 _q0 = _m0.Copy().Normalize();
Vec3 _q1 = (_m1 - _q0 * _q0.Dot(_m1)).Normalize();
Vec3 _q2 = ((_m2 - _q0 * _q0.Dot(_m2)) - _q1 * _q1.Dot(_m2)).Normalize();
float _det = _q0[0] * _q1[1] * _q2[2] + _q0[1] * _q1[2] * _q2[0] + _q0[2] * _q1[0] * _q2[1] - _q0[2] * _q1[1] * _q2[0] - _q0[1] * _q1[0] * _q2[2] - _q0[0] * _q1[2] * _q2[1];
if (_det < 0)
_q0 = -_q0, _q1 = -_q1, _q2 = -_q2;
return Quat().FromMatrixRows(*_q0, *_q1, *_q2);
}
Mat34& CreateRotation(const Quat& _rotation)
{
SetTranslation(Vec3::Zero);
_rotation.ToMatrixRows(m[0], m[1], m[2]);
return *this;
}
bool HasScale(void) const
{
if (!(Abs((m00 * m00 + m10 * m10 + m20 * m20) - 1) < Epsilon))
return true;
if (!(Abs((m01 * m01 + m11 * m11 + m21 * m21) - 1) < Epsilon))
return true;
if (!(Abs((m02 * m02 + m12 * m12 + m22 * m22) - 1) < Epsilon))
return true;
return false;
}
bool HasNegativeScale(void) const
{
return Determinant() < 0;
}
Mat34& SetScale(const Vec3& _scale)
{
Quat _rotation = GetRotation();
_rotation.ToMatrixRows(m[0], m[1], m[2]);
Row(0) *= _scale, Row(1) *= _scale, Row(2) *= _scale;
return *this;
}
Vec3 GetScale(void) const
{
return Vec3(
Sqrt(m00 * m00 + m10 * m10 + m20 * m20),
Sqrt(m01 * m01 + m11 * m11 + m21 * m21),
Sqrt(m02 * m02 + m12 * m12 + m22 * m22));
}
Mat34& CreateScale(const Vec3& _scale)
{
*this = Zero;
m00 = _scale.x, m11 = _scale.y, m22 = _scale.z;
return *this;
}
Mat34& CreateTransform(const Vec3& _translation, const Quat& _rotation, const Vec3& _scale = Vec3::One)
{
// Ordering: Scale, Rotate, Translate
float _r0[3], _r1[3], _r2[3];
_rotation.ToMatrixRows(_r0, _r1, _r2);
m00 = _scale.x * _r0[0], m01 = _scale.y * _r0[1], m02 = _scale.z * _r0[2], m03 = _translation.x;
m10 = _scale.x * _r1[0], m11 = _scale.y * _r1[1], m12 = _scale.z * _r1[2], m13 = _translation.y;
m20 = _scale.x * _r2[0], m21 = _scale.y * _r2[1], m22 = _scale.z * _r2[2], m23 = _translation.z;
return *this;
}
Mat34& CreateInverseTransform(const Vec3& _translation, const Quat& _rotation, const Vec3& _scale = Vec3::One)
{
Vec3 _inv_scale(1 / _scale);
Quat _inv_rotation = _rotation.Copy().Inverse();
Vec3 _inv_translation((-_translation * _inv_rotation) * _inv_scale);
return CreateTransform(_inv_translation, _inv_rotation, _inv_scale);
}
union
{
struct { float m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23; };
float m[3][4]; // [row][col]
float v[12];
};
ENGINE_API static const Mat34 Zero;
ENGINE_API static const Mat34 Identity;
};
//----------------------------------------------------------------------------//
// Mat44
//----------------------------------------------------------------------------//
struct Mat44
{
Mat44(void) { }
Mat44(float _val) { *this = Zero; m[0][0] = _val; m[1][1] = _val; m[2][2] = _val; m[3][3] = _val; }
Mat44(const Mat34& _m34) : m30(0), m31(0), m32(0), m33(1) { memcpy(v, *_m34, 12 * sizeof(float)); }
explicit Mat44(const float* _m44) { memcpy(v, _m44, 16 * sizeof(float)); }
Mat44(float _00, float _01, float _02, float _03, float _10, float _11, float _12, float _13, float _20, float _21, float _22, float _23, float _30, float _31, float _32, float _33) :
m00(_00), m01(_01), m02(_02), m03(_03), m10(_10), m11(_11), m12(_12), m13(_13), m20(_20), m21(_21), m22(_22), m23(_23), m30(_30), m31(_31), m32(_32), m33(_33) { }
Mat44 Copy(void) const { return *this; }
operator const Mat34& (void) const { /*ASSERT(IsAffine());*/ return *(Mat34*)(v); }
const float* operator [] (int _row) const { return m[_row]; }
float* operator [] (int _row) { return m[_row]; }
const float* operator * (void) const { return v; }
float* operator * (void) { return v; }
float& operator () (uint _row, uint _col) { return m[_row][_col]; }
const float operator () (uint _row, uint _col) const { return m[_row][_col]; }
const Vec3& Row(uint _row) const { return *(Vec3*)(m[_row]); }
Vec3& Row(uint _row) { return *(Vec3*)(m[_row]); }
const Vec4& Row4(uint _row) const { return *(Vec4*)(m[_row]); }
Vec4& Row4(uint _row) { return *(Vec4*)(m[_row]); }
Mat44 operator + (const Mat44& _rhs) const { return Copy().Add(_rhs); }
Mat44 operator * (const Mat44& _rhs) const { return Copy().Multiply(_rhs); }
Mat44 operator * (const Mat34& _rhs) const { return Copy().Multiply(_rhs); }
Mat44 operator * (float _rhs) const { return Copy().Multiply(_rhs); }
friend Vec3 operator * (const Vec3& _lhs, const Mat44& _rhs) { return _rhs.Transform(_lhs); } // Vec3 = Vec3 * Mat44
Mat44& operator += (const Mat44& _rhs) { return Add(_rhs); }
Mat44& operator *= (const Mat44& _rhs) { return Multiply(_rhs); }
Mat44& operator *= (const Mat34& _rhs) { return Multiply(_rhs); }
Mat44& operator *= (float _rhs) { return Multiply(_rhs); }
Mat44& Add(const Mat44& _rhs)
{
for (int i = 0; i < 16; ++i)
v[i] += _rhs.v[i];
return *this;
}
Mat44& Multiply(float _rhs)
{
for (int i = 0; i < 16; ++i)
v[i] += _rhs;
return *this;
}
Mat44& Multiply(const Mat44& _rhs)
{
return *this = Mat44(
m00 * _rhs.m00 + m01 * _rhs.m10 + m02 * _rhs.m20 + m03 * _rhs.m30,
m00 * _rhs.m01 + m01 * _rhs.m11 + m02 * _rhs.m21 + m03 * _rhs.m31,
m00 * _rhs.m02 + m01 * _rhs.m12 + m02 * _rhs.m22 + m03 * _rhs.m32,
m00 * _rhs.m03 + m01 * _rhs.m13 + m02 * _rhs.m23 + m03 * _rhs.m33,
m10 * _rhs.m00 + m11 * _rhs.m10 + m12 * _rhs.m20 + m13 * _rhs.m30,
m10 * _rhs.m01 + m11 * _rhs.m11 + m12 * _rhs.m21 + m13 * _rhs.m31,
m10 * _rhs.m02 + m11 * _rhs.m12 + m12 * _rhs.m22 + m13 * _rhs.m32,
m10 * _rhs.m03 + m11 * _rhs.m13 + m12 * _rhs.m23 + m13 * _rhs.m33,
m20 * _rhs.m00 + m21 * _rhs.m10 + m22 * _rhs.m20 + m23 * _rhs.m30,
m20 * _rhs.m01 + m21 * _rhs.m11 + m22 * _rhs.m21 + m23 * _rhs.m31,
m20 * _rhs.m02 + m21 * _rhs.m12 + m22 * _rhs.m22 + m23 * _rhs.m32,
m20 * _rhs.m03 + m21 * _rhs.m13 + m22 * _rhs.m23 + m23 * _rhs.m33,
m30 * _rhs.m00 + m31 * _rhs.m10 + m32 * _rhs.m20 + m33 * _rhs.m30,
m30 * _rhs.m01 + m31 * _rhs.m11 + m32 * _rhs.m21 + m33 * _rhs.m31,
m30 * _rhs.m02 + m31 * _rhs.m12 + m32 * _rhs.m22 + m33 * _rhs.m32,
m30 * _rhs.m03 + m31 * _rhs.m13 + m32 * _rhs.m23 + m33 * _rhs.m33);
}
Mat44& Multiply(const Mat34& _rhs)
{
return *this = Mat44(
m00 * _rhs.m00 + m01 * _rhs.m10 + m02 * _rhs.m20,
m00 * _rhs.m01 + m01 * _rhs.m11 + m02 * _rhs.m21,
m00 * _rhs.m02 + m01 * _rhs.m12 + m02 * _rhs.m22,
m00 * _rhs.m03 + m01 * _rhs.m13 + m02 * _rhs.m23 + m03,
m10 * _rhs.m00 + m11 * _rhs.m10 + m12 * _rhs.m20,
m10 * _rhs.m01 + m11 * _rhs.m11 + m12 * _rhs.m21,
m10 * _rhs.m02 + m11 * _rhs.m12 + m12 * _rhs.m22,
m10 * _rhs.m03 + m11 * _rhs.m13 + m12 * _rhs.m23 + m13,
m20 * _rhs.m00 + m21 * _rhs.m10 + m22 * _rhs.m20,
m20 * _rhs.m01 + m21 * _rhs.m11 + m22 * _rhs.m21,
m20 * _rhs.m02 + m21 * _rhs.m12 + m22 * _rhs.m22,
m20 * _rhs.m03 + m21 * _rhs.m13 + m22 * _rhs.m23 + m23,
m30 * _rhs.m00 + m31 * _rhs.m10 + m32 * _rhs.m20,
m30 * _rhs.m01 + m31 * _rhs.m11 + m32 * _rhs.m21,
m30 * _rhs.m02 + m31 * _rhs.m12 + m32 * _rhs.m22,
m30 * _rhs.m03 + m31 * _rhs.m13 + m32 * _rhs.m23 + m33);
}
Mat44& Inverse(void)
{
float _m00 = m00, _m01 = m01, _m02 = m02, _m03 = m03, _m10 = m10, _m11 = m11, _m12 = m12, _m13 = m13, _m20 = m20, _m21 = m21, _m22 = m22, _m23 = m23, _m30 = m30, _m31 = m31, _m32 = m32, _m33 = m33;
float _v0 = (_m20 * _m31 - _m21 * _m30), _v1 = (_m20 * _m32 - _m22 * _m30), _v2 = (_m20 * _m33 - _m23 * _m30), _v3 = (_m21 * _m32 - _m22 * _m31), _v4 = (_m21 * _m33 - _m23 * _m31), _v5 = (_m22 * _m33 - _m23 * _m32);
float _t00 = +(_v5 * _m11 - _v4 * _m12 + _v3 * _m13), _t10 = -(_v5 * _m10 - _v2 * _m12 + _v1 * _m13), _t20 = +(_v4 * _m10 - _v2 * _m11 + _v0 * _m13), _t30 = -(_v3 * _m10 - _v1 * _m11 + _v0 * _m12);
float _invdet = 1 / (_t00 * _m00 + _t10 * _m01 + _t20 * _m02 + _t30 * _m03);
m00 = _t00 * _invdet;
m10 = _t10 * _invdet;
m20 = _t20 * _invdet;
m30 = _t30 * _invdet;
m01 = -(_v5 * _m01 - _v4 * _m02 + _v3 * _m03) * _invdet;
m11 = +(_v5 * _m00 - _v2 * _m02 + _v1 * _m03) * _invdet;
m21 = -(_v4 * _m00 - _v2 * _m01 + _v0 * _m03) * _invdet;
m31 = +(_v3 * _m00 - _v1 * _m01 + _v0 * _m02) * _invdet;
_v0 = (_m10 * _m31 - _m11 * _m30);
_v1 = (_m10 * _m32 - _m12 * _m30);
_v2 = (_m10 * _m33 - _m13 * _m30);
_v3 = (_m11 * _m32 - _m12 * _m31);
_v4 = (_m11 * _m33 - _m13 * _m31);
_v5 = (_m12 * _m33 - _m13 * _m32);
m02 = +(_v5 * _m01 - _v4 * _m02 + _v3 * _m03) * _invdet;
m12 = -(_v5 * _m00 - _v2 * _m02 + _v1 * _m03) * _invdet;
m22 = +(_v4 * _m00 - _v2 * _m01 + _v0 * _m03) * _invdet;
m32 = -(_v3 * _m00 - _v1 * _m01 + _v0 * _m02) * _invdet;
_v0 = (_m21 * _m10 - _m20 * _m11);
_v1 = (_m22 * _m10 - _m20 * _m12);
_v2 = (_m23 * _m10 - _m20 * _m13);
_v3 = (_m22 * _m11 - _m21 * _m12);
_v4 = (_m23 * _m11 - _m21 * _m13);
_v5 = (_m23 * _m12 - _m22 * _m13);
m03 = -(_v5 * _m01 - _v4 * _m02 + _v3 * _m03) * _invdet;
m13 = +(_v5 * _m00 - _v2 * _m02 + _v1 * _m03) * _invdet;
m23 = -(_v4 * _m00 - _v2 * _m01 + _v0 * _m03) * _invdet;
m33 = +(_v3 * _m00 - _v1 * _m01 + _v0 * _m02) * _invdet;
return *this;
}
Vec3 Transform(const Vec3& _v) const
{
float _iw = 1 / (m30 * _v.x + m31 * _v.y + m32 * _v.z + m33);
return Vec3( (m00 * _v.x + m01 * _v.y + m02 * _v.z + m03) * _iw,
(m10 * _v.x + m11 * _v.y + m12 * _v.z + m13) * _iw,
(m20 * _v.x + m21 * _v.y + m22 * _v.z + m23) * _iw);
}
Mat44& CreatePerspective(float _fov, float _aspect, float _near, float _far, bool _reversed = false)
{
if (_aspect != _aspect)
_aspect = 1; // NaN
if (_far == _near)
_far = _near + Epsilon;
float _h = 1 / Tan(_fov * 0.5f);
float _w = _h / _aspect;
float _d = (_far - _near);
float _q = -(_far + _near) / _d;
float _qn = -2 * (_far * _near) / _d;
if (_reversed)
Swap(_q, _qn);
return *this = Mat44(_w, 0, 0, 0, 0, _h, 0, 0, 0, 0, _q, _qn, 0, 0, -1, 0);
}
Mat44& CreateOrtho2D(float _w, float _h, bool _leftTop = true)
{
*this = Zero;
v[0] = 2 / _w, v[3] = -1, v[10] = -1, v[15] = 1;
if (_leftTop)
v[5] = -2 / _h, v[7] = 1;
else
v[5] = 2 / _h, v[7] = -1;
return *this;
}
union
{
struct { float m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33; };
float m[4][4]; // [row][col]
float v[16];
};
ENGINE_API static const Mat44 Zero;
ENGINE_API static const Mat44 Identity;
};
//----------------------------------------------------------------------------//
//
//----------------------------------------------------------------------------//
}
| 42.0766 | 219 | 0.540013 | Zakhar-V |
ca7f608f4a4652b4ee3ad834d27312c85d43967d | 3,249 | cpp | C++ | src/GuacInstructionParser.cpp | unk0rrupt/collab-vm-server | 30a18cc91b757216a08e900826b589ce29bc3bf0 | [
"Apache-2.0"
] | 74 | 2020-12-20T19:29:21.000Z | 2021-12-04T14:59:29.000Z | src/GuacInstructionParser.cpp | unk0rrupt/collab-vm-server | 30a18cc91b757216a08e900826b589ce29bc3bf0 | [
"Apache-2.0"
] | 2 | 2020-12-27T12:10:50.000Z | 2021-01-24T12:38:24.000Z | src/GuacInstructionParser.cpp | unk0rrupt/collab-vm-server | 30a18cc91b757216a08e900826b589ce29bc3bf0 | [
"Apache-2.0"
] | 4 | 2020-12-20T14:28:11.000Z | 2021-08-20T17:01:11.000Z | #include "GuacInstructionParser.h"
#include "CollabVM.h"
#include <vector>
#include <functional>
#include <string>
namespace GuacInstructionParser
{
typedef void (CollabVMServer::*InstructionHandler)(const std::shared_ptr<CollabVMUser>&, std::vector<char*>&);
struct Instruction
{
std::string opcode;
InstructionHandler handler;
};
static const Instruction instructions[] = {
// Guacamole instructions
{ "mouse", &CollabVMServer::OnMouseInstruction },
{ "key", &CollabVMServer::OnKeyInstruction },
// Custom instructions
{ "rename", &CollabVMServer::OnRenameInstruction },
{ "connect", &CollabVMServer::OnConnectInstruction },
{ "chat", &CollabVMServer::OnChatInstruction },
{ "turn", &CollabVMServer::OnTurnInstruction },
{ "admin", &CollabVMServer::OnAdminInstruction },
{ "nop", &CollabVMServer::OnNopInstruction },
{ "list", &CollabVMServer::OnListInstruction },
{ "vote", &CollabVMServer::OnVoteInstruction },
{ "file", &CollabVMServer::OnFileInstruction }
};
constexpr size_t instruction_count = sizeof(instructions)/sizeof(Instruction);
/**
* Max element size of a Guacamole element.
*/
constexpr std::uint64_t MAX_GUAC_ELEMENT_LENGTH = 2500;
/**
* Max size of a Guacamole frame.
*/
constexpr std::uint64_t MAX_GUAC_FRAME_LENGTH = 6144;
/**
* Decode an instruction from a string.
* \param[in] input input guacamole string to decode
*/
std::vector<std::string> Decode(const std::string& input)
{
std::vector<std::string> output;
if (input.back() != ';')
return output;
if(input.empty() || input.length() >= MAX_GUAC_FRAME_LENGTH)
return output;
std::istringstream iss{input};
while (iss) {
unsigned long long length{0};
iss >> length;
if (!iss)
return std::vector<std::string>();
// Ignore weird elements that could be an attempt to crash the server
if(length >= MAX_GUAC_ELEMENT_LENGTH || length >= input.length())
return std::vector<std::string>();
if (iss.peek() != '.')
return std::vector<std::string>();
iss.get(); // remove the period
std::vector<char> content(length + 1, '\0');
iss.read(content.data(), static_cast<std::streamsize>(length));
output.push_back(std::string(content.data()));
const char& separator = iss.peek();
if (separator != ',') {
if (separator == ';')
return output;
return std::vector<std::string>();
}
iss.get();
}
return std::vector<std::string>();
}
void ParseInstruction(CollabVMServer& server, const std::shared_ptr<CollabVMUser>& user, const std::string& instruction)
{
std::vector<std::string> decoded = Decode(instruction);
if(decoded.empty())
return;
for(size_t i = 0; i < instruction_count; ++i) {
if(instructions[i].opcode == decoded[0]) {
auto arguments = std::vector<std::string>(decoded.begin() + 1, decoded.end());
auto argument_conv = std::vector<char*>();
argument_conv.resize(arguments.size());
for(size_t j = 0; j < arguments.size(); ++j)
argument_conv[j] = const_cast<char*>(arguments[j].c_str());
// Call the instruction handler
InstructionHandler x = instructions[i].handler;
(server.*x)(user, argument_conv);
argument_conv.clear();
}
}
}
}
| 28.752212 | 121 | 0.667898 | unk0rrupt |
ca7f8f20d6226f5647a021787cd7a1f36fcf9078 | 1,797 | cpp | C++ | runtime/tree/pattern/ParseTreePattern.cpp | mengdemao/AntlrExpr | 78ed13bf7f6eda26d3eae81c361e60321643f406 | [
"BSD-3-Clause"
] | 1 | 2021-12-19T14:03:24.000Z | 2021-12-19T14:03:24.000Z | runtime/tree/pattern/ParseTreePattern.cpp | mengdemao/AntlrExpr | 78ed13bf7f6eda26d3eae81c361e60321643f406 | [
"BSD-3-Clause"
] | null | null | null | runtime/tree/pattern/ParseTreePattern.cpp | mengdemao/AntlrExpr | 78ed13bf7f6eda26d3eae81c361e60321643f406 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
#include "tree/ParseTree.h"
#include "tree/pattern/ParseTreePatternMatcher.h"
#include "tree/pattern/ParseTreeMatch.h"
#include "tree/xpath/XPath.h"
#include "tree/xpath/XPathElement.h"
#include "tree/pattern/ParseTreePattern.h"
using namespace antlr4::tree;
using namespace antlr4::tree::pattern;
using namespace antlrcpp;
ParseTreePattern::ParseTreePattern(ParseTreePatternMatcher *matcher, const std::string &pattern, int patternRuleIndex_,
ParseTree *patternTree)
: patternRuleIndex(patternRuleIndex_), _pattern(pattern), _patternTree(patternTree), _matcher(matcher) {
}
ParseTreePattern::~ParseTreePattern() {
}
ParseTreeMatch ParseTreePattern::match(ParseTree *tree) {
return _matcher->match(tree, *this);
}
bool ParseTreePattern::matches(ParseTree *tree) {
return _matcher->match(tree, *this).succeeded();
}
std::vector<ParseTreeMatch> ParseTreePattern::findAll(ParseTree *tree, const std::string &xpath) {
xpath::XPath finder(_matcher->getParser(), xpath);
std::vector<ParseTree *> subtrees = finder.evaluate(tree);
std::vector<ParseTreeMatch> matches;
for (auto *t : subtrees) {
ParseTreeMatch aMatch = match(t);
if (aMatch.succeeded()) {
matches.push_back(aMatch);
}
}
return matches;
}
ParseTreePatternMatcher *ParseTreePattern::getMatcher() const {
return _matcher;
}
std::string ParseTreePattern::getPattern() const {
return _pattern;
}
int ParseTreePattern::getPatternRuleIndex() const {
return patternRuleIndex;
}
ParseTree* ParseTreePattern::getPatternTree() const {
return _patternTree;
}
| 27.646154 | 119 | 0.739009 | mengdemao |
ca7f96498664b6db97b9b5dada55d1605af3d885 | 3,310 | cpp | C++ | Applications/Utils/FileConverter/GMSH2OGS.cpp | yingtaohu/ogs | 651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e | [
"BSD-4-Clause"
] | null | null | null | Applications/Utils/FileConverter/GMSH2OGS.cpp | yingtaohu/ogs | 651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e | [
"BSD-4-Clause"
] | null | null | null | Applications/Utils/FileConverter/GMSH2OGS.cpp | yingtaohu/ogs | 651ca2f903ee0bf5a8cfb505e8e2fd0562b4ce8e | [
"BSD-4-Clause"
] | null | null | null | /**
* \file
* \author Thomas Fischer
* \date 2011-12-13
* \brief Implementation of the GMSH2OGS converter.
*
* \copyright
* Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
// STL
#include <string>
#include <algorithm>
// ThirdParty
#include <tclap/CmdLine.h>
#include "Applications/ApplicationsLib/LogogSetup.h"
// BaseLib
#include "BaseLib/FileTools.h"
#include "BaseLib/RunTime.h"
#ifndef WIN32
#include "BaseLib/MemWatch.h"
#endif
#include "Applications/FileIO/Gmsh/GmshReader.h"
#include "MeshLib/IO/writeMeshToFile.h"
#include "MeshLib/MeshSearch/ElementSearch.h"
#include "MeshLib/Mesh.h"
#include "MeshLib/MeshEditing/RemoveMeshComponents.h"
int main (int argc, char* argv[])
{
ApplicationsLib::LogogSetup logog_setup;
TCLAP::CmdLine cmd("Converting meshes in gmsh file format (ASCII, version 2.2) to a vtk unstructured grid file (new OGS file format) or to the old OGS file format - see options.", ' ', "0.1");
TCLAP::ValueArg<std::string> ogs_mesh_arg(
"o",
"out",
"filename for output mesh (if extension is .msh, old OGS-5 fileformat is written, if extension is .vtu, a vtk unstructure grid file is written (OGS-6 mesh format))",
true,
"",
"filename as string");
cmd.add(ogs_mesh_arg);
TCLAP::ValueArg<std::string> gmsh_mesh_arg(
"i",
"in",
"gmsh input file",
true,
"",
"filename as string");
cmd.add(gmsh_mesh_arg);
TCLAP::SwitchArg exclude_lines_arg("e", "exclude-lines",
"if set, lines will not be written to the ogs mesh");
cmd.add(exclude_lines_arg);
cmd.parse(argc, argv);
// *** read mesh
INFO("Reading %s.", gmsh_mesh_arg.getValue().c_str());
#ifndef WIN32
BaseLib::MemWatch mem_watch;
unsigned long mem_without_mesh (mem_watch.getVirtMemUsage());
#endif
BaseLib::RunTime run_time;
run_time.start();
MeshLib::Mesh* mesh(
FileIO::GMSH::readGMSHMesh(gmsh_mesh_arg.getValue()));
if (mesh == nullptr) {
INFO("Could not read mesh from %s.", gmsh_mesh_arg.getValue().c_str());
return -1;
}
#ifndef WIN32
INFO("Mem for mesh: %i MB",
(mem_watch.getVirtMemUsage() - mem_without_mesh) / (1024 * 1024));
#endif
INFO("Time for reading: %f seconds.", run_time.elapsed());
INFO("Read %d nodes and %d elements.", mesh->getNumberOfNodes(), mesh->getNumberOfElements());
// *** remove line elements on request
if (exclude_lines_arg.getValue()) {
auto ex = MeshLib::ElementSearch(*mesh);
ex.searchByElementType(MeshLib::MeshElemType::LINE);
auto m = MeshLib::removeElements(*mesh, ex.getSearchedElementIDs(), mesh->getName()+"-withoutLines");
if (m != nullptr) {
INFO("Removed %d lines.", mesh->getNumberOfElements() - m->getNumberOfElements());
std::swap(m, mesh);
delete m;
} else {
INFO("Mesh does not contain any lines.");
}
}
// *** write mesh in new format
MeshLib::IO::writeMeshToFile(*mesh, ogs_mesh_arg.getValue());
delete mesh;
}
| 29.81982 | 196 | 0.641088 | yingtaohu |
ca82a20d582a0a492fc78bf81ff35f0f8f012d98 | 6,672 | cc | C++ | pointcloud-fusion/src/dense_map/DepthPredictor.cc | NetEaseAI-CVLab/CNN-MonoFusion | 49598c8e9d2c9ae36c68a50460ae842ac8f43d98 | [
"MIT"
] | 71 | 2018-08-26T07:48:07.000Z | 2022-01-20T16:09:09.000Z | pointcloud-fusion/src/dense_map/DepthPredictor.cc | NeteaseAI-CVLab/CNN-MonoFusion | 49598c8e9d2c9ae36c68a50460ae842ac8f43d98 | [
"MIT"
] | 8 | 2018-10-29T06:41:30.000Z | 2021-07-01T13:12:58.000Z | pointcloud-fusion/src/dense_map/DepthPredictor.cc | NeteaseAI-CVLab/CNN-MonoFusion | 49598c8e9d2c9ae36c68a50460ae842ac8f43d98 | [
"MIT"
] | 8 | 2018-10-25T07:29:05.000Z | 2019-05-29T01:58:31.000Z | #include "DepthPredictor.h"
#include<iostream>
#include<opencv2\core.hpp>
#include<opencv2\highgui.hpp>
#include<opencv2\imgproc.hpp>
using namespace cv;
DepthPredictor::DepthPredictor(ORB_SLAM2::Map* pMap, KeyFrameQueue* frame_queue,
DenseMap* dense_map, std::string setting_file):mpOrbSlamMap(pMap),
m_success(false), m_frame_queue(frame_queue), m_dense_map(dense_map), m_should_finish(false),
m_is_finished(true)
{
FileStorage fs(setting_file, FileStorage::READ);
m_img_width = fs["Camera.width"];
m_img_height = fs["Camera.height"];
m_focal_length = fs["Camera.fx"];
m_depth_grad_thr = fs["Camera.depth_grad_thr"];
m_net_width = fs["Camera.net_width"];
m_net_height = fs["Camera.net_height"];
m_covisible_keyframes = fs["DenseMap.CovisibleForKeyFrames"];
m_covisible_frames = fs["DenseMap.CovisibleForFrames"];
std::cout << "------------------------\nDenseMap DepthPredictor Params" << std::endl;
std::cout << "- Covisible For KeyFrames: " << m_covisible_keyframes << std::endl;
std::cout << "- Covisible For Frames: " << m_covisible_frames << std::endl;
fs.release();
m_first_frameid = 0;
m_success = true;
}
DepthPredictor::~DepthPredictor()
{
request_finish();
}
void DepthPredictor::run()
{
set_finished(false);
while(!should_finish())
{
if(m_frame_queue->size() == 0)
continue;
std::unique_lock <std::mutex> lck(m_dense_map->system_running_mtx);
while(!m_dense_map->get_system_running_status())
{
m_dense_map->system_running_cv.wait(lck);
}
lck.unlock();
OrbKeyFrame curr_frame = m_frame_queue->dequeue();
if(vOrbKeyframes.empty())
{
addKeyframe(curr_frame.frame_idx, curr_frame);
m_dense_map->add_points_from_depth_map(curr_frame);
m_first_frameid = curr_frame.frame_idx;
std::cout << "First keyframe id in densemap: " << m_first_frameid << std::endl;
}
else
{
auto iter = vOrbKeyframes.end() - 1;
OrbKeyFrame ref_keyframe = *iter;
std::vector<OrbKeyFrame*> ref_neighs;
ref_neighs.emplace_back(&ref_keyframe);
if(curr_frame.isKeyframe)
{
//std::cout << "\nDenseMap keyframe size: " << vOrbKeyframes.size()
// << ", keyframe id->" << ref_keyframe.frame_idx
// << ", curr_frame id->" << curr_frame.frame_idx
// << ", this is keyframe" << std::endl;
ORB_SLAM2::KeyFrame *orbslam_kf = mpOrbSlamMap->getKeyframeByframeId(ref_keyframe.frame_idx);
if(orbslam_kf != nullptr)
{
std::vector<ORB_SLAM2::KeyFrame*> vNeighs = orbslam_kf->GetBestCovisibilityKeyFrames(m_covisible_keyframes);
for(auto iter_neigh = vNeighs.begin(); iter_neigh != vNeighs.end(); iter_neigh++)
{
long unsigned int neigh_id = (*iter_neigh)->mnFrameId;
if(neigh_id > m_first_frameid && neigh_id < curr_frame.frame_idx)
{
// get OrbKeyFrame use orbslam neighs_frame_id
long unsigned int neigh_kf_id = map_frameid_keyframeid[neigh_id];
ref_neighs.emplace_back(&vOrbKeyframes[neigh_kf_id]);
}
}
}
else
{
//std::cout << "**keyframe has delete by Map**" << std::endl;
}
//std::cout << "ref_neighs size: " << ref_neighs.size() << ", neigh id:";
//for(auto iter_neigh = ref_neighs.begin(); iter_neigh != ref_neighs.end(); iter_neigh++)
//{
// std::cout << (*iter_neigh)->frame_idx << " ";
//}
//std::cout << "\n";
//if(ref_neighs.size() < 2)
//{
// m_dense_map->cvlibs_greedy_fusion(ref_keyframe, curr_frame);
//}
//else
//{
// m_dense_map->cvlibs_greedy_fusion_covisible(ref_neighs, curr_frame);
//}
// covisible
m_dense_map->cvlibs_greedy_fusion_covisible(ref_neighs, curr_frame);
// add keyframe to densemap keyframe manager
addKeyframe(curr_frame.frame_idx, curr_frame);
}
else
{
//std::cout << "keyframe size: " << orbkeyframes.size() << ", keyframe id->" << ref_keyframe.frame_idx
// << ", curr_frame id->" << curr_frame.frame_idx << std::endl;
//m_dense_map->cvlibs_greedy_fusion_framewise(ref_keyframe, curr_frame);
ORB_SLAM2::KeyFrame *orbslam_kf = mpOrbSlamMap->getKeyframeByframeId(ref_keyframe.frame_idx);
if(orbslam_kf != nullptr)
{
std::vector<ORB_SLAM2::KeyFrame*> vNeighs = orbslam_kf->GetBestCovisibilityKeyFrames(m_covisible_frames);
for(auto iter_neigh = vNeighs.begin(); iter_neigh != vNeighs.end(); iter_neigh++)
{
long unsigned int neigh_id = (*iter_neigh)->mnFrameId;
if(neigh_id > m_first_frameid && neigh_id < curr_frame.frame_idx)
{
// get OrbKeyFrame use orbslam neighs_frame_id
long unsigned int neigh_kf_id = map_frameid_keyframeid[neigh_id];
ref_neighs.emplace_back(&vOrbKeyframes[neigh_kf_id]);
}
}
}
else
{
//std::cout << "**keyframe has delete by Map**" << std::endl;
}
//std::cout << "refneighs num: "<< ref_neighs.size() << std::endl;
m_dense_map->cvlibs_greedy_fusion_framewise_covisible(ref_neighs, curr_frame);
m_dense_map->set_current_Tcw(curr_frame.Tcw);
}
}
}
set_finished(true);
}
void DepthPredictor::set_finished(bool status)
{
std::unique_lock<std::mutex> lock(m_mutex);
m_is_finished = status;
m_should_finish = status;
}
void DepthPredictor::request_finish()
{
std::unique_lock<std::mutex> lock(m_mutex);
m_should_finish = true;
}
bool DepthPredictor::should_finish()
{
std::unique_lock<std::mutex> lock(m_mutex);
return m_should_finish;
}
| 38.566474 | 128 | 0.553357 | NetEaseAI-CVLab |
ca8d3adc7a6941a4f707b96064354bcd423eb344 | 4,599 | cc | C++ | libqpdf/QPDF_String.cc | schwarzeSocke/qpdf | e8b845dd0344c797b58bfa31b810af53595d2599 | [
"Artistic-2.0",
"Unlicense"
] | null | null | null | libqpdf/QPDF_String.cc | schwarzeSocke/qpdf | e8b845dd0344c797b58bfa31b810af53595d2599 | [
"Artistic-2.0",
"Unlicense"
] | null | null | null | libqpdf/QPDF_String.cc | schwarzeSocke/qpdf | e8b845dd0344c797b58bfa31b810af53595d2599 | [
"Artistic-2.0",
"Unlicense"
] | null | null | null | #include <qpdf/QPDF_String.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QTC.hh>
// DO NOT USE ctype -- it is locale dependent for some things, and
// it's not worth the risk of including it in case it may accidentally
// be used.
#include <string.h>
// See above about ctype.
static bool is_ascii_printable(unsigned char ch)
{
return ((ch >= 32) && (ch <= 126));
}
static bool is_iso_latin1_printable(unsigned char ch)
{
return (((ch >= 32) && (ch <= 126)) || (ch >= 160));
}
QPDF_String::QPDF_String(std::string const& val) :
val(val)
{
}
QPDF_String::~QPDF_String()
{
}
std::string
QPDF_String::unparse()
{
return unparse(false);
}
QPDFObject::object_type_e
QPDF_String::getTypeCode() const
{
return QPDFObject::ot_string;
}
char const*
QPDF_String::getTypeName() const
{
return "string";
}
std::string
QPDF_String::unparse(bool force_binary)
{
bool use_hexstring = force_binary;
if (! use_hexstring)
{
unsigned int nonprintable = 0;
int consecutive_printable = 0;
for (unsigned int i = 0; i < this->val.length(); ++i)
{
char ch = this->val.at(i);
// Note: do not use locale to determine printability. The
// PDF specification accepts arbitrary binary data. Some
// locales imply multibyte characters. We'll consider
// something printable if it is printable in 7-bit ASCII.
// We'll code this manually rather than being rude and
// setting locale.
if ((ch == 0) || (! (is_ascii_printable(ch) ||
strchr("\n\r\t\b\f", ch))))
{
++nonprintable;
consecutive_printable = 0;
}
else
{
if (++consecutive_printable > 5)
{
// If there are more than 5 consecutive printable
// characters, I want to see them as such.
nonprintable = 0;
break;
}
}
}
// Use hex notation if more than 20% of the characters are not
// printable in plain ASCII.
if (5 * nonprintable > val.length())
{
use_hexstring = true;
}
}
std::string result;
if (use_hexstring)
{
result += "<" + QUtil::hex_encode(this->val) + ">";
}
else
{
result += "(";
for (unsigned int i = 0; i < this->val.length(); ++i)
{
char ch = this->val.at(i);
switch (ch)
{
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '(':
result += "\\(";
break;
case ')':
result += "\\)";
break;
case '\\':
result += "\\\\";
break;
default:
if (is_iso_latin1_printable(ch))
{
result += this->val.at(i);
}
else
{
result += "\\" + QUtil::int_to_string_base(
static_cast<int>(static_cast<unsigned char>(ch)),
8, 3);
}
break;
}
}
result += ")";
}
return result;
}
std::string
QPDF_String::getVal() const
{
return this->val;
}
std::string
QPDF_String::getUTF8Val() const
{
std::string result;
size_t len = this->val.length();
if ((len >= 2) && (len % 2 == 0) &&
(this->val.at(0) == '\xfe') && (this->val.at(1) == '\xff'))
{
// This is a Unicode string using big-endian UTF-16. This
// code uses unsigned long and unsigned short to hold
// codepoint values. It requires unsigned long to be at least
// 32 bits and unsigned short to be at least 16 bits, but it
// will work fine if they are larger.
unsigned long codepoint = 0L;
for (unsigned int i = 2; i < len; i += 2)
{
// Convert from UTF16-BE. If we get a malformed
// codepoint, this code will generate incorrect output
// without giving a warning. Specifically, a high
// codepoint not followed by a low codepoint will be
// discarded, and a low codepoint not preceded by a high
// codepoint will just get its low 10 bits output.
unsigned short bits =
(static_cast<unsigned char>(this->val.at(i)) << 8) +
static_cast<unsigned char>(this->val.at(i+1));
if ((bits & 0xFC00) == 0xD800)
{
codepoint = 0x10000 + ((bits & 0x3FF) << 10);
continue;
}
else if ((bits & 0xFC00) == 0xDC00)
{
if (codepoint != 0)
{
QTC::TC("qpdf", "QPDF_String non-trivial UTF-16");
}
codepoint += bits & 0x3FF;
}
else
{
codepoint = bits;
}
result += QUtil::toUTF8(codepoint);
codepoint = 0;
}
}
else
{
for (unsigned int i = 0; i < len; ++i)
{
result += QUtil::toUTF8(static_cast<unsigned char>(this->val.at(i)));
}
}
return result;
}
| 21.193548 | 74 | 0.581431 | schwarzeSocke |
ca8e5ae21fc856240d8629d04664d526a7a7820a | 8,880 | cpp | C++ | src/recording.cpp | nyamadan/shader_editor | 477aa7165a6f6d721466a4d2fe4d326cf8c9b5df | [
"MIT"
] | 4 | 2019-01-29T07:31:00.000Z | 2020-02-18T16:19:08.000Z | src/recording.cpp | nyamadan/shader_editor | 477aa7165a6f6d721466a4d2fe4d326cf8c9b5df | [
"MIT"
] | 8 | 2019-02-03T14:15:15.000Z | 2020-07-06T02:46:32.000Z | src/recording.cpp | nyamadan/shader_editor | 477aa7165a6f6d721466a4d2fe4d326cf8c9b5df | [
"MIT"
] | null | null | null | #include "recording.hpp"
#include "file_utils.hpp"
#include <math.h>
bool Recording::getIsRecording() { return isRecording; }
void Recording::start(const int32_t bufferWidth, const int32_t bufferHeight,
const std::string& fileName, const int32_t videoType,
const int32_t webmBitrate,
const unsigned long webmEncodeDeadline) {
this->isRecording = true;
this->videoType = videoType;
this->bufferWidth = bufferWidth;
this->bufferHeight = bufferHeight;
const int32_t ySize = bufferWidth * bufferHeight;
const int32_t uSize = ySize / 4;
const int32_t vSize = uSize;
yuvBuffer = std::make_unique<uint8_t[]>(ySize + uSize + vSize);
switch (videoType) {
case 0: {
fp = fopen(fileName.c_str(), "wb");
fprintf(fp,
"YUV4MPEG2 W%d H%d F30000:1001 Ip A0:0 C420 XYSCSS=420\n",
bufferWidth, bufferHeight);
} break;
case 1: {
pWebmEncoder = std::make_unique<WebmEncoder>(
fileName, 1001, 30000, bufferWidth, bufferHeight, webmBitrate);
} break;
case 2: {
fp = fopen(fileName.c_str(), "wb");
void* pEncoder = nullptr;
h264encoder::CreateOpenH264Encoder(&pEncoder, &pMP4Muxer,
&pMP4H264Writer, bufferWidth,
bufferHeight, fp);
delete pOpenH264Encoder;
pOpenH264Encoder = pEncoder;
} break;
}
}
void Recording::update(bool isLastFrame, int64_t currentFrame,
GLuint writeBuffer, GLuint readBuffer) {
glBindBuffer(GL_PIXEL_PACK_BUFFER, writeBuffer);
glReadPixels(0, 0, bufferWidth, bufferHeight, GL_RGBA, GL_UNSIGNED_BYTE, 0);
if (currentFrame > 0) {
glBindBuffer(GL_PIXEL_PACK_BUFFER, readBuffer);
#ifdef __EMSCRIPTEN__
{
auto size = bufferWidth * bufferHeight * 4;
auto ptr = std::make_unique<uint8_t[]>(size);
// clang-format on
EM_ASM({
Module.ctx.getBufferSubData(
Module.ctx.PIXEL_PACK_BUFFER,
0,
HEAPU8.subarray($0, $0 + $1));
}, ptr.get(), size);
// clang-format off
writeOneFrame(ptr.get(), currentFrame);
}
#else
{
auto* ptr = static_cast<const uint8_t*>(glMapBufferRange(
GL_PIXEL_PACK_BUFFER, 0, bufferWidth * bufferHeight * 4,
GL_MAP_READ_BIT));
if (ptr != nullptr) {
writeOneFrame(ptr, currentFrame);
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
ptr = nullptr;
}
}
#endif
}
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
if (isLastFrame) {
glBindBuffer(GL_PIXEL_PACK_BUFFER, writeBuffer);
#ifdef __EMSCRIPTEN__
{
auto size = bufferWidth * bufferHeight * 4;
auto ptr = std::make_unique<uint8_t[]>(size);
EM_ASM({ Module.ctx.getBufferSubData(Module.ctx.PIXEL_PACK_BUFFER, 0, HEAPU8.subarray($0, $0 + $1)); }, ptr.get(), size);
writeOneFrame(ptr.get(), currentFrame);
}
#else
{
auto* ptr = static_cast<const uint8_t*>(glMapBufferRange(
GL_PIXEL_PACK_BUFFER, 0, bufferWidth * bufferHeight * 4,
GL_MAP_READ_BIT));
if (ptr != nullptr) {
writeOneFrame(ptr, currentFrame);
glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
ptr = nullptr;
}
}
#endif
glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
switch (videoType) {
case 0: {
fclose(fp);
fp = nullptr;
#ifdef __EMSCRIPTEN__
{
std::string buff;
readText("video.y4m", buff);
EM_ASM({
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
const data =HEAPU8.subarray($0, $0 + $1);
const blob = new Blob([data], { type: "octet/stream" });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "video.y4m";
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, buff.c_str(), buff.size());
}
#endif
} break;
case 1: {
pWebmEncoder->finalize(webmEncodeDeadline);
#ifdef __EMSCRIPTEN__
{
std::string buff;
readText("video.webm", buff);
EM_ASM({
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
const data =HEAPU8.subarray($0, $0 + $1);
const blob = new Blob([data], { type: "octet/stream" });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "video.webm";
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, buff.c_str(), buff.size());
}
#endif
} break;
case 2: {
if (pOpenH264Encoder != nullptr) {
h264encoder::Finalize(pOpenH264Encoder, pMP4Muxer,
pMP4H264Writer);
fclose(fp);
pOpenH264Encoder = nullptr;
pMP4Muxer = nullptr;
pMP4H264Writer = nullptr;
fp = nullptr;
#ifdef __EMSCRIPTEN__
{
std::string buff;
readText("video.mp4", buff);
EM_ASM({
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
const data =HEAPU8.subarray($0, $0 + $1);
const blob = new Blob([data], { type: "octet/stream" });
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "video.mp4";
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, buff.c_str(), buff.size());
}
#endif
}
} break;
}
isRecording = false;
}
}
void Recording::cleanup() {
if (pOpenH264Encoder != nullptr) {
h264encoder::DestroyOpenH264Encoder(pOpenH264Encoder);
pOpenH264Encoder = nullptr;
}
}
void Recording::writeOneFrame(const uint8_t* rgbaBuffer, int64_t currentFrame) {
const int32_t ySize = bufferWidth * bufferHeight;
const int32_t uSize = ySize / 4;
const int32_t vSize = uSize;
const int32_t yStride = bufferWidth;
const int32_t uStride = bufferWidth / 2;
const int32_t vStride = uStride;
uint8_t* yBuffer = yuvBuffer.get();
uint8_t* uBuffer = yBuffer + ySize;
uint8_t* vBuffer = uBuffer + uSize;
switch (videoType) {
case 0: {
libyuv::ABGRToI420(rgbaBuffer, bufferWidth * 4, yBuffer, yStride,
uBuffer, uStride, vBuffer, vStride, bufferWidth,
-bufferHeight);
fputs("FRAME\n", fp);
fwrite(yuvBuffer.get(), sizeof(uint8_t),
(int64_t)ySize + uSize + vSize, fp);
} break;
case 1: {
pWebmEncoder->addRGBAFrame(rgbaBuffer, webmEncodeDeadline);
} break;
case 2: {
if (pOpenH264Encoder != nullptr) {
libyuv::ABGRToI420(rgbaBuffer, bufferWidth * 4, yBuffer,
yStride, uBuffer, uStride, vBuffer, vStride,
bufferWidth, -bufferHeight);
int64_t timestamp = roundl((currentFrame + 1) * 1001 / 30000);
h264encoder::EncodeFrame(pOpenH264Encoder, pMP4H264Writer,
yuvBuffer.get(), bufferWidth,
bufferHeight, timestamp);
}
} break;
}
}
Recording::~Recording() { cleanup(); }
| 36.846473 | 133 | 0.488401 | nyamadan |
ca90199c1772317d58b2956be195724ba7d28254 | 7,749 | cxx | C++ | src/texture/RectTexture.cxx | rita0222/FK | bc5786a5da0dd732e2f411c1a953b331323ee432 | [
"BSD-3-Clause"
] | 4 | 2020-05-15T03:43:53.000Z | 2021-06-05T16:21:31.000Z | src/texture/RectTexture.cxx | rita0222/FK | bc5786a5da0dd732e2f411c1a953b331323ee432 | [
"BSD-3-Clause"
] | 1 | 2020-05-19T09:27:16.000Z | 2020-05-21T02:12:54.000Z | src/texture/RectTexture.cxx | rita0222/FK | bc5786a5da0dd732e2f411c1a953b331323ee432 | [
"BSD-3-Clause"
] | null | null | null | #define FK_DEF_SIZETYPE
#include <FK/RectTexture.h>
#include <FK/Error.H>
#include <FK/Window.h>
using namespace std;
using namespace FK;
vector<GLuint> fk_RectTexture::_s_faceIndex = {0, 1, 3, 1, 2, 3};
GLuint fk_RectTexture::_s_faceIBO = 0;
bool fk_RectTexture::_s_faceIndexFlg = false;
fk_RectTexture::Member::Member(void) : repeatFlag(false)
{
return;
}
fk_RectTexture::fk_RectTexture(fk_Image *argImage) :
fk_Texture(argImage), _m(make_unique<Member>())
{
SetObjectType(fk_Type::RECTTEXTURE);
GetFaceSize = []() { return 2; };
StatusUpdate = [this]() {
SizeUpdate();
NormalUpdate();
TexCoordUpdate();
};
FaceIBOSetup = []() {
if(_s_faceIBO == 0) {
_s_faceIBO = GenBuffer();
_s_faceIndexFlg = true;
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _s_faceIBO);
if(_s_faceIndexFlg == true) {
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
GLsizei(6*sizeof(GLuint)),
_s_faceIndex.data(), GL_STATIC_DRAW);
_s_faceIndexFlg = false;
}
};
_m->vertexPosition.setDim(3);
_m->vertexPosition.resize(6);
setShaderAttribute(vertexName, 3, _m->vertexPosition.getP());
_m->vertexNormal.setDim(3);
_m->vertexNormal.resize(6);
setShaderAttribute(normalName, 3, _m->vertexNormal.getP());
_m_texCoord->setDim(2);
_m_texCoord->resize(6);
setShaderAttribute(texCoordName, 2, _m_texCoord->getP());
init();
return;
}
fk_RectTexture::~fk_RectTexture()
{
return;
}
void fk_RectTexture::init(void)
{
BaseInit();
RectInit();
return;
}
void fk_RectTexture::RectInit(void)
{
_m->texSize.set(2.0, 2.0);
setRepeatMode(false);
_m->repeatParam.set(1.0, 1.0);
_m->rectSE[0].set(0.0, 0.0);
_m->rectSE[1].set(1.0, 1.0);
SizeUpdate();
NormalUpdate();
TexCoordUpdate();
}
void fk_RectTexture::SizeUpdate(void)
{
double tmpX = _m->texSize.x/2.0;
double tmpY = _m->texSize.y/2.0;
_m->vertexPosition.resize(4);
_m->vertexPosition.set(0, -tmpX, -tmpY);
_m->vertexPosition.set(1, tmpX, -tmpY);
_m->vertexPosition.set(2, tmpX, tmpY);
_m->vertexPosition.set(3, -tmpX, tmpY);
modifyAttribute(vertexName);
}
void fk_RectTexture::NormalUpdate(void)
{
fk_Vector norm(0.0, 0.0, 1.0);
_m->vertexNormal.resize(4);
for(int i = 0; i < 4; i++) _m->vertexNormal.set(i, norm);
modifyAttribute(normalName);
}
void fk_RectTexture::TexCoordUpdate(void)
{
fk_TexCoord s, e;
const fk_Dimension *imageSize = getImageSize();
const fk_Dimension *bufSize = getBufferSize();
_m_texCoord->resize(4);
if(bufSize == nullptr) return;
if(bufSize->w < 64 || bufSize->h < 64) return;
if(getRepeatMode() == true) {
s.set(0.0, 0.0);
e = getRepeatParam();
} else {
double wScale = double(imageSize->w)/double(bufSize->w);
double hScale = double(imageSize->h)/double(bufSize->h);
s.set(wScale * _m->rectSE[0].x, hScale * _m->rectSE[0].y);
e.set(wScale * _m->rectSE[1].x, hScale * _m->rectSE[1].y);
}
_m_texCoord->set(0, s.x, s.y);
_m_texCoord->set(1, e.x, s.y);
_m_texCoord->set(2, e.x, e.y);
_m_texCoord->set(3, s.x, e.y);
modifyAttribute(texCoordName);
}
bool fk_RectTexture::setTextureSize(double argX, double argY)
{
if(argX < -fk_Math::EPS || argY < -fk_Math::EPS) {
return false;
}
_m->texSize.set(argX, argY);
SizeUpdate();
return true;
}
fk_TexCoord fk_RectTexture::getTextureSize(void)
{
return _m->texSize;
}
void fk_RectTexture::setRepeatMode(bool argFlag)
{
_m->repeatFlag = argFlag;
return;
}
bool fk_RectTexture::getRepeatMode(void)
{
return _m->repeatFlag;
}
void fk_RectTexture::setRepeatParam(double argS, double argT)
{
_m->repeatParam.set(argS, argT);
TexCoordUpdate();
return;
}
fk_TexCoord fk_RectTexture::getRepeatParam(void)
{
return _m->repeatParam;
}
void fk_RectTexture::setTextureCoord(double argSU, double argSV,
double argEU, double argEV)
{
if(argSU < -fk_Math::EPS || argSU > 1.0 + fk_Math::EPS ||
argSV < -fk_Math::EPS || argSV > 1.0 + fk_Math::EPS ||
argEU < -fk_Math::EPS || argEU > 1.0 + fk_Math::EPS ||
argEV < -fk_Math::EPS || argEV > 1.0 + fk_Math::EPS) {
Error::Put("fk_RectTexture", "setTextureCoord", 1, "Texture Coord Error.");
return;
}
_m->rectSE[0].set(argSU, argSV);
_m->rectSE[1].set(argEU, argEV);
TexCoordUpdate();
return;
}
void fk_RectTexture::setTextureCoord(const fk_TexCoord &argS,
const fk_TexCoord &argE)
{
if(argS.x < -fk_Math::EPS || argS.x > 1.0 + fk_Math::EPS ||
argS.y < -fk_Math::EPS || argS.y > 1.0 + fk_Math::EPS ||
argE.x < -fk_Math::EPS || argE.x > 1.0 + fk_Math::EPS ||
argE.y < -fk_Math::EPS || argE.y > 1.0 + fk_Math::EPS) {
Error::Put("fk_RectTexture", "setTextureCoord", 2, "Texture Coord Error.");
return;
}
_m->rectSE[0].set(argS.x, argS.y);
_m->rectSE[1].set(argE.x, argE.y);
TexCoordUpdate();
return;
}
fk_TexCoord fk_RectTexture::getTextureCoord(int argID)
{
if(argID < 0 || argID > 1) {
Error::Put("fk_RectTexture", "getTextureCoord", 1, "ID Error");
return fk_TexCoord(0.0, 0.0);
}
return _m->rectSE[argID];
}
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, 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 copyright holders 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.
*
****************************************************************************/
/****************************************************************************
*
* Copyright (c) 1999-2020, Fine Kernel Project, All rights reserved.
*
* 本ソフトウェアおよびソースコードのライセンスは、基本的に
* 「修正 BSD ライセンス」に従います。以下にその詳細を記します。
*
* ソースコード形式かバイナリ形式か、変更するかしないかを問わず、
* 以下の条件を満たす場合に限り、再頒布および使用が許可されます。
*
* - ソースコードを再頒布する場合、上記の著作権表示、本条件一覧、
* および下記免責条項を含めること。
*
* - バイナリ形式で再頒布する場合、頒布物に付属のドキュメント等の
* 資料に、上記の著作権表示、本条件一覧、および下記免責条項を
* 含めること。
*
* - 書面による特別の許可なしに、本ソフトウェアから派生した製品の
* 宣伝または販売促進に、本ソフトウェアの著作権者の名前または
* コントリビューターの名前を使用してはならない。
*
* 本ソフトウェアは、著作権者およびコントリビューターによって「現
* 状のまま」提供されており、明示黙示を問わず、商業的な使用可能性、
* および特定の目的に対する適合性に関す暗黙の保証も含め、またそれ
* に限定されない、いかなる保証もないものとします。著作権者もコン
* トリビューターも、事由のいかんを問わず、損害発生の原因いかんを
* 問わず、かつ責任の根拠が契約であるか厳格責任であるか(過失その
* 他の)不法行為であるかを問わず、仮にそのような損害が発生する可
* 能性を知らされていたとしても、本ソフトウェアの使用によって発生
* した(代替品または代用サービスの調達、使用の喪失、データの喪失、
* 利益の喪失、業務の中断も含め、またそれに限定されない)直接損害、
* 間接損害、偶発的な損害、特別損害、懲罰的損害、または結果損害に
* ついて、一切責任を負わないものとします。
*
****************************************************************************/
| 26.447099 | 78 | 0.675571 | rita0222 |
ca949ac10fe53519e6ee8e600979a5bc4f059ea8 | 7,980 | cc | C++ | tests/libtests/faults/obsolete/TestEqKinSrc.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 93 | 2015-01-08T16:41:22.000Z | 2022-02-25T13:40:02.000Z | tests/libtests/faults/obsolete/TestEqKinSrc.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 277 | 2015-02-20T16:27:35.000Z | 2022-03-30T21:13:09.000Z | tests/libtests/faults/obsolete/TestEqKinSrc.cc | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | 71 | 2015-03-24T12:11:08.000Z | 2022-03-03T04:26:02.000Z | // -*- C++ -*-
//
// ----------------------------------------------------------------------
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ----------------------------------------------------------------------
//
#include <portinfo>
#include "TestEqKinSrc.hh" // Implementation of class methods
#include "pylith/faults/EqKinSrc.hh" // USES EqKinSrc
#include "TestFaultMesh.hh" // USES createFaultMesh()
#include "pylith/faults/BruneSlipFn.hh" // USES BruneSlipFn
#include "pylith/faults/CohesiveTopology.hh" // USES CohesiveTopology
#include "pylith/topology/Mesh.hh" // USES Mesh
#include "pylith/topology/MeshOps.hh" // USES MeshOps::nondimensionalize()
#include "pylith/topology/Field.hh" // USES Field
#include "pylith/topology/Stratum.hh" // USES Stratum
#include "pylith/topology/VisitorMesh.hh" // USES VecVisitorMesh
#include "pylith/meshio/MeshIOAscii.hh" // USES MeshIOAscii
#include "spatialdata/geocoords/CSCart.hh" // USES CSCart
#include "spatialdata/spatialdb/SimpleDB.hh" // USES SimpleDB
#include "spatialdata/spatialdb/SimpleIOAscii.hh" // USES SimpleIOAscii
#include "spatialdata/units/Nondimensional.hh" // USES Nondimensional
// ----------------------------------------------------------------------
CPPUNIT_TEST_SUITE_REGISTRATION( pylith::faults::TestEqKinSrc );
// ----------------------------------------------------------------------
namespace pylith {
namespace faults {
namespace _TestEqKinSrc {
const PylithScalar lengthScale = 1.0e+3;
const PylithScalar pressureScale = 2.25e+10;
const PylithScalar timeScale = 1.0;
const PylithScalar velocityScale = lengthScale / timeScale;
const PylithScalar densityScale = pressureScale / (velocityScale*velocityScale);
} // namespace _TestTractPerturbation
} // faults
} // pylith
// ----------------------------------------------------------------------
// Test constructor.
void
pylith::faults::TestEqKinSrc::testConstructor(void)
{ // testConstructor
PYLITH_METHOD_BEGIN;
EqKinSrc eqsrc;
PYLITH_METHOD_END;
} // testConstructor
// ----------------------------------------------------------------------
// Test slipFn().
void
pylith::faults::TestEqKinSrc::testSlipFn(void)
{ // testSlipFn
PYLITH_METHOD_BEGIN;
BruneSlipFn slipfn;
EqKinSrc eqsrc;
eqsrc.slipfn(&slipfn);
CPPUNIT_ASSERT(&slipfn == eqsrc._slipfn);
PYLITH_METHOD_END;
} // testSlipFn
// ----------------------------------------------------------------------
// Test initialize(). Use 2-D mesh with Brune slip function to test
// initialize().
void
pylith::faults::TestEqKinSrc::testInitialize(void)
{ // testInitialize
PYLITH_METHOD_BEGIN;
topology::Mesh mesh;
topology::Mesh faultMesh;
EqKinSrc eqsrc;
BruneSlipFn slipfn;
const PylithScalar originTime = 2.45;
_initialize(&mesh, &faultMesh, &eqsrc, &slipfn, originTime);
// Don't have access to details of slip time function, so we can't
// check parameters. Have to rely on test of slip() for verification
// of results.
PYLITH_METHOD_END;
} // testInitialize
// ----------------------------------------------------------------------
// Test slip().
void
pylith::faults::TestEqKinSrc::testSlip(void)
{ // testSlip
PYLITH_METHOD_BEGIN;
const PylithScalar finalSlipE[4] = { 2.3, 0.1, 2.4, 0.2,
};
const PylithScalar slipTimeE[2] = { 1.2, 1.3 };
const PylithScalar riseTimeE[2] = { 1.4, 1.5 };
const PylithScalar originTime = 2.42 / _TestEqKinSrc::timeScale;
topology::Mesh mesh;
topology::Mesh faultMesh;
EqKinSrc eqsrc;
BruneSlipFn slipfn;
_initialize(&mesh, &faultMesh, &eqsrc, &slipfn, originTime);
const spatialdata::geocoords::CoordSys* cs = faultMesh.coordsys();CPPUNIT_ASSERT(cs);
const int spaceDim = cs->spaceDim();
topology::Field slip(faultMesh);
slip.newSection(topology::FieldBase::VERTICES_FIELD, spaceDim);
slip.allocate();
const PylithScalar t = 2.134 / _TestEqKinSrc::timeScale;
eqsrc.slip(&slip, originTime+t);
PetscDM dmMesh = faultMesh.dmMesh();CPPUNIT_ASSERT(dmMesh);
topology::Stratum verticesStratum(dmMesh, topology::Stratum::DEPTH, 0);
const PetscInt vStart = verticesStratum.begin();
const PetscInt vEnd = verticesStratum.end();
topology::VecVisitorMesh slipVisitor(slip);
const PetscScalar* slipArray = slipVisitor.localArray();CPPUNIT_ASSERT(slipArray);
const PylithScalar tolerance = 1.0e-06;
for(PetscInt v = vStart, iPoint = 0; v < vEnd; ++v, ++iPoint) {
PylithScalar slipMag = 0.0;
for (int iDim=0; iDim < spaceDim; ++iDim)
slipMag += pow(finalSlipE[iPoint*spaceDim+iDim], 2);
slipMag = sqrt(slipMag);
const PylithScalar peakRate = slipMag / riseTimeE[iPoint] * 1.745;
const PylithScalar tau = slipMag / (exp(1.0) * peakRate);
const PylithScalar t0 = slipTimeE[iPoint];
const PylithScalar slipNorm = 1.0 - exp(-(t-t0)/tau) * (1.0 + (t-t0)/tau);
const PetscInt off = slipVisitor.sectionOffset(v);
CPPUNIT_ASSERT_EQUAL(spaceDim, slipVisitor.sectionDof(v));
for(PetscInt d = 0; d < spaceDim; ++d) {
const PylithScalar slipE = finalSlipE[iPoint*spaceDim+d] * slipNorm;
CPPUNIT_ASSERT_DOUBLES_EQUAL(slipE, slipArray[off+d]*_TestEqKinSrc::lengthScale, tolerance);
} // for
} // for
PYLITH_METHOD_END;
} // testSlip
// ----------------------------------------------------------------------
// Initialize EqKinSrc.
void
pylith::faults::TestEqKinSrc::_initialize(topology::Mesh* mesh,
topology::Mesh* faultMesh,
EqKinSrc* eqsrc,
BruneSlipFn* slipfn,
const PylithScalar originTime)
{ // _initialize
PYLITH_METHOD_BEGIN;
CPPUNIT_ASSERT(mesh);
CPPUNIT_ASSERT(faultMesh);
CPPUNIT_ASSERT(eqsrc);
CPPUNIT_ASSERT(slipfn);
PetscErrorCode err;
const char* meshFilename = "data/tri3.mesh";
const char* faultLabel = "fault";
const int faultId = 2;
const char* finalSlipFilename = "data/tri3_finalslip.spatialdb";
const char* slipTimeFilename = "data/tri3_sliptime.spatialdb";
const char* peakRateFilename = "data/tri3_risetime.spatialdb";
meshio::MeshIOAscii meshIO;
meshIO.filename(meshFilename);
meshIO.debug(false);
meshIO.interpolate(false);
meshIO.read(mesh);
// Set up coordinates
spatialdata::geocoords::CSCart cs;
const int spaceDim = mesh->dimension();
cs.setSpaceDim(spaceDim);
cs.initialize();
mesh->coordsys(&cs);
// Set scales
spatialdata::units::Nondimensional normalizer;
normalizer.lengthScale(_TestEqKinSrc::lengthScale);
normalizer.pressureScale(_TestEqKinSrc::pressureScale);
normalizer.densityScale(_TestEqKinSrc::densityScale);
normalizer.timeScale(_TestEqKinSrc::timeScale);
topology::MeshOps::nondimensionalize(mesh, normalizer);
// Create fault mesh
TestFaultMesh::createFaultMesh(faultMesh, mesh, faultLabel, faultId);
// Setup databases
spatialdata::spatialdb::SimpleDB dbFinalSlip("final slip");
spatialdata::spatialdb::SimpleIOAscii ioFinalSlip;
ioFinalSlip.filename(finalSlipFilename);
dbFinalSlip.ioHandler(&ioFinalSlip);
spatialdata::spatialdb::SimpleDB dbSlipTime("slip time");
spatialdata::spatialdb::SimpleIOAscii ioSlipTime;
ioSlipTime.filename(slipTimeFilename);
dbSlipTime.ioHandler(&ioSlipTime);
spatialdata::spatialdb::SimpleDB dbRiseTime("rise time");
spatialdata::spatialdb::SimpleIOAscii ioRiseTime;
ioRiseTime.filename(peakRateFilename);
dbRiseTime.ioHandler(&ioRiseTime);
// setup EqKinSrc
slipfn->dbFinalSlip(&dbFinalSlip);
slipfn->dbSlipTime(&dbSlipTime);
slipfn->dbRiseTime(&dbRiseTime);
eqsrc->originTime(originTime);
eqsrc->slipfn(slipfn);
eqsrc->initialize(*faultMesh, normalizer);
PYLITH_METHOD_END;
} // _initialize
// End of file
| 32.571429 | 98 | 0.671303 | Grant-Block |
ca951c7596940c78e70007b91d19727ff4057ba7 | 463 | cpp | C++ | aashishgahlawat/codeforces/A/118-A/118-A-30513113.cpp | aashishgahlawat/CompetetiveProgramming | 12d6b2682765ae05b622968b9a26b0b519e170aa | [
"MIT"
] | null | null | null | aashishgahlawat/codeforces/A/118-A/118-A-30513113.cpp | aashishgahlawat/CompetetiveProgramming | 12d6b2682765ae05b622968b9a26b0b519e170aa | [
"MIT"
] | null | null | null | aashishgahlawat/codeforces/A/118-A/118-A-30513113.cpp | aashishgahlawat/CompetetiveProgramming | 12d6b2682765ae05b622968b9a26b0b519e170aa | [
"MIT"
] | null | null | null | #include <iostream>
#include <string.h>
using namespace std;
int main() {
// your code goes here
string text;
string result="";
cin>>text;
int textLength=text.length();
for(int i=0;i<textLength;++i){
char temp=text[i];
if(temp<97) temp+=32;
if(temp=='a'|| temp=='e'|| temp=='i'|| temp=='o'|| temp=='u' || temp=='y'){
}else{result=result+'.'+temp;}
}
std::cout << result<<endl;
return 0;
} | 21.045455 | 84 | 0.526998 | aashishgahlawat |
ca959a6bfe2f408fa9e2bc58a4c457026b1be35c | 6,611 | cpp | C++ | Testing/Operations/albaASCIIImporterUtilityTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Testing/Operations/albaASCIIImporterUtilityTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Testing/Operations/albaASCIIImporterUtilityTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaASCIIImporterUtilityTest
Authors: Alberto Losi
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include <cppunit/config/SourcePrefix.h>
#include "albaASCIIImporterUtilityTest.h"
#include "albaASCIIImporterUtility.h"
#include "albaString.h"
#include <vcl_fstream.h>
#include <vnl/vnl_vector.h>
#include <iostream>
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::TestConstructor()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtilityTest *utility = new albaASCIIImporterUtilityTest();
cppDEL(utility);
}
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::GetNumberOfRowsTest()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtility *utility = new albaASCIIImporterUtility();
albaString filename = ALBA_DATA_ROOT;
filename<<"/Test_ASCIIImporterUtility/matrix_01.txt";
utility->ReadFile(filename);
CPPUNIT_ASSERT(utility->ReadFile(filename) == ALBA_OK);
CPPUNIT_ASSERT(utility->GetNumberOfRows() == 3);
cppDEL(utility);
}
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::GetNumberOfColsTest()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtility *utility = new albaASCIIImporterUtility();
albaString filename = ALBA_DATA_ROOT;
filename<<"/Test_ASCIIImporterUtility/matrix_01.txt";
utility->ReadFile(filename);
CPPUNIT_ASSERT(utility->ReadFile(filename) == ALBA_OK);
CPPUNIT_ASSERT(utility->GetNumberOfCols() == 3);
cppDEL(utility);
}
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::GetNumberOfScalarsTest()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtility *utility = new albaASCIIImporterUtility();
albaString filename = ALBA_DATA_ROOT;
filename<<"/Test_ASCIIImporterUtility/matrix_01.txt";
utility->ReadFile(filename);
CPPUNIT_ASSERT(utility->ReadFile(filename) == ALBA_OK);
CPPUNIT_ASSERT(utility->GetNumberOfScalars() == 9);
cppDEL(utility);
}
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::GetScalarTest()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtility *utility = new albaASCIIImporterUtility();
albaString filename = ALBA_DATA_ROOT;
filename<<"/Test_ASCIIImporterUtility/matrix_01.txt";
utility->ReadFile(filename);
CPPUNIT_ASSERT(utility->ReadFile(filename) == ALBA_OK);
CPPUNIT_ASSERT(utility->GetScalar(1,1) == 5.0);
cppDEL(utility);
}
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::GetMatrixTest()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtility *utility = new albaASCIIImporterUtility();
albaString filename = ALBA_DATA_ROOT;
/* Create a Matrix equals to the one stored in the ASCII file;
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
*/
double m1[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
double row[3];
filename<<"/Test_ASCIIImporterUtility/matrix_01.txt";
utility->ReadFile(filename);
CPPUNIT_ASSERT(utility->ReadFile(filename) == ALBA_OK);
for (int i = 0; i < 3; i++)
{
utility->ExtractRow(i, row);
for (int j = 0; j < 3; j++)
CPPUNIT_ASSERT(row[j] == m1[i][j]);
}
cppDEL(utility);
}
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::ExtractRowTest()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtility *utility = new albaASCIIImporterUtility();
albaString filename = ALBA_DATA_ROOT;
std::vector<double> v1;
double vd1[3];
/* Create a vector equals to the first row of the matrix stored in the ASCII file;
1.0 2.0 3.0
*/
v1.push_back(1.0);
v1.push_back(2.0);
v1.push_back(3.0);
vd1[0] = 1.0;
vd1[1] = 2.0;
vd1[2] = 3.0;
filename<<"/Test_ASCIIImporterUtility/matrix_01.txt";
utility->ReadFile(filename);
CPPUNIT_ASSERT(utility->ReadFile(filename) == ALBA_OK);
std::vector<double> v2;
utility->ExtractRow(0,v2);
double vd2[3];
utility->ExtractRow(0,vd2);
CPPUNIT_ASSERT((v1[0] == v2[0]) && (v1[1] == v2[1]) && (v1[2] == v2[2]));
CPPUNIT_ASSERT((vd1[0] == vd2[0]) && (vd1[1] == vd2[1]) && (vd1[2] == vd2[2]));
cppDEL(utility);
}
//----------------------------------------------------------------------------
void albaASCIIImporterUtilityTest::ExtractColumnTest()
//----------------------------------------------------------------------------
{
albaASCIIImporterUtility *utility = new albaASCIIImporterUtility();
albaString filename = ALBA_DATA_ROOT;
std::vector<double> v1;
double vd1[3];
/* Create a vector equals to the first column of the matrix stored in the ASCII file;
1.0 4.0 7.0
*/
v1.push_back(1.0);
v1.push_back(4.0);
v1.push_back(7.0);
vd1[0] = 1.0;
vd1[1] = 4.0;
vd1[2] = 7.0;
filename<<"/Test_ASCIIImporterUtility/matrix_01.txt";
utility->ReadFile(filename);
CPPUNIT_ASSERT(utility->ReadFile(filename) == ALBA_OK);
std::vector<double> v2;
utility->ExtractColumn(0,v2);
double vd2[3];
utility->ExtractColumn(0,vd2);
CPPUNIT_ASSERT((v1[0] == v2[0]) && (v1[1] == v2[1]) && (v1[2] == v2[2]));
CPPUNIT_ASSERT((vd1[0] == vd2[0]) && (vd1[1] == vd2[1]) && (vd1[2] == vd2[2]));
cppDEL(utility);
}
| 29.513393 | 87 | 0.543488 | IOR-BIC |
ca95a26830ef766ea1e8f9929f3cb70c3e859a77 | 1,006 | cpp | C++ | chapter08/context/8.10left.cpp | chuckbruno/cpp | 5df742c15d463a46351bd72b5c58144086b0a9d2 | [
"Apache-2.0"
] | null | null | null | chapter08/context/8.10left.cpp | chuckbruno/cpp | 5df742c15d463a46351bd72b5c58144086b0a9d2 | [
"Apache-2.0"
] | null | null | null | chapter08/context/8.10left.cpp | chuckbruno/cpp | 5df742c15d463a46351bd72b5c58144086b0a9d2 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
unsigned long left(unsigned long num, unsigned int cf);
char * left(const char* str, int n = 1);
int main()
{
using namespace std;
const char * trip = "Hawaii!!";
unsigned long n = 12345678;
int i;
char * temp;
for(i=1; i < 10; i++)
{
cout << left(n, i) << endl;
temp = left(trip, i);
cout << temp << endl;
delete[] temp;
}
return 0;
}
unsigned long left(unsigned long num, unsigned ct)
{
unsigned digits = 1;
unsigned long n = num;
if (ct == 0 || num == 0)
return 0;
while(n /= 10)
digits++;
if (digits > ct)
{
ct = digits - ct;
while(ct--)
num /= 10;
return num;
}
else
return num;
}
char* left(const char * str, int n)
{
if (n < 0)
n = 0;
char *p = new char[n+1];
int i;
for (i=0; i < n&& str[i]; i++)
p[i] = str[i];
while (i <= n)
p[i++] = '\0';
return p;
}
| 15.242424 | 55 | 0.461233 | chuckbruno |
ca99662d3c78af6d8914b66de7a7dde6f1da5138 | 408 | hxx | C++ | inc/html5xx.d/S.hxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | inc/html5xx.d/S.hxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | inc/html5xx.d/S.hxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | /*
*
*/
#ifndef _HTML5XX_S_HXX_
#define _HTML5XX_S_HXX_
#include "Element.hxx"
#include "LineElement.hxx"
using namespace std;
namespace html
{
class S: public Element
{
public:
S():
Element(Inline, "s")
{}
S( const string& text ):
Element(Inline, "s")
{
put(new LineElement(text));
}
};
} // end namespace html
#endif // _HTML5XX_S_HXX_
// vi: set ai et sw=2 sts=2 ts=2 :
| 11.027027 | 34 | 0.627451 | astrorigin |
ca9cccc45fccf26be356907bdde968483f7c34e8 | 9,870 | cpp | C++ | C++/CNN3.cpp | FlorentCLMichel/CNN_in_Cpp | 5568e71ec23c45be144a0673e2fc36d4c6f1c5de | [
"MIT"
] | null | null | null | C++/CNN3.cpp | FlorentCLMichel/CNN_in_Cpp | 5568e71ec23c45be144a0673e2fc36d4c6f1c5de | [
"MIT"
] | null | null | null | C++/CNN3.cpp | FlorentCLMichel/CNN_in_Cpp | 5568e71ec23c45be144a0673e2fc36d4c6f1c5de | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <iomanip>
#include <math.h>
#include <vector>
#include <random>
#include <thread>
#include <boost/multi_array.hpp>
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
using namespace std;
namespace p = boost::python;
namespace np = boost::python::numpy;
#include "Layers.cpp"
// precision for floating numbers written in files
constexpr int prec_write_file = 16;
// define a standard normal distribution
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> dis(0.,1.);
// uniform dictribution
std::uniform_real_distribution<> uni(0.,1.);
struct double_and_int{
double d = 0.;
int i = 0;
};
class CNN3{
private:
int num_CLs; // number of convolution layers
int num_FCs; // number of FullCon layers
int img_h_i; // image height
int img_w_i; // image width
int img_h; // image height before the fully connected layers
int img_w; // image width before the fully connected layers
int num_images; // number of images
int num_labels; // number of different possible labels
int n_channels; // number of channels
vector<int> CL_size_filters; // Convolution layers: filter sizes
vector<int> CL_num_filters; // Convolution layers: numbers of filters
vector<int> MP_size; // Maxpool layers: pool sizes
vector<int> FC_size; // FullCon layers: number of neurons
// These four vectors will contain the layers
vector<ConvLayer> CLs; // Convolution layers
vector<ReLU> RLUs; // ReLU layers
vector<MaxPool> MPs; // Maxpool layers
vector<FullCon> FCs; // FullCon layers
vector<SoftMax> SMs; // Softmax layers
public:
CNN3(){
np::initialize(); // required to create numpy arrays (otherwise leads to segmentation faults)
}
CNN3(
int img_w_, // image width
int img_h_, // image height
int n_channels_, // number of channels
p::list& CL_size_filters_, // list of filter sizes
p::list& CL_num_filters_, // list of numbers of filters
p::list& MP_size_, // list of pool sizes
p::list& FC_size_, // list of FullCon sizes
int num_labels_ // number of different possible labels
)
{
// initialization
img_w_i = img_w_;
img_h_i = img_h_;
img_w = img_w_;
img_h = img_h_;
num_labels = num_labels_;
n_channels = n_channels_;
CL_size_filters = int_list_to_vector(CL_size_filters_);
CL_num_filters = int_list_to_vector(CL_num_filters_);
MP_size = int_list_to_vector(MP_size_);
FC_size = int_list_to_vector(FC_size_);
num_CLs = len(CL_size_filters_);
num_FCs = len(FC_size_);
num_images = n_channels; // tracks the number of images
// build the layers
for(int i=0; i<num_CLs; i++){
CLs.push_back(ConvLayer(CL_size_filters[i], num_images, CL_num_filters[i], gen, dis));
num_images = CL_num_filters[i];
img_w = img_w + 1 - CL_size_filters[i];
img_h = img_h + 1 - CL_size_filters[i];
RLUs.push_back(ReLU());
MPs.push_back(MaxPool(MP_size[i]));
img_w = (int) img_w / MP_size[i];
img_h = (int) img_h / MP_size[i];
}
long int n_inputs = num_images*img_h*img_w;
for(int i=0; i<num_FCs; i++){
int n_neurons = FC_size[i];
FCs.push_back(FullCon(n_inputs, n_neurons, gen, dis));
n_inputs = n_neurons;
}
SMs.push_back(SoftMax(n_inputs, num_labels, gen, dis));
np::initialize(); // required to create numpy arrays (otherwise leads to segmentation faults)
}
// save the CNN parameters to a file
void save(char* filename){
ofstream file;
file.open(filename);
file << fixed << setprecision(prec_write_file);
file << num_CLs << sep_val << num_FCs << sep_val << n_channels << sep_val << img_w_i << sep_val << img_h_i << sep_val << img_w << sep_val << img_h << sep_val << num_images << sep_line;
save_vector(CL_size_filters, file);
save_vector(CL_num_filters, file);
save_vector(MP_size, file);
for(int i=0; i<num_CLs; i++){
CLs[i].save(file);
RLUs[i].save(file);
MPs[i].save(file);
}
for(int i=0; i<num_FCs; i++){
FCs[i].save(file);
}
SMs[0].save(file);
file.close();
}
// load the CNN parameters from a file
void load(char* filename){
ifstream file;
file.open(filename);
char c;
file >> num_CLs >> c >> num_FCs >> c >> n_channels >> c >> img_w_i >> c >> img_h_i >> c >> img_w >> c >> img_h >> c >> num_images >> c;
CL_size_filters = load_vector<int>(file);
CL_num_filters = load_vector<int>(file);
MP_size = load_vector<int>(file);
CLs.clear();
RLUs.clear();
CLs.clear();
SMs.clear();
for(int i=0; i<num_CLs; i++){
CLs.push_back(ConvLayer());
CLs[i].load(file);
RLUs.push_back(ReLU());
RLUs[i].load(file);
MPs.push_back(MaxPool());
MPs[i].load(file);
}
for(int i=0; i<num_FCs; i++){
FCs.push_back(FullCon());
FCs[i].load(file);
}
SMs.push_back(SoftMax());
SMs[0].load(file);
file.close();
num_labels = SMs[0].output.size();
}
// forward pass
vector<double> forward(d3_array_type &input, double p_dropout = 0.){
// number and dimensions of images
int nim = input.shape()[0];
int h = input.shape()[1];
int w = input.shape()[2];
if(h != img_h_i || w != img_w_i || nim != n_channels){
cout << "\nInvalid input dimensions!\n" << endl;
}
for(int i=0; i<num_CLs; i++){
d3_array_type output1 = CLs[i].forward(input);
input.resize(boost::extents[output1.shape()[0]][output1.shape()[1]][output1.shape()[2]]);
input = output1;
d3_array_type output2 = MPs[i].forward(input);
input.resize(boost::extents[output2.shape()[0]][output2.shape()[1]][output2.shape()[2]]);
input = output2;
d3_array_type output3 = RLUs[i].forward(input);
input.resize(boost::extents[output3.shape()[0]][output3.shape()[1]][output3.shape()[2]]);
input = output3;
}
vector<double> input_vec;
auto input_shape = input.shape();
for(int i=0; i<num_images; i++){
for(int j=0; j<img_h; j++){
for(int k=0; k<img_w; k++){
input_vec.push_back(input[i][j][k]);
}
}
}
for(int i=0; i<num_FCs; i++){
input_vec = FCs[i].forward(input_vec, gen, uni, p_dropout);
}
return SMs[0].forward(input_vec);
}
// backpropagation
void backprop(vector<double> d_L_d_out_i, double learn_rate){
d3_array_type d_L_d_in(boost::extents[num_images][img_h][img_w]);
vector<double> d_L_d_in_vec = SMs[0].backprop(d_L_d_out_i, learn_rate);
for(int i=num_FCs-1; i>=0; i--){
d_L_d_in_vec = FCs[i].backprop(d_L_d_in_vec, learn_rate);
}
for(int i=0; i<num_images; i++){
for(int j=0; j<img_h; j++){
for(int k=0; k<img_w; k++){
d_L_d_in[i][j][k] = d_L_d_in_vec[i*img_h*img_w + j*img_w + k];
}
}
}
for(int i=num_CLs-1; i>=0; i--){
d3_array_type d_L_d_in3 = RLUs[i].backprop(d_L_d_in);
auto shape = d_L_d_in3.shape();
d_L_d_in.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
d_L_d_in = d_L_d_in3;
d3_array_type d_L_d_in2 = MPs[i].backprop(d_L_d_in);
shape = d_L_d_in2.shape();
d_L_d_in.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
d_L_d_in = d_L_d_in2;
d3_array_type d_L_d_in1 = CLs[i].backprop(d_L_d_in, learn_rate);
shape = d_L_d_in1.shape();
d_L_d_in.resize(boost::extents[shape[0]][shape[1]][shape[2]]);
d_L_d_in = d_L_d_in1;
}
}
// loss function and accuracy (1 if correct answer, 0 otherwise)
double_and_int loss_acc(vector<double> &output, int label){
double_and_int results;
results.d = -log(output[label]);
results.i = 1;
for(int i=0; i<output.size(); i++){
if(output[i] > output[label]){
results.i = 0;
}
}
return results;
}
// Completes a training step on the image 'image' with label 'label'.
// Returns the corss-entropy and accuracy.
double_and_int train(d3_array_type image, int label, double learn_rate = 0.005, double p_dropout = 0.) {
// forward pass
vector<double> output_forward = forward(image, p_dropout);
// gradient of the loss function with respect to the output
vector<double> d_L_d_out;
for(int i=0; i<num_labels; i++){
d_L_d_out.push_back(0.);
}
d_L_d_out[label] = -1./output_forward[label];
// backpropagation
backprop(d_L_d_out, learn_rate);
// return loss and accuracy
return loss_acc(output_forward, label);
}
// full forward propagation - Python wrapper
// input: 2d numpy array
np::ndarray forward_python(np::ndarray image){
d3_array_type input = d3_numpy_to_multi_array(image);
return vector_to_numpy(forward(input));
}
// forward - return loss and accuracy - Python wrapper
p::list forward_la_python(np::ndarray image, int label){
d3_array_type input = d3_numpy_to_multi_array(image);
vector<double> output = forward(input);
double_and_int results = loss_acc(output, label);
p::list results_p;
results_p.append(results.d);
results_p.append(results.i);
return results_p;
}
// full backpropagation - Python wrapper
void backprop_python(np::ndarray d_L_d_out, double learn_rate){
backprop(numpy_to_vector(d_L_d_out), learn_rate);
}
// train - Python wrapper
p::list train_python(np::ndarray image, int label, double learn_rate, double p_dropout) {
double_and_int results;
results = train(d3_numpy_to_multi_array(image), label, learn_rate, p_dropout);
p::list results_p;
results_p.append(results.d);
results_p.append(results.i);
return results_p;
}
};
BOOST_PYTHON_MODULE(CNN3)
{
p::class_<CNN3>("CNN3", p::init<int, int, int, p::list&, p::list&, p::list&, p::list&, int>())
.def(p::init<>())
.def("forward", &CNN3::forward_python)
.def("backprop", &CNN3::backprop_python)
.def("train", &CNN3::train_python)
.def("save", &CNN3::save)
.def("load", &CNN3::load)
.def("forward_la", &CNN3::forward_la_python)
;
}
| 30.276074 | 187 | 0.659574 | FlorentCLMichel |
caa09ae8b80be858449d74a9109aa12068896dd6 | 326 | cpp | C++ | UEL/Lista do caralho/utilities.cpp | FlammaVulpes/random-crappy-stuff | c3fc38f8152393300ea6e8f4637c837a21379bd9 | [
"MIT"
] | null | null | null | UEL/Lista do caralho/utilities.cpp | FlammaVulpes/random-crappy-stuff | c3fc38f8152393300ea6e8f4637c837a21379bd9 | [
"MIT"
] | null | null | null | UEL/Lista do caralho/utilities.cpp | FlammaVulpes/random-crappy-stuff | c3fc38f8152393300ea6e8f4637c837a21379bd9 | [
"MIT"
] | null | null | null | #include "header.hpp"
using namespace std;
void sudSort(int arr[9]){
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9 - i; ++j){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
| 21.733333 | 40 | 0.349693 | FlammaVulpes |
caa8436ece520bc6710797027c8322aae32e9fff | 3,980 | cc | C++ | test/splittest.cc | aalto-speech/morphological-classes | a7dcdb0703b33765ed43a9a56a3ca453dc5ed5e3 | [
"BSD-2-Clause"
] | null | null | null | test/splittest.cc | aalto-speech/morphological-classes | a7dcdb0703b33765ed43a9a56a3ca453dc5ed5e3 | [
"BSD-2-Clause"
] | null | null | null | test/splittest.cc | aalto-speech/morphological-classes | a7dcdb0703b33765ed43a9a56a3ca453dc5ed5e3 | [
"BSD-2-Clause"
] | null | null | null | #include <boost/test/unit_test.hpp>
#include <iostream>
#include <vector>
#include <map>
#include <ctime>
#include <algorithm>
#define private public
#include "Splitting.hh"
#undef private
using namespace std;
void
_assert_same(Splitting& s1,
Splitting& s2)
{
BOOST_CHECK_EQUAL(s1.m_num_classes, s2.m_num_classes);
BOOST_CHECK(s1.m_vocabulary==s2.m_vocabulary);
BOOST_CHECK(s1.m_vocabulary_lookup==s2.m_vocabulary_lookup);
for (int i = 0; i<(int) s1.m_classes.size(); i++)
if (s1.m_classes[i].size()>0)
BOOST_CHECK(s1.m_classes[i]==s2.m_classes[i]);
for (int i = 0; i<(int) s2.m_classes.size(); i++)
if (s2.m_classes[i].size()>0)
BOOST_CHECK(s1.m_classes[i]==s2.m_classes[i]);
BOOST_CHECK(s1.m_word_classes==s2.m_word_classes);
BOOST_CHECK(s1.m_word_counts==s2.m_word_counts);
BOOST_CHECK(s1.m_word_bigram_counts==s2.m_word_bigram_counts);
BOOST_CHECK(s1.m_word_rev_bigram_counts==s2.m_word_rev_bigram_counts);
for (int i = 0; i<(int) s1.m_class_counts.size(); i++)
if (s1.m_class_counts[i]!=0)
BOOST_CHECK_EQUAL(s1.m_class_counts[i], s2.m_class_counts[i]);
for (int i = 0; i<(int) s2.m_class_counts.size(); i++)
if (s2.m_class_counts[i]!=0)
BOOST_CHECK_EQUAL(s1.m_class_counts[i], s2.m_class_counts[i]);
for (int i = 0; i<(int) s1.m_class_bigram_counts.size(); i++)
for (int j = 0; j<(int) s1.m_class_bigram_counts[i].size(); j++)
if (s1.m_class_bigram_counts[i][j]!=0)
BOOST_CHECK_EQUAL(s1.m_class_bigram_counts[i][j], s2.m_class_bigram_counts[i][j]);
for (int i = 0; i<(int) s2.m_class_bigram_counts.size(); i++)
for (int j = 0; j<(int) s2.m_class_bigram_counts[i].size(); j++)
if (s2.m_class_bigram_counts[i][j]!=0)
BOOST_CHECK_EQUAL(s1.m_class_bigram_counts[i][j], s2.m_class_bigram_counts[i][j]);
for (int i = 0; i<(int) s1.m_class_word_counts.size(); i++)
for (auto wit = s1.m_class_word_counts[i].begin(); wit!=s1.m_class_word_counts[i].end(); ++wit) {
BOOST_CHECK(wit->second!=0);
BOOST_CHECK_EQUAL(wit->second, s2.m_class_word_counts[i][wit->first]);
}
for (int i = 0; i<(int) s2.m_class_word_counts.size(); i++)
for (auto cit = s2.m_class_word_counts[i].begin(); cit!=s2.m_class_word_counts[i].end(); ++cit) {
BOOST_CHECK(cit->second!=0);
BOOST_CHECK_EQUAL(cit->second, s1.m_class_word_counts[i][cit->first]);
}
for (int i = 0; i<(int) s1.m_word_class_counts.size(); i++)
for (auto cit = s1.m_word_class_counts[i].begin(); cit!=s1.m_word_class_counts[i].end(); ++cit) {
BOOST_CHECK(cit->second!=0);
BOOST_CHECK_EQUAL(cit->second, s2.m_word_class_counts[i][cit->first]);
}
for (int i = 0; i<(int) s2.m_word_class_counts.size(); i++)
for (auto cit = s2.m_word_class_counts[i].begin(); cit!=s2.m_word_class_counts[i].end(); ++cit) {
BOOST_CHECK(cit->second!=0);
BOOST_CHECK_EQUAL(cit->second, s1.m_word_class_counts[i][cit->first]);
}
BOOST_CHECK_EQUAL(s1.log_likelihood(), s2.log_likelihood());
}
// Test that splitting classes works
BOOST_AUTO_TEST_CASE(DoSplit)
{
map<string, int>class_init_2 = {{"a", 2}, {"b", 3}, {"c", 3}, {"d", 2}, {"e", 3}};
Splitting splitting(2, class_init_2, "data/exchange1.txt");
set<int> class1_words, class2_words;
class1_words.insert(splitting.m_vocabulary_lookup["b"]);
class1_words.insert(splitting.m_vocabulary_lookup["e"]);
class2_words.insert(splitting.m_vocabulary_lookup["c"]);
splitting.do_split(3, class1_words, class2_words);
map<string, int> class_init = {{ "a", 2 }, { "b", 3 }, { "c", 4 }, { "d", 2 }, { "e", 3 }};
Splitting splitting2(3, class_init, "data/exchange1.txt");
_assert_same(splitting, splitting2);
}
| 41.894737 | 105 | 0.628894 | aalto-speech |
caa97883ba0471e8c6f8119830caa82742f4d4d9 | 699 | cpp | C++ | Source/DialogSystemRuntime/Private/Dialog/DialogNodes/DialogNode.cpp | n3td0g/DialogSystem | 5c7919c5d69246c3798f2322b08f0c10c736d0dc | [
"Apache-2.0"
] | null | null | null | Source/DialogSystemRuntime/Private/Dialog/DialogNodes/DialogNode.cpp | n3td0g/DialogSystem | 5c7919c5d69246c3798f2322b08f0c10c736d0dc | [
"Apache-2.0"
] | null | null | null | Source/DialogSystemRuntime/Private/Dialog/DialogNodes/DialogNode.cpp | n3td0g/DialogSystem | 5c7919c5d69246c3798f2322b08f0c10c736d0dc | [
"Apache-2.0"
] | null | null | null | #include "Dialog/DialogNodes/DialogNode.h"
#include "Dialog/DialogProcessor.h"
#include "Dialog/DialogNodes/DialogPhraseNode.h"
void UDialogNode::Invoke(UDialogProcessor* processor)
{
check(processor);
for (auto child : Childs)
{
if (child->Check(processor))
{
processor->SetCurrentNode(child);
return;
}
}
}
bool UDialogNode::Check(UDialogProcessor* processor)
{
return true;
}
TArray<UDialogPhraseNode*> UDialogNode::GetNextPhrases(UDialogProcessor* processor)
{
check(processor);
TArray<UDialogPhraseNode*> result;
for (auto child : Childs)
{
if (child->Check(processor))
result.Append(child->GetNextPhrases(processor));
}
return result;
}
| 18.394737 | 83 | 0.715308 | n3td0g |
caaa8782fe992ed73bb074872440d018af84ec86 | 25,336 | cpp | C++ | code/wxWidgets/src/os2/notebook.cpp | Bloodknight/NeuTorsion | a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea | [
"MIT"
] | 38 | 2016-02-20T02:46:28.000Z | 2021-11-17T11:39:57.000Z | code/wxWidgets/src/os2/notebook.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 17 | 2016-02-20T02:19:55.000Z | 2021-02-08T15:15:17.000Z | code/wxWidgets/src/os2/notebook.cpp | Dwarf-King/TorsionEditor | e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50 | [
"MIT"
] | 46 | 2016-02-20T02:47:33.000Z | 2021-01-31T15:46:05.000Z | ///////////////////////////////////////////////////////////////////////////////
// Name: notebook.cpp
// Purpose: implementation of wxNotebook
// Author: David Webster
// Modified by:
// Created: 10/12/99
// RCS-ID: $Id: notebook.cpp,v 1.23.2.1 2006/01/03 17:02:46 SN Exp $
// Copyright: (c) David Webster
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#if wxUSE_NOTEBOOK
// wxWidgets
#ifndef WX_PRECOMP
#include "wx/app.h"
#include "wx/dcclient.h"
#include "wx/string.h"
#include "wx/settings.h"
#endif // WX_PRECOMP
#include "wx/log.h"
#include "wx/imaglist.h"
#include "wx/event.h"
#include "wx/control.h"
#include "wx/notebook.h"
#include "wx/os2/private.h"
// ----------------------------------------------------------------------------
// macros
// ----------------------------------------------------------------------------
// check that the page index is valid
#define IS_VALID_PAGE(nPage) ( \
/* size_t is _always_ >= 0 */ \
/* ((nPage) >= 0) && */ \
((nPage) < GetPageCount()) \
)
// hide the ugly cast
#define m_hWnd (HWND)GetHWND()
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// event table
// ----------------------------------------------------------------------------
DEFINE_EVENT_TYPE(wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED)
DEFINE_EVENT_TYPE(wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING)
BEGIN_EVENT_TABLE(wxNotebook, wxControl)
EVT_NOTEBOOK_PAGE_CHANGED(-1, wxNotebook::OnSelChange)
EVT_SIZE(wxNotebook::OnSize)
EVT_SET_FOCUS(wxNotebook::OnSetFocus)
EVT_NAVIGATION_KEY(wxNotebook::OnNavigationKey)
END_EVENT_TABLE()
IMPLEMENT_DYNAMIC_CLASS(wxNotebook, wxControl)
IMPLEMENT_DYNAMIC_CLASS(wxNotebookEvent, wxNotifyEvent)
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxNotebook construction
// ----------------------------------------------------------------------------
//
// Common part of all ctors
//
void wxNotebook::Init()
{
m_imageList = NULL;
m_nSelection = -1;
m_nTabSize = 0;
} // end of wxNotebook::Init
//
// Default for dynamic class
//
wxNotebook::wxNotebook()
{
Init();
} // end of wxNotebook::wxNotebook
//
// The same arguments as for wxControl
//
wxNotebook::wxNotebook(
wxWindow* pParent
, wxWindowID vId
, const wxPoint& rPos
, const wxSize& rSize
, long lStyle
, const wxString& rsName
)
{
Init();
Create( pParent
,vId
,rPos
,rSize
,lStyle
,rsName
);
} // end of wxNotebook::wxNotebook
//
// Create() function
//
bool wxNotebook::Create( wxWindow* pParent,
wxWindowID vId,
const wxPoint& rPos,
const wxSize& rSize,
long lStyle,
const wxString& rsName )
{
//
// Base init
//
if (!CreateControl( pParent
,vId
,rPos
,rSize
,lStyle
,wxDefaultValidator
,rsName
))
return false;
//
// Notebook, so explicitly specify 0 as last parameter
//
if (!OS2CreateControl( wxT("NOTEBOOK")
,wxEmptyString
,rPos
,rSize
,lStyle | wxTAB_TRAVERSAL
))
return false;
SetBackgroundColour(wxColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE)));
return true;
} // end of wxNotebook::Create
WXDWORD wxNotebook::OS2GetStyle (
long lStyle
, WXDWORD* pdwExstyle
) const
{
WXDWORD dwTabStyle = wxControl::OS2GetStyle( lStyle
,pdwExstyle
);
dwTabStyle |= WS_TABSTOP | BKS_SOLIDBIND | BKS_ROUNDEDTABS | BKS_TABTEXTCENTER | BKS_TABBEDDIALOG;
if (lStyle & wxNB_BOTTOM)
dwTabStyle |= BKS_MAJORTABBOTTOM | BKS_BACKPAGESBL;
else if (lStyle & wxNB_RIGHT)
dwTabStyle |= BKS_MAJORTABRIGHT | BKS_BACKPAGESBR;
else if (lStyle & wxNB_LEFT)
dwTabStyle |= BKS_MAJORTABLEFT | BKS_BACKPAGESTL;
else // default to top
dwTabStyle |= BKS_MAJORTABTOP | BKS_BACKPAGESTR;
//
// Ex style
//
if (pdwExstyle )
{
//
// Note that we never want to have the default WS_EX_CLIENTEDGE style
// as it looks too ugly for the notebooks
//
*pdwExstyle = 0;
}
return dwTabStyle;
} // end of wxNotebook::OS2GetStyle
// ----------------------------------------------------------------------------
// wxNotebook accessors
// ----------------------------------------------------------------------------
size_t wxNotebook::GetPageCount() const
{
//
// Consistency check
//
wxASSERT((int)m_pages.Count() == (int)::WinSendMsg(GetHWND(), BKM_QUERYPAGECOUNT, (MPARAM)0, (MPARAM)BKA_END));
return m_pages.Count();
} // end of wxNotebook::GetPageCount
int wxNotebook::GetRowCount() const
{
return (int)::WinSendMsg( GetHWND()
,BKM_QUERYPAGECOUNT
,(MPARAM)0
,(MPARAM)BKA_MAJOR
);
} // end of wxNotebook::GetRowCount
int wxNotebook::SetSelection( size_t nPage )
{
wxCHECK_MSG( IS_VALID_PAGE(nPage), -1, wxT("notebook page out of range") );
if (nPage != (size_t)m_nSelection)
{
wxNotebookEvent vEvent( wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGING
,m_windowId
);
vEvent.SetSelection(nPage);
vEvent.SetOldSelection(m_nSelection);
vEvent.SetEventObject(this);
if (!GetEventHandler()->ProcessEvent(vEvent) || vEvent.IsAllowed())
{
//
// Program allows the page change
//
vEvent.SetEventType(wxEVT_COMMAND_NOTEBOOK_PAGE_CHANGED);
GetEventHandler()->ProcessEvent(vEvent);
::WinSendMsg( GetHWND()
,BKM_TURNTOPAGE
,MPFROMLONG((ULONG)m_alPageId[nPage])
,(MPARAM)0
);
}
}
m_nSelection = nPage;
return nPage;
} // end of wxNotebook::SetSelection
bool wxNotebook::SetPageText( size_t nPage,
const wxString& rsStrText )
{
wxCHECK_MSG( IS_VALID_PAGE(nPage), FALSE, wxT("notebook page out of range") );
return (bool)::WinSendMsg( m_hWnd
,BKM_SETTABTEXT
,MPFROMLONG((ULONG)m_alPageId[nPage])
,MPFROMP((PSZ)rsStrText.c_str())
);
} // end of wxNotebook::SetPageText
wxString wxNotebook::GetPageText ( size_t nPage ) const
{
BOOKTEXT vBookText;
wxChar zBuf[256];
wxString sStr;
ULONG ulRc;
wxCHECK_MSG( IS_VALID_PAGE(nPage), wxT(""), wxT("notebook page out of range") );
memset(&vBookText, '\0', sizeof(BOOKTEXT));
vBookText.textLen = 0; // This will get the length
ulRc = LONGFROMMR(::WinSendMsg( m_hWnd
,BKM_QUERYTABTEXT
,MPFROMLONG((ULONG)m_alPageId[nPage])
,MPFROMP(&vBookText)
));
if (ulRc == (ULONG)BOOKERR_INVALID_PARAMETERS || ulRc == 0L)
{
if (ulRc == (ULONG)BOOKERR_INVALID_PARAMETERS)
{
wxLogError(wxT("Invalid Page Id for page text querry."));
}
return wxEmptyString;
}
vBookText.textLen = ulRc + 1; // To get the null terminator
vBookText.pString = (char*)zBuf;
//
// Now get the actual text
//
ulRc = LONGFROMMR(::WinSendMsg( m_hWnd
,BKM_QUERYTABTEXT
,MPFROMLONG((ULONG)m_alPageId[nPage])
,MPFROMP(&vBookText)
));
if (ulRc == (ULONG)BOOKERR_INVALID_PARAMETERS || ulRc == 0L)
{
return wxEmptyString;
}
if (ulRc > 255L)
ulRc = 255L;
vBookText.pString[ulRc] = '\0';
sStr = (wxChar*)vBookText.pString;
return sStr;
} // end of wxNotebook::GetPageText
int wxNotebook::GetPageImage ( size_t nPage ) const
{
wxCHECK_MSG( IS_VALID_PAGE(nPage), -1, wxT("notebook page out of range") );
//
// For OS/2 just return the page
//
return nPage;
} // end of wxNotebook::GetPageImage
bool wxNotebook::SetPageImage (
size_t nPage
, int nImage
)
{
wxBitmap vBitmap = (wxBitmap)m_imageList->GetBitmap(nImage);
return (bool)::WinSendMsg( GetHWND()
,BKM_SETTABBITMAP
,MPFROMLONG((ULONG)m_alPageId[nPage])
,(MPARAM)wxFlipBmp(vBitmap.GetHBITMAP())
);
} // end of wxNotebook::SetPageImage
void wxNotebook::SetImageList (
wxImageList* pImageList
)
{
//
// Does not really do anything yet, but at least we need to
// update the base class.
//
wxNotebookBase::SetImageList(pImageList);
} // end of wxNotebook::SetImageList
// ----------------------------------------------------------------------------
// wxNotebook size settings
// ----------------------------------------------------------------------------
void wxNotebook::SetPageSize (
const wxSize& rSize
)
{
SetSize(rSize);
} // end of wxNotebook::SetPageSize
void wxNotebook::SetPadding (
const wxSize& WXUNUSED(rPadding)
)
{
//
// No padding in OS/2
//
} // end of wxNotebook::SetPadding
void wxNotebook::SetTabSize (
const wxSize& rSize
)
{
::WinSendMsg( GetHWND()
,BKM_SETDIMENSIONS
,MPFROM2SHORT( (USHORT)rSize.x
,(USHORT)rSize.y
)
,(MPARAM)BKA_MAJORTAB
);
} // end of wxNotebook::SetTabSize
// ----------------------------------------------------------------------------
// wxNotebook operations
// ----------------------------------------------------------------------------
//
// Remove one page from the notebook, without deleting
//
wxNotebookPage* wxNotebook::DoRemovePage ( size_t nPage )
{
wxNotebookPage* pPageRemoved = wxNotebookBase::DoRemovePage(nPage);
if (!pPageRemoved)
return NULL;
::WinSendMsg( GetHWND()
,BKM_DELETEPAGE
,MPFROMLONG((ULONG)m_alPageId[nPage])
,(MPARAM)BKA_TAB
);
if (m_pages.IsEmpty())
{
//
// No selection any more, the notebook becamse empty
//
m_nSelection = -1;
}
else // notebook still not empty
{
//
// Change the selected page if it was deleted or became invalid
//
int nSelNew;
if (m_nSelection == (int)GetPageCount())
{
//
// Last page deleted, make the new last page the new selection
//
nSelNew = m_nSelection - 1;
}
else if (nPage <= (size_t)m_nSelection)
{
//
// We must show another page, even if it has the same index
//
nSelNew = m_nSelection;
}
else // nothing changes for the currently selected page
{
nSelNew = -1;
//
// We still must refresh the current page: this needs to be done
// for some unknown reason if the tab control shows the up-down
// control (i.e. when there are too many pages) -- otherwise after
// deleting a page nothing at all is shown
//
m_pages[m_nSelection]->Refresh();
}
if (nSelNew != -1)
{
//
// m_nSelection must be always valid so reset it before calling
// SetSelection()
//
m_nSelection = -1;
SetSelection(nSelNew);
}
}
return pPageRemoved;
} // end of wxNotebook::DoRemovePage
//
// Remove all pages
//
bool wxNotebook::DeleteAllPages()
{
int nPageCount = GetPageCount();
int nPage;
for (nPage = 0; nPage < nPageCount; nPage++)
delete m_pages[nPage];
m_pages.Clear();
::WinSendMsg( GetHWND()
,BKM_DELETEPAGE
,(MPARAM)0
,(MPARAM)BKA_ALL
);
m_nSelection = -1;
return true;
} // end of wxNotebook::DeleteAllPages
//
// Add a page to the notebook
//
bool wxNotebook::AddPage (
wxNotebookPage* pPage
, const wxString& rStrText
, bool bSelect
, int nImageId
)
{
return InsertPage( GetPageCount()
,pPage
,rStrText
,bSelect
,nImageId
);
} // end of wxNotebook::AddPage
//
// Same as AddPage() but does it at given position
//
bool wxNotebook::InsertPage ( size_t nPage,
wxNotebookPage* pPage,
const wxString& rsStrText,
bool bSelect,
int nImageId )
{
ULONG ulApiPage;
wxASSERT( pPage != NULL );
wxCHECK( IS_VALID_PAGE(nPage) || nPage == GetPageCount(), FALSE );
//
// Under OS/2 we can only insert FIRST, LAST, NEXT or PREV. Requires
// two different calls to the API. Page 1 uses the BKA_FIRST. Subsequent
// pages use the previous page ID coupled with a BKA_NEXT call. Unlike
// Windows, OS/2 uses an internal Page ID to ID the pages.
//
// OS/2 also has a nice auto-size feature that automatically sizes the
// the attached window so we don't have to worry about the size of the
// window on the page.
//
if (nPage == 0)
{
ulApiPage = LONGFROMMR(::WinSendMsg( GetHWND()
,BKM_INSERTPAGE
,(MPARAM)0
,MPFROM2SHORT(BKA_AUTOPAGESIZE | BKA_MAJOR, BKA_FIRST)
));
if (ulApiPage == 0L)
{
ERRORID vError;
wxString sError;
vError = ::WinGetLastError(vHabmain);
sError = wxPMErrorToStr(vError);
return FALSE;
}
m_alPageId.Insert((long)ulApiPage, nPage);
}
else
{
ulApiPage = LONGFROMMR(::WinSendMsg( GetHWND()
,BKM_INSERTPAGE
,MPFROMLONG((ULONG)m_alPageId[nPage - 1])
,MPFROM2SHORT(BKA_AUTOPAGESIZE | BKA_MAJOR, BKA_NEXT)
));
if (ulApiPage == 0L)
{
ERRORID vError;
wxString sError;
vError = ::WinGetLastError(vHabmain);
sError = wxPMErrorToStr(vError);
return FALSE;
}
m_alPageId.Insert((long)ulApiPage, nPage);
}
//
// Associate a window handle with the page
//
if (pPage)
{
if (!::WinSendMsg( GetHWND()
,BKM_SETPAGEWINDOWHWND
,MPFROMLONG((ULONG)m_alPageId[nPage])
,MPFROMHWND(pPage->GetHWND())
))
return FALSE;
}
//
// If the inserted page is before the selected one, we must update the
// index of the selected page
//
if (nPage <= (size_t)m_nSelection)
{
//
// One extra page added
//
m_nSelection++;
}
if (pPage)
{
//
// Save the pointer to the page
//
m_pages.Insert( pPage
,nPage
);
}
//
// Now set TAB dimenstions
//
wxWindowDC vDC(this);
wxCoord nTextX;
wxCoord nTextY;
vDC.GetTextExtent(rsStrText, &nTextX, &nTextY);
nTextY *= 2;
nTextX = (wxCoord)(nTextX * 1.3);
if (nTextX > m_nTabSize)
{
m_nTabSize = nTextX;
::WinSendMsg( GetHWND()
,BKM_SETDIMENSIONS
,MPFROM2SHORT((USHORT)m_nTabSize, (USHORT)nTextY)
,(MPARAM)BKA_MAJORTAB
);
}
//
// Now set any TAB text
//
if (!rsStrText.empty())
{
if (!SetPageText( nPage
,rsStrText
))
return FALSE;
}
//
// Now set any TAB bitmap image
//
if (nImageId != -1)
{
if (!SetPageImage( nPage
,nImageId
))
return FALSE;
}
if (pPage)
{
//
// Don't show pages by default (we'll need to adjust their size first)
//
HWND hWnd = GetWinHwnd(pPage);
WinSetWindowULong( hWnd
,QWL_STYLE
,WinQueryWindowULong( hWnd
,QWL_STYLE
) & ~WS_VISIBLE
);
//
// This updates internal flag too - otherwise it will get out of sync
//
pPage->Show(FALSE);
}
//
// Some page should be selected: either this one or the first one if there is
// still no selection
//
int nSelNew = -1;
if (bSelect)
nSelNew = nPage;
else if ( m_nSelection == -1 )
nSelNew = 0;
if (nSelNew != -1)
SetSelection(nSelNew);
InvalidateBestSize();
return TRUE;
} // end of wxNotebook::InsertPage
// ----------------------------------------------------------------------------
// wxNotebook callbacks
// ----------------------------------------------------------------------------
void wxNotebook::OnSize(
wxSizeEvent& rEvent
)
{
rEvent.Skip();
} // end of wxNotebook::OnSize
void wxNotebook::OnSelChange (
wxNotebookEvent& rEvent
)
{
//
// Is it our tab control?
//
if (rEvent.GetEventObject() == this)
{
int nPageCount = GetPageCount();
int nSel;
ULONG ulOS2Sel = (ULONG)rEvent.GetOldSelection();
bool bFound = FALSE;
for (nSel = 0; nSel < nPageCount; nSel++)
{
if (ulOS2Sel == (ULONG)m_alPageId[nSel])
{
bFound = TRUE;
break;
}
}
if (!bFound)
return;
m_pages[nSel]->Show(FALSE);
ulOS2Sel = (ULONG)rEvent.GetSelection();
bFound = FALSE;
for (nSel = 0; nSel < nPageCount; nSel++)
{
if (ulOS2Sel == (ULONG)m_alPageId[nSel])
{
bFound = TRUE;
break;
}
}
if (!bFound)
return;
wxNotebookPage* pPage = m_pages[nSel];
pPage->Show(TRUE);
m_nSelection = nSel;
}
//
// We want to give others a chance to process this message as well
//
rEvent.Skip();
} // end of wxNotebook::OnSelChange
void wxNotebook::OnSetFocus (
wxFocusEvent& rEvent
)
{
//
// This function is only called when the focus is explicitly set (i.e. from
// the program) to the notebook - in this case we don't need the
// complicated OnNavigationKey() logic because the programmer knows better
// what [s]he wants
//
// set focus to the currently selected page if any
//
if (m_nSelection != -1)
m_pages[m_nSelection]->SetFocus();
rEvent.Skip();
} // end of wxNotebook::OnSetFocus
void wxNotebook::OnNavigationKey (
wxNavigationKeyEvent& rEvent
)
{
if (rEvent.IsWindowChange())
{
//
// Change pages
//
AdvanceSelection(rEvent.GetDirection());
}
else
{
//
// We get this event in 2 cases
//
// a) one of our pages might have generated it because the user TABbed
// out from it in which case we should propagate the event upwards and
// our parent will take care of setting the focus to prev/next sibling
//
// or
//
// b) the parent panel wants to give the focus to us so that we
// forward it to our selected page. We can't deal with this in
// OnSetFocus() because we don't know which direction the focus came
// from in this case and so can't choose between setting the focus to
// first or last panel child
//
wxWindow* pParent = GetParent();
if (rEvent.GetEventObject() == pParent)
{
//
// No, it doesn't come from child, case (b): forward to a page
//
if (m_nSelection != -1)
{
//
// So that the page knows that the event comes from it's parent
// and is being propagated downwards
//
rEvent.SetEventObject(this);
wxWindow* pPage = m_pages[m_nSelection];
if (!pPage->GetEventHandler()->ProcessEvent(rEvent))
{
pPage->SetFocus();
}
//else: page manages focus inside it itself
}
else
{
//
// We have no pages - still have to give focus to _something_
//
SetFocus();
}
}
else
{
//
// It comes from our child, case (a), pass to the parent
//
if (pParent)
{
rEvent.SetCurrentFocus(this);
pParent->GetEventHandler()->ProcessEvent(rEvent);
}
}
}
} // end of wxNotebook::OnNavigationKey
// ----------------------------------------------------------------------------
// wxNotebook base class virtuals
// ----------------------------------------------------------------------------
//
// Override these 2 functions to do nothing: everything is done in OnSize
//
void wxNotebook::SetConstraintSizes(
bool WXUNUSED(bRecurse)
)
{
//
// Don't set the sizes of the pages - their correct size is not yet known
//
wxControl::SetConstraintSizes(FALSE);
} // end of wxNotebook::SetConstraintSizes
bool wxNotebook::DoPhase (
int WXUNUSED(nPhase)
)
{
return TRUE;
} // end of wxNotebook::DoPhase
// ----------------------------------------------------------------------------
// wxNotebook Windows message handlers
// ----------------------------------------------------------------------------
bool wxNotebook::OS2OnScroll ( int nOrientation,
WXWORD wSBCode,
WXWORD wPos,
WXHWND wControl )
{
//
// Don't generate EVT_SCROLLWIN events for the WM_SCROLLs coming from the
// up-down control
//
if (wControl)
return FALSE;
return wxNotebookBase::OS2OnScroll( nOrientation
,wSBCode
,wPos
,wControl
);
} // end of wxNotebook::OS2OnScroll
#endif // wxUSE_NOTEBOOK
| 29.529138 | 115 | 0.457018 | Bloodknight |
caaaa6478ddc44585c0f3e4b04eecde8dc93bd25 | 9,485 | cc | C++ | src/utils/oatpp.cc | pnsuau/deepdetect | 655aa483c0f129a0a07c0da9be1f1ab8a465f1be | [
"Apache-2.0"
] | 1 | 2022-01-31T01:10:17.000Z | 2022-01-31T01:10:17.000Z | src/utils/oatpp.cc | maxpark/deepdetect | 1dfd51f59013533cb74d38f5f7fae804046d747f | [
"Apache-2.0"
] | null | null | null | src/utils/oatpp.cc | maxpark/deepdetect | 1dfd51f59013533cb74d38f5f7fae804046d747f | [
"Apache-2.0"
] | null | null | null | /**
* DeepDetect
* Copyright (c) 2021 Jolibrain SASU
* Author: Louis Jean <[email protected]>
*
* This file is part of deepdetect.
*
* deepdetect is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* deepdetect is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with deepdetect. If not, see <http://www.gnu.org/licenses/>.
*/
#include "oatpp.hpp"
#include "dto/ddtypes.hpp"
namespace dd
{
namespace oatpp_utils
{
std::shared_ptr<oatpp::parser::json::mapping::ObjectMapper>
createDDMapper()
{
std::shared_ptr<oatpp::parser::json::mapping::ObjectMapper> object_mapper
= oatpp::parser::json::mapping::ObjectMapper::createShared();
auto deser = object_mapper->getDeserializer();
deser->setDeserializerMethod(DTO::GpuIds::Class::CLASS_ID,
DTO::gpuIdsDeserialize);
deser->setDeserializerMethod(DTO::DTOVector<double>::Class::CLASS_ID,
DTO::vectorDeserialize<double>);
deser->setDeserializerMethod(DTO::DTOVector<uint8_t>::Class::CLASS_ID,
DTO::vectorDeserialize<uint8_t>);
deser->setDeserializerMethod(DTO::DTOVector<bool>::Class::CLASS_ID,
DTO::vectorDeserialize<bool>);
auto ser = object_mapper->getSerializer();
ser->setSerializerMethod(DTO::GpuIds::Class::CLASS_ID,
DTO::gpuIdsSerialize);
ser->setSerializerMethod(DTO::DTOVector<double>::Class::CLASS_ID,
DTO::vectorSerialize<double>);
ser->setSerializerMethod(DTO::DTOVector<uint8_t>::Class::CLASS_ID,
DTO::vectorSerialize<uint8_t>);
ser->setSerializerMethod(DTO::DTOVector<bool>::Class::CLASS_ID,
DTO::vectorSerialize<bool>);
return object_mapper;
}
oatpp::UnorderedFields<oatpp::Any>
dtoToUFields(const oatpp::Void &polymorph)
{
if (polymorph.valueType->classId.id
!= oatpp::data::mapping::type::__class::AbstractObject::CLASS_ID.id)
{
return nullptr;
}
auto dispatcher
= static_cast<const oatpp::data::mapping::type::__class::
AbstractObject::PolymorphicDispatcher *>(
polymorph.valueType->polymorphicDispatcher);
auto fields = dispatcher->getProperties()->getList();
auto object = static_cast<oatpp::BaseObject *>(polymorph.get());
oatpp::UnorderedFields<oatpp::Any> result({});
for (auto const &field : fields)
{
result->emplace(field->name, field->get(object));
}
return result;
}
void dtoToJDoc(const oatpp::Void &polymorph, JDoc &jdoc, bool ignore_null)
{
dtoToJVal(polymorph, jdoc, jdoc, ignore_null);
}
void dtoToJVal(const oatpp::Void &polymorph, JDoc &jdoc, JVal &jval,
bool ignore_null)
{
if (polymorph == nullptr)
{
return;
}
else if (polymorph.valueType == oatpp::Any::Class::getType())
{
auto anyHandle
= static_cast<oatpp::data::mapping::type::AnyHandle *>(
polymorph.get());
dtoToJVal(oatpp::Void(anyHandle->ptr, anyHandle->type), jdoc, jval,
ignore_null);
}
else if (polymorph.valueType == oatpp::String::Class::getType())
{
auto str = polymorph.staticCast<oatpp::String>();
jval.SetString(str->c_str(), jdoc.GetAllocator());
}
else if (polymorph.valueType == oatpp::Int32::Class::getType())
{
int32_t i = polymorph.staticCast<oatpp::Int32>();
jval.SetInt(i);
}
else if (polymorph.valueType == oatpp::UInt32::Class::getType())
{
uint32_t i = polymorph.staticCast<oatpp::UInt32>();
jval.SetUint(i);
}
else if (polymorph.valueType == oatpp::Int64::Class::getType())
{
int64_t i = polymorph.staticCast<oatpp::Int64>();
jval.SetInt64(i);
}
else if (polymorph.valueType == oatpp::UInt64::Class::getType())
{
uint64_t i = polymorph.staticCast<oatpp::UInt64>();
jval.SetUint64(i);
}
else if (polymorph.valueType == oatpp::Float32::Class::getType())
{
float f = polymorph.staticCast<oatpp::Float32>();
jval.SetFloat(f);
}
else if (polymorph.valueType == oatpp::Float64::Class::getType())
{
double f = polymorph.staticCast<oatpp::Float64>();
jval.SetDouble(f);
}
else if (polymorph.valueType == oatpp::Boolean::Class::getType())
{
bool b = polymorph.staticCast<oatpp::Boolean>();
jval = JVal(b);
}
else if (polymorph.valueType == DTO::DTOVector<double>::Class::getType())
{
auto vec = polymorph.staticCast<DTO::DTOVector<double>>();
jval = JVal(rapidjson::kArrayType);
for (size_t i = 0; i < vec->size(); ++i)
{
jval.PushBack(vec->at(i), jdoc.GetAllocator());
}
}
else if (polymorph.valueType
== DTO::DTOVector<uint8_t>::Class::getType())
{
auto vec = polymorph.staticCast<DTO::DTOVector<uint8_t>>();
jval = JVal(rapidjson::kArrayType);
for (size_t i = 0; i < vec->size(); ++i)
{
jval.PushBack(vec->at(i), jdoc.GetAllocator());
}
}
else if (polymorph.valueType == DTO::DTOVector<bool>::Class::getType())
{
auto vec = polymorph.staticCast<DTO::DTOVector<bool>>();
jval = JVal(rapidjson::kArrayType);
for (size_t i = 0; i < vec->size(); ++i)
{
jval.PushBack(JVal(bool(vec->at(i))), jdoc.GetAllocator());
}
}
else if (polymorph.valueType->classId.id
== oatpp::data::mapping::type::__class::AbstractVector::CLASS_ID
.id)
{
auto vec = polymorph.staticCast<oatpp::AbstractVector>();
jval = JVal(rapidjson::kArrayType);
for (size_t i = 0; i < vec->size(); ++i)
{
JVal elemJVal;
dtoToJVal(vec->at(i), jdoc, elemJVal, ignore_null);
jval.PushBack(elemJVal, jdoc.GetAllocator());
}
}
else if (polymorph.valueType->classId.id
== oatpp::data::mapping::type::__class::AbstractPairList::
CLASS_ID.id)
{
jval = JVal(rapidjson::kObjectType);
auto fields = polymorph.staticCast<oatpp::AbstractFields>();
for (auto const &field : *fields)
{
JVal childJVal;
dtoToJVal(field.second, jdoc, childJVal, ignore_null);
if (childJVal.IsNull() && ignore_null)
continue;
jval.AddMember(
JVal().SetString(field.first->c_str(), jdoc.GetAllocator()),
childJVal, jdoc.GetAllocator());
}
}
else if (polymorph.valueType->classId.id
== oatpp::data::mapping::type::__class::AbstractUnorderedMap::
CLASS_ID.id)
{
jval = JVal(rapidjson::kObjectType);
auto fields = polymorph.staticCast<oatpp::AbstractUnorderedFields>();
for (auto const &field : *fields)
{
JVal childJVal;
dtoToJVal(field.second, jdoc, childJVal, ignore_null);
if (childJVal.IsNull() && ignore_null)
continue;
jval.AddMember(
JVal().SetString(field.first->c_str(), jdoc.GetAllocator()),
childJVal, jdoc.GetAllocator());
}
}
else if (polymorph.valueType->classId.id
== oatpp::data::mapping::type::__class::AbstractObject::CLASS_ID
.id)
{
jval = JVal(rapidjson::kObjectType);
auto dispatcher
= static_cast<const oatpp::data::mapping::type::__class::
AbstractObject::PolymorphicDispatcher *>(
polymorph.valueType->polymorphicDispatcher);
auto fields = dispatcher->getProperties()->getList();
auto object = static_cast<oatpp::BaseObject *>(polymorph.get());
for (auto const &field : fields)
{
auto val = field->get(object);
JVal childJVal;
dtoToJVal(val, jdoc, childJVal, ignore_null);
if (childJVal.IsNull() && ignore_null)
continue;
jval.AddMember(
JVal().SetString(field->name, jdoc.GetAllocator()),
childJVal, jdoc.GetAllocator());
}
}
else
{
throw std::runtime_error("dtoToJVal: Type not recognised");
}
}
}
}
| 37.196078 | 79 | 0.557828 | pnsuau |
caaaa7b9d42aac4ffcb53377a17f3c34c011403a | 198 | cpp | C++ | src/Core/p2/iMath.cpp | stravant/bfbbdecomp | 2126be355a6bb8171b850f829c1f2731c8b5de08 | [
"OLDAP-2.7"
] | 1 | 2021-01-05T11:28:55.000Z | 2021-01-05T11:28:55.000Z | src/Core/p2/iMath.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | null | null | null | src/Core/p2/iMath.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | 1 | 2022-03-30T15:15:08.000Z | 2022-03-30T15:15:08.000Z | #include "iMath.h"
#include <cmath>
float32 isin(float32 x)
{
return std::sinf(x);
}
float32 icos(float32 x)
{
return std::cosf(x);
}
float32 itan(float32 x)
{
return std::tanf(x);
} | 11 | 24 | 0.626263 | stravant |
caab829584acfdf7146919f1516fa9f31e7fe843 | 4,057 | cpp | C++ | test/MeLikeyCode-QtGameEngine-2a3d47c/example projects/example3/main.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 16 | 2019-05-23T08:10:39.000Z | 2021-12-21T11:20:37.000Z | test/MeLikeyCode-QtGameEngine-2a3d47c/example projects/example3/main.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | null | null | null | test/MeLikeyCode-QtGameEngine-2a3d47c/example projects/example3/main.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 2 | 2019-05-23T18:37:43.000Z | 2021-08-24T21:29:40.000Z | // Moving/rotating entity
// This example picks up where example 2 left of. I took all of the code that created the entity and its graphics and
// put it into a function called getMinitaurEntity(). We will now take this entity and make it move in response
// to the keyboard keys being pressed. We will also make the entity always face the mouse position.
//
// Have fun with it! I Hope you enjoy this example!
// -Abdullah
#include <QApplication>
#include "qge/MapGrid.h"
#include "qge/Map.h"
#include "qge/Game.h"
#include "qge/Entity.h"
#include "qge/Utilities.h"
#include "qge/EntitySprite.h"
#include "qge/ECKeyboardMoverPerspective.h"
#include "qge/ECMouseFacer.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// create map
qge::Map* map = new qge::Map();
// create map grid
qge::MapGrid* mapGrid = new qge::MapGrid(1,1);
mapGrid->setMapAtPos(map,0,0); // add map to map grid
// create game
qge::Game* game = new qge::Game(mapGrid,0,0);
// create minitaur looking entity (we did this in example 2, I just moved all that code to a function called qge::getMinitaurEntity())
qge::Entity* entity = qge::getMinitaurEntity();
// add the entity into the map at position (300,300)
entity->setPos(QPointF(300,300));
entity->setFacingAngle(0);
map->addEntity(entity);
// play the stand animation of the entity
entity->sprite()->play("stand" ,-1 ,10 ,0);
// == NEW STUFF (we've done all of the above code in previous tutorials) ==
// Let's make the entity move when the arrow keys are pressed.
// The way you usually add behaviors like this to an entity is by attaching "EntityControllers"
// to the entity. There are lots of built in EntityControllers that add lots of different
// types of behaviors to entities. It might be beneficial to look up all (or at least some) of the
// built in EntityControllers.
// All entity controllers inherit from the class EntityController.
// You can use the type hierarchy feature of Qt Creator or inhertence diagram of the doxygen
// generated documentation to find all the classes that inherit from EntityController.
// Lucky for you, there is a pre built EntityController called ECKeyboardMoverPerspective,
// which moves its controlled entity in response to the arrow keys! All we gotta do is attach
// the controller.
qge::ECKeyboardMoverPerspective* keyboardMoverController = new qge::ECKeyboardMoverPerspective(entity);
// That is all! When you construct EntityControllers, you pass the controlled entity into the constructor.
// The controller then starts doing its thaaaaang. Run the game right now and pressed the arrow keys and
// notice that when you press up, the entity moves forward, when you press down it moves backward, etc.
// Look at how much work the entity controller did for you! It listens to keyboard events and in response
// it moves the entity in the correct direction (relative to its facing angle), it even asks the entity
// to play a "walk" animation!
// Now, we want to make the entity always face the mouse. You guessed it, a built in entity controller
// exists for that!
qge::ECMouseFacer* mouseFacerController = new qge::ECMouseFacer(entity);
// Run the game again. Move around the map.
// That is all for this tutorial, hope you found it informative and fun!
// BONUS: Hello folks, I'm back! I have a few things you can experiment with to earn some bonus pats on the back!
// The ECKeyboardMoverPerspective* moves the entity relative to its current facing direction. So when the entity is
// facing angle 20 degrees and you press up, it will move forward at that angle. The ECKeyboardMover4Directional
// controller moves the entity relative to the screen, not its facing direction.
// BONUS OBJECTIVE: Try out ECKeyboardMover4Directional and ECKeyboardMover8Directional (also skim their documentation).
game->launch(); // launch game
return a.exec();
}
| 43.623656 | 138 | 0.721962 | JamesMBallard |
caad201851e378fc0a67abb4f799ad22289e2fa1 | 205 | hpp | C++ | Cfg.hpp | QuariumStackHS/QSR-Tool | f7fb94ebbc18892b536e4e4881a53faa4d9c1342 | [
"Unlicense"
] | null | null | null | Cfg.hpp | QuariumStackHS/QSR-Tool | f7fb94ebbc18892b536e4e4881a53faa4d9c1342 | [
"Unlicense"
] | null | null | null | Cfg.hpp | QuariumStackHS/QSR-Tool | f7fb94ebbc18892b536e4e4881a53faa4d9c1342 | [
"Unlicense"
] | null | null | null | #include "QSR/includes/config.hpp"
Configurator::Configurator()
{
this->buildtype = EXE;
this->CPPLang = CPP17;
this->ProgrameName = "QSR";
this->Termwidth=75;
this->debug=1;
}
//#endif | 20.5 | 34 | 0.643902 | QuariumStackHS |
caad6188476ecb6f8cdfce1dbd2930b28063ca5e | 180 | cpp | C++ | SystemResource/Source/Font/FNT/FNTPage.cpp | BitPaw/BitFireEngine | 2c02a4eae19276bf60ac925e4393966cec605112 | [
"MIT"
] | 5 | 2021-10-19T18:30:43.000Z | 2022-03-19T22:02:02.000Z | SystemResource/Source/Font/FNT/FNTPage.cpp | BitPaw/BitFireEngine | 2c02a4eae19276bf60ac925e4393966cec605112 | [
"MIT"
] | 12 | 2022-03-09T13:40:21.000Z | 2022-03-31T12:47:48.000Z | SystemResource/Source/Font/FNT/FNTPage.cpp | BitPaw/BitFireEngine | 2c02a4eae19276bf60ac925e4393966cec605112 | [
"MIT"
] | null | null | null | #include "FNTPage.h"
BF::FNTPage::FNTPage()
{
PageID = -1;
PageFileName[0] = 0;
CharacteListSize = 0;
CharacteList = 0;
}
BF::FNTPage::~FNTPage()
{
delete[] CharacteList;
}
| 12 | 23 | 0.644444 | BitPaw |
caaec3aba01983cb001bc21d6bf28d79de7152ce | 1,210 | cpp | C++ | waterbox/bsnescore/bsnes/sfc/smp/serialization.cpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 1,414 | 2015-06-28T09:57:51.000Z | 2021-10-14T03:51:10.000Z | waterbox/bsnescore/bsnes/sfc/smp/serialization.cpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 2,369 | 2015-06-25T01:45:44.000Z | 2021-10-16T08:44:18.000Z | waterbox/bsnescore/bsnes/sfc/smp/serialization.cpp | Fortranm/BizHawk | 8cb0ffb6f8964cc339bbe1784838918fb0aa7e27 | [
"MIT"
] | 430 | 2015-06-29T04:28:58.000Z | 2021-10-05T18:24:17.000Z | auto SMP::serialize(serializer& s) -> void {
SPC700::serialize(s);
Thread::serialize(s);
s.integer(io.clockCounter);
s.integer(io.dspCounter);
s.integer(io.apu0);
s.integer(io.apu1);
s.integer(io.apu2);
s.integer(io.apu3);
s.integer(io.timersDisable);
s.integer(io.ramWritable);
s.integer(io.ramDisable);
s.integer(io.timersEnable);
s.integer(io.externalWaitStates);
s.integer(io.internalWaitStates);
s.integer(io.iplromEnable);
s.integer(io.dspAddr);
s.integer(io.cpu0);
s.integer(io.cpu1);
s.integer(io.cpu2);
s.integer(io.cpu3);
s.integer(io.aux4);
s.integer(io.aux5);
s.integer(timer0.stage0);
s.integer(timer0.stage1);
s.integer(timer0.stage2);
s.integer(timer0.stage3);
s.boolean(timer0.line);
s.boolean(timer0.enable);
s.integer(timer0.target);
s.integer(timer1.stage0);
s.integer(timer1.stage1);
s.integer(timer1.stage2);
s.integer(timer1.stage3);
s.boolean(timer1.line);
s.boolean(timer1.enable);
s.integer(timer1.target);
s.integer(timer2.stage0);
s.integer(timer2.stage1);
s.integer(timer2.stage2);
s.integer(timer2.stage3);
s.boolean(timer2.line);
s.boolean(timer2.enable);
s.integer(timer2.target);
}
| 21.607143 | 44 | 0.694215 | Fortranm |
cab74d3a0cfad5f110c0c5cd812810389e7fbb77 | 6,411 | cpp | C++ | src/blinkit/blink/renderer/core/animation/SVGLengthInterpolationType.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 13 | 2020-04-21T13:14:00.000Z | 2021-11-13T14:55:12.000Z | src/blinkit/blink/renderer/core/animation/SVGLengthInterpolationType.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | null | null | null | src/blinkit/blink/renderer/core/animation/SVGLengthInterpolationType.cpp | titilima/blink | 2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad | [
"MIT"
] | 4 | 2020-04-21T13:15:43.000Z | 2021-11-13T14:55:00.000Z | // Copyright 2015 The Chromium 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 "core/animation/SVGLengthInterpolationType.h"
#include "core/animation/InterpolationEnvironment.h"
#include "core/animation/StringKeyframe.h"
#include "core/css/CSSHelper.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGLength.h"
#include "core/svg/SVGLengthContext.h"
namespace blink {
namespace {
enum LengthInterpolatedUnit {
LengthInterpolatedNumber,
LengthInterpolatedPercentage,
LengthInterpolatedEMS,
LengthInterpolatedEXS,
LengthInterpolatedREMS,
LengthInterpolatedCHS,
};
static const CSSPrimitiveValue::UnitType unitTypes[] = {
CSSPrimitiveValue::UnitType::UserUnits,
CSSPrimitiveValue::UnitType::Percentage,
CSSPrimitiveValue::UnitType::Ems,
CSSPrimitiveValue::UnitType::Exs,
CSSPrimitiveValue::UnitType::Rems,
CSSPrimitiveValue::UnitType::Chs
};
const size_t numLengthInterpolatedUnits = WTF_ARRAY_LENGTH(unitTypes);
LengthInterpolatedUnit convertToInterpolatedUnit(CSSPrimitiveValue::UnitType unitType, double& value)
{
switch (unitType) {
case CSSPrimitiveValue::UnitType::Unknown:
default:
ASSERT_NOT_REACHED();
case CSSPrimitiveValue::UnitType::Pixels:
case CSSPrimitiveValue::UnitType::Number:
case CSSPrimitiveValue::UnitType::UserUnits:
return LengthInterpolatedNumber;
case CSSPrimitiveValue::UnitType::Percentage:
return LengthInterpolatedPercentage;
case CSSPrimitiveValue::UnitType::Ems:
return LengthInterpolatedEMS;
case CSSPrimitiveValue::UnitType::Exs:
return LengthInterpolatedEXS;
case CSSPrimitiveValue::UnitType::Centimeters:
value *= cssPixelsPerCentimeter;
return LengthInterpolatedNumber;
case CSSPrimitiveValue::UnitType::Millimeters:
value *= cssPixelsPerMillimeter;
return LengthInterpolatedNumber;
case CSSPrimitiveValue::UnitType::Inches:
value *= cssPixelsPerInch;
return LengthInterpolatedNumber;
case CSSPrimitiveValue::UnitType::Points:
value *= cssPixelsPerPoint;
return LengthInterpolatedNumber;
case CSSPrimitiveValue::UnitType::Picas:
value *= cssPixelsPerPica;
return LengthInterpolatedNumber;
case CSSPrimitiveValue::UnitType::Rems:
return LengthInterpolatedREMS;
case CSSPrimitiveValue::UnitType::Chs:
return LengthInterpolatedCHS;
}
}
} // namespace
PassOwnPtr<InterpolableValue> SVGLengthInterpolationType::neutralInterpolableValue()
{
OwnPtr<InterpolableList> listOfValues = InterpolableList::create(numLengthInterpolatedUnits);
for (size_t i = 0; i < numLengthInterpolatedUnits; ++i)
listOfValues->set(i, InterpolableNumber::create(0));
return listOfValues.release();
}
InterpolationComponent SVGLengthInterpolationType::convertSVGLength(const SVGLength& length)
{
double value = length.valueInSpecifiedUnits();
LengthInterpolatedUnit unitType = convertToInterpolatedUnit(length.typeWithCalcResolved(), value);
double values[numLengthInterpolatedUnits] = { };
values[unitType] = value;
OwnPtr<InterpolableList> listOfValues = InterpolableList::create(numLengthInterpolatedUnits);
for (size_t i = 0; i < numLengthInterpolatedUnits; ++i)
listOfValues->set(i, InterpolableNumber::create(values[i]));
return InterpolationComponent(listOfValues.release());
}
PassRefPtrWillBeRawPtr<SVGLength> SVGLengthInterpolationType::resolveInterpolableSVGLength(const InterpolableValue& interpolableValue, const SVGLengthContext& lengthContext, SVGLengthMode unitMode, bool negativeValuesForbidden)
{
const InterpolableList& listOfValues = toInterpolableList(interpolableValue);
double value = 0;
CSSPrimitiveValue::UnitType unitType = CSSPrimitiveValue::UnitType::UserUnits;
unsigned unitTypeCount = 0;
// We optimise for the common case where only one unit type is involved.
for (size_t i = 0; i < numLengthInterpolatedUnits; i++) {
double entry = toInterpolableNumber(listOfValues.get(i))->value();
if (!entry)
continue;
unitTypeCount++;
if (unitTypeCount > 1)
break;
value = entry;
unitType = unitTypes[i];
}
if (unitTypeCount > 1) {
value = 0;
unitType = CSSPrimitiveValue::UnitType::UserUnits;
// SVGLength does not support calc expressions, so we convert to canonical units.
for (size_t i = 0; i < numLengthInterpolatedUnits; i++) {
double entry = toInterpolableNumber(listOfValues.get(i))->value();
if (entry)
value += lengthContext.convertValueToUserUnits(entry, unitMode, unitTypes[i]);
}
}
if (negativeValuesForbidden && value < 0)
value = 0;
RefPtrWillBeRawPtr<SVGLength> result = SVGLength::create(unitMode); // defaults to the length 0
result->newValueSpecifiedUnits(unitType, value);
return result.release();
}
PassOwnPtr<InterpolationValue> SVGLengthInterpolationType::maybeConvertNeutral(const UnderlyingValue&, ConversionCheckers&) const
{
return InterpolationValue::create(*this, neutralInterpolableValue());
}
PassOwnPtr<InterpolationValue> SVGLengthInterpolationType::maybeConvertSVGValue(const SVGPropertyBase& svgValue) const
{
if (svgValue.type() != AnimatedLength)
return nullptr;
const SVGLength& length = toSVGLength(svgValue);
InterpolationComponent component = convertSVGLength(length);
return InterpolationValue::create(*this, component);
}
PassRefPtrWillBeRawPtr<SVGPropertyBase> SVGLengthInterpolationType::appliedSVGValue(const InterpolableValue& interpolableValue, const NonInterpolableValue*) const
{
ASSERT_NOT_REACHED();
// This function is no longer called, because apply has been overridden.
return nullptr;
}
void SVGLengthInterpolationType::apply(const InterpolableValue& interpolableValue, const NonInterpolableValue* nonInterpolableValue, InterpolationEnvironment& environment) const
{
SVGElement& element = environment.svgElement();
SVGLengthContext lengthContext(&element);
element.setWebAnimatedAttribute(attribute(), resolveInterpolableSVGLength(interpolableValue, lengthContext, m_unitMode, m_negativeValuesForbidden));
}
} // namespace blink
| 37.273256 | 227 | 0.746373 | titilima |
cab9a98baaa96e753bde8c393a76acd970bbc359 | 809 | hpp | C++ | cslibs_math/include/cslibs_math/serialization/vector.hpp | lisilin013/cslibs_math | b1a1bc5bf5a85b2d7467911521806609ed3c16ee | [
"BSD-3-Clause"
] | null | null | null | cslibs_math/include/cslibs_math/serialization/vector.hpp | lisilin013/cslibs_math | b1a1bc5bf5a85b2d7467911521806609ed3c16ee | [
"BSD-3-Clause"
] | null | null | null | cslibs_math/include/cslibs_math/serialization/vector.hpp | lisilin013/cslibs_math | b1a1bc5bf5a85b2d7467911521806609ed3c16ee | [
"BSD-3-Clause"
] | null | null | null | #ifndef CSLIBS_MATH_SERIALIZATION_VECTOR_HPP
#define CSLIBS_MATH_SERIALIZATION_VECTOR_HPP
#include <cslibs_math/linear/vector.hpp>
#include <yaml-cpp/yaml.h>
namespace YAML {
template<typename T, std::size_t Dim>
struct convert<cslibs_math::linear::Vector<T, Dim>>
{
static Node encode(const cslibs_math::linear::Vector<T,Dim> &rhs)
{
Node n;
for(std::size_t i = 0 ; i < Dim ; ++i) {
n.push_back(rhs(i));
}
return n;
}
static bool decode(const Node& n, cslibs_math::linear::Vector<T,Dim> &rhs)
{
if(!n.IsSequence() || n.size() != Dim)
return false;
for(std::size_t i = 0 ; i < Dim ; ++i) {
rhs(i) = n[i].as<T>();
}
return true;
}
};
}
#endif // CSLIBS_MATH_SERIALIZATION_VECTOR_HPP
| 25.28125 | 78 | 0.594561 | lisilin013 |
cabc6d0faedaa5d2437c8bd6213865db7d567a1e | 8,960 | cpp | C++ | azClientFuncs.cpp | jflynn129/M18QxAzureIoT | f8a3a0ef4d16ddeca6235ab9174273ad0757e392 | [
"MIT"
] | null | null | null | azClientFuncs.cpp | jflynn129/M18QxAzureIoT | f8a3a0ef4d16ddeca6235ab9174273ad0757e392 | [
"MIT"
] | null | null | null | azClientFuncs.cpp | jflynn129/M18QxAzureIoT | f8a3a0ef4d16ddeca6235ab9174273ad0757e392 | [
"MIT"
] | 1 | 2021-01-22T22:42:16.000Z | 2021-01-22T22:42:16.000Z | /**
* copyright (c) 2018, James Flynn
* SPDX-License-Identifier: MIT
*/
#include <stdlib.h>
#include "iothub_client_core_common.h"
#include "iothub_client_ll.h"
#include "azure_c_shared_utility/platform.h"
#include "azure_c_shared_utility/agenttime.h"
#include "jsondecoder.h"
#include "led.hpp"
#include "lis2dw12.hpp"
#include "adc.hpp"
#include "barometer.hpp"
#include "hts221.hpp"
#include "gps.hpp"
#include "azure_certs.h"
#include "azIoTClient.h"
#ifdef USE_MQTT
#include "iothubtransportmqtt.h"
#else
#include "iothubtransporthttp.h"
#endif
//The following connection string must be updated for the individual users Azure IoT Device
//static const char* connectionString = "HostName=XXXX;DeviceId=xxxx;SharedAccessKey=xxxx";
static const char* connectionString = "HostName=M18QxIoTClient.azure-devices.net;DeviceId=SK2-IMEI353087080010952;SharedAccessKey=3vyDD6lO1VRCfi1bCZ58QsTUsViEZ3Q4JBErtvQzBcA=";
extern void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char* buffer, size_t size);
extern void prty_json(char* src, int srclen);
char* send_sensrpt(void);
char* send_devrpt(void);
char* send_locrpt(void);
char* send_temprpt(void);
char* send_posrpt(void);
char* send_envrpt(void);
IOTHUBMESSAGE_DISPOSITION_RESULT receiveMessageCallback( IOTHUB_MESSAGE_HANDLE message, void *userContextCallback);
void sendMessage(IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle, char* buffer, size_t size)
{
IOTHUB_MESSAGE_HANDLE messageHandle = IoTHubMessage_CreateFromByteArray((const unsigned char*)buffer, size);
if (messageHandle == NULL) {
printf("unable to create a new IoTHubMessage\r\n");
return;
}
if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, messageHandle, NULL, NULL) != IOTHUB_CLIENT_OK)
printf("FAILED to send!\n");
else
printf("OK\n");
IoTHubMessage_Destroy(messageHandle);
}
IOTHUB_CLIENT_LL_HANDLE setup_azure(void)
{
/* Setup IoTHub client configuration */
#ifndef USE_MQTT
IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, HTTP_Protocol);
#else
IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol);
#endif
if (iotHubClientHandle == NULL) {
printf("Failed on IoTHubClient_Create\r\n");
return NULL;
}
// add the certificate information
if (IoTHubClient_LL_SetOption(iotHubClientHandle, "TrustedCerts", certificates) != IOTHUB_CLIENT_OK) {
IoTHubClient_LL_Destroy(iotHubClientHandle);
printf("failure to set option \"TrustedCerts\"\r\n");
return NULL;
}
// add the certificate information
#ifndef USE_MQTT
// polls will happen effectively at ~10 seconds. The default value of minimumPollingTime is 25 minutes.
// For more information, see:
// https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
unsigned int minimumPollingTime = 9;
if (IoTHubClient_LL_SetOption(iotHubClientHandle, "MinimumPollingTime", &minimumPollingTime) != IOTHUB_CLIENT_OK) {
IoTHubClient_LL_Destroy(iotHubClientHandle);
printf("failure to set option \"MinimumPollingTime\"\r\n");
return NULL;
}
#endif
// set C2D and device method callback
IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, receiveMessageCallback, NULL);
return iotHubClientHandle;
}
//------------------------------------------------------------------
#define SENS_REPORT "{" \
"\"ObjectName\":\"sensor-report\"," \
"\"SOM\":[\"ADC\",\"LIS2DW12-TEMP\",\"LIS2DW12-POS\",\"GPS\"]," \
"\"CLICK\":["
char* send_sensrpt(void)
{
int len = sizeof(SENS_REPORT)+30;
char* ptr = (char*)malloc(len);
snprintf(ptr,len,SENS_REPORT);
if( click_modules & (BAROMETER_CLICK|HTS221_CLICK) ) {
if (click_modules & BAROMETER_CLICK )
strcat(ptr,"\"BAROMETER\"");
if (click_modules & HTS221_CLICK )
strcat(ptr,",\"TEMP&HUMID\"");
}
else
strcat(ptr,"\"NONE\"");
strcat(ptr,"]}");
return ptr;
}
//------------------------------------------------------------------
#define DEV_REPORT "{" \
"\"ObjectName\":\"Device-Info\"," \
"\"ReportingDevice\":\"M18QWG/M18Q2FG-1\"," \
"\"DeviceICCID\":\"%s\"," \
"\"DeviceIMEI\":\"%s\"" \
"}"
char* send_devrpt(void)
{
int len = sizeof(DEV_REPORT)+50;
char* ptr = (char*)malloc(len);
snprintf(ptr,len,DEV_REPORT, iccid, imei);
return ptr;
}
//------------------------------------------------------------------
#define LOC_REPORT "{" \
"\"ObjectName\":\"location-report\"," \
"\"last GPS fix\":\"%s\"," \
"\"lat\":%.02f," \
"\"long\":%.02f" \
"}"
char* send_locrpt(void)
{
gpsstatus *loc;
char temp[25];
struct tm *ptm;
int len = sizeof(LOC_REPORT)+35;
char* ptr = (char*)malloc(len);
loc = gps.getLocation();
ptm = gmtime(&loc->last_good);
strftime(temp,25,"%a %F %X",ptm);
snprintf(ptr,len, LOC_REPORT, temp, loc->last_pos.lat, loc->last_pos.lng);
return ptr;
}
//------------------------------------------------------------------
#define TEMP_REPORT "{" \
"\"ObjectName\":\"temp-report\"," \
"\"Temperature\":%.02f" \
"}"
char* send_temprpt(void)
{
int len = sizeof(TEMP_REPORT)+10;
char* ptr = (char*)malloc(len);
snprintf(ptr,len,TEMP_REPORT, mems.lis2dw12_getTemp());
return ptr;
}
//------------------------------------------------------------------
#define POS_REPORT "{" \
"\"ObjectName\":\"board-position\"," \
"\"Board Moved\":%d," \
"\"Board Position\":%d" \
"}"
char* send_posrpt(void)
{
int len = sizeof(POS_REPORT)+10;
char* ptr = (char*)malloc(len);
snprintf(ptr,len,POS_REPORT, mems.movement_ocured(), mems.lis2dw12_getPosition());
return ptr;
}
//------------------------------------------------------------------
#define ENV_REPORT "{" \
"\"ObjectName\":\"enviroment-report\"," \
"\"Barometer\":%.02f," \
"\"Humidity\":%.01f" \
"}"
char* send_envrpt(void)
{
int len = sizeof(ENV_REPORT)+15;
char* ptr = (char*)malloc(len);
snprintf(ptr,len,ENV_REPORT,
(click_modules & BAROMETER_CLICK )? barom.get_pressure():0,
(click_modules & HTS221_CLICK )? humid.readHumidity():0 );
return ptr;
}
IOTHUBMESSAGE_DISPOSITION_RESULT receiveMessageCallback(
IOTHUB_MESSAGE_HANDLE message,
void *userContextCallback)
{
const unsigned char *buffer = NULL;
char* pmsg = NULL;
size_t size = 0;
if (IOTHUB_MESSAGE_OK != IoTHubMessage_GetByteArray(message, &buffer, &size))
return IOTHUBMESSAGE_ABANDONED;
// message needs to be converted to zero terminated string
char * temp = (char *)malloc(size + 1);
if (temp == NULL)
return IOTHUBMESSAGE_ABANDONED;
strncpy(temp, (char*)buffer, size);
temp[size] = '\0';
if( !strcmp(temp, "REPORT-SENSORS") )
pmsg = send_sensrpt();
else if( !strcmp(temp, "GET-DEV-INFO") )
pmsg = send_devrpt();
else if( !strcmp(temp, "GET-LOCATION") )
pmsg = send_locrpt();
else if( !strcmp(temp, "GET-TEMP") )
pmsg = send_temprpt();
else if( !strcmp(temp, "GET-POS") )
pmsg = send_posrpt();
else if( !strcmp(temp, "GET-ENV") )
pmsg = send_envrpt();
else if( !strcmp(temp, "LED-ON-MAGENTA") ){
status_led.action(Led::LED_ON,Led::MAGENTA);
if( verbose ) printf("Turning LED on to Magenta.\n");
}
else if( !strcmp(temp, "LED-BLINK-MAGENTA") ){
status_led.action(Led::LED_BLINK,Led::MAGENTA);
if( verbose ) printf("Setting LED to blink Magenta\n");
}
else if( !strcmp(temp, "LED-OFF") ){
status_led.action(Led::LED_OFF,Led::BLACK);
if( verbose ) printf("Turning LED off.\n");
}
else if( strstr(temp, "SET-PERIOD") ) {
sscanf(temp,"SET-PERIOD %d",&report_period);
int i=report_period % REPORT_PERIOD_RESOLUTION;
if( i != 0 )
report_period += (REPORT_PERIOD_RESOLUTION-i);
if( verbose ) printf("Report Period remotely set to %d.\n",report_period);
}
else
printf("Received message: '%s'\r\n", temp);
if( pmsg != NULL ) {
printf("(----)Azure IoT Hub requested response sent - ");
sendMessage(IoTHub_client_ll_handle, pmsg, strlen(pmsg));
if( verbose )
prty_json(pmsg,strlen(pmsg));
free(pmsg);
}
free(temp);
return IOTHUBMESSAGE_ACCEPTED;
}
| 31.328671 | 176 | 0.598549 | jflynn129 |
cabf1c68839bdff822b88f1cd76fc6a87b883e94 | 4,478 | cpp | C++ | src/TrackTile.cpp | VictorieeMan/PianoGame_Compilable | da441618227c84a46eed9fed723ffded5f200dea | [
"MIT"
] | 54 | 2016-05-25T07:39:10.000Z | 2022-03-06T01:11:00.000Z | src/TrackTile.cpp | VictorieeMan/PianoGame_Compilable | da441618227c84a46eed9fed723ffded5f200dea | [
"MIT"
] | null | null | null | src/TrackTile.cpp | VictorieeMan/PianoGame_Compilable | da441618227c84a46eed9fed723ffded5f200dea | [
"MIT"
] | 18 | 2018-03-09T12:50:19.000Z | 2022-03-22T06:11:19.000Z |
// Copyright (c)2007 Nicholas Piegdon
// See license.txt for license information
#include "TrackTile.h"
#include "libmidi/Midi.h"
#include "Renderer.h"
#include "Tga.h"
const static int GraphicWidth = 36;
const static int GraphicHeight = 36;
TrackTile::TrackTile(int x, int y, size_t track_id, Track::TrackColor color, Track::Mode mode)
: m_x(x), m_y(y), m_track_id(track_id), m_color(color), m_mode(mode), m_preview_on(false)
{
// Initialize the size and position of each button
whole_tile = ButtonState(0, 0, TrackTileWidth, TrackTileHeight);
button_mode_left = ButtonState( 2, 68, GraphicWidth, GraphicHeight);
button_mode_right = ButtonState(192, 68, GraphicWidth, GraphicHeight);
button_color = ButtonState(228, 68, GraphicWidth, GraphicHeight);
button_preview = ButtonState(264, 68, GraphicWidth, GraphicHeight);
}
void TrackTile::Update(const MouseInfo &translated_mouse)
{
// Update the mouse state of each button
whole_tile.Update(translated_mouse);
button_preview.Update(translated_mouse);
button_color.Update(translated_mouse);
button_mode_left.Update(translated_mouse);
button_mode_right.Update(translated_mouse);
if (button_mode_left.hit)
{
int mode = static_cast<int>(m_mode) - 1;
if (mode < 0) mode = 3;
m_mode = static_cast<Track::Mode>(mode);
}
if (button_mode_right.hit)
{
int mode = static_cast<int>(m_mode) + 1;
if (mode > 3) mode = 0;
m_mode = static_cast<Track::Mode>(mode);
}
if (button_preview.hit)
{
m_preview_on = !m_preview_on;
}
if (button_color.hit && m_mode != Track::ModeNotPlayed && m_mode != Track::ModePlayedButHidden)
{
int color = static_cast<int>(m_color) + 1;
if (color >= Track::UserSelectableColorCount) color = 0;
m_color = static_cast<Track::TrackColor>(color);
}
}
int TrackTile::LookupGraphic(TrackTileGraphic graphic, bool button_hovering) const
{
// There are three sets of graphics
// set 0: window lit, hovering
// set 1: window lit, not-hovering
// set 2: window unlit, (implied not-hovering)
int graphic_set = 2;
if (whole_tile.hovering) graphic_set--;
if (button_hovering) graphic_set--;
const int set_offset = GraphicWidth * Graphic_COUNT;
const int graphic_offset = GraphicWidth * graphic;
return (set_offset * graphic_set) + graphic_offset;
}
void TrackTile::Draw(Renderer &renderer, const Midi *midi, Tga *buttons, Tga *box) const
{
const MidiTrack &track = midi->Tracks()[m_track_id];
bool gray_out_buttons = false;
Color light = Track::ColorNoteWhite[m_color];
Color medium = Track::ColorNoteBlack[m_color];
if (m_mode == Track::ModePlayedButHidden || m_mode == Track::ModeNotPlayed)
{
gray_out_buttons = true;
light = Renderer::ToColor(0xB0,0xB0,0xB0);
medium = Renderer::ToColor(0x70,0x70,0x70);
}
Color color_tile = medium;
Color color_tile_hovered = light;
renderer.SetOffset(m_x, m_y);
renderer.SetColor(whole_tile.hovering ? color_tile_hovered : color_tile);
renderer.DrawTga(box, -10, -6);
renderer.SetColor(White);
// Write song info to the tile
TextWriter instrument(95, 12, renderer, false, 14);
instrument << track.InstrumentName();
TextWriter note_count(95, 33, renderer, false, 14);
note_count << static_cast<const unsigned int>(track.Notes().size());
int color_offset = GraphicHeight * static_cast<int>(m_color);
if (gray_out_buttons) color_offset = GraphicHeight * Track::UserSelectableColorCount;
renderer.DrawTga(buttons, BUTTON_RECT(button_mode_left), LookupGraphic(GraphicLeftArrow, button_mode_left.hovering), color_offset);
renderer.DrawTga(buttons, BUTTON_RECT(button_mode_right), LookupGraphic(GraphicRightArrow, button_mode_right.hovering), color_offset);
renderer.DrawTga(buttons, BUTTON_RECT(button_color), LookupGraphic(GraphicColor, button_color.hovering), color_offset);
TrackTileGraphic preview_graphic = GraphicPreviewTurnOn;
if (m_preview_on) preview_graphic = GraphicPreviewTurnOff;
renderer.DrawTga(buttons, BUTTON_RECT(button_preview), LookupGraphic(preview_graphic, button_preview.hovering), color_offset);
// Draw mode text
TextWriter mode(42, 76, renderer, false, 14);
mode << Track::ModeText[m_mode];
renderer.ResetOffset();
}
| 34.713178 | 138 | 0.698526 | VictorieeMan |
cac166fde2d68f743a9e0ea6effd8bd943fec48f | 2,575 | hpp | C++ | miniapps/solvers/lor_mms.hpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | miniapps/solvers/lor_mms.hpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | miniapps/solvers/lor_mms.hpp | adantra/mfem | e48b5ffa1a8cdb5a18c0c3c28ab48fbdcd7ad298 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_LOR_MMS_HPP
#define MFEM_LOR_MMS_HPP
extern bool grad_div_problem;
namespace mfem
{
static constexpr double pi = M_PI, pi2 = M_PI*M_PI;
// Exact solution for definite Helmholtz problem with RHS corresponding to f
// defined below.
double u(const Vector &xvec)
{
int dim = xvec.Size();
double x = pi*xvec[0], y = pi*xvec[1];
if (dim == 2) { return sin(x)*sin(y); }
else { double z = pi*xvec[2]; return sin(x)*sin(y)*sin(z); }
}
double f(const Vector &xvec)
{
int dim = xvec.Size();
double x = pi*xvec[0], y = pi*xvec[1];
if (dim == 2)
{
return sin(x)*sin(y) + 2*pi2*sin(x)*sin(y);
}
else // dim == 3
{
double z = pi*xvec[2];
return sin(x)*sin(y)*sin(z) + 3*pi2*sin(x)*sin(y)*sin(z);
}
}
// Exact solution for definite Maxwell and grad-div problems with RHS
// corresponding to f_vec below.
void u_vec(const Vector &xvec, Vector &u)
{
int dim = xvec.Size();
double x = pi*xvec[0], y = pi*xvec[1];
if (dim == 2)
{
u[0] = cos(x)*sin(y);
u[1] = sin(x)*cos(y);
}
else // dim == 3
{
double z = pi*xvec[2];
u[0] = cos(x)*sin(y)*sin(z);
u[1] = sin(x)*cos(y)*sin(z);
u[2] = sin(x)*sin(y)*cos(z);
}
}
void f_vec(const Vector &xvec, Vector &f)
{
int dim = xvec.Size();
double x = pi*xvec[0], y = pi*xvec[1];
if (grad_div_problem)
{
if (dim == 2)
{
f[0] = (1 + 2*pi2)*cos(x)*sin(y);
f[1] = (1 + 2*pi2)*cos(y)*sin(x);
}
else // dim == 3
{
double z = pi*xvec[2];
f[0] = (1 + 3*pi2)*cos(x)*sin(y)*sin(z);
f[1] = (1 + 3*pi2)*cos(y)*sin(x)*sin(z);
f[2] = (1 + 3*pi2)*cos(z)*sin(x)*sin(y);
}
}
else
{
if (dim == 2)
{
f[0] = cos(x)*sin(y);
f[1] = sin(x)*cos(y);
}
else // dim == 3
{
double z = pi*xvec[2];
f[0] = cos(x)*sin(y)*sin(z);
f[1] = sin(x)*cos(y)*sin(z);
f[2] = sin(x)*sin(y)*cos(z);
}
}
}
} // namespace mfem
#endif
| 24.065421 | 80 | 0.546408 | adantra |
cac2563e46f2138efc6fe54934946099ef721ffd | 1,924 | cpp | C++ | examples/eigen.cpp | bjornpiltz/CppCodeGenVar | 4f4707c88202695300e55db8909af29107bdc157 | [
"MIT"
] | 6 | 2018-01-23T09:41:05.000Z | 2021-11-03T05:44:14.000Z | examples/eigen.cpp | bjornpiltz/CppCodeGenVar | 4f4707c88202695300e55db8909af29107bdc157 | [
"MIT"
] | 14 | 2018-01-18T13:16:20.000Z | 2018-02-25T21:42:34.000Z | examples/eigen.cpp | bjornpiltz/CppCodeGenVar | 4f4707c88202695300e55db8909af29107bdc157 | [
"MIT"
] | null | null | null | #include <codegenvar/Eigen>
#include <Eigen/Geometry>
#include <iostream>
using namespace codegenvar;
int main()
{
const Symbol x("x"), y("y"), dx("dx"), dy("dy"), a("a");
const Vec2 p(x, y);
const Vec3 P = p.homogeneous();
const Vec2 diff(dx, dy);
std::cout << "p = " << p.transpose() << std::endl;
std::cout << "translate by " << diff.transpose() << std::endl;
std::cout << "rotate by " << a << std::endl << std::endl;
std::cout << "P = " << P.transpose() << std::endl << std::endl;
Mat23 t;
t << Symbol(1), Symbol(0), diff(0),
Symbol(0), Symbol(1), diff(1);
std::cout << "p + diff = " << (p+diff).transpose() << std::endl << std::endl;
std::cout << "t = " << std::endl << t << std::endl << std::endl;
std::cout << "t*P = " << (t*P).transpose() << std::endl << std::endl;
Mat3 T;
T << t(0, 0), t(0, 1), t(0, 2),
t(1, 0), t(1, 1), t(1, 2),
Symbol(0), Symbol(0), Symbol(1);
std::cout << "T = " << std::endl << T << std::endl << std::endl;
std::cout << "T*P = " << (T*P).transpose() << std::endl << std::endl;
Mat2 r;
r << cos(a), -sin(a),
sin(a), cos(a);
std::cout << "r = " << std::endl << r << std::endl << std::endl;
std::cout << "r*p = " << (r*p).transpose() << std::endl << std::endl;
Mat3 R;
R << r(0, 0) , r(0, 1), Symbol(0),
r(1, 0) , r(1, 1), Symbol(0),
Symbol(0), Symbol(0), Symbol(1);
std::cout << "R = " << std::endl << R << std::endl << std::endl;
std::cout << "R*P = " << (R*P).transpose() << std::endl << std::endl;
std::cout << "T*R = " << std::endl << T*R << std::endl << std::endl;
std::cout << "T*R*P = " << (T*R*P).transpose() << std::endl << std::endl;
std::cout << "R*T = " << std::endl << R*T << std::endl << std::endl;
std::cout << "R*T*P = " << (R*T*P).transpose() << std::endl << std::endl;
return 0;
} | 33.172414 | 81 | 0.464137 | bjornpiltz |
cac2a31a88f5db4bfea02e6e8a36879a119b151a | 1,728 | cpp | C++ | src/afk/component/ScriptsComponent.cpp | christocs/ICT397 | 5ff6e4ed8757effad19b88fdb91f36504208f942 | [
"ISC"
] | null | null | null | src/afk/component/ScriptsComponent.cpp | christocs/ICT397 | 5ff6e4ed8757effad19b88fdb91f36504208f942 | [
"ISC"
] | null | null | null | src/afk/component/ScriptsComponent.cpp | christocs/ICT397 | 5ff6e4ed8757effad19b88fdb91f36504208f942 | [
"ISC"
] | null | null | null | #include "ScriptsComponent.hpp"
#include <string>
#include "afk/Afk.hpp"
#include "afk/io/Log.hpp"
#include "afk/io/Path.hpp"
using Afk::ScriptsComponent;
ScriptsComponent::ScriptsComponent(GameObject e, lua_State *lua_state)
: loaded_files(), last_write(), lua(lua_state) {
this->owning_entity = e;
}
auto ScriptsComponent::add_script(const path &script_path, EventManager *evt_mgr)
-> ScriptsComponent & {
const auto abs_path = Afk::get_absolute_path(script_path);
auto lua_script = std::shared_ptr<LuaScript>(new LuaScript{evt_mgr, this->lua, this});
lua_script->load(abs_path);
this->loaded_files.emplace(abs_path, lua_script);
this->last_write.emplace(abs_path, std::filesystem::last_write_time(abs_path));
return *this;
}
auto ScriptsComponent::remove_script(const path &script_path) -> void {
const auto abs_path = Afk::get_absolute_path(script_path);
this->loaded_files.erase(abs_path);
}
auto ScriptsComponent::get_script_table(const std::string &script_path) -> LuaRef {
const auto full_path = Afk::get_absolute_path(script_path);
auto f = this->global_tables.find(full_path);
if (f != this->global_tables.end()) {
return f->second;
}
auto new_tbl = LuaRef::newTable(this->lua);
this->global_tables.emplace(full_path, new_tbl);
return new_tbl;
}
auto ScriptsComponent::check_live_reload() -> void {
for (auto &script : this->loaded_files) {
const auto &script_path = script.first;
auto recent_write = std::filesystem::last_write_time(script_path);
if (recent_write > this->last_write[script_path]) {
script.second->unload();
script.second->load(script_path);
this->last_write[script_path] = recent_write;
}
}
}
| 33.230769 | 88 | 0.722801 | christocs |
cac90e18423d20b1de43ed694fb3f2dc728eb82f | 1,384 | cpp | C++ | 101/oops/about_inheritance.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | 2 | 2021-04-21T07:59:45.000Z | 2021-05-13T05:53:00.000Z | 101/oops/about_inheritance.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | null | null | null | 101/oops/about_inheritance.cpp | hariharanragothaman/Learning-STL | 7e5f58083212d04b93159d44e1812069171aa349 | [
"MIT"
] | 1 | 2021-04-17T15:32:18.000Z | 2021-04-17T15:32:18.000Z | #include <iostream>
using namespace std;
/*
* Inheritance provides a way to create a new class from an existing class
* New class is a specialized version of existing class
*
* Base Class (Parent) : inherited by child class
* Derived class (Child) : inherits from the base class
*/
/*
Here Undergrad class inherits Student Class
class Student
{
};
class Undergrad : public Student
{
};
*/
/* Rules classification
*
* An object of the child has:
* 1. All members defined in the child class.
* 2. All members declared in the parent class.
*
* An object of the child class can use:
* 1. All public members defined in the child class
* 2. All public members defined in the parent class
*
* Protected Members:
* -> Protected members is similar to private - but accessible by objects of derived class
* -> allows derived class to know details of parents
*
*/
// Base Class
class Shape
{
public:
Shape()
{
length = 0;
}
void setlength(int l)
{
length = l;
}
protected:
int length;
};
// Derived Class
class Square: public Shape{
public:
Square(): Shape()
{
length = 0;
}
int get_Area()
{
return (length*length);
}
};
int main()
{
Square sq;
sq.setlength(5);
cout << "The total area of the square is: " << sq.get_Area() << endl;
return 0;
} | 16.47619 | 91 | 0.631503 | hariharanragothaman |
cac90f9778320bbbc544d5218bc94bfb2ee6de72 | 20,771 | cpp | C++ | src/texedit.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | null | null | null | src/texedit.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 3 | 2019-09-10T03:50:40.000Z | 2019-09-23T04:20:14.000Z | src/texedit.cpp | SiriusTR/dle-experimental | 2ee17b4277b68eef57960d5cf9762dd986eaa0d9 | [
"MIT"
] | 1 | 2021-10-02T14:16:28.000Z | 2021-10-02T14:16:28.000Z |
#include "stdafx.h"
#include <string.h>
#include <stdio.h>
#include <string.h>
#include <commdlg.h>
#include <math.h>
#include "mine.h"
#include "dle-xp.h"
#include "toolview.h"
#include "PaletteManager.h"
#include "TextureManager.h"
//------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP (CPaletteWnd, CWnd)
#if 0
ON_WM_LBUTTONDOWN ()
ON_WM_RBUTTONDOWN ()
ON_WM_LBUTTONUP ()
ON_WM_RBUTTONUP ()
#endif
END_MESSAGE_MAP ()
//------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP (CTextureEdit, CDialog)
ON_WM_PAINT ()
ON_WM_MOUSEMOVE ()
ON_WM_LBUTTONDOWN ()
ON_WM_RBUTTONDOWN ()
ON_WM_LBUTTONUP ()
ON_WM_RBUTTONUP ()
ON_BN_CLICKED (IDC_TEXEDIT_DEFAULT, OnDefault)
ON_BN_CLICKED (IDC_TEXEDIT_UNDO, OnUndo)
ON_BN_CLICKED (IDC_TEXEDIT_LOAD, OnLoad)
ON_BN_CLICKED (IDC_TEXEDIT_SAVE, OnSave)
END_MESSAGE_MAP ()
//------------------------------------------------------------------------------
CPaletteWnd::CPaletteWnd ()
{
m_nWidth =
m_nHeight = 0;
m_pDC = null;
m_pOldPal = null;
}
//------------------------------------------------------------------------------
CPaletteWnd::~CPaletteWnd ()
{
}
//------------------------------------------------------------------------------
#define MINRGB(rgb) (((rgb)->peRed < (rgb)->peGreen) ? ((rgb)->peRed < (rgb)->peBlue) ? (rgb)->peRed : (rgb)->peBlue : ((rgb)->peGreen < (rgb)->peBlue) ? (rgb)->peGreen : (rgb)->peBlue)
#define MAXRGB(rgb) (((rgb)->peRed > (rgb)->peGreen) ? ((rgb)->peRed > (rgb)->peBlue) ? (rgb)->peRed : (rgb)->peBlue : ((rgb)->peGreen > (rgb)->peBlue) ? (rgb)->peGreen : (rgb)->peBlue)
#define sqr(v) (((int)(v))*((int)(v)))
int CPaletteWnd::CmpColors (PALETTEENTRY *c, PALETTEENTRY *m)
{
int i = c->peRed + c->peGreen + c->peBlue; //Luminance (c->peRed, c->peGreen, c->peBlue);
int j = m->peRed + m->peGreen + m->peBlue; //Luminance (m->peRed, m->peGreen, m->peBlue);
if (i < j)
return -1;
if (i > j)
return 1;
if (c->peRed < m->peRed)
return -1;
if (c->peRed > m->peRed)
return 1;
if (c->peGreen < m->peGreen)
return -1;
if (c->peGreen > m->peGreen)
return 1;
if (c->peBlue < m->peBlue)
return -1;
if (c->peBlue > m->peBlue)
return 1;
return 0;
}
//------------------------------------------------------------------------------
void CPaletteWnd::SortPalette (int left, int right)
{
int l = left,
r = right;
PALETTEENTRY m = m_palColors [(l + r) / 2];
do {
while (CmpColors (m_palColors + l, &m) < 0)
l++;
while (CmpColors (m_palColors + r, &m) > 0)
r--;
if (l <= r) {
if (l < r) {
PALETTEENTRY h = m_palColors [l];
m_palColors [l] = h = m_palColors [r];
m_palColors [r] = h;
ubyte i = m_nSortedPalIdx [l];
m_nSortedPalIdx [l] = m_nSortedPalIdx [r];
m_nSortedPalIdx [r] = i;
}
l++;
r--;
}
}
while (l <= r);
if (left < r)
SortPalette (left, r);
if (l < right)
SortPalette (l, right);
}
//------------------------------------------------------------------------------
void CPaletteWnd::CreatePalette ()
{
for (int i = 0; i < 256; i++) {
m_nSortedPalIdx [i] = i;
RgbFromIndex (i, m_palColors [i]);
}
}
//------------------------------------------------------------------------------
void CPaletteWnd::Update ()
{
InvalidateRect (null);
UpdateWindow ();
}
//------------------------------------------------------------------------------
int CPaletteWnd::Create (CWnd *pParentWnd, int nWidth, int nHeight)
{
CRect rc;
m_pParentWnd = pParentWnd;
pParentWnd->GetClientRect (rc);
m_nWidth = nWidth;
m_nHeight = nHeight;
if (m_nWidth < 0)
m_nWidth = rc.Width () / 8;
if (m_nHeight < 0) {
m_nHeight = rc.Height () / 8;
if (m_nWidth * m_nHeight > 256)
m_nHeight = (256 + m_nWidth - 1) / m_nWidth;
}
return CWnd::Create (null, null, WS_CHILD | WS_VISIBLE, rc, pParentWnd, 0);
}
//------------------------------------------------------------------------------
bool CPaletteWnd::SelectColor (CPoint& point, int& color, PALETTEENTRY *pRGB)
{
CRect rcPal;
GetClientRect (rcPal);
//ClientToScreen (rcPal);
// if over palette, redefine foreground color
if (PtInRect (rcPal, point)) {
int x, y;
// x = ((point.x - rcPal.left) >> 3)&127;
// y = ((point.y - rcPal.top) >> 3)&31;
x = (int) ((double) (point.x - rcPal.left) * ((double) m_nWidth / rcPal.Width ()));
y = (int) ((double) (point.y - rcPal.top) * ((double) m_nHeight / rcPal.Height ()));
int c = m_nWidth * y + x;
if (c > 255)
return false;
color = m_nSortedPalIdx [c];
if (pRGB)
*pRGB = m_palColors [c];
//RgbFromIndex (color, pRGB);
return true;
}
return false;
}
//------------------------------------------------------------------------------
void CPaletteWnd::SetPalettePixel (int x, int y)
{
CRect rc;
GetClientRect (&rc);
int dx, dy;
for (dy = 0; dy < 8; dy++)
for (dx = 0; dx < 8; dx++)
m_pDC->SetPixel ((x << 3) + dx + rc.left, (y << 3) + dy + rc.top, /*PALETTEINDEX*/ (y * m_nWidth + x));
}
//------------------------------------------------------------------------------
void CPaletteWnd::DrawPalette (void)
{
if (!BeginPaint ())
return;
CreatePalette ();
//SortPalette (0, 255);
CRect rc;
GetClientRect (&rc);
ubyte *bmPalette = new ubyte [m_nWidth * m_nHeight];
int h, i, c, w, x, y;
for (c = 0, y = m_nHeight - 1; (y >= 0); y--) {
for (x = 0, h = y * m_nWidth; x < m_nWidth; x++, h++) {
if (!y)
y = 0;
bmPalette [h] = (c < 256) ? m_nSortedPalIdx [c++] : 0;
}
}
BITMAPINFO* bmi = paletteManager.BMI ();
bmi->bmiHeader.biWidth = m_nWidth;
bmi->bmiHeader.biHeight = m_nHeight;
bmi->bmiHeader.biBitCount = 8;
bmi->bmiHeader.biClrUsed = 0;
//CPalette *pOldPalette = m_pDC->SelectPalette (paletteManager.Render (), FALSE);
//m_pDC->RealizePalette ();
if (m_nWidth & 1)
for (i = 0; i < m_nHeight; i++) {
w = (i == m_nHeight - 1) ? 256 % m_nWidth : m_nWidth;
StretchDIBits (m_pDC->m_hDC, 0, i * 8, w * 8, 8, 0, 0, w, 1,
(void *) (bmPalette + (m_nHeight - i - 1) * m_nWidth), bmi,
DIB_RGB_COLORS, SRCCOPY);
}
else
StretchDIBits (m_pDC->m_hDC, 0, 0, m_nWidth * 8, m_nHeight * 8, 0, 0, m_nWidth, m_nHeight,
(void *) bmPalette, bmi, DIB_RGB_COLORS, SRCCOPY);
//m_pDC->SelectPalette (pOldPalette, FALSE);
free (bmPalette);
EndPaint ();
}
//------------------------------------------------------------------------------
bool CPaletteWnd::BeginPaint ()
{
if (!IsWindow (m_hWnd))
return false;
if (m_pDC)
return false;
if (!(m_pDC = GetDC ()))
return false;
m_pOldPal = m_pDC->SelectPalette (paletteManager.Render (), FALSE);
m_pDC->RealizePalette ();
return true;
}
//------------------------------------------------------------------------------
void CPaletteWnd::EndPaint ()
{
if (m_pDC) {
if (m_pOldPal) {
m_pDC->SelectPalette (m_pOldPal, FALSE);
m_pOldPal = null;
}
ReleaseDC (m_pDC);
m_pDC = null;
}
Update ();
}
//------------------------------------------------------------------------------
#if 0
void CPaletteWnd::OnLButtonDown (UINT nFlags, CPoint point)
{
m_pParentWnd->SendMessage (WM_LBUTTONDOWN, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16));
}
//------------------------------------------------------------------------------
void CPaletteWnd::OnRButtonDown (UINT nFlags, CPoint point)
{
m_pParentWnd->SendMessage (WM_RBUTTONDOWN, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16));
}
//------------------------------------------------------------------------------
void CPaletteWnd::OnLButtonUp (UINT nFlags, CPoint point)
{
m_pParentWnd->SendMessage (WM_LBUTTONUP, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16));
}
//------------------------------------------------------------------------------
void CPaletteWnd::OnRButtonUp (UINT nFlags, CPoint point)
{
m_pParentWnd->SendMessage (WM_RBUTTONUP, (WPARAM) nFlags, (LPARAM) point.x + (((LPARAM) point.y) << 16));
}
#endif
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
CTextureEdit::CTextureEdit (const CTexture *pTexture, CWnd *pParent)
: CDialog (IDD_EDITTEXTURE, pParent)
{
*m_szColors = '\0';
m_pDC = null;
m_pPaintWnd = null;
m_pOldPal = null;
m_lBtnDown =
m_rBtnDown = false;
m_nTexAll = pTexture->Index ();
strcpy_s (m_szName, sizeof (m_szName), pTexture->Name ());
_strlwr_s (m_szName, sizeof (m_szName));
}
//------------------------------------------------------------------------------
CTextureEdit::~CTextureEdit ()
{
m_texture [0].Clear ();
m_texture [1].Clear ();
}
//------------------------------------------------------------------------------
BOOL CTextureEdit::OnInitDialog ()
{
if (!textureManager.Available ())
return FALSE;
CDialog::OnInitDialog ();
CWnd* pWnd;
CRect rc;
const CTexture *pTexture = textureManager.TextureByIndex (m_nTexAll);
pWnd = GetDlgItem (IDC_TEXEDIT_TEXTURE);
pWnd->GetClientRect (rc);
m_textureWnd.Create (null, null, WS_CHILD | WS_VISIBLE, rc, pWnd, 0);
pWnd = GetDlgItem (IDC_TEXEDIT_PALETTE);
pWnd->GetClientRect (rc);
m_paletteWnd.Create (pWnd, 32, 8);
pWnd = GetDlgItem (IDC_TEXEDIT_LAYERS);
pWnd->GetClientRect (rc);
m_layerWnd.Create (null, null, WS_CHILD | WS_VISIBLE, rc, pWnd, 0);
// set cursor styles for bitmap windows
SetCursor (LoadCursor (AfxGetInstanceHandle (), "PENCIL_CURSOR"));
// PaletteButton->SetCursor(null, IDC_CROSS);
m_fgColor = 0; // black
m_bgColor = 1; // white
m_lBtnDown = false;
m_rBtnDown = false;
m_bModified = false;
m_bPendingRevert = false;
if ((pTexture->Buffer () == null) || !pTexture->IsLoaded ()) {
DEBUGMSG (" Texture tool: Invalid texture");
EndDialog (IDCANCEL);
}
else if (!m_texture [0].Copy (*pTexture)) {
DEBUGMSG (" Texture tool: Not enough memory for texture editing");
EndDialog (IDCANCEL);
}
m_texture [1].Clear ();
if (!m_texture [1].Copy (m_texture [0]))
DEBUGMSG (" Texture tool: Not enough memory for undo function");
Backup ();
Refresh ();
m_nWidth = pTexture->Width ();
m_nHeight = pTexture->Height ();
return TRUE;
}
//------------------------------------------------------------------------------
void CTextureEdit::DoDataExchange (CDataExchange *pDX)
{
DDX_Text (pDX, IDC_TEXEDIT_COLORS, m_szColors, sizeof (m_szColors));
}
//------------------------------------------------------------------------------
void CTextureEdit::Backup (void)
{
if (m_texture [1].Buffer ())
m_texture [1].Copy (m_texture [0]);
}
//------------------------------------------------------------------------------
bool CTextureEdit::PtInRect (CRect& rc, CPoint& pt)
{
return (pt.x >= rc.left) && (pt.x < rc.right) && (pt.y >= rc.top) && (pt.y < rc.bottom);
}
//------------------------------------------------------------------------------
void CTextureEdit::OnButtonDown (UINT nFlags, CPoint point, int& color)
{
CRect rcEdit, rcPal;
GetClientRect (&m_textureWnd, rcEdit);
GetClientRect (&m_paletteWnd, rcPal);
if (PtInRect (rcEdit, point)) {
Backup ();
ColorPoint (nFlags, point, color);
}
else if (PtInRect (rcPal, point)) {
point.x -= rcPal.left;
point.y -= rcPal.top;
if (m_paletteWnd.SelectColor (point, color))
DrawLayers ();
}
}
//------------------------------------------------------------------------------
void CTextureEdit::OnOK ()
{
if (m_bModified)
textureManager.OverrideTexture (m_nTexAll, &m_texture [0]);
else if (m_bPendingRevert)
textureManager.RevertTexture (m_nTexAll);
CDialog::OnOK ();
}
//------------------------------------------------------------------------------
void CTextureEdit::OnLButtonDown (UINT nFlags, CPoint point)
{
m_lBtnDown = TRUE;
OnButtonDown (nFlags, point, m_fgColor);
}
//------------------------------------------------------------------------------
void CTextureEdit::OnRButtonDown (UINT nFlags, CPoint point)
{
m_rBtnDown = TRUE;
OnButtonDown (nFlags, point, m_bgColor);
}
//------------------------------------------------------------------------------
void CTextureEdit::OnLButtonUp (UINT nFlags, CPoint point)
{
m_lBtnDown = FALSE;
}
//------------------------------------------------------------------------------
void CTextureEdit::OnRButtonUp (UINT nFlags, CPoint point)
{
m_rBtnDown = FALSE;
}
//------------------------------------------------------------------------------
void CTextureEdit::OnMouseMove (UINT nFlags, CPoint point)
{
if (m_lBtnDown)
ColorPoint (nFlags, point, m_fgColor);
else if (m_rBtnDown)
ColorPoint (nFlags, point, m_bgColor);
}
//------------------------------------------------------------------------------
bool CTextureEdit::BeginPaint (CWnd *pWnd)
{
if (m_pDC)
return false;
if (!(m_pDC = pWnd->GetDC ()))
return false;
m_pPaintWnd = pWnd;
m_pOldPal = m_pDC->SelectPalette (paletteManager.Render (), FALSE);
m_pDC->RealizePalette ();
return true;
}
//------------------------------------------------------------------------------
void CTextureEdit::EndPaint ()
{
if (m_pPaintWnd) {
if (m_pDC) {
if (m_pOldPal) {
m_pDC->SelectPalette (m_pOldPal, FALSE);
m_pOldPal = null;
}
m_pPaintWnd->ReleaseDC (m_pDC);
m_pDC = null;
}
Update (m_pPaintWnd);
m_pPaintWnd = null;
}
}
//------------------------------------------------------------------------------
void CTextureEdit::GetClientRect (CWnd *pWnd, CRect& rc)
{
CRect rcc;
int dx, dy;
pWnd->GetClientRect (&rcc);
pWnd->GetWindowRect (rc);
dx = rc.Width () - rcc.Width ();
dy = rc.Height () - rcc.Height ();
ScreenToClient (rc);
rc.DeflateRect (dx / 2, dy / 2);
}
//------------------------------------------------------------------------------
// CTextureEdit - ColorPoint
//
// Action - Uses coordinates to determine which pixel mouse cursor is
// over. If it is over the palette, the palette box will be updated with
// the new color. If it is over the texture, the texture will be updated
// with the color.
// If control key is held down, color is defined by bitmap instead.
//------------------------------------------------------------------------------
void CTextureEdit::ColorPoint (UINT nFlags, CPoint& point, int& color)
{
CRect rcEdit;
GetClientRect (&m_textureWnd, rcEdit);
if (m_texture [0].Format () == TGA) {
m_lBtnDown = m_rBtnDown = false;
ErrorMsg ("Cannot edit TGA images.");
}
else if (PtInRect (rcEdit, point)) {
int x, y, nPixel;
m_bModified = TRUE; // mark this as m_bModified
// x = ((point.x - rcEdit.left) >> 2) & 63;
// y = ((point.y - rcEdit.top) >> 2) & 63;
x = (int) ((double) (point.x - rcEdit.left) * (double (m_nWidth) / rcEdit.Width ()));
y = (int) ((double) (point.y - rcEdit.top) * (double (m_nHeight) / rcEdit.Height ()));
nPixel = m_nWidth * (m_nHeight - 1 - y) + x;
if (nFlags & MK_CONTROL) {
color = paletteManager.ClosestColor (m_texture [0][nPixel]);
DrawLayers ();
}
else if (BeginPaint (&m_textureWnd)) {
m_texture [0][nPixel] = *paletteManager.Current (color);
if (color >= 254)
m_texture [0][nPixel].a = 0;
SetTexturePixel (x, y);
EndPaint ();
}
}
}
//------------------------------------------------------------------------------
void CTextureEdit::OnPaint () //EvDrawItem(UINT, DRAWITEMSTRUCT &)
{
CDialog::OnPaint ();
Refresh ();
}
//------------------------------------------------------------------------------
void CTextureEdit::OnLoad ()
{
char szFile [MAX_PATH] = {0};
const char *szDefExt = m_texture [0].Format () == BMP ? "bmp" : "tga";
CFileManager::tFileFilter filters [] = {
{ "Truevision Targa", "tga" },
{ "256 color Bitmap Files", "bmp" }
};
bool bFuncRes;
sprintf_s (szFile, ARRAYSIZE (szFile), "*.%s", szDefExt);
if (CFileManager::RunOpenFileDialog (szFile, ARRAYSIZE (szFile), filters, ARRAYSIZE (filters), m_hWnd)) {
Backup ();
bFuncRes = m_texture [0].LoadFromFile (szFile);
if (bFuncRes) {
Refresh ();
m_nWidth = m_texture [0].Width ();
m_nHeight = m_texture [0].Height ();
m_nSize = m_texture [0].Size ();
m_bModified = TRUE;
}
else
OnUndo ();
}
}
//------------------------------------------------------------------------------
void CTextureEdit::OnSave ()
{
char szFile [MAX_PATH] = { 0 };
const char *szExt = m_texture [0].Format () == BMP ? "bmp" : "tga";
CFileManager::tFileFilter filters [] = {
{ "256 color Bitmap Files", "bmp" },
{ "Truevision Targa", "tga" }
};
CFileManager::tFileFilter *filter = m_texture [0].Format () == BMP ? &filters [0] : &filters [1];
sprintf_s (szFile, ARRAYSIZE (szFile), "%s.%s", m_szName, szExt);
if (CFileManager::RunSaveFileDialog (szFile, ARRAYSIZE (szFile), filter, 1, m_hWnd)) {
_strlwr_s (szFile, sizeof (szFile));
m_texture [0].Save (szFile);
}
}
//------------------------------------------------------------------------------
void CTextureEdit::OnUndo ()
{
if (m_texture [1].Buffer ()) {
m_texture [0].Copy (m_texture [1]);
// This combination should only happen immediately after OnDefault.
// In this case we reverse it so the user is still prompted on save.
if (m_bPendingRevert && !m_bModified) {
m_bModified = true;
m_bPendingRevert = false;
}
Refresh ();
}
}
void CTextureEdit::Update (CWnd *pWnd)
{
pWnd->InvalidateRect (null);
pWnd->UpdateWindow ();
}
//------------------------------------------------------------------------------
void CTextureEdit::OnDefault (void)
{
if (QueryMsg("Are you sure you want to restore this texture\n"
"back to its original texture\n") == IDYES) {
Backup ();
m_texture [0].Copy (*textureManager.BaseTextures (m_nTexAll));
m_bModified = false;
m_bPendingRevert = true;
Refresh ();
}
}
//------------------------------------------------------------------------------
void CTextureEdit::DrawTexture (void)
{
if (!BeginPaint (&m_textureWnd))
return;
m_pDC->SetStretchBltMode (STRETCH_DELETESCANS);
BITMAPINFO* bmi = paletteManager.BMI ();
bmi->bmiHeader.biWidth =
bmi->bmiHeader.biHeight = m_texture [0].RenderWidth ();
bmi->bmiHeader.biBitCount = 32;
//bmi->bmiHeader.biSizeImage = m_texture [0].BufSize ();
bmi->bmiHeader.biClrUsed = 0;
CRect rc;
m_textureWnd.GetClientRect (&rc);
StretchDIBits (m_pDC->m_hDC, 0, 0, rc.right, rc.bottom, 0, 0, m_texture [0].RenderWidth (), m_texture [0].RenderWidth (),
(void *) m_texture [0].RenderBuffer (), bmi, DIB_RGB_COLORS, SRCCOPY);
EndPaint ();
}
//------------------------------------------------------------------------------
void CTextureEdit::DrawPalette (void)
{
m_paletteWnd.DrawPalette ();
}
//------------------------------------------------------------------------------
void CTextureEdit::DrawLayers ()
{
if (!BeginPaint (&m_layerWnd))
return;
CRect rc;
m_layerWnd.GetClientRect (&rc);
rc.DeflateRect (10, 10);
rc.right -= 10;
rc.bottom -= 10;
m_pDC->FillSolidRect (&rc, PALETTEINDEX (m_bgColor));
rc.OffsetRect (10, 10);
m_pDC->FillSolidRect (&rc, PALETTEINDEX (m_fgColor));
EndPaint ();
// set message
char fg_color[30];
char bg_color[30];
switch(m_fgColor) {
case 255:
strcpy_s (fg_color, sizeof (fg_color), "transparent");
break;
case 254:
strcpy_s (fg_color, sizeof (fg_color), "see thru");
break;
default :
sprintf_s (fg_color, sizeof (fg_color), "color %d", m_fgColor);
break;
}
switch(m_bgColor) {
case 255:
strcpy_s (bg_color, sizeof (bg_color), "transparent");
break;
case 254:
strcpy_s (bg_color, sizeof (bg_color), "see thru");
break;
default :
sprintf_s (bg_color, sizeof (bg_color), "color %d", m_bgColor);
break;
}
sprintf_s (m_szColors, sizeof (m_szColors), "foreground = %s, background = %s.", fg_color, bg_color);
UpdateData (FALSE);
}
//------------------------------------------------------------------------------
void CTextureEdit::Refresh (void)
{
DrawTexture ();
DrawPalette ();
DrawLayers ();
}
//------------------------------------------------------------------------------
void CTextureEdit::SetTexturePixel (int x, int y)
{
CRect rc;
int cx, cy;
double xs, ys;
#ifdef _DEBUG
CBGR& rgb = m_texture [0][(63 - y) * 64 + x];
int color = rgb.ColorRef ();
#else
int color = m_texture [0][(63 - y) * 64 + x].ColorRef ();
#endif
m_textureWnd.GetClientRect (&rc);
cx = rc.Width ();
cy = rc.Height ();
xs = (double) cx / 64.0;
ys = (double) cy / 64.0;
x = rc.left + (int) ((double) x * xs);
y = rc.top + (int) ((double) y * ys);
int dx, dy;
xs /= 4.0;
ys /= 4.0;
for (dy = 0; dy < 4; dy++)
for (dx = 0; dx < 4; dx++)
m_pDC->SetPixel (x + (int) ((double) dx * xs), y + (int) ((double) dy * ys), color);
}
//------------------------------------------------------------------------------
void CTextureEdit::SetPalettePixel (int x, int y)
{
CRect rc;
m_paletteWnd.GetClientRect (&rc);
int dx, dy;
for (dy = 0; dy < 8; dy++)
for (dx = 0; dx < 8; dx++)
m_pDC->SetPixel ((x << 3) + dx + rc.left, (y << 3) + dy + rc.top, PALETTEINDEX (y * 32 + x));
}
//------------------------------------------------------------------------------
| 26.940337 | 185 | 0.532088 | SiriusTR |
cac943660942cad7fa85c2ae48db7c5f5575ad5a | 477 | cpp | C++ | hooks/hooks/hooked_lockcursor.cpp | DomesticTerrorist/Doubletap.Space-v3-SRC | caa2e09fc5e15a268ed735debe811a19fe96a08c | [
"MIT"
] | 3 | 2021-08-18T10:19:25.000Z | 2021-08-31T04:45:26.000Z | hooks/hooks/hooked_lockcursor.cpp | DomesticTerrorist/Doubletap.Space-v3-SRC | caa2e09fc5e15a268ed735debe811a19fe96a08c | [
"MIT"
] | null | null | null | hooks/hooks/hooked_lockcursor.cpp | DomesticTerrorist/Doubletap.Space-v3-SRC | caa2e09fc5e15a268ed735debe811a19fe96a08c | [
"MIT"
] | 4 | 2021-08-18T06:57:26.000Z | 2021-09-02T15:22:36.000Z | // This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
#include "..\hooks.hpp"
using LockCursor_t = void(__thiscall*)(void*);
void __stdcall hooks::hooked_lockcursor()
{
static auto original_fn = surface_hook->get_func_address <LockCursor_t> (67);
if (!menu_open)
return original_fn(m_surface());
m_surface()->UnlockCursor();
} | 29.8125 | 96 | 0.706499 | DomesticTerrorist |
cad2c3baaa4ab70e2f9e6384e047468d2bf3a435 | 1,794 | cpp | C++ | CXXPRIMER/test.cpp | Clelo4/OS_study | cf12a4721c3c9c338f91c2cdf069ac3b49b60522 | [
"MIT"
] | null | null | null | CXXPRIMER/test.cpp | Clelo4/OS_study | cf12a4721c3c9c338f91c2cdf069ac3b49b60522 | [
"MIT"
] | null | null | null | CXXPRIMER/test.cpp | Clelo4/OS_study | cf12a4721c3c9c338f91c2cdf069ac3b49b60522 | [
"MIT"
] | null | null | null | /**
* @file 1.cpp
* @author Jack
* @mail [email protected]
* @date 2021-12-28
* @version 0.1
*
* @copyright Copyright (c) 2021
*/
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <type_traits>
#include <vector>
class B;
class A {
public:
A(int a, int b = 1, int c = 1) { printf("a: %d, b: %d\n", a, b); }
friend class B;
protected:
int prot_mem = 1;
private:
int private_mem = 2;
};
class B : private A {
public:
B(int a) : A(a) {}
using A::private_mem;
using A::prot_mem;
};
void fn(const A &arg){};
void fn() {
static int count = -1;
++count;
std::cout << "fn count: " << count << std::endl;
};
// 64位系统
#include <stdio.h>
struct {
int x;
char y;
} s;
int main() {
int a = 1;
int *b = &a;
if (std::is_same<decltype(*b), int &>::value) {
std::printf("decltype(*b) is same as int&\n");
}
if (std::is_same<decltype((a)), int &>::value) {
std::printf("decltype((a)) is same as int&\n");
}
std::string s = "A";
for (auto &c : s) {
if (std::is_same<decltype(c), char &>::value) {
std::printf("decltype(c) is same as char&\n");
}
}
std::vector<int> is;
if (std::is_same<decltype(is.begin() - is.end()),
std::vector<int>::difference_type>::value) {
std::printf(
"decltype(is.begin() - is.end()) is same as "
"std::vector<int>::difference_type\n");
}
int arr1[] = {1, 2, 3, 4};
decltype(std::begin(arr1)) b_ptr;
std::vector<int> vi(std::begin(arr1), std::end(arr1));
fn(1);
A a1 = {1, 2};
B b1{1};
std::cout << "b1.prot_mem: " << b1.prot_mem << std::endl;
std::cout << "b1.private_mem: " << b1.private_mem << std::endl;
for (int i = 0; i < 10; ++i) fn();
printf("%d\n", sizeof(s)); // 输出24
return 0;
}
| 20.62069 | 68 | 0.554069 | Clelo4 |
cad2cf6ce997ee6f1ed98c20b9f1d3d20c6e4471 | 11,262 | hpp | C++ | lib/gfx/include/gfx_draw_helpers.hpp | codewitch-honey-crisis/gfx_demo | 90545974ff95d5b0e4f5f5320ac6b05b8172a0ec | [
"MIT"
] | 58 | 2021-05-10T23:25:06.000Z | 2022-03-22T00:59:04.000Z | lib/gfx/include/gfx_draw_helpers.hpp | codewitch-honey-crisis/gfx_demo | 90545974ff95d5b0e4f5f5320ac6b05b8172a0ec | [
"MIT"
] | 3 | 2021-07-28T16:26:35.000Z | 2022-02-18T21:45:09.000Z | lib/gfx/include/gfx_draw_helpers.hpp | codewitch-honey-crisis/gfx_demo | 90545974ff95d5b0e4f5f5320ac6b05b8172a0ec | [
"MIT"
] | 5 | 2021-07-16T12:00:48.000Z | 2022-02-14T02:04:06.000Z | #ifndef HTCW_GFX_DRAW_HELPERS_HPP
#define HTCW_GFX_DRAW_HELPERS_HPP
#include "gfx_positioning.hpp"
namespace gfx {
namespace helpers {
template<typename Destination,typename Source,bool HasAlpha>
struct blender {
static gfx_result point(Destination& destination,point16 pt,Source& source,point16 spt, typename Source::pixel_type pixel) {
typename Destination::pixel_type px;
// printf("pixel.native_value = %d\r\n",(int)pixel.native_value);
gfx_result r=convert_palette(destination,source,pixel,&px);
//printf("px.native_value = %d\r\n",(int)px.native_value);
if(gfx_result::success!=r) {
return r;
}
return destination.point(pt,px);
}
};
template<typename Destination,typename Source>
struct blender<Destination,Source,true> {
static gfx_result point(Destination& destination,point16 pt,Source& source,point16 spt, typename Source::pixel_type pixel) {
double alpha = pixel.template channelr<channel_name::A>();
if(0.0==alpha) return gfx_result::success;
if(1.0==alpha) return blender<Destination,Source,false>::point(destination,pt,source,spt,pixel);
typename Source::pixel_type spx;
gfx_result r=source.point(spt,&spx);
if(gfx_result::success!=r) {
return r;
}
rgb_pixel<HTCW_MAX_WORD> bg;
r=convert_palette_to(source,spx,&bg);
if(gfx_result::success!=r) {
return r;
}
rgb_pixel<HTCW_MAX_WORD> fg;
r=convert_palette_to(source,pixel,&fg);
if(gfx_result::success!=r) {
return r;
}
r=fg.blend(bg,alpha,&fg);
if(gfx_result::success!=r) {
return r;
}
typename Destination::pixel_type px;
r=convert_palette_from(destination,fg,&px);
if(gfx_result::success!=r) {
return r;
}
return destination.point(pt,px);
}
};
template<typename Destination,bool Batch,bool Async>
struct batcher {
inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) {
return gfx_result::success;
}
inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) {
return destination.point(location,pixel);
}
inline static gfx_result commit_batch(Destination& destination,bool async) {
return gfx_result::success;
}
};
template<typename Destination>
struct batcher<Destination,false,true> {
inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) {
return gfx_result::success;
}
inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) {
if(async) {
return destination.point_async(location,pixel);
} else {
return destination.point(location,pixel);
}
}
inline static gfx_result commit_batch(Destination& destination,bool async) {
return gfx_result::success;
}
};
template<typename Destination,bool Batch,bool Async, bool Read>
struct alpha_batcher {
inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) {
return batcher<Destination,Batch,Async>::begin_batch(destination,bounds,async);
}
inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) {
return batcher<Destination,Batch,Async>::write_batch(destination,location,pixel,async);
}
inline static gfx_result commit_batch(Destination& destination,bool async) {
return batcher<Destination,Batch,Async>::commit_batch(destination,async);
}
};
template<typename Destination,bool Batch,bool Async>
struct alpha_batcher<Destination,Batch,Async,true> {
inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) {
return batcher<Destination,false,Async>::begin_batch(destination,bounds,async);
}
inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) {
return batcher<Destination,false,Async>::write_batch(destination,location,pixel,async);
}
inline static gfx_result commit_batch(Destination& destination,bool async) {
return batcher<Destination,false,Async>::commit_batch(destination,async);
}
};
template<typename Destination>
struct batcher<Destination,true,false> {
inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) {
return destination.begin_batch(bounds);
}
inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) {
return destination.write_batch(pixel);
}
inline static gfx_result commit_batch(Destination& destination,bool async) {
return destination.commit_batch();
}
};
template<typename Destination>
struct batcher<Destination,true,true> {
inline static gfx_result begin_batch(Destination& destination,const rect16& bounds,bool async) {
if(async) {
return destination.begin_batch_async(bounds);
} else {
return destination.begin_batch(bounds);
}
}
inline static gfx_result write_batch(Destination& destination,point16 location,typename Destination::pixel_type pixel,bool async) {
if(async) {
return destination.write_batch_async(pixel);
} else {
return destination.write_batch(pixel);
}
}
inline static gfx_result commit_batch(Destination& destination,bool async) {
if(async) {
return destination.commit_batch_async();
} else {
return destination.commit_batch();
}
}
};
template<typename Destination,bool Suspend,bool Async>
struct suspender {
inline suspender(Destination& dest,bool async=false) {
}
inline suspender(const suspender& rhs) = default;
inline suspender& operator=(const suspender& rhs)=default;
inline ~suspender() =default;
inline static gfx_result suspend(Destination& dst) {
return gfx_result::success;
}
inline static gfx_result resume(Destination& dst,bool force=false) {
return gfx_result::success;
}
inline static gfx_result suspend_async(Destination& dst) {
return gfx_result::success;
}
inline static gfx_result resume_async(Destination& dst,bool force=false) {
return gfx_result::success;
}
};
template<typename Destination>
struct suspender<Destination,true,false> {
Destination& destination;
inline suspender(Destination& dest,bool async=false) : destination(dest) {
suspend(destination);
}
inline suspender(const suspender& rhs) {
suspend(destination);
}
inline suspender& operator=(const suspender& rhs) {
destination = rhs.destination;
suspend(destination);
return *this;
}
inline ~suspender() {
resume(destination);
}
inline static gfx_result suspend(Destination& dst) {
return dst.suspend();
}
inline static gfx_result resume(Destination& dst,bool force=false) {
if(force) {
return resume(dst,true);
}
return dst.resume();
}
inline static gfx_result suspend_async(Destination& dst) {
return suspend(dst);
}
inline static gfx_result resume_async(Destination& dst,bool force=false) {
if(force) {
return resume(dst,true);
}
return resume(dst);
}
};
template<typename Destination>
struct suspender<Destination,true,true> {
Destination& destination;
const bool async;
inline suspender(Destination& dest,bool async=false) : destination(dest),async(async) {
if(async) {
suspend_async(destination);
return;
}
suspend(destination);
}
inline suspender(const suspender& rhs) {
destination = rhs.destination;
if(async) {
suspend_async(destination);
return;
}
suspend(destination);
}
inline suspender& operator=(const suspender& rhs) {
destination = rhs.destination;
if(async) {
suspend_async(destination);
return *this;
}
suspend(destination);
return *this;
}
inline ~suspender() {
if(async) {
resume_async(destination);
return;
}
resume(destination);
}
inline static gfx_result suspend(Destination& dst) {
return dst.suspend();
}
inline static gfx_result resume(Destination& dst,bool force=false) {
if(force) {
return dst.resume(true);
}
return dst.resume();
}
inline static gfx_result suspend_async(Destination& dst) {
return dst.suspend_async();
}
inline static gfx_result resume_async(Destination& dst,bool force=false) {
if(force) {
dst.resume_async(true);
}
return dst.resume_async();
}
};
}
}
#endif | 43.992188 | 143 | 0.551234 | codewitch-honey-crisis |
cad317aafe7c0078ca77280af0b65a64d4ac8d9a | 21,455 | cpp | C++ | src/lib/objects/aobject.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | 1 | 2021-03-16T21:47:41.000Z | 2021-03-16T21:47:41.000Z | src/lib/objects/aobject.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | src/lib/objects/aobject.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | /****************************************************************************
** $Id: aobject.cpp,v 1.3 2008/11/09 21:09:11 leader Exp $
**
** Code file of the Ananas Object of Ananas
** Designer and Engine applications
**
** Created : 20031201
**
** Copyright (C) 2003-2004 Leader InfoTech. All rights reserved.
** Copyright (C) 2005-2006 Grigory Panov <gr1313 at mail.ru>, Yoshkar-Ola.
**
** This file is part of the Library of the Ananas
** automation accounting system.
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
** See http://www.leaderit.ru/page=ananas or email [email protected]
** See http://www.leaderit.ru/gpl/ for GPL licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
#include <qobject.h>
#include <q3sqlcursor.h>
#include <q3sqlpropertymap.h>
#include <qdialog.h>
#include "adatabase.h"
#include "aobject.h"
#include "aform.h"
#include "alog.h"
/*!
* \en
* Craeate abstract aObject.
* \param parent - parent object
* \param name - name of object
* \_en
* \ru
* Создает абстрактный не связанный с базой данных объект управления данными.
* Созданный таким образом объект не использует информацию из метаданных о составе и
* типах полей. То есть он не является какой-либо моделью данных. И на самом деле малопригоден
* для использования. В дазе данных ни как не отражается создание этого объекта. Для того,
* что бы зарегистрировать вновь созданный абстрактный объект в базе данных, необходимо
* сначала проинициализировать его с использованием метаданных, а затем вызвать метод New().
* \_ru
*/
aObject::aObject( QObject *parent, const char *name )
:QObject( parent, name )
{
db = 0;
vInited = false;
filtred = false;
selectFlag = false;
}
/*!
* \en
* Create aObject, inited by md object.
* md object finding by name
* \param oname - md name of object, name contens prefix
* Document. for documents,
* InfoRegister. for information registers,
* Catalogue. for catalogues,
* AccumulationRegister. for Accumulation registers,
* DocJournal. for journals
* \param adb - link on object aDataBase used for work
* \param parent - parent object
* \param name - name of object
* \_en
* \ru
* Создает объект как модель данных, описанную в метаданных. На описание в метаданных
* указывает один из передаваемых при вызове параметров - имя элемента метаданных.
* После успешного создания объекта с ним можно работать как с объектом данных со структурой,
* описанной в метаданных, и индентифицируемой именем, переданным в параметрах вызова.
*
* \_ru
*/
aObject::aObject( const QString &oname, aDatabase *adb, QObject *parent, const char *name )
:QObject( parent, name )
{
vInited = false;
filtred = false;
selectFlag = false;
db = adb;
if ( adb )
{
obj = adb->cfg.find( oname );
setObject( obj );
}
}
/*!
* Create aObject, inited by md object.
* \param context - hi leve md object
* \param adb - link on object aDataBase used for work
* \param parent - parent object
* \param name - name of object
*/
aObject::aObject( aCfgItem context, aDatabase *adb, QObject *parent, const char *name )
:QObject( parent, name )
{
filtred = false;
vInited = false;
db = adb;
if ( adb )
{
setObject( context );
}
}
/*!
* virtual destructor.
*/
aObject::~aObject()
{
}
/*!
* Tune on metadata object and it's database tables.
* \param adb - link on database object
* \return error code
*/
ERR_Code
aObject::init()
{
if ( isInited() ) return err_noerror;
return initObject();
}
/*!
* Set new object type after create
* /param newobject - new md object
* \return error code
*/
ERR_Code
aObject::setObject( aCfgItem newobject )
{
setInited( false );
obj = newobject;
return init();
}
/*!
* Init object after create.
* Need setObject( id ), where id - if of the metadata object of the adb->cfg loaded Configuration.
* \return error code
*/
ERR_Code
aObject::initObject()
{
aCfgItem fg, f;
QString tname;
setInited( true );
// db = adb;
md = 0;
if ( db ) md = &db->cfg;
else
{
aLog::print(aLog::Error, tr("aObject have no database!"));
return err_nodatabase;
}
if ( obj.isNull() )
{
aLog::print(aLog::Error, tr("aObject md object not found"));
return err_objnotfound;
}
return err_noerror;
}
/*!
*
*/
bool
aObject::checkStructure()
{
return false;
}
/*!
* Return the table of object by it's name.
* /param name - name of table for main table use name="" or empty parametr
* /return link on aDataTable or 0 if table not found
*/
aDataTable *
aObject::table( const QString &name )
{
if ( !dbtables[ name ] )
{
if (name!="" && !name.isEmpty())
{
aLog::print(aLog::Error, tr("aObject table with name %1 not found").arg(name));
cfg_message(1, tr("Table `%s' not found.\n").utf8(),(const char*) name);
}
// else
// {
// cfg_message(1, tr("Table name is empty.\n").utf8());
// }
return 0;
}
return dbtables[ name ];
}
/*!
* Insert table name and it link into internal buffer.
* used for finding table by it's md name or some default name
* /param dbname - database name of table
* /param obj - md object, used for aDataTable initing
* /param name - name of table, used for finding table in buffer
* /return error code
*/
ERR_Code
aObject::tableInsert( const QString &dbname, aCfgItem obj, const QString &name )
{
if ( db )
{
aDataTable *t = db->table( dbname );
if ( !t )
return err_notable;
t->setObject( obj );
dbtables.insert( name, t );
return err_noerror;
}
aLog::print(aLog::Error, tr("aObject have no database!"));
return err_nodatabase;
}
/*!
* Insert table name and it link into internal buffer.
* used for finding table by it's md name or some default name
* table not inited by md object
* /param dbname - database name of table
* /param name - name of table, used for finding table in buffer
* /return error code
*/
ERR_Code
aObject::tableInsert( const QString &dbname, const QString &name )
{
if ( db ) {
aDataTable *t = db->table( dbname );
if ( !t ) return err_notable;
dbtables.insert( name, t );
return err_noerror;
}
aLog::print(aLog::Error, tr("aObject have no database!"));
return err_nodatabase;
}
/*!
* Remove table from buffer.
* /param name - table name
* /return err_notable if table not found
*/
ERR_Code
aObject::tableRemove( const QString &name )
{
if ( !dbtables[name] )
{
aLog::print(aLog::Error, tr("aObject table with name %1 not found").arg(name));
return err_notable;
}
dbtables.remove( name );
return err_noerror;
}
/*!
*
*/
QString
aObject::trSysName( const QString & )
{
return "";
}
/*!
* Gets system field value.
* \param name (in) - field name.
* \return field value or QVariant::Invalid if field no exist.
*/
QVariant
aObject::sysValue( const QString & name, const QString &tableName )
{
aDataTable *t = table( tableName );
if ( t && t->sysFieldExists( name ) )
{
return t->sysValue(name);
}
else return QVariant::Invalid;
}
/*!
* Sets system field value.
* \param name (in) - field name.
* \param value (in) - sets value.
*/
int
aObject::setSysValue( const QString & name, QVariant value, const QString &tableName )
{
aDataTable *t = table( tableName );
if ( t )
{
t->setSysValue( name, value );
return err_noerror;
}
return err_notable;
}
/*!
* Return field value of the primary object database table.
*/
QVariant
aObject::Value( const QString & name, const QString &tableName )
{
aDataTable *t = table( tableName );
QString trName = trSysName(name);
if ( trName != "" ) return sysValue( trName );
else
{
if ( t ) return t->value( name );
}
return QVariant("");
}
/*!
* Set field value of the primary object database table.
*/
int
aObject::SetValue( const QString & name, const QVariant &value, const QString &tableName )
{
aDataTable *t = table( tableName );
QString trName = trSysName(name);
if ( trName != "" ) return setSysValue( trName, value );
else
{
if ( t )
{
t->setValue( name, value );
return err_noerror;
}
}
return err_notable;
// return setTValue( "", name, value );
}
/*!
* Check object selecting.
* \return true if object record selected in database.
*/
bool
aObject::IsSelected()
{
return selected();
}
/*!
*
*/
bool
aObject::IsMarkDeleted(const QString & tname)
{
aDataTable *t = table( tname );
if ( t && t->sysFieldExists( "df" ) ) return t->sysValue( "df" ).toInt() == 1;
return false;
}
/*!
*
*/
bool
aObject::IsMarked()
{
aDataTable *t = table();
if ( t && t->sysFieldExists( "mf" ) ) return t->sysValue( "mf" ).toInt() == 1;
return false;
}
/*!
*
*/
/*
int
aObject::TableSetMarkDeleted( bool Deleted, const QString & tname )
{
aDataTable *t = table( tname );
if ( t && t->sysFieldExists( "df" ) ) {
QString v = "0";
if ( Deleted ) v = "1";
t->setSysValue( "df", QVariant( v ) );
return err_noerror;
}
return err_incorrecttype; // Object can not be mark deleted
}
*/
/*!
*
*/
int
aObject::SetMarkDeleted( bool Deleted, const QString & tname )
{
aDataTable *t = table( tname );
if ( t && t->sysFieldExists( "df" ) )
{
QString v = "0";
if ( Deleted ) v = "1";
t->setSysValue( "df", QVariant( v ) );
return err_noerror;
}
else
{
aLog::print(aLog::Error, tr("aObject have no system field %1").arg("df"));
return err_incorrecttype; // Object can not be mark deleted
}
}
/*!
*
*/
int
aObject::SetMarked( bool Marked )
{
aDataTable *t = table();
if ( t && t->sysFieldExists( "mf" ) ) {
QString v = "";
if ( Marked ) v = "1";
t->setSysValue( "mf", QVariant( v ) );
// t->printRecord();
return err_noerror;
}
aLog::print(aLog::Error, tr("aObject have no system field %1").arg("mf"));
return err_incorrecttype; // Object can not be marked
}
/*!
* Add new object record in database.
*/
int
aObject::New()
{
aDataTable *t = table();
if ( !t ) return err_notable;
setSelected ( t->New() );
/* Q_ULLONG Uid = t->primeInsert()->value("id").toULongLong();
if ( t->insert() )
{
if ( t->select(QString("id=%1").arg(Uid), false) )
if ( t->first() )
{
setSelected(true);
return err_noerror;
}
return err_selecterror;
}
*/ if ( selected() ) return err_noerror;
return err_inserterror;
}
/*!
* Copy current selected object data in database.
*/
/*Q_ULLONG
aObject::copy( const QString & tablename )
{
aDataTable * t = table( tablename );
if ( !t ) return 0;
if ( !selected(tablename) ) return 0;
QSqlRecord * r = t->primeUpdate();
Q_ULLONG Uid = db->uid( t->id );
r->setValue("id",Uid);
if ( t->insert() ) return Uid;
else return 0;
}
*/
/*!
*
*/
int
aObject::Copy()
{
// QSqlRecord r;
// Q_ULLONG Uid = copy();
// if ( !Uid ) return err_copyerror;
aDataTable *t = table();
if ( t->Copy() ) return err_noerror;
// if ( t->select(QString("id=%1").arg(Uid)) )
// if ( t->first() )
// return err_noerror;
return err_copyerror;
}
/*!
* Delete curent selected object record from database.
*/
int
aObject::Delete()
{
aDataTable * t = table();
if ( !t ) return err_notable;
db->markDeleted(getUid());
t->Delete();
// if ( !selected() ) return err_notselected;
// t->primeDelete();
// t->del();
setSelected (false);
return err_noerror;
}
/*!
*\~english
* Update curent selected object record to database.
*\~russian
*\~
*/
int
aObject::Update()
{
aDataTable *t = table();
QSqlRecord *r;
int i;
if ( !t ) return err_notable;
t->Update();
/*
r = t->primeUpdate();
t->printRecord();
for ( i=0;i<r->count();i++ ) r->setValue( i, t->value( i ) );
t->update();
*/
if ( t->lastError().type() )
{
//debug_message("update error %i %s\n",t->lastError().type(), ( const char *)t->lastError().text());
aLog::print(aLog::Error, tr("aObject update error. Driver message: %1").arg(t->lastError().text()));
return err_updateerror;
}
else {
return err_noerror;
}
}
/*!
*\~english
* Update object attributes from curent selected object database record.
*\~russian
*\~
*//*
void
aObject::updateAttributes( const QString & tname )
{
aDataTable *t = table();
}
*/
/*!
*\~english
* Conduct document.
* Do nothing. Added for wDocument compatibility.
*\~russian
* Проводит документ.
* Ничего не делает. Предназначена для совместимости и работы в wDocument.
*\~
*\return \~english error code - abstract object.\~russian код ошибки - абстрактный обект.\~
*/
int
aObject::Conduct()
{
return err_abstractobj;
}
/*!
*\~english
* UnConduct document.
* Do nothing. Added for wDocument compatibility.
*\~russian
* Распроводит документ.
* Ничего не делает. Предназначена для совместимости и работы в wDocument.
*\~
*\return \~english error code - abstract object.\~russian код ошибки - абстрактный обект.\~
*/
int
aObject::UnConduct()
{
return err_abstractobj;
}
bool
aObject::IsConducted()
{
return 0;
}
/*!
*\~english
* Return document database id.
* always return 0. Added for wJournal compatibility.
*\~russian
* Возвращает id документа в базе данных.
* Всегда возвращает 0. Предназначена для совместимости и работы в wJournal.
*\~
*\return \~english 0.\~russian 0.\~
*/
qulonglong
aObject::docId()
{
return 0;
}
/*!
* \ru
* Позиционирует указатель в БД на запись, соотвествующую объекту
* с указанным идентификатором.
* \param id - Идентификатор объекта.
* \return возвращает код ошибки или 0 в случае успеха.
* \_ru
*/
ERR_Code
aObject::select( qulonglong id )
{
aDataTable * t = table();
if ( !t ) return err_notable;
setSelected (false);
long otype = db->uidType( id );
// debug_message("otype=%li\n",otype);
if ( !otype ) return err_objnotfound;
if ( concrete && ( otype != t->getMdObjId() ) ) return err_incorrecttype;
if ( !concrete )
{
aCfgItem tmpObj = md->find( otype );
if ( tmpObj.isNull() ) return err_objnotfound;
setObject ( tmpObj );
}
if ( t->select( QString("id=%1").arg(id), false ) )
if ( t->first() )
{
// t->primeUpdate();
setSelected (true);
// t->printRecord();
return err_noerror;
}
else return err_notselected;
return err_selecterror;
}
/*!
*
*/
ERR_Code
aObject::select(const QString & query, const QString &tableName)
{
aDataTable * t = table(tableName);
if ( !t ) return err_notable;
if (t->select(query))
if( t->first() )
{
setSelected (true);
return err_noerror;
}
else return err_notselected;
return err_selecterror;
}
/*!
* Return field value of the secondary object database table.
*/
QVariant
aObject::tValue( const QString & tablename, const QString & name )
{
aDataTable *t = table( tablename );
//CHECK_POINT
if ( t ) return t->value( name );
return QVariant("");
}
/*!
* Set field value of the secondary object database table.
*/
ERR_Code
aObject::setTValue( const QString & tablename, const QString & name, const QVariant &value )
{
aDataTable *t = table( tablename );
if ( t )
{
t->setValue( name, value );
return err_noerror;
}
return err_notable;
}
/*!
*
*/
ERR_Code
aObject::decodeDocNum( QString nm, QString & pref, int & num)
{
aLog::print(aLog::Debug, tr("aObject decode doc number %1").arg(nm));
int pos = -1;
for ( uint i = nm.length(); i > 0; i-- )
{
if ( ( nm.at(i-1) >='0' ) && ( nm.at(i-1) <= '9' ) )
continue;
else
{
pos = i;
break;
}
}
if ( pos == -1 )
{
//CHECK_POINT
pref = "";
num = nm.toInt();
return err_incorrectname;
}
if ( pos == ( int ) nm.length() )
{
//CHECK_POINT
pref = nm;
num = -1;
return err_incorrectname;
}
//CHECK_POINT
pref = nm.left( pos );
num = nm.mid(pos).toInt();
aLog::print(aLog::Debug, tr("aObject decode doc number ok, pref=%1 num=%2").arg(pref).arg(num));
return err_noerror;
}
/*!
*
*/
/*
bool
aObject::Next()
{
return table()->next();
// return dbtables[""]->next();
}
*/
/*!
*
*/
/*
bool
aObject::Prev()
{
// return dbtables[""]->prev();
return table()->prev();
}
*/
/*!
*
*/
/*
bool
aObject::First()
{
// return dbtables[""]->first();
return table()->first();
}
*/
/*!
*
*/
/*
bool
aObject::Last()
{
// return dbtables[""]->last();
return table()->last();
}
*/
/*!
*
*/
bool
aObject::Next( const QString& tableName )
{
return table(tableName)->next();
}
/*!
*
*/
bool
aObject::Prev( const QString& tableName )
{
return table(tableName)->prev();
}
/*!
*
*/
bool
aObject::First( const QString& tableName )
{
return table(tableName)->first();
}
/*!
*
*/
bool
aObject::Last( const QString& tableName )
{
return table(tableName)->last();
}
/*!
* \ru
* Возвращает уникальный идентификатор объекта из базы данных.
* В качестве объекта например может выступать "Приходная накладная" от такого-то числа за таким то номером.
* Каждый вновь созданный в системе документ или элемент справочника, включая группы справочника имеет свой уникальный
* неповторяющийся идентификатор. Если какое-либо поле, какого-либо объекта имеет тип Объект (например Document.Накладная),
* то в качестве значения ему нужно задавать уникальный идентификатор объекта, возвращаемый функцией Uid().
* Не существует возможности изменить существующий идентификатор какого-либо объекта. Созданием и управлением
* идентификаторами объектов занимается система.
* \return строка со значением уникального идентификатора.
* \_ru
*/
QString
aObject::Uid()
{
return QString::number(getUid());
}
/*!
*
*/
qulonglong
aObject::getUid()
{
qulonglong Uid = 0;
if ( selected() ) Uid = table()->sysValue("id").toULongLong();
return Uid;
}
/*!
*
*/
void
aObject::setSelected( bool sel, const QString & tablename )
{
if ( tablename == "" ) selectFlag = sel;
else table(tablename)->selected = sel;
}
/*!
*
*/
bool
aObject::selected( const QString & tablename )
{
if ( tablename == "" ) return selectFlag;
else return table(tablename)->selected;
}
/*!
*
*/
ERR_Code
aObject::setTFilter( const QString & tname, const QString & valname, const QVariant & value )
{
aDataTable * t = dbtables[tname];
if ( !t ) return err_notable;
if ( t->setFilter( valname, value ) ) return err_noerror;
else return err_fieldnotfound;
}
/*!
*
*/
ERR_Code
aObject::clearTFilter( const QString & tname )
{
aDataTable * t = dbtables[tname];
if ( !t ) return err_notable;
t->clearFilter();
return err_noerror;
}
/*!
*
*/
int
aObject::SetFilter( const QString & valname, const QVariant & value )
{
int err = setTFilter( "", valname, value );
filtred = !err;
return err;
}
/*!
*
*/
int
aObject::ClearFilter()
{
filtred = false;
return clearTFilter("");
}
/*!
*
*/
int
aObject::TableSetFilter( const QString & tname, const QString & valname, const QVariant & value )
{
return setTFilter( tname, valname, value );
}
/*!
*
*/
int
aObject::TableClearFilter( const QString & tname )
{
return clearTFilter(tname);
}
/*!
* \ru
* Обновляет базу данных данными табличной части объекта. Обычно вызывается
* после метода TableSetValue.
* \param tablename - имя таблицы. Необходим для указания имени, так как
* в объекте возможно наличие нескольких табличных частей.
* \return возвращает код ошибки или 0 в случае успеха.
* \_ru
*/
int
aObject::TableUpdate( const QString & tablename )
{
aDataTable *t = table( tablename );
if ( !t )
{
aLog::print(aLog::Error, tr("aObject table update: no table found with name %1").arg(tablename));
return err_notable;
}
// t->primeUpdate();
t->Update();
if (t->lastError().type())
{
aLog::print(aLog::Error, tr("aObject update error. Driver message: %1").arg(t->lastError().text()));
return err_updateerror;
}
return err_noerror;
}
/*!
*
*/
QString
aObject::displayString()
{
QString res="***";
int stdfc = 0, fid;
aCfgItem sw, f;
sw = displayStringContext();
// if ( md->objClass( obj ) == md_catalogue ) {
// sw = md->find( md->find( obj, md_element ), md_string_view );
// } else {
// sw = md->find( obj, md_string_view );
// }
if ( !sw.isNull() ) {
stdfc = md->attr( sw, mda_stdf ).toInt();
switch ( stdfc ) {
case 0:
fid = md->sText( sw, md_fieldid ).toInt();
res = table()->sysValue( QString( "uf%1" ).arg( fid ) ).toString();
//printf("fid=%i res=%s\n",fid, ( const char *) res );
break;
case 1:
break;
case 2:
break;
}
}
else
{
aLog::print(aLog::Debug, tr("aObject display string context is null"));
}
// res =
return res;
}
aCfgItem
aObject::displayStringContext()
{
return md->find( obj, md_string_view );
}
/**
* \ru
* Вид объекта, так как он описан в метаданных.
* \_ru
*/
QString
aObject::Kind( const QString & name )
{
QString wasKind = md->objClass( obj );
if ( !name.isEmpty() ) {
// Set new kind.
}
return wasKind;
}
| 18.869833 | 123 | 0.633605 | leaderit |
cad3e94e1b59a1fdce02299341fce844a0656a78 | 1,993 | cpp | C++ | Problems/CtCi6thEd/Chapter-3/stackMin.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | 1 | 2021-07-08T01:02:06.000Z | 2021-07-08T01:02:06.000Z | Problems/CtCi6thEd/Chapter-3/stackMin.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | null | null | null | Problems/CtCi6thEd/Chapter-3/stackMin.cpp | pedrotorreao/DSA | 31f9dffbed5275590d5c7b7f6a73fd6dea411564 | [
"MIT"
] | null | null | null | /*********************************************************************************************/
/* Problem: Stack Min (CtCi 3.2) ********/
/*********************************************************************************************/
/*
--Problem statement:
How would you design a stack which, in addition to push and pop, has a function min which
returns the minimum elements? Push, pop and min should all operate in O(1) time.
--Reasoning:
Use two stacks, one to store all the elements and one to keep track of the min values.
--Time complexity:
O(1), operations do not depend on the size of the stack.
--Space complexity:
O(n), in the worst case scenario where the input is made of elements sorted in descending order,
we'd have to store all elements in the second stack.
*/
#include <iostream>
#include <vector>
#include <climits>
#include "stack/stack.h"
class StackMin
{
private:
Stack<int> st_values, st_min;
public:
void push(int value)
{
st_values.push(value);
if (min() >= value)
{
st_min.push(value);
}
}
void pop(void)
{
if (min() == st_values.peek())
{
st_min.pop();
}
st_values.pop();
}
int peek(void)
{
return st_values.peek();
}
int min(void)
{
if (st_min.isEmpty())
{
return INT_MAX;
}
return st_min.peek();
}
StackMin() {}
~StackMin() = default;
};
// driver code:
int main()
{
StackMin st;
std::vector<int> values{11, 5, 3, 9, 23, -2, 47, 1};
for (auto v : values)
{
st.push(v);
}
std::cout << "Min element in the stack: " << st.min() << "\n";
std::cout << "Top element in the stack: " << st.peek() << "\n";
st.pop();
std::cout << "Min element in the stack: " << st.min() << "\n";
std::cout << "Top element in the stack: " << st.peek() << "\n";
st.pop();
st.pop();
std::cout << "Min element in the stack: " << st.min() << "\n";
std::cout << "Top element in the stack: " << st.peek() << "\n";
return 0;
} | 20.760417 | 98 | 0.530858 | pedrotorreao |
cad64800a8364134b661a3cdcf4d3ccc8041f3f3 | 1,080 | cpp | C++ | 2021/04. Conditions/20311006/7. CircleIntercept 2.0/7. CircleIntercept 2.0.cpp | GeorgiIT/CS104 | 7efcc069256dfdb5bc18bd76fbb683edf2cde230 | [
"MIT"
] | 7 | 2021-03-24T16:30:45.000Z | 2022-03-27T09:02:15.000Z | 2021/04. Conditions/20311006/7. CircleIntercept 2.0/7. CircleIntercept 2.0.cpp | GeorgiIT/CS104 | 7efcc069256dfdb5bc18bd76fbb683edf2cde230 | [
"MIT"
] | null | null | null | 2021/04. Conditions/20311006/7. CircleIntercept 2.0/7. CircleIntercept 2.0.cpp | GeorgiIT/CS104 | 7efcc069256dfdb5bc18bd76fbb683edf2cde230 | [
"MIT"
] | 17 | 2021-03-22T09:42:22.000Z | 2022-03-28T03:24:07.000Z | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
float Ax, Ay, Ar, Bx, By, Br;
cout << "Enter first circle [x y r]:" << endl;
cin >> Ax >> Ay >> Ar;
cout << "Enter second circle [x y r]:" << endl;
cin >> Bx >> By >> Br;
float d = sqrt(pow((Ax - Bx), 2) + pow((Ay - By), 2));
float a = (pow(Ar, 2) - pow(Br, 2) + pow(d, 2)) / (2 * d);
float h= sqrt(pow(Ar, 2) - pow(a, 2));
float x = Ax + a * (Bx - Ax) / d;
float y = Ay + a * (By - Ay) / d;
float Cx = x + (By - Ay) * h / d;
float Cy = y - (Bx - Ax) * h / d;
float Dx = x - (By - Ay) * h / d;
float Dy = y + (Bx - Ax) * h / d;
if (Ar + Br < d) cout << "No interception points.";
else if (Ar + Br == d)
{
cout << "One interception point." << endl;
cout << "x = " << x << ", y = " << y << endl;
}
else if (Ar + Br > d)
{
cout << "Two interception points." << endl;
cout << "Cx = " << Cx << ", Cy = " << Cy << endl;
cout << "Dx = " << Dx << ", Dy = " << Dy << endl;
}
return 0;
}
| 31.764706 | 62 | 0.424074 | GeorgiIT |
cad88d7a70ebfce8c460486420008734b51228f4 | 7,388 | cpp | C++ | src/src/state_expresslrs.cpp | cruwaller/FENIX-rx5808-pro-diversity | 6d1c07bde3c0782a599c3a0a40db8dacc522ef6e | [
"MIT"
] | 1 | 2020-08-20T19:58:13.000Z | 2020-08-20T19:58:13.000Z | src/src/state_expresslrs.cpp | cruwaller/FENIX-rx5808-pro-diversity | 6d1c07bde3c0782a599c3a0a40db8dacc522ef6e | [
"MIT"
] | null | null | null | src/src/state_expresslrs.cpp | cruwaller/FENIX-rx5808-pro-diversity | 6d1c07bde3c0782a599c3a0a40db8dacc522ef6e | [
"MIT"
] | null | null | null | #include <stdint.h>
#include "settings_eeprom.h"
#include "state_expresslrs.h"
#include "ui.h"
#include "temperature.h"
#include "touchpad.h"
#include "comm_espnow.h"
#include "protocol_ExpressLRS.h"
void StateMachine::ExLRSStateHandler::onEnter()
{
//onUpdateDraw(false);
}
void StateMachine::ExLRSStateHandler::onUpdate()
{
onUpdateDraw(TouchPad::touchData.buttonPrimary);
}
void StateMachine::ExLRSStateHandler::onUpdateDraw(uint8_t tapAction)
{
uint32_t off_x = 20, off_x2 = off_x + 17 * Ui::CHAR_W, off_y = 20;
int16_t cursor_x = TouchPad::touchData.cursorX, cursor_y = TouchPad::touchData.cursorY;
uint8_t region = expresslrs_params_get_region();
if (drawHeader())
return;
// Mode
Ui::display.setCursor(off_x, off_y);
Ui::display.print("Mode (Hz):");
Ui::display.setCursor(off_x2, off_y);
if (region == 3)
Ui::display.print("50 125 250");
else
Ui::display.print("50 100 200");
off_y += 20;
// RF Power
Ui::display.setCursor(off_x, off_y);
Ui::display.print("Power (mW):");
Ui::display.setCursor(off_x2, off_y);
Ui::display.print("25 50 100");
off_y += 20;
// TLM Rate
Ui::display.setCursor(off_x, off_y);
Ui::display.print("Telemetry:");
Ui::display.setCursor(off_x2, off_y);
Ui::display.print("On Off");
off_y += 20;
// Set VTX channel
Ui::display.setCursor(off_x, off_y);
Ui::display.print("VTX channel:");
Ui::display.setCursor(off_x2, off_y);
Ui::display.print("SEND");
off_y += 20;
/*************************************/
// Print current settings
off_y += 20;
Ui::display.setCursor(off_x, off_y);
Ui::display.print("== Current settings ==");
off_y += 12;
off_x = 40;
off_x2 = off_x + 100;
Ui::display.setCursor(off_x, off_y);
Ui::display.print("Frequency:");
Ui::display.setCursor(off_x2, off_y);
switch (expresslrs_params_get_region()) {
case 0:
Ui::display.print("915MHz");
break;
case 1:
Ui::display.print("868MHz");
break;
case 2:
Ui::display.print("433MHz");
break;
case 3:
Ui::display.print("2.4GHz");
break;
default:
Ui::display.print("---");
break;
};
off_y += 10;
Ui::display.setCursor(off_x, off_y);
Ui::display.print("Rate:");
Ui::display.setCursor(off_x2, off_y);
switch (expresslrs_params_get_rate()) {
case 0:
Ui::display.print((region == 3) ? "250Hz" : "200Hz");
break;
case 1:
Ui::display.print((region == 3) ? "125Hz" : "100Hz");
break;
case 2:
Ui::display.print("50Hz");
break;
default:
Ui::display.print("---");
break;
};
off_y += 10;
Ui::display.setCursor(off_x, off_y);
Ui::display.print("Power:");
Ui::display.setCursor(off_x2, off_y);
switch (expresslrs_params_get_power()) {
case 0:
Ui::display.print("dynamic");
break;
case 1:
Ui::display.print("10mW");
break;
case 2:
Ui::display.print("25mW");
break;
case 3:
Ui::display.print("50mW");
break;
case 4:
Ui::display.print("100mW");
break;
case 5:
Ui::display.print("250mW");
break;
case 6:
Ui::display.print("500mW");
break;
case 7:
Ui::display.print("1000mW");
break;
case 8:
Ui::display.print("2000mW");
break;
default:
Ui::display.print("---");
break;
};
off_y += 10;
Ui::display.setCursor(off_x, off_y);
Ui::display.print("Telemetry:");
Ui::display.setCursor(off_x2, off_y);
switch (expresslrs_params_get_tlm()) {
case 0:
Ui::display.print("OFF");
break;
case 1:
Ui::display.print("1/128");
break;
case 2:
Ui::display.print("1/64");
break;
case 3:
Ui::display.print("1/32");
break;
case 4:
Ui::display.print("1/16");
break;
case 5:
Ui::display.print("1/8");
break;
case 6:
Ui::display.print("1/4");
break;
case 7:
Ui::display.print("1/2");
break;
default:
Ui::display.print("---");
break;
};
// Draw Mode box
if (cursor_y > 16 && cursor_y < 31)
{
if ( // 50
cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 19 * 8 + 3))
{
Ui::display.rect(20 + 17 * 8 - 4, 16, 23, 15, 100);
if (tapAction)
expresslrs_rate_send(ExLRS_50Hz);
}
else if ( // 100
cursor_x > (20 + 23 * 8 - 4) && cursor_x < (20 + 26 * 8 + 3))
{
Ui::display.rect(20 + 23 * 8 - 4, 16, 31, 15, 100);
if (tapAction)
expresslrs_rate_send(ExLRS_100Hz);
}
else if ( // 200
cursor_x > (20 + 30 * 8 - 4) && cursor_x < (20 + 33 * 8 + 3))
{
Ui::display.rect(20 + 30 * 8 - 4, 16, 31, 15, 100);
if (tapAction)
expresslrs_rate_send(ExLRS_200Hz);
}
}
// Draw RF Power box
else if (cursor_y > 36 && cursor_y < 51)
{
if ( // 25mW
cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 19 * 8 + 3))
{
Ui::display.rect(20 + 17 * 8 - 4, 36, 23, 15, 100);
if (tapAction)
expresslrs_power_send(ExLRS_PWR_25mW);
}
else if ( // 50mW
cursor_x > (20 + 23 * 8 - 4) && cursor_x < (20 + 25 * 8 + 3))
{
Ui::display.rect(20 + 23 * 8 - 4, 36, 23, 15, 100);
if (tapAction)
expresslrs_power_send(ExLRS_PWR_50mW);
}
else if ( // 100mW
cursor_x > (20 + 30 * 8 - 4) && cursor_x < (20 + 33 * 8 + 3))
{
Ui::display.rect(20 + 30 * 8 - 4, 36, 31, 15, 100);
if (tapAction)
expresslrs_power_send(ExLRS_PWR_100mW);
}
}
// Draw TLM box
else if (cursor_y > 56 && cursor_y < 71)
{
if ( // On
cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 19 * 8 + 3))
{
Ui::display.rect(20 + 17 * 8 - 4, 56, 23, 15, 100);
if (tapAction)
expresslrs_tlm_send(ExLRS_TLM_ON);
}
else if ( // Off
cursor_x > (20 + 23 * 8 - 4) && cursor_x < (20 + 26 * 8 + 3))
{
Ui::display.rect(20 + 23 * 8 - 4, 56, 31, 15, 100);
if (tapAction)
expresslrs_tlm_send(ExLRS_TLM_OFF);
}
}
// Draw VTX SEND box
else if (cursor_y > 76 && cursor_y < 91)
{
if (cursor_x > (20 + 17 * 8 - 4) && cursor_x < (20 + 21 * 8 + 3))
{
Ui::display.rect((20 + 17 * 8 - 4), 76, (4 + 4 * 8 + 3), 15, 100);
if (tapAction)
expresslrs_vtx_freq_send(Channels::getFrequency(Receiver::activeChannel));
}
}
}
| 27.774436 | 91 | 0.479561 | cruwaller |
cadd46c3909b89e1617961c273435bb98b73f88f | 5,703 | cpp | C++ | src/Webinaria/Grabber.cpp | mkmpvtltd1/Webinaria | 41d86467800adb48e77ab49b92891fae2a99bb77 | [
"MIT"
] | 5 | 2015-03-31T15:51:22.000Z | 2022-03-10T07:01:56.000Z | src/Webinaria/Grabber.cpp | mkmpvtltd1/Webinaria | 41d86467800adb48e77ab49b92891fae2a99bb77 | [
"MIT"
] | null | null | null | src/Webinaria/Grabber.cpp | mkmpvtltd1/Webinaria | 41d86467800adb48e77ab49b92891fae2a99bb77 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "Grabber.h"
using namespace WebinariaApplication::WebinariaLogical;
//////////////////////////////////////////////////////////////////////////
// Public methods //
//////////////////////////////////////////////////////////////////////////
// Default constructor
CGrabber::CGrabber(HWND hWnd): AllocateBytes(0),
IsCapturing(false),
File(NULL),
hMainWnd(hWnd),
pME(NULL),
pDF(NULL),
pVW(NULL),
pRender(NULL),
pSink(NULL),
//////////////////////
ghDevNotify(0),
gpUnregisterDeviceNotification(0),
gpRegisterDeviceNotification(0),
g_dwGraphRegister(0)
//////////////////////
{
/*File = new wchar_t[10];
WIN32_FIND_DATA fd;
HANDLE hr = FindFirstFile("tmp",&fd);
FindClose(hr);
if (hr == INVALID_HANDLE_VALUE)
CreateDirectory("tmp",NULL);
else
{
hr = FindFirstFile("tmp\\~.avi",&fd);
if ( hr != INVALID_HANDLE_VALUE)
DeleteFile("tmp\\~.avi");
FindClose(hr);
}
wcscpy(File, L"tmp\\~.avi");*/
//\\tmp
// Register for device add/remove notifications
DEV_BROADCAST_DEVICEINTERFACE filterData;
ZeroMemory(&filterData, sizeof(DEV_BROADCAST_DEVICEINTERFACE));
filterData.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
filterData.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
filterData.dbcc_classguid = AM_KSCATEGORY_CAPTURE;
gpUnregisterDeviceNotification = NULL;
gpRegisterDeviceNotification = NULL;
// dynload device removal APIs
{
HMODULE hmodUser = GetModuleHandle(TEXT("user32.dll"));
//ASSERT(hmodUser); // we link to user32
gpUnregisterDeviceNotification = (PUnregisterDeviceNotification)
GetProcAddress(hmodUser, "UnregisterDeviceNotification");
// m_pRegisterDeviceNotification is prototyped differently in unicode
gpRegisterDeviceNotification = (PRegisterDeviceNotification)
GetProcAddress(hmodUser,
#ifdef UNICODE
"RegisterDeviceNotificationW"
#else
"RegisterDeviceNotificationA"
#endif
);
// failures expected on older platforms.
/*ASSERT(gpRegisterDeviceNotification && gpUnregisterDeviceNotification ||
!gpRegisterDeviceNotification && !gpUnregisterDeviceNotification);*/
}
ghDevNotify = NULL;
if(gpRegisterDeviceNotification)
{
ghDevNotify = gpRegisterDeviceNotification(hMainWnd, &filterData, DEVICE_NOTIFY_WINDOW_HANDLE);
//ASSERT(ghDevNotify != NULL);
}
}
// Virtual destructor
CGrabber::~CGrabber(void)
{
if (File != NULL)
delete[] File;
IsCapturing = false;
AllocateBytes = 0;
SAFE_RELEASE(pSink);
SAFE_RELEASE(pME);
SAFE_RELEASE(pDF);
SAFE_RELEASE(pVW);
SAFE_RELEASE(pRender);
}
// Get interface for provide media events
IMediaEventEx * CGrabber::GetMediaEventInterface()
{
return pME;
}
// Return full path to current file for captured data
wchar_t * CGrabber::GetSelectFile() const
{
wchar_t * tmp = new wchar_t[wcslen(File)+1];
wcscpy(tmp,File);
return tmp;
}
// Update and retrive current capturing file size
unsigned long long CGrabber::GetCapFileSize()
{
HANDLE hFile = CreateFileW( File,
GENERIC_READ,
FILE_SHARE_READ,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0 );
if(hFile == INVALID_HANDLE_VALUE)
{
return 0;
}
unsigned long SizeHigh;
unsigned long SizeLow = GetFileSize(hFile, &SizeHigh);
CapFileSize = SizeLow + ((unsigned long long)SizeHigh << 32);
if(!CloseHandle(hFile))
{
CapFileSize = 0;
}
return CapFileSize;
}
// Function to Measure Available Disk Space
unsigned long long CGrabber::GetFreeDiskSpaceInBytes()
{
DWORD dwFreeClusters, dwBytesPerSector, dwSectorsPerCluster, dwClusters;
wchar_t RootName[MAX_PATH];
LPWSTR ptmp=0; // Required argument
ULARGE_INTEGER ulA, ulB, ulFreeBytes;
// Need to find path for root directory on drive containing this file.
GetFullPathNameW( File, NUMELMS(RootName), RootName, &ptmp);
// Truncate this to the name of the root directory
if(RootName[0] == '\\' && RootName[1] == '\\')
{
// Path begins with \\server\share\path so skip the first three backslashes
ptmp = &RootName[2];
while(*ptmp && (*ptmp != '\\'))
{
ptmp++;
}
if(*ptmp)
{
// Advance past the third backslash
ptmp++;
}
}
else
{
// Path must be drv:\path
ptmp = RootName;
}
// Find next backslash and put a null after it
while(*ptmp && (*ptmp != '\\'))
{
ptmp++;
}
// Found a backslash ?
if(*ptmp)
{
// Skip it and insert null
ptmp++;
*ptmp = '\0';
}
// The only real way of finding out free disk space is calling
// GetDiskFreeSpaceExA, but it doesn't exist on Win95
HINSTANCE h = LoadLibrary(TEXT("kernel32.dll\0"));
if(h)
{
typedef BOOL(WINAPI *ExtFunc)(LPCWSTR RootName, PULARGE_INTEGER pulA, PULARGE_INTEGER pulB, PULARGE_INTEGER pulFreeBytes);
ExtFunc pfnGetDiskFreeSpaceExW = (ExtFunc)GetProcAddress(h, "GetDiskFreeSpaceExW");
FreeLibrary(h);
if(pfnGetDiskFreeSpaceExW)
{
if(!pfnGetDiskFreeSpaceExW(RootName, &ulA, &ulB, &ulFreeBytes))
return -1;
else
return (ulFreeBytes.QuadPart);
}
}
if(!GetDiskFreeSpaceW(RootName, &dwSectorsPerCluster, &dwBytesPerSector, &dwFreeClusters, &dwClusters))
return (-1);
else
return(dwSectorsPerCluster * dwBytesPerSector * dwFreeClusters);
}
// Function for select file for saving captured information
bool CGrabber::SelectFile()
{
USES_CONVERSION;
if(OpenFileDialog())
{
OFSTRUCT os;
// We have a capture file name
// If this is a new file, then invite the user to allocate some space
if(OpenFile(W2A(File), &os, OF_EXIST) == HFILE_ERROR)
{
//nothing
}
}
else
return false;
if(pSink)
{
HRESULT hr = pSink->SetFileName(File, NULL);
}
return true;
}
| 23.861925 | 124 | 0.676311 | mkmpvtltd1 |
cadd8abc4d2c83c0b3b3aefd622051866e31a55b | 3,236 | cpp | C++ | src/proofnetwork/user.cpp | DmitryNesterenok/proofbase | acd8e9420ddbd33d0ed933060e6082477cce1f0a | [
"BSD-3-Clause"
] | null | null | null | src/proofnetwork/user.cpp | DmitryNesterenok/proofbase | acd8e9420ddbd33d0ed933060e6082477cce1f0a | [
"BSD-3-Clause"
] | null | null | null | src/proofnetwork/user.cpp | DmitryNesterenok/proofbase | acd8e9420ddbd33d0ed933060e6082477cce1f0a | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2018, OpenSoft Inc.
* 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 OpenSoft 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.
*
*/
#include "proofnetwork/user.h"
#include "proofnetwork/user_p.h"
using namespace Proof;
User::User(const QString &userName) : User(*new UserPrivate(userName))
{}
User::User(Proof::UserPrivate &dd) : NetworkDataEntity(dd)
{}
QString User::userName() const
{
Q_D_CONST(User);
return d->userName;
}
QString User::fullName() const
{
Q_D_CONST(User);
return d->fullName;
}
QString User::email() const
{
Q_D_CONST(User);
return d->email;
}
UserQmlWrapper *User::toQmlWrapper(QObject *parent) const
{
UserSP castedSelf = castedSelfPtr<User>();
Q_ASSERT(castedSelf);
return new UserQmlWrapper(castedSelf, parent);
}
UserSP User::create(const QString &userName)
{
UserSP result(new User(userName));
initSelfWeakPtr(result);
return result;
}
UserPrivate::UserPrivate(const QString &userName) : userName(userName)
{
setDirty(!userName.isEmpty());
}
void User::updateSelf(const NetworkDataEntitySP &other)
{
Q_D(User);
UserSP castedOther = qSharedPointerCast<User>(other);
d->setUserName(castedOther->userName());
d->setFullName(castedOther->fullName());
d->setEmail(castedOther->email());
NetworkDataEntity::updateSelf(other);
}
void UserPrivate::setUserName(const QString &arg)
{
Q_Q(User);
if (userName != arg) {
userName = arg;
emit q->userNameChanged(arg);
}
}
void UserPrivate::setFullName(const QString &arg)
{
Q_Q(User);
if (fullName != arg) {
fullName = arg;
emit q->fullNameChanged(arg);
}
}
void UserPrivate::setEmail(const QString &arg)
{
Q_Q(User);
if (email != arg) {
email = arg;
emit q->emailChanged(arg);
}
}
| 29.153153 | 101 | 0.717862 | DmitryNesterenok |
cadedb4dec156252ce1748b4dac7cd5f88a358c1 | 416 | hpp | C++ | lib/kernel/src/kernel/stacksize.hpp | daantimmer/dtos | 20b1e8463983394296690131ad0fb77a32e05574 | [
"MIT"
] | 1 | 2020-05-31T22:49:39.000Z | 2020-05-31T22:49:39.000Z | lib/kernel/src/kernel/stacksize.hpp | daantimmer/dtos | 20b1e8463983394296690131ad0fb77a32e05574 | [
"MIT"
] | 1 | 2022-01-03T23:55:34.000Z | 2022-01-03T23:55:34.000Z | lib/kernel/src/kernel/stacksize.hpp | daantimmer/dtos | 20b1e8463983394296690131ad0fb77a32e05574 | [
"MIT"
] | null | null | null | #pragma once
#include "type_safe/strong_typedef.hpp"
#include <cstddef>
namespace kernel
{
struct StackSize_t
: type_safe::strong_typedef<StackSize_t, std::size_t>
, type_safe::strong_typedef_op::addition<StackSize_t>
, type_safe::strong_typedef_op::subtraction<StackSize_t>
{
using type_safe::strong_typedef<StackSize_t, std::size_t>::strong_typedef;
};
} | 27.733333 | 83 | 0.689904 | daantimmer |
cadf4fd3b8d50e506571832aae0832c4a8c3391b | 7,228 | cpp | C++ | Src/OpenGL/Shapes/GLOpenAssetImportMesh.cpp | StavrosBizelis/NetworkDistributedDeferredShading | 07c03ce9b13bb5adb164cd4321b2bba284e49b4d | [
"MIT"
] | null | null | null | Src/OpenGL/Shapes/GLOpenAssetImportMesh.cpp | StavrosBizelis/NetworkDistributedDeferredShading | 07c03ce9b13bb5adb164cd4321b2bba284e49b4d | [
"MIT"
] | null | null | null | Src/OpenGL/Shapes/GLOpenAssetImportMesh.cpp | StavrosBizelis/NetworkDistributedDeferredShading | 07c03ce9b13bb5adb164cd4321b2bba284e49b4d | [
"MIT"
] | null | null | null | /***********************************************************************
* AUTHOR: <Doublecross>
* FILE: GLOpenAssetImportMesh.cpp
* DATE: Mon Jun 11 16:21:07 2018
* DESCR:
***********************************************************************/
#include "OpenGL/Shapes/GLOpenAssetImportMesh.h"
#include <assert.h>
#include "gl/include/glew.h"
#include "gl/gl.h"
#include <windows.h>
GLOpenAssetImportMesh::MeshEntry::MeshEntry()
{
vbo = INVALID_OGL_VALUE;
ibo = INVALID_OGL_VALUE;
NumIndices = 0;
MaterialIndex = INVALID_MATERIAL;
};
GLOpenAssetImportMesh::MeshEntry::~MeshEntry()
{
if (vbo != INVALID_OGL_VALUE)
glDeleteBuffers(1, &vbo);
if (ibo != INVALID_OGL_VALUE)
glDeleteBuffers(1, &ibo);
}
void GLOpenAssetImportMesh::MeshEntry::Init(const std::vector<Vertex>& Vertices,
const std::vector<unsigned int>& Indices)
{
NumIndices = Indices.size();
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * Vertices.size(), &Vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * NumIndices, &Indices[0], GL_STATIC_DRAW);
}
/*
* Method: GLOpenAssetImportMesh::Load
* Params: const std::string &Filename
* Returns: bool
* Effects:
*/
bool
GLOpenAssetImportMesh::Load(const std::string &Filename)
{
// Release the previously loaded mesh (if it exists)
Release();
bool Ret = false;
Assimp::Importer Importer;
const aiScene* pScene = Importer.ReadFile(Filename.c_str(), aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
if (pScene) {
Ret = InitFromScene(pScene, Filename);
}
else {
MessageBox(NULL, Importer.GetErrorString(), "Error loading mesh model", MB_ICONHAND);
}
return Ret;
}
std::shared_ptr<ITexture> GLOpenAssetImportMesh::GetTexture()
{
if (1 < m_Textures.size() && m_Textures[1])
return m_Textures[1];
return nullptr;
}
void GLOpenAssetImportMesh::Clear()
{
//for (unsigned int i = 0 ; i < m_Textures.size() ; i++) {
// SAFE_DELETE(m_Textures[i]);
//}
glDeleteVertexArrays(1, &m_vao);
m_Entries.clear();
m_Textures.clear();
}
/*
* Method: GLOpenAssetImportMesh::Create
* Params:
* Returns: void
* Effects:
*/
void
GLOpenAssetImportMesh::Create()
{
}
/*
* Method: GLOpenAssetImportMesh::Render
* Params:
* Returns: void
* Effects:
*/
void
GLOpenAssetImportMesh::Render()
{
glBindVertexArray(m_vao);
for (unsigned int i = 0 ; i < m_Entries.size() ; i++) {
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, m_Entries[i].vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)20);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)32);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_Entries[i].ibo);
glDrawElements(GL_TRIANGLES, m_Entries[i].NumIndices, GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
}
}
/*
* Method: GLOpenAssetImportMesh::Release
* Params:
* Returns: void
* Effects:
*/
void
GLOpenAssetImportMesh::Release()
{
if( m_vao != 0)
{
glDeleteVertexArrays(1, &m_vao);
m_vao = 0;
}
}
bool GLOpenAssetImportMesh::InitFromScene(const aiScene* pScene, const std::string& Filename)
{
m_Entries.resize(pScene->mNumMeshes);
m_Textures.resize(pScene->mNumMaterials);
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
// Initialize the meshes in the scene one by one
for (unsigned int i = 0 ; i < m_Entries.size() ; i++) {
const aiMesh* paiMesh = pScene->mMeshes[i];
InitMesh(i, paiMesh);
}
return InitMaterials(pScene, Filename);
}
void GLOpenAssetImportMesh::InitMesh(unsigned int Index, const aiMesh* paiMesh)
{
m_Entries[Index].MaterialIndex = paiMesh->mMaterialIndex;
std::vector<Vertex> Vertices;
std::vector<unsigned int> Indices;
const aiVector3D Zero3D(0.0f, 0.0f, 0.0f);
for (unsigned int i = 0 ; i < paiMesh->mNumVertices ; i++) {
const aiVector3D* pPos = &(paiMesh->mVertices[i]);
const aiVector3D* pNormal = &(paiMesh->mNormals[i]);
const aiVector3D* pTexCoord = paiMesh->HasTextureCoords(0) ? &(paiMesh->mTextureCoords[0][i]) : &Zero3D;
const aiVector3D* pTangent = paiMesh->HasTangentsAndBitangents() ? &(paiMesh->mTangents[i]) : &Zero3D;
Vertex v(glm::vec3(pPos->x, pPos->y, pPos->z),
glm::vec2(pTexCoord->x, 1.0f-pTexCoord->y),
glm::vec3(pNormal->x, pNormal->y, pNormal->z),
glm::vec3(pTangent->x, pTangent->y, pTangent->z)
);
Vertices.push_back(v);
}
for (unsigned int i = 0 ; i < paiMesh->mNumFaces ; i++) {
const aiFace& Face = paiMesh->mFaces[i];
assert(Face.mNumIndices == 3);
Indices.push_back(Face.mIndices[0]);
Indices.push_back(Face.mIndices[1]);
Indices.push_back(Face.mIndices[2]);
}
m_Entries[Index].Init(Vertices, Indices);
}
bool GLOpenAssetImportMesh::InitMaterials(const aiScene* pScene, const std::string& Filename)
{
// Extract the directory part from the file name
std::string::size_type SlashIndex = Filename.find_last_of("\\");
std::string Dir;
if (SlashIndex == std::string::npos) {
Dir = ".";
}
else if (SlashIndex == 0) {
Dir = "\\";
}
else {
Dir = Filename.substr(0, SlashIndex);
}
bool Ret = true;
// Initialize the materials
for (unsigned int i = 0 ; i < pScene->mNumMaterials ; i++) {
const aiMaterial* pMaterial = pScene->mMaterials[i];
m_Textures[i] = NULL;
if (pMaterial->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
aiString Path;
if (pMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS)
{
std::string FullPath = Dir + "\\" + Path.data;
m_Textures[i] = std::make_shared<GLTexture>();
if (!m_Textures[i]->Load(FullPath, true)) {
MessageBox(NULL, FullPath.c_str(), "Error loading mesh texture", MB_ICONHAND);
// delete m_Textures[i];
m_Textures[i] = NULL;
Ret = false;
}
else {
printf("Loaded texture '%s'\n", FullPath.c_str());
}
}
}
// Load a single colour texture matching the diffuse colour if no texture added
if (!m_Textures[i]) {
aiColor3D color (0.f,0.f,0.f);
pMaterial->Get(AI_MATKEY_COLOR_DIFFUSE,color);
m_Textures[i] = std::make_shared<GLTexture>();
char data[3];
data[0] = (char) (color[2]*255);
data[1] = (char) (color[1]*255);
data[2] = (char) (color[0]*255);
m_Textures[i]->CreateFromData(data, 1, 1, 24, false);
}
}
return Ret;
}
| 26.671587 | 163 | 0.642778 | StavrosBizelis |
cadf83d04a50f806791698ba7f714e12ae0b80dd | 1,229 | hxx | C++ | Legolas/Matrix/tst/PoissonEquation2DTT/LaplacianMatrixDefinition.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/tst/PoissonEquation2DTT/LaplacianMatrixDefinition.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/tst/PoissonEquation2DTT/LaplacianMatrixDefinition.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | 1 | 2021-02-11T14:43:25.000Z | 2021-02-11T14:43:25.000Z | /**
* project DESCARTES
*
* @file LaplacianMatrixDefinition.hxx
*
* @author Laurent PLAGNE
* @date june 2004 - january 2005
*
* @par Modifications
* - author date object
*
* (c) Copyright EDF R&D - CEA 2001-2005
*/
#ifndef __LEGOLAS_LAPLACIANMATRIXDEFINITION_HXX__
#define __LEGOLAS_LAPLACIANMATRIXDEFINITION_HXX__
#include "Legolas/Matrix/MatrixStructures/MatrixStructureTags.hxx"
#include "Legolas/Matrix/Helper/DefaultMatrixDefinition.hxx"
class LaplacianMatrixDefinition : public Legolas::DefaultMatrixDefinition<double> {
public:
// Types that must be defined to model the MATRIX_DEFINITION concept
typedef Legolas::TriDiagonal MatrixStructure;
typedef double RealType;
typedef double GetElement;
typedef Legolas::MatrixShape<1> Data;
// 3 static functions to be defined to model the TRIDIAGONAL_MATRIX_DEFINITION concept
static inline GetElement diagonalGetElement( int i , const Data & data) { return -2.0;}
static inline GetElement upperDiagonalGetElement( int i , const Data & data) { return 1.0;}
static inline GetElement lowerDiagonalGetElement( int i , const Data & data) { return 1.0;}
};
#endif
| 27.931818 | 93 | 0.71847 | LaurentPlagne |
cae654e9332356a12d0a2c043548f0c35e29f5cc | 2,446 | cpp | C++ | templates/bcc_node.cpp | ssstare/icpc | 4f0ed7b045297459a6abfd880e0b995124af4bd0 | [
"MIT"
] | 7 | 2021-03-30T06:19:09.000Z | 2022-03-27T12:50:36.000Z | templates/bcc_node.cpp | ssstare/icpc | 4f0ed7b045297459a6abfd880e0b995124af4bd0 | [
"MIT"
] | null | null | null | templates/bcc_node.cpp | ssstare/icpc | 4f0ed7b045297459a6abfd880e0b995124af4bd0 | [
"MIT"
] | null | null | null | const int kN = 10000 + 5;
const int kM = 100000 + 5;
int dfn[kN],low[kN],head[kN],etot,btot,n,m,nq,belong[kN];
bool is_cut[kN],visited[kN];
std::stack<int> stack;
struct Edge {
int v,next,belong;
bool visited,is_cut;
}g[kM<<1];
std::vector<int> graph[kN+kM];
void add_edge(int u,int v) {
g[etot].belong = -1; g[etot].visited = g[etot].is_cut = false;
g[etot].v = v; g[etot].next = head[u]; head[u] = etot ++;
}
void tarjan(int u,int root,int tim) {
dfn[u] = low[u] = tim;
visited[u] = true;
int child_count = 0;
for (int i = head[u]; i != -1; i = g[i].next) {
Edge &e = g[i];
if (e.visited) continue;
stack.push(i);
g[i].visited = g[i^1].visited = true;
if (visited[e.v]) {
low[u] = std::min(low[u],dfn[e.v]);
continue;
}
tarjan(e.v,root,tim+1);
g[i].is_cut = g[i^1].is_cut = (low[e.v]>dfn[u] || g[i].is_cut);
if (u!=root) is_cut[u] |= (low[e.v]>=dfn[u]);
if (low[e.v]>=dfn[u] || u==root) {
while (true) {
int id = stack.top(); stack.pop();
g[id].belong = g[id^1].belong = btot;
if (id==i) break;
}
btot ++;
}
low[u] = std::min(low[e.v],low[u]);
child_count ++;
}
if (u==root && child_count>1) is_cut[u] = true;
}
void bcc() {
for (int i = 0; i < n; ++ i) {
dfn[i] = 0;
is_cut[i] = false;
visited[i] = false;
}
btot = 0;
for (int i = 0; i < n; ++ i) {
if (!visited[i]) {
tarjan(i,i,1);
}
}
}
void build() {
std::fill(graph,graph+n+m,std::vector<int>());
for (int u = 0; u < n; ++ u) {
if (is_cut[u] || head[u]==-1) {
int id = btot ++;
belong[u] = id;
for (int i = head[u]; i != -1; i = g[i].next) {
Edge &e = g[i];
int v = e.belong;
graph[id].push_back(v);
graph[v].push_back(id);
}
}
}
for (int u = 0; u < btot; ++ u) {
std::sort(graph[u].begin(),graph[u].end());
graph[u].erase(std::unique(graph[u].begin(),graph[u].end()),graph[u].end());
}
for (int i = 0; i < m; ++ i) {
int u = g[i<<1].v;
int v = g[i<<1|1].v;
if (!is_cut[u]) belong[u] = g[i<<1].belong;
if (!is_cut[v]) belong[v] = g[i<<1].belong;
}
}
int main() {
while (scanf("%d%d",&n,&m)==2) {
std::fill(head,head+n,-1); etot = 0;
for (int i = 0; i < m; ++ i) {
int a,b;
scanf("%d%d",&a,&b); a --; b --;
add_edge(a,b);
add_edge(b,a);
}
bcc();
build();
}
return 0;
}
| 23.747573 | 80 | 0.481194 | ssstare |
cae84a603c57abf08c19870047ccb549991766cb | 1,962 | cpp | C++ | theforgottenserver/rsa.cpp | eclipse606/TFS-Exclusive-0.5.2 | beb8e40341f97933b0f42bc43fe7579b14723adc | [
"Unlicense"
] | null | null | null | theforgottenserver/rsa.cpp | eclipse606/TFS-Exclusive-0.5.2 | beb8e40341f97933b0f42bc43fe7579b14723adc | [
"Unlicense"
] | null | null | null | theforgottenserver/rsa.cpp | eclipse606/TFS-Exclusive-0.5.2 | beb8e40341f97933b0f42bc43fe7579b14723adc | [
"Unlicense"
] | 1 | 2022-01-18T01:08:43.000Z | 2022-01-18T01:08:43.000Z | /**
* The Forgotten Server - a free and open-source MMORPG server emulator
* Copyright (C) 2016 Mark Samman <[email protected]>
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "otpch.h"
#include "rsa.h"
RSA::RSA()
{
mpz_init(n);
mpz_init2(d, 1024);
}
RSA::~RSA()
{
mpz_clear(n);
mpz_clear(d);
}
void RSA::setKey(const char* pString, const char* qString)
{
mpz_t p, q, e;
mpz_init2(p, 1024);
mpz_init2(q, 1024);
mpz_init(e);
mpz_set_str(p, pString, 10);
mpz_set_str(q, qString, 10);
// e = 65537
mpz_set_ui(e, 65537);
// n = p * q
mpz_mul(n, p, q);
mpz_t p_1, q_1, pq_1;
mpz_init2(p_1, 1024);
mpz_init2(q_1, 1024);
mpz_init2(pq_1, 1024);
mpz_sub_ui(p_1, p, 1);
mpz_sub_ui(q_1, q, 1);
// pq_1 = (p -1)(q - 1)
mpz_mul(pq_1, p_1, q_1);
// d = e^-1 mod (p - 1)(q - 1)
mpz_invert(d, e, pq_1);
mpz_clear(p_1);
mpz_clear(q_1);
mpz_clear(pq_1);
mpz_clear(p);
mpz_clear(q);
mpz_clear(e);
}
void RSA::decrypt(char* msg) const
{
mpz_t c, m;
mpz_init2(c, 1024);
mpz_init2(m, 1024);
mpz_import(c, 128, 1, 1, 0, 0, msg);
// m = c^d mod n
mpz_powm(m, c, d, n);
size_t count = (mpz_sizeinbase(m, 2) + 7) / 8;
memset(msg, 0, 128 - count);
mpz_export(msg + (128 - count), nullptr, 1, 1, 0, 0, m);
mpz_clear(c);
mpz_clear(m);
}
| 20.87234 | 74 | 0.662589 | eclipse606 |
caf2bc15a7f3e198804f3348a3325093db8435bc | 12,547 | cpp | C++ | duilib/Control/List.cpp | colinjiang007/NIM_Duilib_Mini | d3784824b15c812787dd19c652db817b2793b265 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | duilib/Control/List.cpp | colinjiang007/NIM_Duilib_Mini | d3784824b15c812787dd19c652db817b2793b265 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | duilib/Control/List.cpp | colinjiang007/NIM_Duilib_Mini | d3784824b15c812787dd19c652db817b2793b265 | [
"BSD-2-Clause",
"MIT"
] | null | null | null | #include "StdAfx.h"
namespace ui
{
ListBox::ListBox(Layout* pLayout) :
ScrollableBox(pLayout),
m_bScrollSelect(false),
m_iCurSel(-1),
m_pCompareFunc(nullptr),
m_pCompareData(NULL),
m_bSelNextWhenRemoveActive(true)
{
}
void ListBox::SetAttribute(LPCTSTR szName, LPCTSTR szValue)
{
CUiString strName(szName);
CUiString strValue(szValue);
if( strName == _T("scrollselect") ) {
SetScrollSelect(strValue == _T("true"));
}
else {
ScrollableBox::SetAttribute(szName, szValue);
}
}
void ListBox::HandleMessage(EventArgs& event)
{
if (!IsMouseEnabled() && event.Type > kEventMouseBegin && event.Type < kEventMouseEnd) {
if (m_pParent != NULL) m_pParent->HandleMessageTemplate(event);
else ScrollableBox::HandleMessage(event);
return;
}
switch (event.Type) {
case kEventMouseButtonDown:
case kEventMouseButtonUp:
return;
case kEventKeyDown:
switch (event.chKey) {
case VK_UP:
SelectItem(FindSelectable(m_iCurSel - 1, false), true);
return;
case VK_DOWN:
SelectItem(FindSelectable(m_iCurSel + 1, true), true);
return;
case VK_HOME:
SelectItem(FindSelectable(0, false), true);
return;
case VK_END:
SelectItem(FindSelectable(GetCount() - 1, true), true);
return;
}
break;
case kEventMouseScrollWheel:
{
int detaValue = event.wParam;
if (detaValue > 0) {
if (m_bScrollSelect) {
SelectItem(FindSelectable(m_iCurSel - 1, false), true);
return;
}
break;
}
else {
if (m_bScrollSelect) {
SelectItem(FindSelectable(m_iCurSel + 1, true), true);
return;
}
break;
}
}
break;
}
ScrollableBox::HandleMessage(event);
}
void ListBox::HandleMessageTemplate(EventArgs& event)
{
ScrollableBox::HandleMessageTemplate(event);
}
int ListBox::GetCurSel() const
{
return m_iCurSel;
}
void ListBox::SelectNextWhenActiveRemoved(bool bSelectNextItem)
{
m_bSelNextWhenRemoveActive = bSelectNextItem;
}
bool ListBox::SelectItem(int iIndex, bool bTakeFocus, bool bTrigger)
{
//if( iIndex == m_iCurSel ) return true;
int iOldSel = m_iCurSel;
// We should first unselect the currently selected item
if (m_iCurSel >= 0) {
Control* pControl = GetItemAt(m_iCurSel);
if (pControl != NULL) {
ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl);
if (pListItem != NULL) pListItem->OptionTemplate<Box>::Selected(false, bTrigger);
}
m_iCurSel = -1;
}
if (iIndex < 0) return false;
Control* pControl = GetItemAt(iIndex);
if (pControl == NULL) return false;
if (!pControl->IsVisible()) return false;
if (!pControl->IsEnabled()) return false;
ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl);
if (pListItem == NULL) return false;
m_iCurSel = iIndex;
pListItem->OptionTemplate<Box>::Selected(true, bTrigger);
if (GetItemAt(m_iCurSel)) {
CUiRect rcItem = GetItemAt(m_iCurSel)->GetPos();
EnsureVisible(rcItem);
}
if (bTakeFocus) pControl->SetFocus();
if (m_pWindow != NULL && bTrigger) {
m_pWindow->SendNotify(this, kEventSelect, m_iCurSel, iOldSel);
}
return true;
}
void ListBox::EnsureVisible(const CUiRect& rcItem)
{
CUiRect rcNewItem = rcItem;
rcNewItem.Offset(-GetScrollPos().cx, -GetScrollPos().cy);
CUiRect rcList = GetPos();
CUiRect rcListInset = m_pLayout->GetPadding();
rcList.left += rcListInset.left;
rcList.top += rcListInset.top;
rcList.right -= rcListInset.right;
rcList.bottom -= rcListInset.bottom;
ScrollBar* pHorizontalScrollBar = GetHorizontalScrollBar();
if (pHorizontalScrollBar && pHorizontalScrollBar->IsVisible()) rcList.bottom -= pHorizontalScrollBar->GetFixedHeight();
if (rcNewItem.left >= rcList.left && rcNewItem.top >= rcList.top
&& rcNewItem.right <= rcList.right && rcNewItem.bottom <= rcList.bottom) {
if (m_pParent && dynamic_cast<ListContainerElement*>(m_pParent) != NULL) {
dynamic_cast<ListContainerElement*>(m_pParent)->GetOwner()->EnsureVisible(rcNewItem);
}
return;
}
int dx = 0;
if (rcNewItem.left < rcList.left) dx = rcNewItem.left - rcList.left;
if (rcNewItem.right > rcList.right) dx = rcNewItem.right - rcList.right;
int dy = 0;
if (rcNewItem.top < rcList.top) dy = rcNewItem.top - rcList.top;
if (rcNewItem.bottom > rcList.bottom) dy = rcNewItem.bottom - rcList.bottom;
CUiSize sz = GetScrollPos();
SetScrollPos(CUiSize(sz.cx + dx, sz.cy + dy));
}
void ListBox::StopScroll()
{
m_scrollAnimation.Reset();
}
bool ListBox::ButtonDown(EventArgs& msg)
{
bool ret = __super::ButtonDown(msg);
StopScroll();
return ret;
}
bool ListBox::ScrollItemToTop(LPCTSTR strItemName)
{
for (auto it = m_items.begin(); it != m_items.end(); it++) {
if ((*it)->GetName() == strItemName) {
if (GetScrollRange().cy != 0) {
CUiSize scrollPos = GetScrollPos();
scrollPos.cy = (*it)->GetPos().top - m_pLayout->GetInternalPos().top;
if (scrollPos.cy >= 0) {
SetScrollPos(scrollPos);
return true;
}
else {
return false;
}
}
else {
return false;
}
}
}
return false;
}
Control* ListBox::GetTopItem()
{
int listTop = GetPos().top + m_pLayout->GetPadding().top + GetScrollPos().cy;
for (auto it = m_items.begin(); it != m_items.end(); it++) {
if ((*it)->IsVisible() && !(*it)->IsFloat() && (*it)->GetPos().bottom >= listTop) {
return (*it);
}
}
return nullptr;
}
bool ListBox::SetItemIndex(Control* pControl, std::size_t iIndex)
{
int iOrginIndex = GetItemIndex(pControl);
if( iOrginIndex == -1 ) return false;
if( iOrginIndex == (int)iIndex ) return true;
ListContainerElement* pSelectedListItem = NULL;
if( m_iCurSel >= 0 ) pSelectedListItem = dynamic_cast<ListContainerElement*>(GetItemAt(m_iCurSel));
if( !ScrollableBox::SetItemIndex(pControl, iIndex) ) return false;
std::size_t iMinIndex = min((std::size_t)iOrginIndex, iIndex);
std::size_t iMaxIndex = max((std::size_t)iOrginIndex, iIndex);
for(std::size_t i = iMinIndex; i < iMaxIndex + 1; ++i) {
Control* pItemControl = GetItemAt(i);
ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pItemControl);
if( pListItem != NULL ) {
pListItem->SetIndex((int)i);
}
}
if( m_iCurSel >= 0 && pSelectedListItem != NULL ) m_iCurSel = pSelectedListItem->GetIndex();
return true;
}
void ListBox::Previous()
{
if (m_iCurSel > 0) {
SelectItem(m_iCurSel - 1);
}
}
void ListBox::Next()
{
int count = GetCount();
if (m_iCurSel < count - 1) {
SelectItem(m_iCurSel + 1);
}
}
void ListBox::ActiveItem()
{
if (m_iCurSel >= 0) {
ListContainerElement* item = dynamic_cast<ListContainerElement*>( GetItemAt(m_iCurSel) );
item->InvokeDoubleClickEvent();
}
}
bool ListBox::Add(Control* pControl)
{
// Override the Add() method so we can add items specifically to
// the intended widgets. Headers are assumed to be
// answer the correct interface so we can add multiple list headers.
// The list items should know about us
ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl);
if( pListItem != NULL ) {
pListItem->SetOwner(this);
pListItem->SetIndex(GetCount());
}
return ScrollableBox::Add(pControl);
}
bool ListBox::AddAt(Control* pControl, int iIndex)
{
// Override the AddAt() method so we can add items specifically to
// the intended widgets. Headers and are assumed to be
// answer the correct interface so we can add multiple list headers.
if (!ScrollableBox::AddAt(pControl, iIndex)) return false;
// The list items should know about us
ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(pControl);
if( pListItem != NULL ) {
pListItem->SetOwner(this);
pListItem->SetIndex(iIndex);
}
for(int i = iIndex + 1; i < GetCount(); ++i) {
Control* p = GetItemAt(i);
pListItem = dynamic_cast<ListContainerElement*>(p);
if( pListItem != NULL ) {
pListItem->SetIndex(i);
}
}
if( m_iCurSel >= iIndex ) m_iCurSel += 1;
return true;
}
bool ListBox::Remove(Control* pControl)
{
int iIndex = GetItemIndex(pControl);
if (iIndex == -1) return false;
return RemoveAt(iIndex);
}
bool ListBox::RemoveAt(int iIndex)
{
if (!ScrollableBox::RemoveAt(iIndex)) return false;
for(int i = iIndex; i < GetCount(); ++i) {
Control* p = GetItemAt(i);
ListContainerElement* pListItem = dynamic_cast<ListContainerElement*>(p);
if( pListItem != NULL ) pListItem->SetIndex(i);
}
if( iIndex == m_iCurSel && m_iCurSel >= 0 ) {
if (m_bSelNextWhenRemoveActive)
SelectItem(FindSelectable(m_iCurSel--, false));
else
m_iCurSel = -1;
}
else if( iIndex < m_iCurSel ) m_iCurSel -= 1;
return true;
}
void ListBox::RemoveAll()
{
m_iCurSel = -1;
ScrollableBox::RemoveAll();
}
bool ListBox::SortItems(PULVCompareFunc pfnCompare, UINT_PTR dwData)
{
if (!pfnCompare)
return false;
if (m_items.size() == 0)
{
return true;
}
m_pCompareFunc = pfnCompare;
m_pCompareData = dwData;
qsort_s(&(*m_items.begin()), m_items.size(), sizeof(Control*), ListBox::ItemComareFunc, this);
ListContainerElement *pItem = NULL;
for (int i = 0; i < (int)m_items.size(); ++i)
{
pItem = dynamic_cast<ListContainerElement*>(static_cast<Control*>(m_items[i]));
if (pItem) {
pItem->SetIndex(i);
pItem->Selected(false, true);
}
}
SelectItem(-1);
SetPos(GetPos());
Invalidate();
return true;
}
int __cdecl ListBox::ItemComareFunc(void *pvlocale, const void *item1, const void *item2)
{
ListBox *pThis = (ListBox*)pvlocale;
if (!pThis || !item1 || !item2)
return 0;
return pThis->ItemComareFunc(item1, item2);
}
int __cdecl ListBox::ItemComareFunc(const void *item1, const void *item2)
{
Control *pControl1 = *(Control**)item1;
Control *pControl2 = *(Control**)item2;
return m_pCompareFunc((UINT_PTR)pControl1, (UINT_PTR)pControl2, m_pCompareData);
}
bool ListBox::GetScrollSelect()
{
return m_bScrollSelect;
}
void ListBox::SetScrollSelect(bool bScrollSelect)
{
m_bScrollSelect = bScrollSelect;
}
/////////////////////////////////////////////////////////////////////////////////////
//
//
ListContainerElement::ListContainerElement() :
m_iIndex(-1),
m_pOwner(nullptr)
{
m_uTextStyle = DT_LEFT | DT_VCENTER | DT_END_ELLIPSIS | DT_NOCLIP | DT_SINGLELINE;
SetReceivePointerMsg(false);
}
void ListContainerElement::SetVisible(bool bVisible)
{
__super::SetVisible(bVisible);
if (!IsVisible() && m_bSelected) {
m_bSelected = false;
if (m_pOwner != NULL) m_pOwner->SelectItem(-1);
}
}
void ListContainerElement::Selected(bool bSelected, bool trigger)
{
if (!IsEnabled()) return;
if (bSelected && m_pOwner != NULL) m_pOwner->SelectItem(m_iIndex, false, trigger);
}
void ListContainerElement::HandleMessage(EventArgs& event)
{
if (!IsMouseEnabled() && event.Type > kEventMouseBegin && event.Type < kEventMouseEnd) {
if (m_pOwner != NULL) m_pOwner->HandleMessageTemplate(event);
else Box::HandleMessage(event);
return;
}
else if (event.Type == kEventInternalDoubleClick) {
if (IsActivatable()) {
InvokeDoubleClickEvent();
}
return;
}
else if (event.Type == kEventKeyDown && IsEnabled()) {
if (event.chKey == VK_RETURN) {
if (IsActivatable()) {
if (m_pWindow != NULL) m_pWindow->SendNotify(this, kEventReturn);
}
return;
}
}
else if (event.Type == kEventInternalMenu && IsEnabled()) {
Selected(true, true);
m_pWindow->SendNotify(this, kEventMouseMenu);
Invalidate();
return;
}
__super::HandleMessage(event);
// An important twist: The list-item will send the event not to its immediate
// parent but to the "attached" list. A list may actually embed several components
// in its path to the item, but key-presses etc. needs to go to the actual list.
//if( m_pOwner != NULL ) m_pOwner->HandleMessage(event); else Control::HandleMessage(event);
}
IListOwner* ListContainerElement::GetOwner()
{
return m_pOwner;
}
void ListContainerElement::SetOwner(IListOwner* pOwner)
{
m_pOwner = pOwner;
}
int ListContainerElement::GetIndex() const
{
return m_iIndex;
}
void ListContainerElement::SetIndex(int iIndex)
{
m_iIndex = iIndex;
}
void ListContainerElement::InvokeDoubleClickEvent()
{
if( m_pWindow != NULL ) m_pWindow->SendNotify(this, kEventMouseDoubleClick);
}
} // namespace ui
| 26.248954 | 121 | 0.672193 | colinjiang007 |
caf3f99cca726a33c339a3d00fcccd4e7813deb4 | 348 | cxx | C++ | examples/01_SimpleExamples/05_MultiObjects/src/main.cxx | GailKabala/LearnVulkan | 672ee38755413889f2e1fe4d226e200955da9278 | [
"MIT"
] | null | null | null | examples/01_SimpleExamples/05_MultiObjects/src/main.cxx | GailKabala/LearnVulkan | 672ee38755413889f2e1fe4d226e200955da9278 | [
"MIT"
] | null | null | null | examples/01_SimpleExamples/05_MultiObjects/src/main.cxx | GailKabala/LearnVulkan | 672ee38755413889f2e1fe4d226e200955da9278 | [
"MIT"
] | null | null | null | #include "multiobjects.h"
int main(int argc,char** argv){
bool debug=false;
MultiImageSampler* pMultiImageSampler=new MultiImageSampler(debug);
pMultiImageSampler->initVulkan();
pMultiImageSampler->initWindow();
pMultiImageSampler->prepare();
pMultiImageSampler->renderLoop();
delete pMultiImageSampler;
return 1;
}
| 29 | 71 | 0.735632 | GailKabala |
caf595b951216a3f914c7bb1f4fb18703cbebd7f | 5,671 | cpp | C++ | src/comm/serialport.cpp | robertrau/libpifly | c69e0161f85668637ef5eb1387f48929b247964a | [
"MIT"
] | null | null | null | src/comm/serialport.cpp | robertrau/libpifly | c69e0161f85668637ef5eb1387f48929b247964a | [
"MIT"
] | null | null | null | src/comm/serialport.cpp | robertrau/libpifly | c69e0161f85668637ef5eb1387f48929b247964a | [
"MIT"
] | null | null | null | /*
Author: Robert F. Rau II
Copyright (C) 2017 Robert F. Rau II
*/
#include "comm/serialport.h"
#include "comm/commexception.h"
#include <iostream>
#include <unistd.h>
namespace PiFly
{
namespace Comm
{
SerialPort::SerialPort(string devPath, Baudrate baud, bool blocking) :
mBlocking(blocking)
{
if(mBlocking) {
serialFd = open(devPath.c_str(), O_RDWR);
} else {
serialFd = open(devPath.c_str(), O_RDWR | O_NONBLOCK | O_NDELAY);
}
if(serialFd < 0) {
throw CommFdException(errno);
}
memset(&serialTTY, 0, sizeof(termios));
if(tcgetattr(serialFd, &serialTTY) != 0) {
throw CommFdException(errno);
}
if(cfsetispeed(&serialTTY, linuxBaudrateMap(baud)) != 0) {
throw CommFdException(errno);
}
if(cfsetospeed(&serialTTY, linuxBaudrateMap(baud)) != 0) {
throw CommFdException(errno);
}
// make a raw serial port
cfmakeraw(&serialTTY);
if(tcsetattr(serialFd, TCSANOW, &serialTTY) != 0) {
throw CommFdException(errno);
}
}
SerialPort::~SerialPort() {
if(serialFd >= 0) {
close(serialFd);
}
}
size_t SerialPort::read(SerialBuffer::iterator first, size_t readBytes) {
if(!mBlocking) {
int resp = ::read(serialFd, static_cast<void*>(&(*first)), readBytes);
if(resp > 0) {
return resp;
} else if((resp < 0) && (errno != EAGAIN)) {
throw CommFdException(errno);
} else {
return 0;
}
} else {
int resp = ::read(serialFd, static_cast<void*>(&(*first)), readBytes);
if(resp > 0) {
return resp;
} else if(resp == 0) {
throw CommFdException(errno);
} else {
throw CommFdException(resp);
}
}
}
void SerialPort::write(const SerialBuffer& buffer) {
size_t bytesWritten = 0;
ssize_t resp;
do {
resp = ::write(serialFd, static_cast<const void*>(buffer.data()), buffer.size());
if(resp > 0) {
bytesWritten += resp;
} else if(resp == 0) {
throw CommFdException(errno);
} else {
throw CommFdException(resp);
}
} while(bytesWritten < buffer.size());
}
void SerialPort::setBaudrate(Baudrate baud) {
if(cfsetispeed(&serialTTY, linuxBaudrateMap(baud)) != 0) {
throw CommFdException(errno);
}
if(cfsetospeed(&serialTTY, linuxBaudrateMap(baud)) != 0) {
throw CommFdException(errno);
}
if(tcsetattr(serialFd, TCSANOW, &serialTTY) != 0) {
throw CommFdException(errno);
}
}
SerialPort::Baudrate SerialPort::getBaudrate() {
speed_t currentBaud = cfgetispeed(&serialTTY);
return linuxBaudrateMap(currentBaud);
}
void SerialPort::flush() {
tcflush(serialFd, TCIOFLUSH);
}
SerialPort::Baudrate SerialPort::linuxBaudrateMap(speed_t baud) {
switch(baud) {
case B0:
return Baudrate_0;
case B50:
return Baudrate_50;
case B75:
return Baudrate_75;
case B110:
return Baudrate_110;
case B134:
return Baudrate_134;
case B150:
return Baudrate_150;
case B200:
return Baudrate_200;
case B300:
return Baudrate_300;
case B600:
return Baudrate_600;
case B1200:
return Baudrate_1200;
case B1800:
return Baudrate_1800;
case B2400:
return Baudrate_2400;
case B4800:
return Baudrate_4800;
case B9600:
return Baudrate_9600;
case B19200:
return Baudrate_19200;
case B38400:
return Baudrate_38400;
case B57600:
return Baudrate_57600;
case B115200:
return Baudrate_115200;
case B230400:
return Baudrate_230400;
default:
std::cout << "linuxBaudrateMap speed_t Input baud: " << baud << "\n";
throw CommException("Unsupported baudrate");
}
}
speed_t SerialPort::linuxBaudrateMap(Baudrate baud) {
switch(baud) {
case Baudrate_0:
return B0;
case Baudrate_50:
return B50;
case Baudrate_75:
return B75;
case Baudrate_110:
return B110;
case Baudrate_134:
return B134;
case Baudrate_150:
return B150;
case Baudrate_200:
return B200;
case Baudrate_300:
return B300;
case Baudrate_600:
return B600;
case Baudrate_1200:
return B1200;
case Baudrate_1800:
return B1800;
case Baudrate_2400:
return B2400;
case Baudrate_4800:
return B4800;
case Baudrate_9600:
return B9600;
case Baudrate_19200:
return B19200;
case Baudrate_38400:
return B38400;
case Baudrate_57600:
return B57600;
case Baudrate_115200:
return B115200;
case Baudrate_230400:
return B230400;
default:
std::cout << "linuxBaudrateMap Baudrate Input baud: " << baud << "\n";
throw CommException("Unsupported baudrate");
}
}
string SerialPort::baudrateString(Baudrate baud) {
switch(baud) {
case Baudrate_0:
return "0";
case Baudrate_50:
return "50";
case Baudrate_75:
return "75";
case Baudrate_110:
return "110";
case Baudrate_134:
return "134";
case Baudrate_150:
return "150";
case Baudrate_200:
return "200";
case Baudrate_300:
return "300";
case Baudrate_600:
return "600";
case Baudrate_1200:
return "1200";
case Baudrate_1800:
return "1800";
case Baudrate_2400:
return "2400";
case Baudrate_4800:
return "4800";
case Baudrate_9600:
return "9600";
case Baudrate_19200:
return "19200";
case Baudrate_38400:
return "38400";
case Baudrate_57600:
return "57600";
case Baudrate_115200:
return "115200";
case Baudrate_230400:
return "230400";
default:
return "unsupported";
}
}
}
} | 22.152344 | 85 | 0.631811 | robertrau |
caf83c749a0090f67d34ad9943669a21bbb4264c | 2,578 | hpp | C++ | include/atma/hash.hpp | omnigoat/atma | 73833f41373fac2af695587786c00a307046de64 | [
"MIT"
] | 7 | 2016-04-08T03:53:42.000Z | 2020-07-06T05:52:35.000Z | include/atma/hash.hpp | omnigoat/atma | 73833f41373fac2af695587786c00a307046de64 | [
"MIT"
] | 1 | 2018-04-14T13:56:06.000Z | 2018-04-14T13:56:06.000Z | include/atma/hash.hpp | omnigoat/atma | 73833f41373fac2af695587786c00a307046de64 | [
"MIT"
] | null | null | null | #pragma once
import atma.types;
namespace atma
{
struct hasher_t;
template <typename T>
struct hash_t
{
auto operator()(T const& x) const -> size_t;
auto operator()(hasher_t& hsh, T const& x) const -> void;
};
struct hasher_t
{
hasher_t(uint64 seed = 0);
template <typename T>
auto operator ()(T const& t) -> hasher_t&;
auto operator ()(void const* datav, size_t size) -> hasher_t&;
auto result() -> uint64;
private:
auto mmix(uint64& h, uint64 k) const -> void
{
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
}
void mix_tail(const uchar*& data, size_t& size)
{
while (size && (size < 8 || count_))
{
tail_ |= *data << (count_ * 8);
++data;
++count_;
--size;
if (count_ == 8)
{
mmix(hash_, tail_);
tail_ = 0;
count_ = 0;
}
}
}
private:
static const uint64 m = 0xc6a4a7935bd1e995ull;
static const int r = 47;
uint64 hash_;
uint64 tail_;
uint64 count_;
size_t size_;
};
inline auto hash(void const* key, size_t size, uint seed) -> uint64
{
return hasher_t(seed)(key, size).result();
}
template <typename T>
inline auto hash(T const& t) -> uint64
{
auto hasher = hasher_t{};
hash_t<T>{}(hasher, t);
return hasher.result();
}
struct std_hash_functor_adaptor_t
{
template <typename T>
auto operator ()(T const& x) const -> size_t
{
return hasher_t()(&x, sizeof(T)).result();
}
};
template <typename T>
inline auto hash_t<T>::operator()(T const& x) const -> size_t
{
return hasher_t{}(x).result();
}
template <typename T>
inline auto hash_t<T>::operator()(hasher_t& hsh, T const& x) const -> void
{
hsh(&x, sizeof(T));
}
inline hasher_t::hasher_t(uint64 seed)
: hash_(seed)
, tail_()
, count_()
, size_()
{
}
inline auto hasher_t::operator ()(void const* datav, size_t size) -> hasher_t&
{
auto data = reinterpret_cast<uchar const*>(datav);
size_ += size;
mix_tail(data, size);
while (size >= 8)
{
uint64 k = *(uint64*)data;
mmix(hash_, k);
data += 8;
size -= 8;
}
mix_tail(data, size);
return *this;
}
inline auto hasher_t::result() -> uint64
{
mmix(hash_, tail_);
mmix(hash_, size_);
hash_ ^= hash_ >> r;
hash_ *= m;
hash_ ^= hash_ >> r;
return hash_;
}
template <typename T>
inline auto hasher_t::operator ()(T const& t) -> hasher_t&
{
hash_t<T>()(*this, t);
return *this;
}
}
| 16.960526 | 80 | 0.557797 | omnigoat |
caf9506bec8989b42c3c560844f90f1c57e823e2 | 2,178 | hpp | C++ | schmidt.hpp | deakinYellow/utility-math | 7b465ca7031fe85579c13d81732d8b20bbbf1acb | [
"Apache-2.0"
] | null | null | null | schmidt.hpp | deakinYellow/utility-math | 7b465ca7031fe85579c13d81732d8b20bbbf1acb | [
"Apache-2.0"
] | null | null | null | schmidt.hpp | deakinYellow/utility-math | 7b465ca7031fe85579c13d81732d8b20bbbf1acb | [
"Apache-2.0"
] | null | null | null | #include <iostream>
//#define USING_MLOGD
#include "utility/tool.h"
#include <Eigen/Core>
//#include <Eigen/Geometry> // Eigen 几何模块
/**
* @brief 使用Gramy-Schmidt方法实现向量正交化,并单位化
* @param [in] a 向量a
* @param [in] b 向量b
* @param [in] c 向量c
* @param [out] An 标准化后的向量A
* @param [out] Bn 标准化后的向量B
* @param [out] Cn 标准化后的向量C
* @retval
* @note a,b,c必须为线性无关组
*/
static void schmidtOrthogonalV3D(
Eigen::Vector3d a,
Eigen::Vector3d b,
Eigen::Vector3d c,
Eigen::Vector3d* An,
Eigen::Vector3d* Bn,
Eigen::Vector3d* Cn ){
Eigen::Vector3d A,B,C;
//A直接赋值为a
A = a;
//MLOGD("vector A: %.3lf %.3f %.3f", A.x(), A.y(), A.z() );
//求B
double xab = A.dot(b) / A.dot( A );
B = b - xab * A;
//MLOGD("vector B: %.3lf %.3f %.3f", B.x(), B.y(), B.z() );
//求C
double xac = A.dot( c ) / A.dot( A );
double xbc = B.dot( c ) / B.dot( B );
C = c - ( xac * A ) - ( xbc * B );
//MLOGD("vector C: %.3lf %.3f %.3f", C.x(), C.y(), C.z() );
//单位化并输出
*An = A.normalized();
*Bn = B.normalized();
*Cn = C.normalized();
//MLOGD("normalized vector A: %.3lf %.3f %.3f", An->x(), An->y(), An->z() );
//MLOGD("normalized vector B: %.3lf %.3f %.3f", Bn->x(), Bn->y(), Bn->z() );
//MLOGD("normalized vector C: %.3lf %.3f %.3f", Cn->x(), Cn->y(), Cn->z() );
}
//--------------------测试函数----------------------------
static void schmidtOrthogonalTest( void ) {
//线性无关组1
Eigen::Vector3d a(1,1.2,0);
Eigen::Vector3d b(1,2,0);
Eigen::Vector3d c(0,1,1);
//线性无关组2
Eigen::Vector3d v1(9,1.2,2.4);
Eigen::Vector3d v2(1,2,6.7);
Eigen::Vector3d v3(5,1.5,1);
Eigen::Vector3d A,B,C;
schmidtOrthogonalV3D( a, b, c, &A, &B, &C );
//schmidtOrthogonalV3D( v1, v2, v3, &A, &B, &C );
TPLOGI("normalized vector A: %.3lf %.3f %.3f", A.x(), A.y(), A.z() );
TPLOGI("normalized vector B: %.3lf %.3f %.3f", B.x(), B.y(), B.z() );
TPLOGI("normalized vector C: %.3lf %.3f %.3f", C.x(), C.y(), C.z() );
}
| 30.25 | 80 | 0.472452 | deakinYellow |
cafe7f9a3dcf63e01d84bde0d9fcec87c6cea065 | 927 | cpp | C++ | codes/sub/src/comms/comms.cpp | tofu-micom/RCJ2021_Exhibition | 55877e2dd6be3ef1b660f98725a83c3aaef21cb1 | [
"MIT"
] | null | null | null | codes/sub/src/comms/comms.cpp | tofu-micom/RCJ2021_Exhibition | 55877e2dd6be3ef1b660f98725a83c3aaef21cb1 | [
"MIT"
] | null | null | null | codes/sub/src/comms/comms.cpp | tofu-micom/RCJ2021_Exhibition | 55877e2dd6be3ef1b660f98725a83c3aaef21cb1 | [
"MIT"
] | null | null | null | //
// Created by 平地浩一 on 2021/03/23.
//
#include "comms.h"
DigitalIn a(PA_7);
DigitalIn b(PA_6);
DigitalOut RA(PB_0);
DigitalOut RB(PA_12);
DigitalOut LA(PB_3);
// PB_7 許さん!!!
DigitalOut LB(PB_6);
BufferedSerial pc(USBTX, USBRX);
void comms_init() {
RA.write(0);
RB.write(0);
LA.write(0);
LB.write(0);
}
void comms_read() {
bool A = a.read();
bool B = b.read();
static bool AA;
static bool BB;
if (A != AA || B != BB) {
if (A && !B) {
// 左超信地
RA.write(0);
RB.write(1);
LA.write(1);
LB.write(0);
} else if (!A && B) {
// 右超信地
RA.write(1);
RB.write(0);
LA.write(0);
LB.write(1);
} else if (!A && !B) {
// 停止
RA.write(1);
RB.write(1);
LA.write(1);
LB.write(1);
} else if (A && B) {
// 前進
RA.write(0);
RB.write(1);
LA.write(0);
LB.write(1);
}
}
AA = A;
BB = B;
} | 15.982759 | 33 | 0.483279 | tofu-micom |
1b083c392d9a102b70f99fbfab61f86ef34ef17d | 8,170 | cpp | C++ | app/viewport/render/task.cpp | mbd-shift/nodecad | cd8203c4b53608d015632a2b2fc324bcf6dec4b0 | [
"MIT",
"Unlicense"
] | 2,059 | 2015-01-18T16:21:33.000Z | 2022-03-25T21:54:24.000Z | app/viewport/render/task.cpp | hzeller/antimony | 37324614f873d653594f25c2b8ee05fd4782e1d8 | [
"Unlicense",
"MIT"
] | 209 | 2015-01-22T22:37:45.000Z | 2021-04-14T20:49:40.000Z | app/viewport/render/task.cpp | hzeller/antimony | 37324614f873d653594f25c2b8ee05fd4782e1d8 | [
"Unlicense",
"MIT"
] | 187 | 2015-02-04T16:19:43.000Z | 2022-02-12T17:12:24.000Z | #include <boost/python.hpp>
#include <boost/format.hpp>
#include "viewport/render/task.h"
#include "viewport/render/instance.h"
#include "fab/types/shape.h"
#include "fab/util/region.h"
#include "fab/tree/render.h"
RenderTask::RenderTask(RenderInstance* parent, PyObject* s, QMatrix4x4 M,
QVector2D clip, int refinement)
: shape(s), M(M), clip(clip), refinement(refinement)
{
Py_INCREF(shape);
future = QtConcurrent::run(this, &RenderTask::async);
watcher.setFuture(future);
connect(&watcher, &decltype(watcher)::finished,
parent, &RenderInstance::onTaskFinished);
}
RenderTask::~RenderTask()
{
Py_DECREF(shape);
}
void RenderTask::halt()
{
halt_flag = 1;
}
RenderTask* RenderTask::getNext(RenderInstance* parent) const
{
return refinement > 1
? new RenderTask(parent, shape, M, clip, refinement - 1)
: NULL;
}
void RenderTask::async()
{
QTime timer;
timer.start();
boost::python::extract<const Shape&> get_shape(shape);
Q_ASSERT(get_shape.check());
const Shape& s = get_shape();
if (!std::isinf(s.bounds.xmin) && !std::isinf(s.bounds.xmax) &&
!std::isinf(s.bounds.xmin) && !std::isinf(s.bounds.xmax))
{
if (std::isinf(s.bounds.zmin) || std::isinf(s.bounds.zmax))
{
render2d(s);
}
else
{
render3d(s);
}
}
// Set color from shape or to white
color = (s.r != -1 && s.g != -1 && s.g != -1)
? QColor(s.r, s.g, s.b) : QColor(255, 255, 255);
// Compensate for screen scale
float scale = sqrt(pow(M(0, 0), 2) +
pow(M(0, 1), 2) +
pow(M(0, 2), 2));
size /= scale;
render_time = timer.elapsed();
}
void RenderTask::render3d(const Shape& s)
{
Transform T = getTransform(M);
Shape transformed = s.map(T);
Bounds b = render(&transformed, transformed.bounds, 1.0 / refinement);
{ // Apply a transform-less mapping to the bounds
auto m = M;
m.setColumn(3, {0, 0, 0, m(3,3)});
pos = m.inverted() * QVector3D(
(b.xmin + b.xmax)/2,
(b.ymin + b.ymax)/2,
(b.zmin + b.zmax)/2);
}
size = {b.xmax - b.xmin,
b.ymax - b.ymin,
b.zmax - b.zmin};
flat = false;
}
void RenderTask::render2d(const Shape& s)
{
QMatrix4x4 matrix_flat = M;
matrix_flat(0, 2) = 0;
matrix_flat(1, 2) = 0;
matrix_flat(2, 0) = 0;
matrix_flat(2, 1) = 0;
matrix_flat(2, 2) = 1;
Shape s_flat(s.math, Bounds(s.bounds.xmin, s.bounds.ymin, 0,
s.bounds.xmax, s.bounds.ymax, 0));
Transform T_flat = getTransform(matrix_flat);
Shape transformed = s_flat.map(T_flat);
// Render the flattened shape, but with bounds equivalent to the shape's
// position in a 3D bounding box.
Bounds b3d_ = Bounds(s.bounds.xmin, s.bounds.ymin, 0,
s.bounds.xmax, s.bounds.ymax, 0.0001).
map(getTransform(M));
Bounds b3d = render(&transformed, b3d_, 1.0 / refinement);
{ // Apply a transform-less mapping to the bounds
auto m = M;
m.setColumn(3, {0, 0, 0, m(3, 3)});
pos = m.inverted() *
QVector3D((b3d.xmin + b3d.xmax)/2,
(b3d.ymin + b3d.ymax)/2,
(b3d.zmin + b3d.zmax)/2);
}
size = {b3d.xmax - b3d.xmin,
b3d.ymax - b3d.ymin,
b3d.zmax - b3d.zmin};
// Apply a gradient to the depth-map based on tilt
if (M(1,2))
{
bool direction = M(2,2) > 0;
for (int j=0; j < depth.height(); ++j)
{
for (int i=0; i < depth.width(); ++i)
{
uint8_t pix = depth.pixel(i, j) & 0xff;
if (pix)
{
if (direction)
pix *= j / float(depth.height());
else
pix *= 1 - j / float(depth.height());
depth.setPixel(i, j, pix | (pix << 8) | (pix << 16));
}
}
}
}
{ // Set normals to a flat value (rather than derivatives)
float xy = sqrt(pow(M(0,2),2) + pow(M(1,2),2));
float z = fabs(M(2,2));
float len = sqrt(pow(xy, 2) + pow(z, 2));
xy /= len;
z /= len;
shaded.fill((int(z * 255) << 16) | int(xy * 255));
}
flat = true;
}
Transform RenderTask::getTransform(QMatrix4x4 m)
{
QMatrix4x4 mf = m.inverted();
QMatrix4x4 mi = mf.inverted();
Transform T = Transform(
(boost::format("++*Xf%g*Yf%g*Zf%g") %
mf(0,0) % mf(0,1) % mf(0,2)).str(),
(boost::format("++*Xf%g*Yf%g*Zf%g") %
mf(1,0) % mf(1,1) % mf(1,2)).str(),
(boost::format("++*Xf%g*Yf%g*Zf%g") %
mf(2,0) % mf(2,1) % mf(2,2)).str(),
(boost::format("++*Xf%g*Yf%g*Zf%g") %
mi(0,0) % mi(0,1) % mi(0,2)).str(),
(boost::format("++*Xf%g*Yf%g*Zf%g") %
mi(1,0) % mi(1,1) % mi(1,2)).str(),
(boost::format("++*Xf%g*Yf%g*Zf%g") %
mi(2,0) % mi(2,1) % mi(2,2)).str());
return T;
}
////////////////////////////////////////////////////////////////////////////////
Bounds RenderTask::render(Shape* shape, Bounds b_, float scale)
{
// Screen-space clipping:
// x and y are clipped to the window;
// z is clipped assuming a voxel depth of max(width, height)
const float xmin = -M(0,3) - clip.x() / 2;
const float xmax = -M(0,3) + clip.x() / 2;
const float ymin = -M(1,3) - clip.y() / 2;
const float ymax = -M(1,3) + clip.y() / 2;
const float zmin = -M(2,3) - fmax(clip.x(), clip.y()) / 2;
const float zmax = -M(2,3) + fmax(clip.x(), clip.y()) / 2;
Bounds b(fmax(xmin, b_.xmin), fmax(ymin, b_.ymin), fmax(zmin, b_.zmin),
fmin(xmax, b_.xmax), fmin(ymax, b_.ymax), fmin(zmax, b_.zmax));
depth = QImage((b.xmax - b.xmin) * scale, (b.ymax - b.ymin) * scale,
QImage::Format_RGB32);
shaded = QImage(depth.width(), depth.height(), depth.format());
depth.fill(0x000000);
uint16_t* d16(new uint16_t[depth.width() * depth.height()]);
uint16_t** d16_rows(new uint16_t*[depth.height()]);
uint8_t (*s8)[3] = new uint8_t[depth.width() * depth.height()][3];
uint8_t (**s8_rows)[3] = new decltype(s8)[depth.height()];
for (int i=0; i < depth.height(); ++i)
{
d16_rows[i] = &d16[depth.width() * i];
s8_rows[i] = &s8[depth.width() * i];
}
memset(d16, 0, depth.width() * depth.height() * 2);
memset(s8, 0, depth.width() * depth.height() * 3);
Region r = (Region) {
.imin=0, .jmin=0, .kmin=0,
.ni=(uint32_t)depth.width(), .nj=(uint32_t)depth.height(),
.nk=uint32_t(fmax(1, (b.zmax - b.zmin) * scale))
};
build_arrays(&r, b.xmin, b.ymin, b.zmin,
b.xmax, b.ymax, b.zmax);
render16(shape->tree.get(), r, d16_rows, &halt_flag, nullptr);
shaded8(shape->tree.get(), r, d16_rows, s8_rows, &halt_flag, nullptr);
free_arrays(&r);
// Copy from bitmap arrays into a QImage
for (int j=0; j < depth.height(); ++j)
{
for (int i=0; i < depth.width(); ++i)
{
uint16_t pix16 = d16_rows[j][i];
uint8_t pix8 = pix16 >> 8;
uint8_t* norm = s8_rows[j][i];
if (pix8)
{
depth.setPixel(i, j,
pix8 | (pix8 << 8) | (pix8 << 16));
if (pix16 < UINT16_MAX)
{
shaded.setPixel(i, j,
norm[0] | (norm[1] << 8) | (norm[2] << 16));
}
else
{
shaded.setPixel(i, j,
0 | (0 << 8) | (255 << 16));
}
}
}
}
delete [] s8;
delete [] s8_rows;
delete [] d16;
delete [] d16_rows;
return b;
}
| 29.92674 | 80 | 0.487271 | mbd-shift |
db46a53f1b80be09f414f81993846f8b94a43480 | 3,749 | cpp | C++ | Server/shared/SocketMgr.cpp | APistole/KnightOnline | 80268e2fa971389a3e94c430966a7943c2631dbf | [
"MIT"
] | 191 | 2016-03-05T16:44:15.000Z | 2022-03-09T00:52:31.000Z | Server/shared/SocketMgr.cpp | APistole/KnightOnline | 80268e2fa971389a3e94c430966a7943c2631dbf | [
"MIT"
] | 128 | 2016-08-31T04:09:06.000Z | 2022-01-14T13:42:56.000Z | Server/shared/SocketMgr.cpp | APistole/KnightOnline | 80268e2fa971389a3e94c430966a7943c2631dbf | [
"MIT"
] | 165 | 2016-03-05T16:43:59.000Z | 2022-01-22T00:52:25.000Z | #include "stdafx.h"
#include "SocketMgr.h"
bool SocketMgr::s_bRunningCleanupThread = true;
std::recursive_mutex SocketMgr::s_disconnectionQueueLock;
std::queue<Socket *> SocketMgr::s_disconnectionQueue;
Thread SocketMgr::s_cleanupThread;
Atomic<uint32_t> SocketMgr::s_refCounter;
uint32_t THREADCALL SocketCleanupThread(void * lpParam)
{
while (SocketMgr::s_bRunningCleanupThread)
{
SocketMgr::s_disconnectionQueueLock.lock();
while (!SocketMgr::s_disconnectionQueue.empty())
{
Socket *pSock = SocketMgr::s_disconnectionQueue.front();
if (pSock->GetSocketMgr())
pSock->GetSocketMgr()->DisconnectCallback(pSock);
SocketMgr::s_disconnectionQueue.pop();
}
SocketMgr::s_disconnectionQueueLock.unlock();
sleep(100);
}
return 0;
}
SocketMgr::SocketMgr() : m_threadCount(0),
m_bWorkerThreadsActive(false),
m_bShutdown(false)
{
static bool bRefCounterInitialised = false;
if (!bRefCounterInitialised)
{
s_refCounter = 0;
bRefCounterInitialised = true;
}
IncRef();
Initialise();
}
void SocketMgr::SpawnWorkerThreads()
{
if (m_bWorkerThreadsActive)
return;
m_bWorkerThreadsActive = true;
m_thread = new Thread(SocketWorkerThread, this);
if (!s_cleanupThread.isStarted())
s_cleanupThread.start(SocketCleanupThread);
}
uint32_t THREADCALL SocketMgr::SocketWorkerThread(void * lpParam)
{
SocketMgr *socketMgr = (SocketMgr *)lpParam;
HANDLE cp = socketMgr->GetCompletionPort();
DWORD len;
Socket * s = nullptr;
OverlappedStruct * ov = nullptr;
LPOVERLAPPED ol_ptr;
while (socketMgr->m_bWorkerThreadsActive)
{
if (!GetQueuedCompletionStatus(cp, &len, (PULONG_PTR)&s, &ol_ptr, INFINITE))
{
if (s != nullptr)
s->Disconnect();
continue;
}
ov = CONTAINING_RECORD(ol_ptr, OverlappedStruct, m_overlap);
if (ov->m_event == SOCKET_IO_THREAD_SHUTDOWN)
{
delete ov;
return 0;
}
if (ov->m_event < NUM_SOCKET_IO_EVENTS)
ophandlers[ov->m_event](s, len);
}
return 0;
}
void SocketMgr::Initialise()
{
m_completionPort = nullptr;
}
void SocketMgr::CreateCompletionPort()
{
SetCompletionPort(CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, (ULONG_PTR)0, 0));
}
void SocketMgr::SetupWinsock()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2,0), &wsaData);
}
void HandleReadComplete(Socket * s, uint32_t len)
{
if (s->IsDeleted())
return;
s->m_readEvent.Unmark();
if (len)
{
s->GetReadBuffer().IncrementWritten(len);
s->OnRead();
s->SetupReadEvent();
}
else
{
// s->Delete(); // Queue deletion.
s->Disconnect();
}
}
void HandleWriteComplete(Socket * s, uint32_t len)
{
if (s->IsDeleted())
return;
s->m_writeEvent.Unmark();
s->BurstBegin(); // Lock
s->GetWriteBuffer().Remove(len);
if( s->GetWriteBuffer().GetContiguousBytes() > 0 )
s->WriteCallback();
else
s->DecSendLock();
s->BurstEnd(); // Unlock
}
void HandleShutdown(Socket * s, uint32_t len) {}
void SocketMgr::OnConnect(Socket *pSock) {}
void SocketMgr::DisconnectCallback(Socket *pSock) {}
void SocketMgr::OnDisconnect(Socket *pSock)
{
Guard lock(s_disconnectionQueueLock);
s_disconnectionQueue.push(pSock);
}
void SocketMgr::ShutdownThreads()
{
OverlappedStruct * ov = new OverlappedStruct(SOCKET_IO_THREAD_SHUTDOWN);
PostQueuedCompletionStatus(m_completionPort, 0, (ULONG_PTR)0, &ov->m_overlap);
m_bWorkerThreadsActive = false;
m_thread->waitForExit();
delete m_thread;
}
void SocketMgr::Shutdown()
{
if (m_bShutdown)
return;
ShutdownThreads();
DecRef();
m_bShutdown = true;
}
void SocketMgr::SetupSockets()
{
SetupWinsock();
}
void SocketMgr::CleanupSockets()
{
if (s_cleanupThread.isStarted())
{
s_bRunningCleanupThread = false;
s_cleanupThread.waitForExit();
}
WSACleanup();
}
SocketMgr::~SocketMgr()
{
Shutdown();
}
| 19.42487 | 91 | 0.721792 | APistole |
db48a0c83037ef203780e5c422d63b26c3d86677 | 5,303 | cpp | C++ | src/qt/qtbase/tests/auto/network/socket/qudpsocket/clientserver/main.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | src/qt/qtbase/tests/auto/network/socket/qudpsocket/clientserver/main.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/tests/auto/network/socket/qudpsocket/clientserver/main.cpp | power-electro/phantomjs-Gohstdriver-DIY-openshift | a571d301a9658a4c1b524d07e15658b45f8a0579 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtNetwork>
class ClientServer : public QUdpSocket
{
Q_OBJECT
public:
enum Type {
ConnectedClient,
UnconnectedClient,
Server
};
ClientServer(Type type, const QString &host, quint16 port)
: type(type)
{
switch (type) {
case Server:
if (bind(0, ShareAddress | ReuseAddressHint)) {
printf("%d\n", localPort());
} else {
printf("XXX\n");
}
break;
case ConnectedClient:
connectToHost(host, port);
startTimer(250);
printf("ok\n");
break;
case UnconnectedClient:
peerAddress = host;
peerPort = port;
if (bind(QHostAddress::Any, port + 1, ShareAddress | ReuseAddressHint)) {
startTimer(250);
printf("ok\n");
} else {
printf("XXX\n");
}
break;
}
fflush(stdout);
connect(this, SIGNAL(readyRead()), this, SLOT(readTestData()));
}
protected:
void timerEvent(QTimerEvent *event)
{
static int n = 0;
switch (type) {
case ConnectedClient:
write(QByteArray::number(n++));
break;
case UnconnectedClient:
writeDatagram(QByteArray::number(n++), peerAddress, peerPort);
break;
default:
break;
}
QUdpSocket::timerEvent(event);
}
private slots:
void readTestData()
{
printf("readData()\n");
switch (type) {
case ConnectedClient: {
while (bytesAvailable() || hasPendingDatagrams()) {
QByteArray data = readAll();
printf("got %d\n", data.toInt());
}
break;
}
case UnconnectedClient: {
while (hasPendingDatagrams()) {
QByteArray data;
data.resize(pendingDatagramSize());
readDatagram(data.data(), data.size());
printf("got %d\n", data.toInt());
}
break;
}
case Server: {
while (hasPendingDatagrams()) {
QHostAddress sender;
quint16 senderPort;
QByteArray data;
data.resize(pendingDatagramSize());
readDatagram(data.data(), data.size(), &sender, &senderPort);
printf("got %d\n", data.toInt());
printf("sending %d\n", data.toInt() * 2);
writeDatagram(QByteArray::number(data.toInt() * 2), sender, senderPort);
}
break;
}
}
fflush(stdout);
}
private:
Type type;
QHostAddress peerAddress;
quint16 peerPort;
};
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
ClientServer::Type type;
if (app.arguments().size() < 4) {
qDebug("usage: %s [ConnectedClient <server> <port>|UnconnectedClient <server> <port>|Server]", argv[0]);
return 1;
}
QString arg = app.arguments().at(1).trimmed().toLower();
if (arg == "connectedclient") {
type = ClientServer::ConnectedClient;
} else if (arg == "unconnectedclient") {
type = ClientServer::UnconnectedClient;
} else if (arg == "server") {
type = ClientServer::Server;
} else {
qDebug("usage: %s [ConnectedClient <server> <port>|UnconnectedClient <server> <port>|Server]", argv[0]);
return 1;
}
ClientServer clientServer(type, app.arguments().at(2),
app.arguments().at(3).toInt());
return app.exec();
}
#include "main.moc"
| 31.754491 | 112 | 0.561192 | power-electro |
db4a5dd01fea6491f5006a190a1ebe1138736b9a | 872 | cpp | C++ | experiments/step_crawling/cpp_robot_server/server_node.cpp | yifan-hou/hybrid_servoing | 4d3a2cc047a3bad5ded19934247b5ab5e598f911 | [
"MIT"
] | 16 | 2020-04-15T04:45:02.000Z | 2022-01-13T03:28:46.000Z | experiments/step_crawling/cpp_robot_server/server_node.cpp | yifan-hou/hybrid_servoing | 4d3a2cc047a3bad5ded19934247b5ab5e598f911 | [
"MIT"
] | null | null | null | experiments/step_crawling/cpp_robot_server/server_node.cpp | yifan-hou/hybrid_servoing | 4d3a2cc047a3bad5ded19934247b5ab5e598f911 | [
"MIT"
] | null | null | null | #include "step_crawling.h"
#include <RobotUtilities/utilities.h>
#include <ati_netft/ati_netft.h>
#include <abb_egm/abb_egm.h>
#include <ur_socket/ur_socket.h>
using namespace std;
using namespace RUT;
int main(int argc, char* argv[]) {
ROS_INFO_STREAM("Step crawling task server node starting");
ros::init(argc, argv, "step_crawling_node");
ros::NodeHandle hd;
Clock::time_point time0 = std::chrono::high_resolution_clock::now();
ATINetft ati;
cout << "[test] initializing ft sensor:\n";
ati.init(hd, time0);
cout << "[test] initializing robot:\n";
URSocket *robot = URSocket::Instance();
robot->init(hd, time0);
StepCrawlingTaskServer task_server;
task_server.init(&hd, time0, &ati, robot);
task_server.initStepCrawlingTaskServer();
task_server.hostServices();
ROS_INFO_STREAM(endl << "[MAIN] Rest in Peace." << endl);
return 0;
} | 26.424242 | 70 | 0.716743 | yifan-hou |
db4d1277a1b457e6e3ef93a80a16b4171e2ff0ee | 6,543 | cpp | C++ | src/writers/r_writer.cpp | danielnavarrogomez/Anaquin | 563dbeb25aff15a55e4309432a967812cbfa0c98 | [
"BSD-3-Clause"
] | null | null | null | src/writers/r_writer.cpp | danielnavarrogomez/Anaquin | 563dbeb25aff15a55e4309432a967812cbfa0c98 | [
"BSD-3-Clause"
] | null | null | null | src/writers/r_writer.cpp | danielnavarrogomez/Anaquin | 563dbeb25aff15a55e4309432a967812cbfa0c98 | [
"BSD-3-Clause"
] | null | null | null | #include "stats/analyzer.hpp"
#include "writers/r_writer.hpp"
using namespace Anaquin;
// Defined in main.cpp
extern Path __output__;
// Defined in resources.cpp
extern Scripts PlotLinear();
// Defined in resources.cpp
extern Scripts PlotFold();
// Defined in resources.cpp
extern Scripts PlotLogistic();
Scripts RWriter::createLogistic(const FileName &file,
const std::string &title,
const std::string &xlab,
const std::string &ylab,
const std::string &expected,
const std::string &measured,
bool showLOQ)
{
return (boost::format(PlotLogistic()) % date()
% __full_command__
% __output__
% file
% title
% xlab
% ylab
% ("log2(data$" + expected + ")")
% ("data$" + measured)
% (showLOQ ? "TRUE" : "FALSE")).str();
}
Scripts RWriter::createFold(const FileName &file,
const Path &path,
const std::string &title,
const std::string &xlab,
const std::string &ylab,
const std::string &expected,
const std::string &measured,
bool shouldLog,
const std::string &extra)
{
const auto exp = shouldLog ? ("log2(data$" + expected + ")") : ("data$" + expected);
const auto obs = shouldLog ? ("log2(data$" + measured + ")") : ("data$" + measured);
return (boost::format(PlotFold()) % date()
% __full_command__
% path
% file
% title
% xlab
% ylab
% exp
% obs
% "TRUE"
% extra).str();
}
Scripts RWriter::createMultiLinear(const FileName &file,
const Path &path,
const std::string &title,
const std::string &xlab,
const std::string &ylab,
const std::string &expected,
const std::string &measured,
const std::string &xname,
bool showLOQ,
bool shouldLog,
const std::string &extra)
{
const auto exp = shouldLog ? ("log2(data$" + expected + ")") : ("data$" + expected);
const auto obs = shouldLog ? ("log2(data[,3:ncol(data)])") : ("data[,3:ncol(data)]");
return (boost::format(PlotLinear()) % date()
% __full_command__
% path
% file
% title
% xlab
% ylab
% exp
% obs
% xname
% (showLOQ ? "TRUE" : "FALSE")
% extra).str();
}
Scripts RWriter::createRConjoint(const FileName &file,
const Scripts &script,
const Path &path,
const std::string &title,
const std::string &xlab,
const std::string &ylab,
const std::string &x,
const std::string &y)
{
return (boost::format(script) % date()
% __full_command__
% path
% file
% title
% xlab
% ylab
% x
% y).str();
}
Scripts RWriter::createRLinear(const FileName &file,
const Path &path,
const std::string &title,
const std::string &xlab,
const std::string &ylab,
const std::string &expected,
const std::string &measured,
const std::string &xname,
bool showLOQ,
const std::string &script)
{
return (boost::format(script.empty() ? PlotLinear() : script)
% date()
% __full_command__
% path
% file
% title
% xlab
% ylab
% expected
% measured
% xname
% (showLOQ ? "TRUE" : "FALSE")).str();
}
Scripts RWriter::createScript(const FileName &file, const Scripts &script)
{
return (boost::format(script) % date()
% __full_command__
% __output__
% file).str();
}
Scripts RWriter::createScript(const FileName &file, const Scripts &script, const std::string &x)
{
return (boost::format(script) % date()
% __full_command__
% __output__
% file
% x).str();
}
| 42.487013 | 96 | 0.32508 | danielnavarrogomez |
db4e7ed1ba533943e6b3cde934a3bab7d6e3157a | 2,209 | cpp | C++ | src/bug_10.cpp | happanda/advent_2017 | 9e705f3088d79dac0caa471154ae88ed5106b2d2 | [
"MIT"
] | null | null | null | src/bug_10.cpp | happanda/advent_2017 | 9e705f3088d79dac0caa471154ae88ed5106b2d2 | [
"MIT"
] | null | null | null | src/bug_10.cpp | happanda/advent_2017 | 9e705f3088d79dac0caa471154ae88ed5106b2d2 | [
"MIT"
] | null | null | null | #include "advent.h"
inline void reverse(std::vector<int>& vect, int from, int length)
{
int const vsize = vect.size();
if (length > vsize)
return;
for (int i = 0; i < length / 2; ++i)
std::swap(vect[(from + i) % vsize], vect[(from + length - i - 1) % vsize]);
}
inline std::string knotHash(std::string const& input)
{
int const numRounds = 64;
int const seqLength = 256;
int const xorLength = 16;
std::vector<int> sequence;
std::generate_n(std::back_inserter(sequence), seqLength, [&sequence]() {return sequence.size(); });
std::vector<int> lengths;
std::transform(input.begin(), input.end(), std::back_inserter(lengths), [](char symbol) { return static_cast<int>(symbol); });
for (int n : { 17, 31, 73, 47, 23 })
lengths.push_back(n);
int curInd = 0;
int skipSize = 0;
for (int r = 0; r < numRounds; ++r)
{
for (int length : lengths)
{
if (length > static_cast<int>(sequence.size()))
continue;
reverse(sequence, curInd, length);
curInd += (length + skipSize) % seqLength;
skipSize = (skipSize + 1) % seqLength;
}
}
std::string xored(2 * seqLength / xorLength, 0);
for (int i = 0; i < seqLength / xorLength; ++i)
{
int xorResult = 0;
for (int j = 0; j < xorLength; ++j)
{
xorResult ^= sequence[i * xorLength + j];
}
char hex1 = (xorResult / 16) % 16;
char hex0 = xorResult % 16;
if (hex1 < 10)
xored[i * 2] = hex1 + '0';
else
xored[i * 2] = hex1 - 10 + 'a';
if (hex0 < 10)
xored[i * 2 + 1] = hex0 + '0';
else
xored[i * 2 + 1] = hex0 - 10 + 'a';
}
return xored;
}
void BugFix<10>::solve1st()
{
int const seqLength = 256;
std::vector<int> sequence;
std::generate_n(std::back_inserter(sequence), seqLength, [&sequence]() {return sequence.size(); });
std::string word;
int curInd = 0;
int skipSize = 0;
while (std::getline(*mIn, word, ','))
{
int const length = std::stoi(word);
if (length > static_cast<int>(sequence.size()))
continue;
reverse(sequence, curInd, length);
curInd += (length + skipSize) % seqLength;
++skipSize;
}
*mOut << sequence[0] * sequence[1] << std::endl;
}
void BugFix<10>::solve2nd()
{
std::string input;
*mIn >> input;
*mOut << knotHash(input) << std::endl;
}
| 22.773196 | 127 | 0.609325 | happanda |
db52b53a633360f262474ffbf9e3a3fb7a3ee542 | 11,578 | cpp | C++ | lib/orvis/Scene.cpp | f-schroeder/orvis | 440de86bc4331100f24efb192d8781240a59f80e | [
"MIT"
] | null | null | null | lib/orvis/Scene.cpp | f-schroeder/orvis | 440de86bc4331100f24efb192d8781240a59f80e | [
"MIT"
] | null | null | null | lib/orvis/Scene.cpp | f-schroeder/orvis | 440de86bc4331100f24efb192d8781240a59f80e | [
"MIT"
] | null | null | null | #include "Scene.hpp"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/config.h>
#include <numeric>
#include <execution>
#include "Util.hpp"
#include "stb/stb_image.h"
Scene::Scene(const std::filesystem::path& filename)
{
const auto path = util::resourcesPath / filename;
const auto pathString = path.string();
Assimp::Importer importer;
std::cout << "Loading model from " << filename.string() << std::endl;
// aiComponent_TANGENTS_AND_BITANGENTS flips the winding order (assimp-internal bug)
const aiScene * assimpScene = importer.ReadFile(pathString.c_str(), aiProcess_GenSmoothNormals |
aiProcess_Triangulate | aiProcess_GenUVCoords | aiProcess_JoinIdenticalVertices |
aiProcess_RemoveComponent | aiComponent_ANIMATIONS | aiComponent_BONEWEIGHTS |
aiComponent_CAMERAS | aiComponent_LIGHTS /*| aiComponent_TANGENTS_AND_BITANGENTS*/ | aiComponent_COLORS |
aiProcess_SplitLargeMeshes | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials |
aiProcess_OptimizeMeshes | aiProcess_SortByPType | aiProcess_FindDegenerates | aiProcess_FindInvalidData);
if (!assimpScene || assimpScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE)
{
const std::string err = importer.GetErrorString();
throw std::runtime_error("Assimp import failed: " + err);
}
std::cout << "Assimp import complete. Processing Model..." << std::endl;
// - - - M E S H E S - - -
if (assimpScene->HasMeshes())
{
const auto numMeshes = assimpScene->mNumMeshes;
m_meshes.resize(numMeshes);
for (int i = 0; i < static_cast<int>(numMeshes); ++i)
{
m_meshes[i] = std::shared_ptr<Mesh>(new Mesh(assimpScene->mMeshes[i], assimpScene->mMaterials[assimpScene->mMeshes[i]->mMaterialIndex], path));
}
}
// - - - M O D E L M A T R I C E S - - -
static_assert(sizeof(aiMatrix4x4) == sizeof(glm::mat4));
std::function<void(aiNode* node, glm::mat4 trans)> traverseChildren = [this, &traverseChildren](aiNode* node, glm::mat4 trans)
{
// check if transformation exists
if (std::none_of(&node->mTransformation.a1, (&node->mTransformation.d4) + 1,
[](float f) { return std::isnan(f) || std::isinf(f); }))
{
// accumulate transform
const glm::mat4 transform = reinterpret_cast<glm::mat4&>(node->mTransformation);
trans *= transform;
}
// assign transformation to meshes
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(node->mNumMeshes); ++i)
{
m_meshes[node->mMeshes[i]]->modelMatrix = trans;
}
// recursively work on the child nodes
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(node->mNumChildren); ++i)
{
traverseChildren(node->mChildren[i], trans);
}
};
const auto root = assimpScene->mRootNode;
std::thread modelMatThread([&]()
{
traverseChildren(root, glm::mat4(1.0f));
calculateBoundingBox();
});
{ // running in parallel --> no model-matrices available in this scope!
updateMultiDrawBuffers();
updateMaterialBuffer();
m_cullingProgram.attachNew(GL_COMPUTE_SHADER, ShaderFile::load("compute/viewFrustumCulling.comp"));
m_lightIndexBuffer.resize(1, GL_DYNAMIC_STORAGE_BIT);
}
modelMatThread.join();
updateModelMatrices();
updateBoundingBoxBuffer();
std::cout << "Loading complete: " << filename.string() << std::endl;
importer.FreeScene();
}
void Scene::render(const Program& program, bool overwriteCameraBuffer) const
{
// BINDINGS
m_indirectDrawBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::indirectDraw);
m_bBoxBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::boundingBoxes);
m_modelMatBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::modelMatrices);
m_materialBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::materials);
m_lightBuffer.bind(GL_SHADER_STORAGE_BUFFER, BufferBinding::lights);
if (overwriteCameraBuffer)
m_camera->uploadToGpu();
// CULLING
m_cullingProgram.use();
glDispatchCompute(static_cast<GLuint>(glm::ceil(m_indirectDrawBuffer.size() / 64.0f)), 1, 1);
glMemoryBarrier(GL_COMMAND_BARRIER_BIT | GL_SHADER_STORAGE_BARRIER_BIT);
// DRAW
program.use();
m_multiDrawVao.bind();
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, *m_indirectDrawBuffer.id());
glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_INT, nullptr, static_cast<GLsizei>(m_indirectDrawBuffer.size()), 0);
}
const Bounds& Scene::calculateBoundingBox()
{
struct Reduction
{
Bounds operator()(Bounds b, const std::shared_ptr<Mesh>& x) const {
return b +
Bounds(x->modelMatrix * glm::vec4(x->bounds.min, 1.0f), x->modelMatrix * glm::vec4(x->bounds.max, 1.0f));
}
Bounds operator()(const std::shared_ptr<Mesh>& x, Bounds b) const {
return b +
Bounds(x->modelMatrix * glm::vec4(x->bounds.min, 1.0f), x->modelMatrix * glm::vec4(x->bounds.max, 1.0f));
}
Bounds operator()(const std::shared_ptr<Mesh>& a, const std::shared_ptr<Mesh>& b) const
{
Bounds bounds;
bounds = bounds + Bounds(a->modelMatrix * glm::vec4(a->bounds.min, 1.0f), a->modelMatrix * glm::vec4(a->bounds.max, 1.0f));
return bounds + Bounds(b->modelMatrix * glm::vec4(b->bounds.min, 1.0f), b->modelMatrix * glm::vec4(b->bounds.max, 1.0f));
}
Bounds operator()(Bounds b, const Bounds& x) const { return b + x; }
};
bounds = std::reduce(std::execution::par_unseq, m_meshes.begin(), m_meshes.end(), Bounds(), Reduction());
if (m_camera)
m_camera->setSpeed(0.1f * glm::length(bounds[1] - bounds[0]));
return bounds;
}
void Scene::updateModelMatrices()
{
std::vector<glm::mat4> modelMatrices(m_meshes.size());
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(modelMatrices.size()); ++i)
modelMatrices[i] = m_meshes[i]->modelMatrix;
if (modelMatrices.size() != static_cast<size_t>(m_modelMatBuffer.size()))
m_modelMatBuffer.resize(modelMatrices.size(), GL_DYNAMIC_STORAGE_BIT);
m_modelMatBuffer.assign(modelMatrices);
}
void Scene::updateBoundingBoxBuffer()
{
std::vector<Bounds> boundingBoxes(m_meshes.size());
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(boundingBoxes.size()); ++i)
boundingBoxes[i] = m_meshes[i]->bounds;
if (boundingBoxes.size() != static_cast<size_t>(m_bBoxBuffer.size()))
m_bBoxBuffer.resize(boundingBoxes.size(), GL_DYNAMIC_STORAGE_BIT);
m_bBoxBuffer.assign(boundingBoxes);
}
void Scene::updateMaterialBuffer()
{
std::vector<Material> materials(m_meshes.size());
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(materials.size()); ++i)
materials[i] = m_meshes[i]->material;
if (materials.size() != static_cast<size_t>(m_materialBuffer.size()))
m_materialBuffer.resize(materials.size(), GL_DYNAMIC_STORAGE_BIT);
m_materialBuffer.assign(materials);
}
void Scene::updateLightBuffer()
{
std::vector<Light> lights(m_lights.size());
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(lights.size()); ++i)
{
m_lights[i]->recalculateLightSpaceMatrix(*this);
lights[i] = *m_lights[i];
}
if (lights.size() != static_cast<size_t>(m_lightBuffer.size()))
m_lightBuffer.resize(lights.size(), GL_DYNAMIC_STORAGE_BIT);
m_lightBuffer.assign(lights);
}
void Scene::updateShadowMaps()
{
for (int i = 0; i < static_cast<int>(m_lights.size()); ++i)
{
m_lightIndexBuffer.assign(i);
m_lightIndexBuffer.bind(GL_UNIFORM_BUFFER, BufferBinding::lightIndex);
m_lights[i]->updateShadowMap(*this);
}
}
void Scene::addMesh(const std::shared_ptr<Mesh>& mesh)
{
m_meshes.push_back(mesh);
std::thread bBoxThread([&]() { calculateBoundingBox(); });
updateModelMatrices();
updateMultiDrawBuffers();
updateBoundingBoxBuffer();
updateMaterialBuffer();
bBoxThread.join();
}
void Scene::addLight(const std::shared_ptr<Light>& light)
{
m_lights.push_back(light);
updateLightBuffer();
updateShadowMaps();
}
void Scene::setCamera(const std::shared_ptr<Camera>& camera)
{
m_camera = camera;
m_camera->setSpeed(0.1f * glm::length(bounds[1] - bounds[0]));
}
std::shared_ptr<Camera> Scene::getCamera() const
{
return m_camera;
}
const std::deque<std::shared_ptr<Mesh>>& Scene::getMeshes() const
{
return m_meshes;
}
void Scene::reorderMeshes()
{
std::deque<std::shared_ptr<Mesh>> orderedMeshes;
for (const auto& mesh : m_meshes)
{
if (mesh->isTransparent())
orderedMeshes.push_back(mesh);
else
orderedMeshes.push_front(mesh);
}
m_meshes = orderedMeshes;
updateModelMatrices();
updateMultiDrawBuffers();
updateBoundingBoxBuffer();
updateMaterialBuffer();
}
void Scene::updateMultiDrawBuffers()
{
std::vector<GLuint> allIndices;
std::vector<glm::vec4> allVertices;
std::vector<glm::vec4> allNormals;
std::vector<glm::vec2> allUVs;
std::vector<IndirectDrawCommand> indirectDrawParams;
GLuint start = 0;
GLuint baseVertexOffset = 0;
for (const auto& mesh : m_meshes)
{
allIndices.insert(allIndices.end(), mesh->indices.begin(), mesh->indices.end());
allVertices.insert(allVertices.end(), mesh->vertices.begin(), mesh->vertices.end());
allNormals.insert(allNormals.end(), mesh->normals.begin(), mesh->normals.end());
allUVs.insert(allUVs.end(), mesh->uvs.begin(), mesh->uvs.end());
const auto count = static_cast<GLuint>(mesh->indices.size());
indirectDrawParams.push_back({ count, 1U, start, baseVertexOffset, 0U });
start += count;
baseVertexOffset += static_cast<GLuint>(mesh->vertices.size());
}
m_multiDrawIndexBuffer.resize(allIndices.size(), GL_DYNAMIC_STORAGE_BIT);
m_multiDrawIndexBuffer.assign(allIndices);
m_multiDrawVertexBuffer.resize(allVertices.size(), GL_DYNAMIC_STORAGE_BIT);
m_multiDrawVertexBuffer.assign(allVertices);
m_multiDrawNormalBuffer.resize(allNormals.size(), GL_DYNAMIC_STORAGE_BIT);
m_multiDrawNormalBuffer.assign(allNormals);
m_multiDrawUVBuffer.resize(allUVs.size(), GL_DYNAMIC_STORAGE_BIT);
m_multiDrawUVBuffer.assign(allUVs);
m_indirectDrawBuffer.resize(indirectDrawParams.size(), GL_DYNAMIC_STORAGE_BIT);
m_indirectDrawBuffer.assign(indirectDrawParams);
m_multiDrawVao.format(VertexAttributeBinding::vertices, 4, GL_FLOAT, false, 0);
m_multiDrawVao.setVertexBuffer(m_multiDrawVertexBuffer, VertexAttributeBinding::vertices, 0, sizeof(glm::vec4));
m_multiDrawVao.binding(VertexAttributeBinding::vertices);
m_multiDrawVao.format(VertexAttributeBinding::normals, 4, GL_FLOAT, true, 0);
m_multiDrawVao.setVertexBuffer(m_multiDrawNormalBuffer, VertexAttributeBinding::normals, 0, sizeof(glm::vec4));
m_multiDrawVao.binding(VertexAttributeBinding::normals);
m_multiDrawVao.format(VertexAttributeBinding::texCoords, 2, GL_FLOAT, false, 0);
m_multiDrawVao.setVertexBuffer(m_multiDrawUVBuffer, VertexAttributeBinding::texCoords, 0, sizeof(glm::vec2));
m_multiDrawVao.binding(VertexAttributeBinding::texCoords);
m_multiDrawVao.setElementBuffer(m_multiDrawIndexBuffer);
}
| 34.561194 | 155 | 0.682156 | f-schroeder |
db58527125571dfd22175d05ec81f1e14c2605fd | 3,485 | cpp | C++ | GeneratorSource/Source/Panels/PanelList.cpp | ercdndrs/Arduino-Source | c0490f0f06aaa38759aa8f11def9e1349e551679 | [
"MIT"
] | null | null | null | GeneratorSource/Source/Panels/PanelList.cpp | ercdndrs/Arduino-Source | c0490f0f06aaa38759aa8f11def9e1349e551679 | [
"MIT"
] | null | null | null | GeneratorSource/Source/Panels/PanelList.cpp | ercdndrs/Arduino-Source | c0490f0f06aaa38759aa8f11def9e1349e551679 | [
"MIT"
] | null | null | null | /* List of all Panels
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include "Common/Qt/StringException.h"
#include "Common/Qt/QtJsonTools.h"
#include "JsonSettings.h"
#include "JsonProgram.h"
#include "Tools/PersistentSettings.h"
#include "PanelList.h"
#include <iostream>
using std::cout;
using std::endl;
namespace PokemonAutomation{
const std::vector<std::unique_ptr<ConfigSet>>& SETTINGS_LIST(){
static std::vector<std::unique_ptr<ConfigSet>> list;
if (!list.empty()){
return list;
}
QString path = settings.path + CONFIG_FOLDER_NAME + "/SettingsList.txt";
QFile file(path);
if (!file.open(QFile::ReadOnly)){
// QMessageBox box;
// box.critical(nullptr, "Error", "Unable to open settings list: " + settings_path);
return list;
}
cout << "File = " << path.toUtf8().data() << endl;
QTextStream stream(&file);
while (!stream.atEnd()){
QString line = stream.readLine();
if (line.isEmpty()){
continue;
}
cout << "Open: " << line.toUtf8().data() << endl;
try{
QString path = settings.path + CONFIG_FOLDER_NAME + "/" + line + ".json";
list.emplace_back(new Settings_JsonFile(path));
}catch (const StringException& str){
cout << "Error: " << str.message().toUtf8().data() << endl;
}
}
file.close();
return list;
}
const std::map<QString, ConfigSet*>& SETTINGS_MAP(){
static std::map<QString, ConfigSet*> map;
if (!map.empty()){
return map;
}
for (const auto& program : SETTINGS_LIST()){
auto ret = map.emplace(program->name(), program.get());
if (!ret.second){
throw StringException("Duplicate program name: " + program->name());
}
}
return map;
}
const std::vector<std::unique_ptr<Program>>& PROGRAM_LIST(){
static std::vector<std::unique_ptr<Program>> list;
if (!list.empty()){
return list;
}
QString path = settings.path + CONFIG_FOLDER_NAME + "/ProgramList.txt";
QFile file(path);
if (!file.open(QFile::ReadOnly)){
// QMessageBox box;
// box.critical(nullptr, "Error", "Unable to open programs list: " + settings_path);
return list;
}
cout << "File = " << path.toUtf8().data() << endl;
QTextStream stream(&file);
while (!stream.atEnd()){
QString line = stream.readLine();
if (line.isEmpty()){
continue;
}
cout << "Open: " << line.toUtf8().data() << endl;
try{
QString path = settings.path + CONFIG_FOLDER_NAME + "/" + line + ".json";
list.emplace_back(new Program_JsonFile(path));
}catch (const StringException& str){
cout << "Error: " << str.message().toUtf8().data() << endl;
}
}
file.close();
return list;
}
const std::map<QString, Program*>& PROGRAM_MAP(){
static std::map<QString, Program*> map;
if (map.empty()){
for (const auto& program : PROGRAM_LIST()){
auto ret = map.emplace(program->name(), program.get());
if (!ret.second){
throw StringException("Duplicate program name: " + program->name());
}
}
}
return map;
}
}
| 28.104839 | 92 | 0.55868 | ercdndrs |
db5b4cd53cee3cd795f7a29cf3eeea0d2529fa5a | 3,580 | cpp | C++ | third_party/libosmium/test/t/basic/test_node.cpp | Mapotempo/osrm-backend | a62c10321c0a269e218ab4164c4ccd132048f271 | [
"BSD-2-Clause"
] | 1 | 2016-11-29T15:02:40.000Z | 2016-11-29T15:02:40.000Z | third_party/libosmium/test/t/basic/test_node.cpp | aaronbenz/osrm-backend | 758d4023050d1f49971f919cea872a2276dafe14 | [
"BSD-2-Clause"
] | 1 | 2019-02-04T18:10:57.000Z | 2019-02-04T18:10:57.000Z | third_party/libosmium/test/t/basic/test_node.cpp | Mapotempo/osrm-backend | a62c10321c0a269e218ab4164c4ccd132048f271 | [
"BSD-2-Clause"
] | null | null | null | #include "catch.hpp"
#include <boost/crc.hpp>
#include <osmium/osm/crc.hpp>
#include <osmium/osm/node.hpp>
#include "helper.hpp"
TEST_CASE("Basic_Node") {
osmium::CRC<boost::crc_32_type> crc32;
SECTION("node_builder") {
osmium::memory::Buffer buffer(10000);
osmium::Node& node = buffer_add_node(buffer,
"foo",
{{"amenity", "pub"}, {"name", "OSM BAR"}},
{3.5, 4.7});
node.set_id(17)
.set_version(3)
.set_visible(true)
.set_changeset(333)
.set_uid(21)
.set_timestamp(123);
REQUIRE(osmium::item_type::node == node.type());
REQUIRE(node.type_is_in(osmium::osm_entity_bits::node));
REQUIRE(node.type_is_in(osmium::osm_entity_bits::nwr));
REQUIRE(17l == node.id());
REQUIRE(17ul == node.positive_id());
REQUIRE(3 == node.version());
REQUIRE(true == node.visible());
REQUIRE(false == node.deleted());
REQUIRE(333 == node.changeset());
REQUIRE(21 == node.uid());
REQUIRE(std::string("foo") == node.user());
REQUIRE(123 == node.timestamp());
REQUIRE(osmium::Location(3.5, 4.7) == node.location());
REQUIRE(2 == node.tags().size());
crc32.update(node);
REQUIRE(crc32().checksum() == 0xc696802f);
node.set_visible(false);
REQUIRE(false == node.visible());
REQUIRE(true == node.deleted());
}
SECTION("node_default_attributes") {
osmium::memory::Buffer buffer(10000);
osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{});
REQUIRE(0l == node.id());
REQUIRE(0ul == node.positive_id());
REQUIRE(0 == node.version());
REQUIRE(true == node.visible());
REQUIRE(0 == node.changeset());
REQUIRE(0 == node.uid());
REQUIRE(std::string("") == node.user());
REQUIRE(0 == node.timestamp());
REQUIRE(osmium::Location() == node.location());
REQUIRE(0 == node.tags().size());
}
SECTION("set_node_attributes_from_string") {
osmium::memory::Buffer buffer(10000);
osmium::Node& node = buffer_add_node(buffer,
"foo",
{{"amenity", "pub"}, {"name", "OSM BAR"}},
{3.5, 4.7});
node.set_id("-17")
.set_version("3")
.set_visible(true)
.set_changeset("333")
.set_uid("21");
REQUIRE(-17l == node.id());
REQUIRE(17ul == node.positive_id());
REQUIRE(3 == node.version());
REQUIRE(true == node.visible());
REQUIRE(333 == node.changeset());
REQUIRE(21 == node.uid());
}
SECTION("large_id") {
osmium::memory::Buffer buffer(10000);
osmium::Node& node = buffer_add_node(buffer, "", {}, osmium::Location{});
int64_t id = 3000000000l;
node.set_id(id);
REQUIRE(id == node.id());
REQUIRE(static_cast<osmium::unsigned_object_id_type>(id) == node.positive_id());
node.set_id(-id);
REQUIRE(-id == node.id());
REQUIRE(static_cast<osmium::unsigned_object_id_type>(id) == node.positive_id());
}
SECTION("tags") {
osmium::memory::Buffer buffer(10000);
osmium::Node& node = buffer_add_node(buffer,
"foo",
{{"amenity", "pub"}, {"name", "OSM BAR"}},
{3.5, 4.7});
REQUIRE(nullptr == node.tags().get_value_by_key("fail"));
REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity"));
REQUIRE(std::string("pub") == node.get_value_by_key("amenity"));
REQUIRE(std::string("default") == node.tags().get_value_by_key("fail", "default"));
REQUIRE(std::string("pub") == node.tags().get_value_by_key("amenity", "default"));
REQUIRE(std::string("pub") == node.get_value_by_key("amenity", "default"));
}
}
| 28.412698 | 87 | 0.603631 | Mapotempo |
db5b6d341ba5c92e5aad480e3a7e19853caf3240 | 1,051 | cpp | C++ | dynamicProgramming/IncreasingSubsequence/increasingSubsequence.cpp | MrCarZ/cses-solutions | 9ea0ad65572bf9d4c321a3ae313c22f64f1ac9a7 | [
"MIT"
] | null | null | null | dynamicProgramming/IncreasingSubsequence/increasingSubsequence.cpp | MrCarZ/cses-solutions | 9ea0ad65572bf9d4c321a3ae313c22f64f1ac9a7 | [
"MIT"
] | null | null | null | dynamicProgramming/IncreasingSubsequence/increasingSubsequence.cpp | MrCarZ/cses-solutions | 9ea0ad65572bf9d4c321a3ae313c22f64f1ac9a7 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
const int MAXN = 2E+5 + 5;
const int MAXX = 1E+9 + 7;
int n, vec[MAXN],vec2[MAXN],dp[MAXN];
vector<int> fenwick(MAXN, 0);
void add(int pos, int val){
for(int i = pos; i<=n; i+=i&(-i)){
fenwick[i] = max(val, fenwick[i]);
}
}
int get(int pos){
int ans = -MAXX;
for(int i = pos; i>0; i-=i&(-i)){
ans = max(ans, fenwick[i]);
}
return ans;
}
int main(){
ios::sync_with_stdio(0);
cin>>n;
map<int,int> comp;
for(int i = 1; i<=n; i++){
cin>>vec[i];
vec2[i] = vec[i];
}
sort(vec2, vec2+n+1);
int counter = 1;
for(int i = 1; i<=n; i++){
if(comp[vec2[i]] == 0){
comp[vec2[i]] = counter++;
}
}
for(int i = 1; i<=n; i++) {vec[i] = comp[vec[i]];}
int ans = -MAXX;
for(int i = 1; i<=n; i++){
dp[i] = 1;
dp[i] = max(get(vec[i]-1)+1, dp[i]);
add(vec[i], dp[i]);
ans = max(ans, dp[i]);
}
cout<<ans<<'\n';
return 0;
} | 17.229508 | 54 | 0.444339 | MrCarZ |
db6005fb4b088d339a2014db33c55affca188efe | 7,852 | cpp | C++ | training/work/demo_manipulation/src/robot_io/src/nodes/open_close_grasp_action_server.cpp | asct/industrial_training | f69c54cad966382ce93b34138696a99abc66f444 | [
"Apache-2.0"
] | 324 | 2015-01-31T07:35:37.000Z | 2022-03-27T09:30:14.000Z | training/work/demo_manipulation/src/robot_io/src/nodes/open_close_grasp_action_server.cpp | asct/industrial_training | f69c54cad966382ce93b34138696a99abc66f444 | [
"Apache-2.0"
] | 226 | 2015-01-20T17:15:56.000Z | 2022-01-19T04:55:23.000Z | training/work/demo_manipulation/src/robot_io/src/nodes/open_close_grasp_action_server.cpp | asct/industrial_training | f69c54cad966382ce93b34138696a99abc66f444 | [
"Apache-2.0"
] | 219 | 2015-03-29T03:05:11.000Z | 2022-03-23T11:12:43.000Z | /*
* OpenCloseGraspActionServer.cpp
*
* Created on: Apr 19, 2013
* Author: jnicho
*/
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Southwest Research Institute
* 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 Southwest Research Institute, 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.
*/
#include <ros/ros.h>
#include <actionlib/server/action_server.h>
#include <object_manipulation_msgs/GraspHandPostureExecutionAction.h>
#include <object_manipulation_msgs/GraspHandPostureExecutionGoal.h>
#include <robot_io/DigitalOutputUpdate.h>
#include <soem_beckhoff_drivers/DigitalMsg.h>
using namespace object_manipulation_msgs;
using namespace actionlib;
typedef robot_io::DigitalOutputUpdate::Request DigitalOutputType;
static const std::string OUTPUT_TOPIC = "/digital_outputs";
static const std::string INPUT_TOPIC = "/digital_inputs";
static const std::string OUTPUT_SERVICE = "/digital_output_update";
class SimpleGraspActionServer
{
private:
typedef ActionServer<GraspHandPostureExecutionAction> GEAS;
typedef GEAS::GoalHandle GoalHandle;
public:
SimpleGraspActionServer(ros::NodeHandle &n) :
node_(n),
action_server_(node_, "grasp_execution_action",
boost::bind(&SimpleGraspActionServer::goalCB, this, _1),
boost::bind(&SimpleGraspActionServer::cancelCB, this, _1),
false),
use_sensor_feedback_(false),
suction_on_output_channel_(DigitalOutputType::SUCTION1_ON),
suction_check_input_channel_(DigitalOutputType::SUCTION1_ON)
{
}
~SimpleGraspActionServer()
{
}
void init()
{
ros::NodeHandle pn("/");
std::string nodeName = ros::this_node::getName();
// service client
service_client_ = pn.serviceClient<robot_io::DigitalOutputUpdate>(OUTPUT_SERVICE);
while(!service_client_.waitForExistence(ros::Duration(5.0f)))
{
ROS_INFO_STREAM(nodeName<<": Waiting for "<<OUTPUT_SERVICE<<" to start");
}
if(!fetchParameters() )
{
ROS_ERROR_STREAM(nodeName<<": Did not find required ros parameters, exiting");
ros::shutdown();
return;
}
if(!validateChannelIndices())
{
ROS_ERROR_STREAM(nodeName<<": One or more parameter values are invalid");
ros::shutdown();
return;
}
action_server_.start();
ROS_INFO_STREAM(nodeName<<": Grasp execution action node started");
}
private:
void goalCB(GoalHandle gh)
{
std::string nodeName = ros::this_node::getName();
ROS_INFO("%s",(nodeName + ": Received grasping goal").c_str());
robot_io::DigitalOutputUpdate::Request req;
robot_io::DigitalOutputUpdate::Response res;
bool success;
switch(gh.getGoal()->goal)
{
case GraspHandPostureExecutionGoal::PRE_GRASP:
gh.setAccepted();
ROS_INFO_STREAM(nodeName + ": Pre-grasp command accepted");
req.bit_index = suction_on_output_channel_;
req.output_bit_state = true;
if(service_client_.call(req,res))
{
gh.setSucceeded();
ROS_INFO_STREAM(nodeName + ": Pre-grasp command succeeded");
}
else
{
gh.setAborted();
ROS_INFO_STREAM(nodeName + ": Pre-grasp command aborted");
}
break;
case GraspHandPostureExecutionGoal::GRASP:
gh.setAccepted();
ROS_INFO_STREAM(nodeName + ": Grasp command accepted");
req.bit_index = suction_on_output_channel_;
req.output_bit_state = false;
success = service_client_.call(req,res);
if(success)
{
if(use_sensor_feedback_ && !checkSensorState())
{
gh.setAborted();
ROS_INFO_STREAM(nodeName + ": Grasp command aborted");
break;
}
}
else
{
gh.setAborted();
ROS_INFO_STREAM(nodeName + ": Grasp command aborted");
break;
}
gh.setSucceeded();
ROS_INFO_STREAM(nodeName + ": Grasp command succeeded");
break;
case GraspHandPostureExecutionGoal::RELEASE:
gh.setAccepted();
ROS_INFO_STREAM(nodeName + ": Release command accepted");
req.bit_index = suction_on_output_channel_;
req.output_bit_state = true;
if(service_client_.call(req,res))
{
gh.setSucceeded();
ROS_INFO_STREAM(nodeName + ": Release command succeeded");
}
else
{
gh.setAborted();
ROS_INFO_STREAM(nodeName + ": Release command aborted");
}
break;
default:
ROS_WARN_STREAM(nodeName + ": Unidentified grasp request, rejecting request");
gh.setRejected();
break;
}
}
void cancelCB(GoalHandle gh)
{
std::string nodeName = ros::this_node::getName();
ROS_INFO_STREAM(nodeName + ": Canceling current grasp action");
gh.setCanceled();
ROS_INFO_STREAM(nodeName + ": Current grasp action has been canceled");
}
bool fetchParameters()
{
ros::NodeHandle nh;
bool success = true;
nh.getParam("use_sensor_feedback",use_sensor_feedback_);
success = success && nh.getParam("suction_on_output_channel",suction_on_output_channel_);
success = success && nh.getParam("suction_check_output_channel",suction_check_input_channel_);
return success;
}
bool validateChannelIndices()
{
typedef robot_io::DigitalOutputUpdate::Request DigitalOutputType;
if(suction_on_output_channel_ >= (int)DigitalOutputType::COUNT || suction_on_output_channel_ == (int)DigitalOutputType::COLLISION)
{
return false;
}
if(suction_check_input_channel_ >= int(DigitalOutputType::COUNT))
{
return false;
}
return true;
}
bool checkSensorState()
{
ros::NodeHandle nh("/");
soem_beckhoff_drivers::DigitalMsg::ConstPtr input_msg_ =
ros::topic::waitForMessage<soem_beckhoff_drivers::DigitalMsg>(INPUT_TOPIC,nh,ros::Duration(2.0f));
if(!input_msg_)
{
ROS_ERROR_STREAM(ros::this_node::getName()<<": Input message received invalid");
return true;
}
else
{
return ((input_msg_->values[suction_check_input_channel_] == 1) ? true : false);
}
}
// ros comm
ros::NodeHandle node_;
GEAS action_server_;
ros::ServiceClient service_client_;
// ros parameters
int suction_on_output_channel_; // index value to output channel for suction
int suction_check_input_channel_; // index value to input channel for vacuum sensor
bool use_sensor_feedback_;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "grasp_execution_action_node");
ros::NodeHandle node("");
SimpleGraspActionServer ge(node);
ge.init();
ros::spin();
return 0;
}
| 27.550877 | 133 | 0.710265 | asct |
db61705d57f0223b23905967953c5dffa451a9b5 | 1,651 | cpp | C++ | Intro/program_10/asciiDowning.cpp | JasonD94/HighSchool | e37bb56b8149acc87cdb5e37ea619ab6db58fc29 | [
"MIT"
] | null | null | null | Intro/program_10/asciiDowning.cpp | JasonD94/HighSchool | e37bb56b8149acc87cdb5e37ea619ab6db58fc29 | [
"MIT"
] | null | null | null | Intro/program_10/asciiDowning.cpp | JasonD94/HighSchool | e37bb56b8149acc87cdb5e37ea619ab6db58fc29 | [
"MIT"
] | null | null | null | #include <iostream.h>
#include <conio.h>
void convert (char letter);
main()
{
int x = 2; //for the do/while
char b; //to accept letter input
do{
cout<<"Welcome to the Letter Converter Program. \n";
cout<<"This program will accept a letter and convert it between \n"; //introduction
cout<<"uppercase and lower case. \n";
cout<<"\nEnter a letter to convert. -> ";
cin>>b;
convert(b); //sends b to the function convert, doesn't return.
do{
cout<<"\nTo stop the program, enter 1. To rerun the program, enter 2. -> ";
cin>>x;
cout<<endl;
// this makes it so only 1 or 2 can be entered - cannot enter 3 to quit for instance.
}while((x != 1) && (x != 2));
clrscr();
}while(x==2);
return 0;
}
void convert (char letter)
{
//The letter must be between 65-90 and 97-122 to be 'a to z'.
//Which is why 91-96 is not allowed.
if(letter >= 65 && letter <= 122)
{
//uppercase to lower case.
if(letter >= 65 && letter <= 90)
{
letter = letter + 32;
cout<<endl<<letter<<endl;
letter = letter - 32; //without this it seems to convert it back to uppercase, but this fixes that issue.
}
//for 91 to 96, which are not letters.
if(letter >=91 && letter <= 96)
{
cout<<"\nYou didn't enter a letter; try again. \n";
}
//lower case to upper case.
if(letter >= 97 && letter <= 122)
{
letter = letter - 32;
cout<<endl<<letter<<endl;
}
}
else //if the user enters something else that isn't letter (65-90 or 97-122), the program prints this.
{
cout<<"\nYou didn't enter a letter; try again. \n";
}
}
| 23.253521 | 109 | 0.591157 | JasonD94 |
db69cf0301c2eb940418a74f1332a35457e560fd | 17,960 | cc | C++ | paddle/fluid/operators/detection/generate_mask_labels_op.cc | Thunderbrook/Paddle | 4870c9bc99c6bd3b814485d7d4f525fe68ccd9a5 | [
"Apache-2.0"
] | 1 | 2021-12-27T02:48:34.000Z | 2021-12-27T02:48:34.000Z | paddle/fluid/operators/detection/generate_mask_labels_op.cc | Thunderbrook/Paddle | 4870c9bc99c6bd3b814485d7d4f525fe68ccd9a5 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/operators/detection/generate_mask_labels_op.cc | Thunderbrook/Paddle | 4870c9bc99c6bd3b814485d7d4f525fe68ccd9a5 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2018 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 <math.h>
#include <algorithm>
#include <string>
#include <vector>
#include "paddle/fluid/framework/lod_tensor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/detection/bbox_util.h"
#include "paddle/fluid/operators/detection/mask_util.h"
#include "paddle/fluid/operators/gather.h"
#include "paddle/fluid/operators/math/concat_and_split.h"
#include "paddle/fluid/operators/math/math_function.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
const int kBoxDim = 4;
template <typename T>
void AppendMask(LoDTensor* out, int64_t offset, Tensor* to_add) {
auto* out_data = out->data<T>();
auto* to_add_data = to_add->data<T>();
memcpy(out_data + offset, to_add_data, to_add->numel() * sizeof(T));
}
class GenerateMaskLabelsOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("ImInfo"), "Input(ImInfo) shouldn't be null.");
PADDLE_ENFORCE(ctx->HasInput("GtClasses"),
"Input(GtClasses) shouldn't be null.");
PADDLE_ENFORCE(ctx->HasInput("IsCrowd"),
"Input(IsCrowd) shouldn't be null.");
PADDLE_ENFORCE(ctx->HasInput("GtSegms"),
"Input(GtSegms) shouldn't be null.");
PADDLE_ENFORCE(ctx->HasInput("Rois"), "Input(Rois) shouldn't be null.");
PADDLE_ENFORCE(ctx->HasInput("LabelsInt32"),
"Input(LabelsInt32) shouldn't be null.");
PADDLE_ENFORCE(
ctx->HasOutput("MaskRois"),
"Output(MaskRois) of GenerateMaskLabelsOp should not be null");
PADDLE_ENFORCE(
ctx->HasOutput("RoiHasMaskInt32"),
"Output(RoiHasMaskInt32) of GenerateMaskLabelsOp should not be null");
PADDLE_ENFORCE(
ctx->HasOutput("MaskInt32"),
"Output(MaskInt32) of GenerateMaskLabelsOp should not be null");
auto im_info_dims = ctx->GetInputDim("ImInfo");
auto gt_segms_dims = ctx->GetInputDim("GtSegms");
PADDLE_ENFORCE_EQ(im_info_dims.size(), 2,
"The rank of Input(ImInfo) must be 2.");
PADDLE_ENFORCE_EQ(gt_segms_dims.size(), 2,
"The rank of Input(GtSegms) must be 2.");
PADDLE_ENFORCE_EQ(gt_segms_dims[1], 2,
"The second dim of Input(GtSegms) must be 2.");
int num_classes = ctx->Attrs().Get<int>("num_classes");
int resolution = ctx->Attrs().Get<int>("resolution");
ctx->SetOutputDim("MaskRois", {-1, 4});
ctx->SetOutputDim("RoiHasMaskInt32", {-1, 1});
ctx->SetOutputDim("MaskInt32", {-1, num_classes * resolution * resolution});
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext& ctx) const override {
auto data_type = OperatorWithKernel::IndicateVarDataType(ctx, "Rois");
return framework::OpKernelType(data_type, platform::CPUPlace());
}
};
/*
* Expand masks from shape (#masks, M ** 2) to (#masks, #classes * M ** 2)
* to encode class specific mask targets.
*/
template <typename T>
static inline void ExpandMaskTarget(const platform::CPUDeviceContext& ctx,
const Tensor& masks,
const Tensor& mask_class_labels,
const int resolution, const int num_classes,
Tensor* mask_targets) {
const uint8_t* masks_data = masks.data<uint8_t>();
int64_t num_mask = masks.dims()[0];
const int* mask_class_labels_data = mask_class_labels.data<int>();
const int M = resolution * resolution;
const int mask_dim = M * num_classes;
int* mask_targets_data =
mask_targets->mutable_data<int>({num_mask, mask_dim}, ctx.GetPlace());
math::set_constant(ctx, mask_targets, -1);
for (int64_t mask_id = 0; mask_id < num_mask; ++mask_id) {
int cls = mask_class_labels_data[mask_id];
int start = M * cls;
if (cls > 0) {
for (int i = 0; i < M; ++i) {
mask_targets_data[mask_id * mask_dim + start + i] =
static_cast<int>(masks_data[mask_id * M + i]);
}
}
}
}
template <typename T>
std::vector<Tensor> SampleMaskForOneImage(
const platform::CPUDeviceContext& ctx, const Tensor& im_info,
const Tensor& gt_classes, const Tensor& is_crowd, const Tensor& gt_segms,
const Tensor& rois, const Tensor& label_int32, const int num_classes,
const int resolution, const framework::LoD& segm_length) {
// Prepare the mask targets by associating one gt mask to each training roi
// that has a fg (non-bg) class label.
const int64_t gt_size = static_cast<int64_t>(gt_classes.dims()[0]);
const int64_t roi_size = static_cast<int64_t>(rois.dims()[0]);
const int* gt_classes_data = gt_classes.data<int>();
const int* is_crowd_data = is_crowd.data<int>();
const int* label_int32_data = label_int32.data<int>();
PADDLE_ENFORCE_EQ(roi_size, label_int32.dims()[0]);
std::vector<int> mask_gt_inds, fg_inds;
std::vector<std::vector<std::vector<T>>> gt_polys;
auto polys_num = segm_length[1];
auto segm_lod_offset = framework::ConvertToOffsetBasedLoD(segm_length);
auto lod1 = segm_lod_offset[1];
auto lod2 = segm_lod_offset[2];
const T* polys_data = gt_segms.data<T>();
for (int64_t i = 0; i < gt_size; ++i) {
if ((gt_classes_data[i] > 0) && (is_crowd_data[i] == 0)) {
mask_gt_inds.emplace_back(i);
// slice fg segmentation polys
int poly_num = polys_num[i];
std::vector<std::vector<T>> polys;
int s_idx = lod1[i];
for (int j = 0; j < poly_num; ++j) {
int s = lod2[s_idx + j];
int e = lod2[s_idx + j + 1];
PADDLE_ENFORCE_NE(s, e);
std::vector<T> plts(polys_data + s * 2, polys_data + e * 2);
polys.push_back(plts);
}
gt_polys.push_back(polys);
}
}
for (int64_t i = 0; i < roi_size; ++i) {
if (label_int32_data[i] > 0) {
fg_inds.emplace_back(i);
}
}
int gt_num = mask_gt_inds.size();
int fg_num = fg_inds.size();
Tensor boxes_from_polys;
boxes_from_polys.mutable_data<T>({gt_num, 4}, platform::CPUPlace());
Poly2Boxes(gt_polys, boxes_from_polys.data<T>());
std::vector<int> roi_has_mask =
std::vector<int>(fg_inds.begin(), fg_inds.end());
Tensor mask_class_labels;
Tensor masks;
Tensor rois_fg;
auto im_scale = im_info.data<T>()[2];
if (fg_num > 0) {
// Class labels for the foreground rois
mask_class_labels.mutable_data<int>({fg_num, 1}, ctx.GetPlace());
Gather<int>(label_int32_data, 1, fg_inds.data(), fg_inds.size(),
mask_class_labels.data<int>());
uint8_t* masks_data = masks.mutable_data<uint8_t>(
{fg_num, resolution * resolution}, ctx.GetPlace());
// Find overlap between all foreground rois and the bounding boxes
// enclosing each segmentation
T* rois_fg_data = rois_fg.mutable_data<T>({fg_num, 4}, ctx.GetPlace());
Gather<T>(rois.data<T>(), 4, fg_inds.data(), fg_inds.size(),
rois_fg.data<T>());
for (int k = 0; k < rois_fg.numel(); ++k) {
rois_fg_data[k] = rois_fg_data[k] / im_scale;
}
Tensor overlaps_bbfg_bbpolys;
overlaps_bbfg_bbpolys.mutable_data<T>({fg_num, gt_num}, ctx.GetPlace());
BboxOverlaps<T>(rois_fg, boxes_from_polys, &overlaps_bbfg_bbpolys);
// Map from each fg rois to the index of the mask with highest overlap
// (measured by bbox overlap)
T* overlaps_bbfg_bbpolys_data = overlaps_bbfg_bbpolys.data<T>();
std::vector<int> fg_masks_inds;
for (int64_t i = 0; i < fg_num; ++i) {
const T* v = overlaps_bbfg_bbpolys_data + i * gt_num;
T max_overlap = std::numeric_limits<T>::min();
int id = 0;
for (int64_t j = 0; j < gt_num; ++j) {
if (v[j] > max_overlap) {
max_overlap = v[j];
id = j;
}
}
fg_masks_inds.push_back(id);
}
// add fg targets
for (int64_t i = 0; i < fg_num; ++i) {
int fg_polys_ind = fg_masks_inds[i];
T* roi_fg = rois_fg_data + i * 4;
uint8_t* mask = masks_data + i * resolution * resolution;
Polys2MaskWrtBox(gt_polys[fg_polys_ind], roi_fg, resolution, mask);
}
} else {
// The network cannot handle empty blobs, so we must provide a mask
// We simply take the first bg roi, given it an all -1's mask (ignore
// label), and label it with class zero (bg).
int bg_num = 1;
T* rois_fg_data = rois_fg.mutable_data<T>({bg_num, 4}, ctx.GetPlace());
const T* rois_data = rois.data<T>();
std::vector<int> bg_inds;
for (int64_t i = 0; i < roi_size; ++i) {
if (label_int32_data[i] == 0) {
bg_inds.emplace_back(i);
rois_fg_data[0] = rois_data[0] / im_scale;
rois_fg_data[1] = rois_data[1] / im_scale;
rois_fg_data[2] = rois_data[2] / im_scale;
rois_fg_data[3] = rois_data[3] / im_scale;
break;
}
}
masks.mutable_data<uint8_t>({bg_num, resolution * resolution},
ctx.GetPlace());
math::set_constant(ctx, &masks, -1);
int* mask_class_labels_data =
mask_class_labels.mutable_data<int>({bg_num, 1}, ctx.GetPlace());
mask_class_labels_data[0] = 0;
roi_has_mask = std::vector<int>(bg_inds.begin(), bg_inds.end());
}
Tensor masks_expand;
ExpandMaskTarget<T>(ctx, masks, mask_class_labels, resolution, num_classes,
&masks_expand);
T* rois_fg_data = rois_fg.data<T>();
for (int k = 0; k < rois_fg.numel(); ++k) {
rois_fg_data[k] = rois_fg_data[k] * im_scale;
}
Tensor roi_has_mask_t;
int roi_has_mask_size = roi_has_mask.size();
int* roi_has_mask_data =
roi_has_mask_t.mutable_data<int>({roi_has_mask_size, 1}, ctx.GetPlace());
std::copy(roi_has_mask.begin(), roi_has_mask.end(), roi_has_mask_data);
std::vector<Tensor> res;
res.emplace_back(rois_fg);
res.emplace_back(roi_has_mask_t);
res.emplace_back(masks_expand);
return res;
}
template <typename T>
class GenerateMaskLabelsKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* im_info = ctx.Input<LoDTensor>("ImInfo");
auto* gt_classes = ctx.Input<LoDTensor>("GtClasses");
auto* is_crowd = ctx.Input<LoDTensor>("IsCrowd");
auto* gt_segms = ctx.Input<LoDTensor>("GtSegms");
auto* rois = ctx.Input<LoDTensor>("Rois");
auto* label_int32 = ctx.Input<LoDTensor>("LabelsInt32");
auto* mask_rois = ctx.Output<LoDTensor>("MaskRois");
auto* roi_has_mask_int32 = ctx.Output<LoDTensor>("RoiHasMaskInt32");
auto* mask_int32 = ctx.Output<LoDTensor>("MaskInt32");
int num_classes = ctx.Attr<int>("num_classes");
int resolution = ctx.Attr<int>("resolution");
PADDLE_ENFORCE_EQ(gt_classes->lod().size(), 1UL,
"GenerateMaskLabelsOp gt_classes needs 1 level of LoD");
PADDLE_ENFORCE_EQ(is_crowd->lod().size(), 1UL,
"GenerateMaskLabelsOp is_crowd needs 1 level of LoD");
PADDLE_ENFORCE_EQ(rois->lod().size(), 1UL,
"GenerateMaskLabelsOp rois needs 1 level of LoD");
PADDLE_ENFORCE_EQ(label_int32->lod().size(), 1UL,
"GenerateMaskLabelsOp label_int32 needs 1 level of LoD");
PADDLE_ENFORCE_EQ(gt_segms->lod().size(), 3UL);
int64_t n = static_cast<int64_t>(gt_classes->lod().back().size() - 1);
PADDLE_ENFORCE_EQ(gt_segms->lod()[0].size() - 1, n);
int mask_dim = num_classes * resolution * resolution;
int roi_num = rois->lod().back()[n];
mask_rois->mutable_data<T>({roi_num, kBoxDim}, ctx.GetPlace());
roi_has_mask_int32->mutable_data<int>({roi_num, 1}, ctx.GetPlace());
mask_int32->mutable_data<int>({roi_num, mask_dim}, ctx.GetPlace());
framework::LoD lod;
std::vector<size_t> lod0(1, 0);
int64_t num_mask = 0;
auto& dev_ctx = ctx.device_context<platform::CPUDeviceContext>();
auto gt_classes_lod = gt_classes->lod().back();
auto is_crowd_lod = is_crowd->lod().back();
auto rois_lod = rois->lod().back();
auto label_int32_lod = label_int32->lod().back();
auto gt_segms_lod = gt_segms->lod();
for (int i = 0; i < n; ++i) {
if (rois_lod[i] == rois_lod[i + 1]) {
lod0.emplace_back(num_mask);
continue;
}
Tensor im_info_slice = im_info->Slice(i, i + 1);
Tensor gt_classes_slice =
gt_classes->Slice(gt_classes_lod[i], gt_classes_lod[i + 1]);
Tensor is_crowd_slice =
is_crowd->Slice(is_crowd_lod[i], is_crowd_lod[i + 1]);
Tensor label_int32_slice =
label_int32->Slice(label_int32_lod[i], label_int32_lod[i + 1]);
Tensor rois_slice = rois->Slice(rois_lod[i], rois_lod[i + 1]);
auto sub_lod_and_offset =
framework::GetSubLoDAndAbsoluteOffset(gt_segms_lod, i, i + 1, 0);
auto lod_length = sub_lod_and_offset.first;
size_t s = sub_lod_and_offset.second.first;
size_t e = sub_lod_and_offset.second.second;
Tensor gt_segms_slice = gt_segms->Slice(s, e);
std::vector<Tensor> tensor_output = SampleMaskForOneImage<T>(
dev_ctx, im_info_slice, gt_classes_slice, is_crowd_slice,
gt_segms_slice, rois_slice, label_int32_slice, num_classes,
resolution, lod_length);
Tensor sampled_mask_rois = tensor_output[0];
Tensor sampled_roi_has_mask_int32 = tensor_output[1];
Tensor sampled_mask_int32 = tensor_output[2];
AppendMask<T>(mask_rois, kBoxDim * num_mask, &sampled_mask_rois);
AppendMask<int>(roi_has_mask_int32, num_mask,
&sampled_roi_has_mask_int32);
AppendMask<int>(mask_int32, mask_dim * num_mask, &sampled_mask_int32);
num_mask += sampled_mask_rois.dims()[0];
lod0.emplace_back(num_mask);
}
lod.emplace_back(lod0);
mask_rois->set_lod(lod);
roi_has_mask_int32->set_lod(lod);
mask_int32->set_lod(lod);
mask_rois->Resize({num_mask, kBoxDim});
roi_has_mask_int32->Resize({num_mask, 1});
mask_int32->Resize({num_mask, mask_dim});
}
};
class GenerateMaskLabelsOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("ImInfo",
"(Tensor), This input is a 2D Tensor with shape [B, 3]. "
"B is the number of input images, "
"each element consists of im_height, im_width, im_scale.");
AddInput("GtClasses",
"(LoDTensor), This input is a 2D LoDTensor with shape [M, 1]. "
"M is the number of groundtruth, "
"each element is a class label of groundtruth.");
AddInput(
"IsCrowd",
"(LoDTensor), This input is a 2D LoDTensor with shape [M, 1]. "
"M is the number of groundtruth, "
"each element is a flag indicates whether a groundtruth is crowd.");
AddInput(
"GtSegms",
"(LoDTensor), This input is a 2D LoDTensor with shape [S, 2], it's LoD "
"level is 3. The LoD[0] represents the gt objects number of each "
"instance. LoD[1] represents the segmentation counts of each objects. "
"LoD[2] represents the polygons number of each segmentation. S the "
"total number of polygons coordinate points. Each element is (x, y) "
"coordinate points.");
AddInput(
"Rois",
"(LoDTensor), This input is a 2D LoDTensor with shape [R, 4]. "
"R is the number of rois which is the output of "
"generate_proposal_labels, "
"each element is a bounding box with (xmin, ymin, xmax, ymax) format.");
AddInput("LabelsInt32",
"(LoDTensor), This intput is a 2D LoDTensor with shape [R, 1], "
"each element repersents a class label of a roi");
AddOutput(
"MaskRois",
"(LoDTensor), This output is a 2D LoDTensor with shape [P, 4]. "
"P is the number of mask, "
"each element is a bounding box with [xmin, ymin, xmax, ymax] format.");
AddOutput("RoiHasMaskInt32",
"(LoDTensor), This output is a 2D LoDTensor with shape [P, 1], "
"each element repersents the output mask rois index with regard "
"to input rois");
AddOutput("MaskInt32",
"(LoDTensor), This output is a 4D LoDTensor with shape [P, Q], "
"Q equal to num_classes * resolution * resolution");
AddAttr<int>("num_classes", "Class number.");
AddAttr<int>("resolution", "Resolution of mask.");
AddComment(R"DOC(
This operator can be, for given the RoIs and corresponding labels,
to sample foreground RoIs. This mask branch also has
a :math: `K \\times M^{2}` dimensional output targets for each foreground
RoI, which encodes K binary masks of resolution M x M, one for each of the
K classes. This mask targets are used to compute loss of mask branch.
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(
generate_mask_labels, ops::GenerateMaskLabelsOp,
ops::GenerateMaskLabelsOpMaker,
paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);
REGISTER_OP_CPU_KERNEL(generate_mask_labels,
ops::GenerateMaskLabelsKernel<float>);
| 40.45045 | 80 | 0.656069 | Thunderbrook |
db6bb91b83fd89ae8b6602365f75524a668fea88 | 2,036 | cc | C++ | input.cc | psaksa/git-junction | 55cb940704d8d8dcf773e8917809a972c078976f | [
"MIT"
] | null | null | null | input.cc | psaksa/git-junction | 55cb940704d8d8dcf773e8917809a972c078976f | [
"MIT"
] | null | null | null | input.cc | psaksa/git-junction | 55cb940704d8d8dcf773e8917809a972c078976f | [
"MIT"
] | null | null | null | /* git-junction
* Copyright (c) 2016-2017 by Pauli Saksa
*
* Licensed under The MIT License, see file LICENSE.txt in this source tree.
*/
#include "input.hh"
#include "exception.hh"
#include "terminal_input.hh"
#include "utils.hh"
#include <iostream>
#include <sstream>
#include <unistd.h>
//
bool accept_field_functor::accept_size(std::string::size_type size,
std::string::size_type min,
std::string::size_type max)
{
if (size < min) {
std::cout << "too short, " << min << '-' << max << " characters\n";
return false;
}
if (size > max) {
std::cout << "too long, " << min << '-' << max << " characters\n";
return false;
}
return true;
}
accept_field_functor::~accept_field_functor()
{
}
// *********************************************************
bool accept_yes_or_no::operator() (std::string &input) const
{
if (input.size() < 2
|| input.size() > 3)
{
return false;
}
lowercase(input);
return input == "yes"
|| input == "no";
}
// *********************************************************
static std::string read_line(const std::string &prompt, bool hide)
{
terminal_input term_input{hide};
std::cout << prompt << std::flush;
std::ostringstream oss;
char inp;
while (true) {
const int i =read(STDIN_FILENO, &inp, 1);
if (i != 1) {
std::cout << '\n';
throw stdin_exception{};
}
if (inp == '\n' || inp == '\r')
break;
if (inp >= 0 && inp < 32)
continue;
oss << inp;
}
return oss.str();
}
// *********************************************************
std::string read_field(const std::string prompt, bool hide, const accept_field_functor &accept)
{
while (true) {
std::string input =read_line(prompt, hide);
if (accept(input)) // accept() may modify input
return input;
}
}
| 20.989691 | 95 | 0.48723 | psaksa |
db6db73822024f7d160709380af99ee169922697 | 432 | hpp | C++ | Source/Decoder.hpp | Myles-Trevino/Resonance | 47ff7c51caa8fc15862818f56a232c3e71dd7e0a | [
"Apache-2.0"
] | 1 | 2020-09-07T13:03:34.000Z | 2020-09-07T13:03:34.000Z | Source/Decoder.hpp | Myles-Trevino/Resonance | 47ff7c51caa8fc15862818f56a232c3e71dd7e0a | [
"Apache-2.0"
] | null | null | null | Source/Decoder.hpp | Myles-Trevino/Resonance | 47ff7c51caa8fc15862818f56a232c3e71dd7e0a | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 Myles Trevino
Licensed under the Apache License, Version 2.0
https://www.apache.org/licenses/LICENSE-2.0
*/
#pragma once
#include <string>
#include <vector>
namespace LV::Decoder
{
void load_track_information(const std::string& file);
void initialize_resampler_and_decoder();
void load_samples();
void destroy();
// Getters.
const std::vector<float>& get_data();
const int get_sample_rate();
} | 14.896552 | 54 | 0.729167 | Myles-Trevino |
db70c1001508c517af633b42da7527881f544186 | 209 | cpp | C++ | main.cpp | fubieslc/flube | e3e9f08b00a767ae80981dd25dd40aff07a431ae | [
"libtiff",
"BSD-3-Clause"
] | null | null | null | main.cpp | fubieslc/flube | e3e9f08b00a767ae80981dd25dd40aff07a431ae | [
"libtiff",
"BSD-3-Clause"
] | null | null | null | main.cpp | fubieslc/flube | e3e9f08b00a767ae80981dd25dd40aff07a431ae | [
"libtiff",
"BSD-3-Clause"
] | null | null | null | // main.cpp
//
#include "Core.hpp"
int main(int argc, char** argv) {
if (Core.Init()) {
Core.Quit();
return -1;
}
else {
Core.MainLoop();
Core.Quit();
return 0;
}
return 0;
} | 11.611111 | 34 | 0.507177 | fubieslc |
db70f6231304eca566a5b0200e9a8fb443ab0e8d | 6,148 | cpp | C++ | skyline-continuous/src/src/main.cpp | alex-kulikov-git/skyline-computation | e2fc8328f712a2ec0bfcad797a79cf9cbda524a8 | [
"MIT"
] | null | null | null | skyline-continuous/src/src/main.cpp | alex-kulikov-git/skyline-computation | e2fc8328f712a2ec0bfcad797a79cf9cbda524a8 | [
"MIT"
] | null | null | null | skyline-continuous/src/src/main.cpp | alex-kulikov-git/skyline-computation | e2fc8328f712a2ec0bfcad797a79cf9cbda524a8 | [
"MIT"
] | null | null | null | /*
* main.cpp
* Created on: July 5, 2018
* Author: Oleksii Kulikov
*/
#include <iostream>
#include <chrono>
#include "bnl.hpp"
#include "output.hpp"
#include "generator.hpp"
#include "old_bnl.hpp"
#include "old_dnc.hpp"
#include "dnc.hpp"
#include "nnl.hpp"
#include "parallel_dnc.hpp"
static std::size_t n = 0, dimension = 0;
void init(){
std::cout << "Number of tuples: \nn = ";
std::cin >> n;
std::cout << "Number of dimensions: \ndimensions = ";
std::cin >> dimension;
}
// @param cp gives the variation of the algorithm ( 0: getNext | 1: consume/produce | 2: parallel consume/produce )
double test_algorithm(Output &output, int cp){
std::chrono::_V2::system_clock::time_point start = std::chrono::high_resolution_clock::now();
switch(cp){
case 0:
output.getTuples();
break;
case 1:
output.getTuplesCP();
break;
case 2:
output.getTuplesParallelCP();
break;
default:
break;
}
std::chrono::_V2::system_clock::time_point finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish - start;
output.print();
std::cout << "Elapsed time: " << elapsed.count() << "s\n\n";
return elapsed.count();
}
bool check_results(const std::vector<std::vector<std::vector<double>>> &results){
static bool output = true;
// check if sizes are equal
for(auto r:results){
if(results[0].size() != r.size()){
std::cout << "Result sizes do not match.\n";
output = false;
}
}
// check if results match
for(std::size_t i = 1; i < results.size(); i++){
for(std::size_t j = 0; j < results[0].size(); j++){
if(std::find(results[i].begin(), results[i].end(), results[0][j]) == results[i].end()) {
std::cout << "Tuple[" << j << "] in result 0 does not exist in result " << i << ".\n";
output = false;
}
}
}
return output;
}
int main()
{
init();
BNL *bnl_pointer;
Output *output_pointer;
// BNL iterator model
Generator g(bnl_pointer, n, dimension);
BNL bnl_im(output_pointer, &g);
Output o1(&bnl_im);
g.set_parent(&bnl_im);
bnl_im.set_parent(&o1);
std::cout << "Computing Skyline with iterator model BNL...\n";
double elapsed_1 = test_algorithm(o1, 0);
// BNL produce/consume
BNL bnl_pc(output_pointer, &g);
Output o2(&bnl_pc);
g.set_parent(&bnl_pc);
bnl_pc.set_parent(&o2);
std::cout << "Computing Skyline with produce/consume BNL...\n";
double elapsed_2 = test_algorithm(o2, 1);
// NNL produce/consume
NNL nnl_pc(output_pointer, &g);
Output o3(&nnl_pc);
g.set_parent(&nnl_pc);
nnl_pc.set_parent(&o3);
std::cout << "Computing Skyline with produce/consume NNL...\n";
double elapsed_3 = test_algorithm(o3, 1);
// NNL produce/consume parallelized
NNL nnl_parallel_pc(output_pointer, &g);
Output o4(&nnl_parallel_pc);
g.set_parent(&nnl_parallel_pc);
nnl_parallel_pc.set_parent(&o4);
std::cout << "Computing Skyline with produce/consume parallelized NNL...\n";
double elapsed_4 = test_algorithm(o4, 2);
// DNC produce/consume
DNC dnc(output_pointer, &g);
Output o5(&dnc);
g.set_parent(&dnc);
dnc.set_parent(&o5);
std::cout << "Computing Skyline with produce/consume DNC...\n";
double elapsed_5 = test_algorithm(o5, 1);
// DNC produce/consume parallelized
Parallel_DNC parallel_dnc(output_pointer, &g);
Output o6(¶llel_dnc);
g.set_parent(¶llel_dnc);
parallel_dnc.set_parent(&o6);
std::cout << "Computing Skyline with parallel produce/consume DNC...\n";
double elapsed_6 = test_algorithm(o6, 1);
// OLD VERSIONS FOR TESTING
// Old version of BNL
// OldBNL old_bnl;
// auto start = std::chrono::high_resolution_clock::now();
// std::cout << "Computing Skyline with normal BNL...\n";
// std::vector<std::vector<double>> result_bnl = old_bnl.computeSkyline(g.getTuples(), n);
// auto finish = std::chrono::high_resolution_clock::now();
// std::chrono::duration<double> elapsed_7 = finish - start;
// std::cout << "Resulting Skyline: \n";
// for(std::vector<std::vector<double>>::size_type i = 0; i < result_bnl.size(); i++){
// std::cout << "Tuple[" << i << "] is (";
// for(std::vector<double>::size_type j = 0; j < result_bnl[i].size(); j++){
// std::cout << result_bnl[i][j] << ' ';
// }
// std::cout << ")\n";
// }
// std::cout << "\nElapsed time: " << elapsed_7.count() << "s\n\n";
// Old version of DNC
// OldDNC old_dnc;
// start = std::chrono::high_resolution_clock::now();
// std::cout << "Computing Skyline with normal DNC...\n";
// std::vector<std::vector<double>> result_old_dnc = old_dnc.computeSkyline(g.getTuples(), dimension);
// finish = std::chrono::high_resolution_clock::now();
// std::chrono::duration<double> elapsed_8 = finish - start;
// std::cout << "Resulting Skyline: \n";
// for(std::vector<std::vector<double>>::size_type i = 0; i < result_old_dnc.size(); i++){
// std::cout << "Tuple[" << i << "] is (";
// for(std::vector<double>::size_type j = 0; j < result_old_dnc[i].size(); j++){
// std::cout << result_old_dnc[i][j] << ' ';
// }
// std::cout << ")\n";
// }
// std::cout << "\nElapsed time: " << elapsed_8.count() << "s\n\n";
// Total
std::cout << "Input was: n = " << n << " dimension = " << dimension << "\n\n";
std::cout << "Results are: ";
std::vector<std::vector<std::vector<double>>> to_check;
to_check.push_back(o1.getStorage());
to_check.push_back(o2.getStorage());
to_check.push_back(o3.getStorage());
to_check.push_back(o4.getStorage());
to_check.push_back(o5.getStorage());
to_check.push_back(o6.getStorage());
// to_check.push_back(result_bnl);
// to_check.push_back(result_old_dnc);
if(check_results(to_check))
std::cout << "OK\n";
else std::cout << "NOT OK\n";
std::cout << "\nExecution time\n";
std::cout << "Iterator Model BNL: " << elapsed_1 << "s\n";
std::cout << "Produce/Consume BNL " << elapsed_2 << "s\n";
std::cout << "Produce/Consume NNL: " << elapsed_3 << "s\n";
std::cout << "Produce/Consume NNL Parallelized: " << elapsed_4 << "s\n";
std::cout << "Produce/Consume DNC: " << elapsed_5 << "s\n";
std::cout << "Produce/Consume DNC Parallelized: " << elapsed_6 << "s\n";
// std::cout << "Normal BNL: " << elapsed_7.count() << "s\n";
// std::cout << "Normal DNC: " << elapsed_8.count() << "s\n";
return 0;
}
| 31.690722 | 115 | 0.652082 | alex-kulikov-git |
db71160728a089fda4b16b0ff3b5aeedbf75c233 | 28,682 | cpp | C++ | src/XESCore/TensorRoads.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 71 | 2015-12-15T19:32:27.000Z | 2022-02-25T04:46:01.000Z | src/XESCore/TensorRoads.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 19 | 2016-07-09T19:08:15.000Z | 2021-07-29T10:30:20.000Z | src/XESCore/TensorRoads.cpp | rromanchuk/xptools | deff017fecd406e24f60dfa6aae296a0b30bff56 | [
"X11",
"MIT"
] | 42 | 2015-12-14T19:13:02.000Z | 2022-03-01T15:15:03.000Z | /*
* Copyright (c) 2007, Laminar Research.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "TensorRoads.h"
#include "MapDefs.h"
#include "../RenderFarmUI/RF_DEMGraphics.h"
#include "DEMDefs.h"
#include "MapAlgs.h"
#include "MapOverlay.h"
#include "MapTopology.h"
#include "PolyRasterUtils.h"
#include "TensorUtils.h"
#include "MathUtils.h"
#include "ParamDefs.h"
#include "GISTool_Globals.h"
#include "PerfUtils.h"
#include "MapCreate.h"
#include "XUtils.h"
#define ADVANCE_RATIO 0.0005
#define PROFILE_PERFORMANCE 1
#if PROFILE_PERFORMANCE
#define TIMER(x) StElapsedTime __PerfTimer##x(#x);
#else
#define TIMER(x)
#endif
// SEt this to 1 to see the road restriction DEM - can explain why no roads showed up in a location.
#define SHOW_ROAD_RESTRICT 0
// Make roads EVEN if origin code says not to. Useful for testing maybe.
#define IGNORE_ORIGIN_CODES 0
// Show roads as debug mesh lines
#define SHOW_GENERATED_ROADS 0
// Ignore urban density - useful for debugging
#define IGNORE_DENSITY 1
/*
Back before we had OSM, TensorRoads generated the "fake" road grids for urban areas where we lacked true vector data. This came from
an academic paper. Here are the major ideas:
- A "tensor field is a "flow field" - that is, a field of 2-d vector directions.
- The idea was two-step: make a flow field that loosel corresponds to how we want the road grid to "flow", then turn the tensor field into
roads.
TENSOR FIELDS
A tensor field is a field of 3-d rotations - its "flow" is bent by the rotations.
What's cool about tensors (as opposed to a normal 2-d field of vectors indicating direction, or a 2-d field of angles) is that tensor
fields are affine transforms and thus we can add them together and scale them. In other words, the same kinds of "blending" that would
make an image look good produces VERY reasonable and sane results for tensor fields.
Furthermore, tensor fields can be defined functionally - thus we can do a "composition of functions" (with the functions weighted.
In fact, that is exactly what we do: we can build a tensor out of:
- The terrain gradient, which will make the road grid follow the terrain.
- Linear or circular pre-defined functions, which may have attenuation.
- We can build linear gradients that scale off known edges to enforce the grid along highways.
With the right blending gradients, we get a reasonably sane tensor map that seems to reflect 'local stuff'.
TENSOR 2 ROADS
The way we convert our tensor field is pretty easy. We create "seed" points along known highways (seed roads) and at those seed points
we make a small step either along or normal to the flow. We then drop a seed for our cross-street and keep going.
The result will be a sort of emergent grid that bends around the natural "flow" of the tensor field. If our tensor field is aesthetically
pleasing (in otherwords, fly) then the road grid won't look that bad.
There are some heuristics in this seeding to try to weed out and generally sanatize the emerging edges, as well as to keep the process fast.
For example, we use a raster mask to avoid over-adding roads. (If the algorithm is allowed to run forever, it will eventually fill in an
infinite number of infinitely thin lines, for certain tensors.)
*/
/************************************************************************************************************************************************
*
************************************************************************************************************************************************/
inline bool RoadsForThisFace(Face_handle f)
{
return !f->data().IsWater() && f->data().mTerrainType != terrain_Airport
#if !IGNORE_ORIGIN_CODES
&& f->data().mParams.count(af_OriginCode)
&& f->data().mParams[af_OriginCode] == 2.0
#endif
;
}
bool CrossCheck(const Segment2& s1, const Segment2& s2, Point2& p)
{
if(s1.p1 == s2.p1 ||
s1.p1 == s2.p2 ||
s1.p2 == s2.p1 ||
s1.p2 == s2.p2) return false;
if(!s1.could_intersect(s2)) return false;
if(s1.p1.y() == s2.p1.y())
{
DebugAssert(s1.p1.x() != s2.p2.x());
if (s1.p1.x() < s2.p1.x())
{
if (s1.intersect(s2,p) && p != s1.p1 && p != s1.p2)
{
// printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y,
// s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y,
// s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y);
return true;
} else return false;
}
else
{
if (s2.intersect(s1,p))
{
// printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y,
// s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y,
// s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y);
return true;
} else return false;
}
}
else
{
if (s1.p1.y() < s2.p1.y())
{
if (s1.intersect(s2,p))
{
// printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y,
// s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y,
// s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y);
return true;
} else return false;
}
else
{
if (s2.intersect(s1,p))
{
// printf("Generated %lf,%lf from %lf,%lf->%lf,%lf x %lf,%lf->%lf,%lf\n",p.x,p.y,
// s2.p1.x,s2.p1.y,s2.p2.x,s2.p2.y,
// s1.p1.x,s1.p1.y,s1.p2.x,s1.p2.y);
return true;
} else return false;
}
}
}
Halfedge_handle InsertOneEdge(const Point_2& p1, const Point_2& p2, Pmwx& io_map, Locator& io_locator)
{
DebugAssert(p1 != p2);
Vertex_handle v1, v2;
Face_handle f;
CGAL::Object obj1 = io_locator.locate(p1);
CGAL::Object obj2 = io_locator.locate(p2);
bool has_v1 = CGAL::assign(v1, obj1);
bool has_v2 = CGAL::assign(v2, obj2);
Curve_2 s(Segment_2(p1,p2));
if(has_v1 && has_v2) return io_map.insert_at_vertices(s, v1,v2);
else if (has_v1) return io_map.insert_from_left_vertex(s, v1);
else if (has_v2) return io_map.insert_from_right_vertex(s, v2);
else if(CGAL::assign(f,obj1)) return io_map.insert_in_face_interior(s,f);
else {
//return CGAL::insert_curve(io_map,s);
DebugAssert(!"Not disjoint!!");
return Halfedge_handle();
}
}
/*
void SetRoadProps(Halfedge_handle e)
{
if (!e->data().mDominant) e = e->twin();
e->data().mSegments.push_back(GISNetworkSegment_t());
e->data().mSegments.back().mFeatType = road_LocalUnsep;
}
*/
inline bool LessEdgesThan(Face_handle f, int c)
{
if(f->is_unbounded()) return false;
Pmwx::Ccb_halfedge_circulator circ,stop;
circ = stop = f->outer_ccb();
do {
if(c-- <= 0) return false;
++circ;
} while(circ != stop);
for(Pmwx::Hole_iterator h = f->holes_begin(); h != f->holes_end(); ++h)
{
circ = stop = *h;
do {
if(c-- <= 0) return false;
++circ;
} while(circ != stop);
}
return true;
}
void BulkZapRoads(const DEMGeo& inUrbanDensity, Pmwx& io_map)
{
printf("BEFORE ZAP: %llu generated roads.\n",(unsigned long long)io_map.number_of_halfedges() / 2);
for(Pmwx::Edge_iterator e = io_map.edges_begin(); e != io_map.edges_end(); )
{
if((e->source()->degree() > 2 && e->target()->degree() > 2 && // If we have a real intersection on both sides AND
e->face() != e->twin()->face() && // We divide two DIFFERENT faces (so we don't make an island) AND
LessEdgesThan(e->face(), 6) && // The faces aren't too complex
LessEdgesThan(e->twin()->face(), 6)) ||
(e->source()->degree() == 1 || e->target()->degree() == 1) // Or if we're an antenna
)
{
Point_2 mp(CGAL::midpoint(e->source()->point(),e->target()->point()));
double d = inUrbanDensity.get(inUrbanDensity.lon_to_x(CGAL::to_double(mp.x())),inUrbanDensity.lat_to_y(CGAL::to_double(mp.y())));
if(e->source()->degree() == 1 || e->target()->degree() == 1)
d = min(d,0.5); // always think of nuking antennas
#if IGNORE_DENSITY
d =1.0;
#endif
if(!RollDice(d))
{
Halfedge_handle k = e;
++e;
io_map.remove_edge(k);
}
else
++e;
} else
++e;
}
printf("AFTER ZAP: %llu generated roads.\n",(unsigned long long)io_map.number_of_halfedges() / 2);
}
void BulkInsertRoads(vector<Segment2> roads, Pmwx& io_map)
{
GIS_halfedge_data hed;
hed.mSegments.push_back(GISNetworkSegment_t());
hed.mSegments.back().mFeatType = road_Local;
vector<Segment_2> road_vec(roads.size());
vector<GIS_halfedge_data> data_vec(roads.size(),hed);
for(int n = 0; n < roads.size(); ++n)
road_vec[n] = Segment_2(ben2cgal<Point_2>(roads[n].p1),ben2cgal<Point_2>(roads[n].p2));
Map_CreateWithLineData(io_map, road_vec, data_vec);
}
int ThinLine(list<Point2>& pts, double max_dist_move, double max_dist_seg)
{
max_dist_move *= max_dist_move;
max_dist_seg *= max_dist_seg;
int t=0;
while(1)
{
list<Point2>::iterator best_dead = pts.end();
double d_sq = 0.0f;
for(list<Point2>::iterator i = pts.begin(); i != pts.end(); ++i)
{
if(i != pts.begin())
{
list<Point2>::iterator p(i), n(i);
--p;
++n;
if(n != pts.end())
{
Segment2 span(*p, *n);
if(span.squared_length() < max_dist_seg)
{
Point2 pp(span.projection(*i));
double my_dist = Segment2(pp, *i).squared_length();
if(my_dist < max_dist_move && my_dist > d_sq)
{
best_dead = i;
d_sq = my_dist;
}
}
}
}
}
if(best_dead == pts.end()) break;
pts.erase(best_dead);
++t;
}
return t;
}
/************************************************************************************************************************************************
*
************************************************************************************************************************************************/
RoadPrefs_t gRoadPrefs = { 10.0, 50000.0, 0.8, 1.0 };
struct TensorSeed {
Point2 p;
bool major;
int x;
int y;
};
typedef list<TensorSeed> SeedQueue;
struct Tensor_info {
const DEMGeo * elev;
const DEMGeo * grdx;
const DEMGeo * grdy;
const DEMGeo * uden;
const DEMGeo * urad;
const DEMGeo * usqr;
Bbox2 bounds;
};
inline int dem_get(const DEMGeo& d, int x, int y)
{
float e[9];
e[0] = d.get(x-1,y-1);
e[1] = d.get(x ,y-1);
e[2] = d.get(x+1,y-1);
e[3] = d.get(x-1,y );
e[4] = d.get(x ,y );
e[5] = d.get(x+1,y );
e[6] = d.get(x-1,y+1);
e[7] = d.get(x ,y+1);
e[8] = d.get(x+1,y+1);
if(e[4] == DEM_NO_DATA) return DEM_NO_DATA;
int f = 0;
bool h = false;
for(int n = 0; n < 9; ++n)
if(e[n] != DEM_NO_DATA)
{
h = true;
f |= (int) e[n];
}
return h ? f : DEM_NO_DATA;
}
static Vector2 Tensor_Func(const Point2& p, void * ref)
{
Tensor_info * i = (Tensor_info *) ref;
double lon = interp(0,i->bounds.p1.x(),1,i->bounds.p2.x(),p.x());
double lat = interp(0,i->bounds.p1.y(),1,i->bounds.p2.y(),p.y());
double xe = i->elev->lon_to_x(lon);
double ye = i->elev->lat_to_y(lat);
double xr = i->urad->lon_to_x(lon);
double yr = i->urad->lat_to_y(lat);
double xu = i->usqr->lon_to_x(lon);
double yu = i->usqr->lat_to_y(lat);
double xg = i->grdx->lon_to_x(lon);
double yg = i->grdx->lat_to_y(lat);
double sq_w = 0.0f;
double ir_w = 1.0f;
float sqv = i->usqr->get(xu,yu);
if (sqv == 1.0) sq_w = 1.f, ir_w = 0.0f;
if (sqv == 2.0) sq_w = 0.f, ir_w = 1.0f;
Vector2 basis = (Gradient2Tensor(Vector2(i->elev->gradient_x_bilinear(xe,ye),i->elev->gradient_y_bilinear(xe,ye))) * gRoadPrefs.elevation_weight);
if(ir_w > 0.0f)
basis += (Gradient2Tensor(Vector2(i->urad->gradient_x_bilinear(xr,yr),i->urad->gradient_y_bilinear(xr,yr))) * gRoadPrefs.radial_weight * ir_w);
if (sq_w > 0.0f)
basis += Vector2(i->grdx->get(xg,yg),i->grdy->get(xg,yg));
return basis;
}
bool CheckSeed(
const TensorSeed& s,
DEMGeo& d)
{
int old = dem_get(d,s.x,s.y);
if(old==DEM_NO_DATA) return false;
int mask = s.major ? 1 : 2;
if ((old & mask) == 0)
{
return true;
}
return false;
}
void QueueSeed(
const Point2& p,
bool major,
DEMGeo& dem,
SeedQueue& q)
{
TensorSeed s;
s.p = p;
s.major = major;
s.x = dem.lon_to_x(p.x());
s.y = dem.lat_to_y(p.y());
int old = dem_get(dem,s.x,s.y);
if(old==DEM_NO_DATA)return;
int mask = s.major ? 5 : 6;
if ((old & mask) == 0)
{
old |= 4;
dem(s.x,s.y) = old;
q.push_back(s);
}
}
bool CheckStats(const Point2& p, const Point2& p_old, const DEMGeo& elev, const DEMGeo& slope, const DEMGeo& density, float amp)
{
// return true;
float d = density.get(density.lon_to_x(p.x()),density.lat_to_y(p.y()));
float s = slope.get(slope.lon_to_x(p.x()),slope.lat_to_y(p.y()));
if(d == DEM_NO_DATA) return false;
d += amp;
if (!RollDice(d)) return false;
// if (!RollDice((d*gRoadPrefs.density_amp))) return false;
float ss = fabs(elev.value_linear(p.x(),p.y())-elev.value_linear(p_old.x(),p_old.y()));
float rr = pythag(elev.x_dist_to_m(elev.lon_to_x(p.x())-elev.lon_to_x(p_old.x())),
elev.y_dist_to_m(elev.lat_to_y(p.y())-elev.lat_to_y(p_old.y())));
if(rr==0.0) return true;
if(RollDice(ss / rr)*gRoadPrefs.slope_amp)return false;
// if(RollDice(s * gRoadPrefs.slope_amp)) return false;
return true;
}
bool CheckAndRegister(
const Point2& p,
DEMGeo& dem,
int& ox,
int& oy,
int& ctr,
bool major)
{
int x = intlim(dem.lon_to_x(p.x()),0,dem.mWidth -1);
int y = intlim(dem.lat_to_y(p.y()),0,dem.mHeight-1);
if(x == ox && y == oy)
return (ctr-- > 0);
ox =x;
oy =y;
ctr = 10;
int old = dem.get(x,y);
if(old==DEM_NO_DATA)return false;
int mask = major ? 1 : 2;
if ((old & mask) == 0)
{
old |= mask;
dem(x,y) = old;
return true;
}
return false;
}
void TensorForFace(
const DEMGeo& inElevation,
const DEMGeo& inUrbanDensity,
const DEMGeo& inUrbanRadial,
const DEMGeo& inUrbanSquare,
const DEMGeo& inGridX,
const DEMGeo& inGridY,
Tensor_info& t)
{
t.elev = &inElevation;
t.urad = &inUrbanRadial;
t.usqr = &inUrbanSquare;
t.uden = &inUrbanDensity;
t.grdx = &inGridX;
t.grdy = &inGridY;
t.bounds.p1.x_ = inElevation.mWest ;
t.bounds.p1.y_ = inElevation.mSouth;
t.bounds.p2.x_ = inElevation.mEast ;
t.bounds.p2.y_ = inElevation.mNorth;
}
void RasterEdge(
Halfedge_handle e,
DEMGeo& dem,
Vector2 (* tensorFunc)(const Point2& p, void * ref),
void * tensorRef)
{
int x1 = intlim(dem.lon_to_x(CGAL::to_double(e->source()->point().x())),0,dem.mWidth-1);
int x2 = intlim(dem.lon_to_x(CGAL::to_double(e->target()->point().x())),0,dem.mWidth-1);
int y1 = intlim(dem.lat_to_y(CGAL::to_double(e->source()->point().y())),0,dem.mHeight-1);
int y2 = intlim(dem.lat_to_y(CGAL::to_double(e->target()->point().y())),0,dem.mHeight-1);
Vector2 road_dir(cgal2ben(e->source()->point()),cgal2ben(e->target()->point()));
road_dir.normalize();
if(std::abs(x2-x1) > std::abs(y2-y1))
{
// "Horizontal line"
if(x2 < x1)
{
swap(x1,x2);
swap(y1,y2);
}
for(int x = x1; x <= x2; ++x)
{
int y = intlim(interp(x1,y1,x2,y2,x),0,dem.mHeight-1);
Vector2 e(Tensor2Eigen(tensorFunc(
Point2(interp(0,0,dem.mWidth -1,1,x),
interp(0,0,dem.mHeight-1,1,y)),tensorRef)));
double align_major = fabs(road_dir.dot(e));
e = e.perpendicular_ccw();
double align_minor = fabs(road_dir.dot(e));
int old = dem.get(x,y);
if(align_major > 0.7) old |= 1;
if(align_minor > 0.7) old |= 2;
dem(x,y)=old;
}
}
else
{
// "Vertical line"
if(y2 < y1)
{
swap(x1,x2);
swap(y1,y2);
}
for(int y = y1; y < y2; ++y)
{
int x = intlim(interp(y1,x1,y2,x2,y),0,dem.mWidth-1);
Vector2 e(Tensor2Eigen(tensorFunc(
Point2(interp(0,0,dem.mWidth -1,1,x),
interp(0,0,dem.mHeight-1,1,y)),tensorRef)));
double align_major = fabs(road_dir.dot(e));
e = e.perpendicular_ccw();
double align_minor = fabs(road_dir.dot(e));
int old = dem.get(x,y);
if(align_major > 0.8) old |= 1;
if(align_minor > 0.8) old |= 2;
dem(x,y)=old;
}
}
}
void BuildRoadsForFace(
Pmwx& ioMap,
const DEMGeo& inElevation,
const DEMGeo& inSlope,
const DEMGeo& inUrbanDensity,
const DEMGeo& inUrbanRadial,
const DEMGeo& inUrbanSquare,
Face_handle inFace,
ProgressFunc inProg,
ImageInfo * ioTensorImage,
double outTensorBounds[4])
{
Pmwx::Face_iterator f;
int rx1, rx2, x, y;
Tensor_info t;
// gMeshLines.clear();
// gMeshPoints.clear();
DEMGeo road_restrict(inElevation.mWidth,inElevation.mHeight);
DEMGeo grid_x(inElevation.mWidth,inElevation.mHeight);
DEMGeo grid_y(inElevation.mWidth,inElevation.mHeight);
road_restrict.copy_geo_from(inElevation);
grid_x.copy_geo_from(inElevation);
grid_y.copy_geo_from(inElevation);
/**********************************************************************************************************************************
* INITIALIZE THE ROAD RESTRICTION GRID USING WATER AND OTHER NON-PASSABLES!
**********************************************************************************************************************************/
// Best to zap out a lot here since more possiblep points means more time in the alg.
{
TIMER(burn_water)
set<Face_handle> no_road_faces;
set<Halfedge_handle> bounds;
PolyRasterizer<double> raster;
for(f = ioMap.faces_begin(); f != ioMap.faces_end(); ++f)
if (!f->is_unbounded())
if(!RoadsForThisFace(f))
no_road_faces.insert(f);
FindEdgesForFaceSet<Pmwx>(no_road_faces, bounds);
y = SetupRasterizerForDEM(bounds, road_restrict, raster);
raster.StartScanline(y);
while (!raster.DoneScan())
{
while (raster.GetRange(rx1, rx2))
{
rx1 = intlim(rx1,0,road_restrict.mWidth-1);
rx2 = intlim(rx2,0,road_restrict.mWidth-1);
for (x = rx1; x < rx2; ++x)
{
road_restrict(x,y)=3.0;
}
}
++y;
if (y >= road_restrict.mHeight)
break;
raster.AdvanceScanline(y);
}
{
DEMGeo temp(road_restrict);
for(y = 0; y < temp.mHeight; ++y)
for(x = 0; x < temp.mWidth ; ++x)
{
if(temp.get_radial(x,y,1,0.0) != 0.0)
road_restrict(x,y) = 3.0;
}
}
}
/**********************************************************************************************************************************
* BURN EACH VECTOR INTO THE RESTRICTION GRID TOO
**********************************************************************************************************************************/
{
TIMER(burn_roads)
TensorForFace(
inElevation,
inUrbanDensity,
inUrbanRadial,
inUrbanSquare,
grid_x,
grid_y,
t);
for(Pmwx::Edge_iterator e = ioMap.edges_begin(); e != ioMap.edges_end(); ++e)
RasterEdge(e, road_restrict, Tensor_Func, &t);
}
#if DEV
// gDem[dem_Wizard] = road_restrict;
#endif
/**********************************************************************************************************************************
* BUILD GRID TENSOR FIELD
**********************************************************************************************************************************/
// Running a tensor func that accesses every polygon vertex in its evaluator would be unacceptably slow. So we simply rasterize
// each polygon's interior using its own internal tensor func, which simplifies the cost of building this. This lowers the accuracy
// of the grid tensor field, but we don't care that much anyway.
{
TIMER(calc_linear_tensors)
// int tcalcs = 0;
for(f = ioMap.faces_begin(); f != ioMap.faces_end(); ++f)
if (!f->is_unbounded())
if(RoadsForThisFace(f))
{
// First build a polygon with tensor weights for the face we're working on.
vector<Point2> poly;
vector<Vector2> tensors;
PolyRasterizer<double> raster;
Pmwx::Ccb_halfedge_circulator circ = f->outer_ccb();
Pmwx::Ccb_halfedge_circulator start = circ;
Bbox2 bounds(cgal2ben(circ->source()->point()));
do {
poly.push_back(cgal2ben(circ->target()->point()));
bounds += cgal2ben(circ->target()->point());
Vector2 prev( cgal2ben(circ->source()->point()),cgal2ben(circ->target()->point()));
Vector2 next( cgal2ben(circ->next()->source()->point()),cgal2ben(circ->next()->target()->point()));
prev.normalize();
next.normalize();
Vector2 v(prev+next);
v.normalize();
tensors.push_back(/*Eigen2Tensor*/(v));
++circ;
} while (circ != start);
for(Pmwx::Hole_iterator h = f->holes_begin(); h != f->holes_end(); ++h)
{
Pmwx::Ccb_halfedge_circulator circ(*h);
Pmwx::Ccb_halfedge_circulator start = circ;
do {
poly.push_back(cgal2ben(circ->target()->point()));
Vector2 prev( cgal2ben(circ->source()->point()),cgal2ben(circ->target()->point()));
Vector2 next( cgal2ben(circ->next()->source()->point()),cgal2ben(circ->next()->target()->point()));
prev.normalize();
next.normalize();
Vector2 v(prev+next);
v.normalize();
tensors.push_back(/*Eigen2Tensor*/(v));
++circ;
} while(circ != start);
}
// Now rasterize into the polygon...
double sz = (bounds.p2.y() - bounds.p1.y()) * (bounds.p2.x() - bounds.p1.x());
y = SetupRasterizerForDEM(f, road_restrict, raster);
raster.StartScanline(y);
while (!raster.DoneScan())
{
while (raster.GetRange(rx1, rx2))
{
rx1 = intlim(rx1,0,road_restrict.mWidth-1);
rx2 = intlim(rx2,0,road_restrict.mWidth-1);
for (x = rx1; x < rx2; ++x)
if(road_restrict.get(x,y) != 3.0)
{
float sq = inUrbanSquare.get(
inUrbanSquare.lon_to_x(grid_x.x_to_lon(x)),
inUrbanSquare.lat_to_y(grid_x.y_to_lat(y)));
if(sq == 1.0)
{
Vector2 t(grid_x.get(x,y),grid_y.get(x,y));
for (int n = 0; n < poly.size(); ++n)
{
// ++tcalcs;
t += (Linear_Tensor(poly[n],tensors[n], 4.0 / sz, Point2(road_restrict.x_to_lon(x),road_restrict.y_to_lat(y))));
}
grid_x(x,y) = t.dx;
grid_y(x,y) = t.dy;
}
}
}
++y;
if (y >= road_restrict.mHeight)
break;
raster.AdvanceScanline(y);
}
}
// printf("Total tensor calcs for road grid: %d\n",tcalcs);
}
/**********************************************************************************************************************************
* SEED THE QUEUE!
**********************************************************************************************************************************/
SeedQueue seedQ;
{
TIMER(build_seedQ)
for(Pmwx::Vertex_iterator v = ioMap.vertices_begin(); v != ioMap.vertices_end(); ++v)
{
bool has_road = false;
Pmwx::Halfedge_around_vertex_circulator circ(v->incident_halfedges());
Pmwx::Halfedge_around_vertex_circulator stop(circ);
do {
if (!circ->data().mSegments.empty() ||
!circ->twin()->data().mSegments.empty())
{
has_road = true;
break;
}
++circ;
} while (circ != stop);
if(has_road)
{
QueueSeed(cgal2ben(v->point()),false,road_restrict,seedQ);
}
}
printf("Queued %llu seeds origially.\n", (unsigned long long)seedQ.size());
}
/**********************************************************************************************************************************
* RUN THROUGH THE QUEUE, BUILDING ROADS
**********************************************************************************************************************************/
vector<Segment2> roads;
int ctr=0;
{
TIMER(eval_seed_Q)
while(!seedQ.empty())
{
++ctr;
if(CheckSeed(seedQ.front(),road_restrict))
{
list<Point2> pts;
Point2 fp(seedQ.front().p);
Point2 bp(fp);
pts.push_back(fp);
bool front_alive = true;
bool back_alive = true;
bool major = seedQ.front().major;
int fx(seedQ.front().x);
int fy(seedQ.front().y);
int fc=10,bc=10;
int bx = fx, by = fy;
Vector2 fe(0.0,0.0);
Vector2 be(0.0,0.0);
do {
if (front_alive)
{
Vector2 e = Tensor2Eigen(Tensor_Func(
Point2(interp(road_restrict.mWest , 0, road_restrict.mEast ,1,fp.x()),
interp(road_restrict.mSouth, 0, road_restrict.mNorth,1,fp.y())),&t));
if (!seedQ.front().major) e = e.perpendicular_ccw();
if(e.dot(fe) < 0) e = -e;
fe = e;
e *= ADVANCE_RATIO;
fp += e;
front_alive = CheckAndRegister(fp,road_restrict,fx, fy, fc, major);
if(front_alive) front_alive = CheckStats(fp,pts.front(),inElevation,inSlope, inUrbanDensity, gRoadPrefs.density_amp);
if(front_alive)
{
pts.push_front(fp);
if (CheckStats(fp,pts.front(),inElevation,inSlope, inUrbanDensity, 0.0f))
QueueSeed(fp,!major,road_restrict,seedQ);
}
}
if (back_alive)
{
Vector2 e = -Tensor2Eigen(Tensor_Func(
Point2(interp(road_restrict.mWest , 0, road_restrict.mEast ,1,bp.x()),
interp(road_restrict.mSouth, 0, road_restrict.mNorth,1,bp.y())),&t));
if (!seedQ.front().major) e = e.perpendicular_ccw();
if (e.dot(be) < 0) e = -e;
be = e;
e *= ADVANCE_RATIO;
bp+= e;
back_alive = CheckAndRegister(bp,road_restrict,bx, by, bc, major);
if(back_alive) back_alive = CheckStats(bp,pts.back(),inElevation,inSlope, inUrbanDensity, gRoadPrefs.density_amp);
if(back_alive) {
pts.push_back(bp);
if(CheckStats(bp,pts.back(),inElevation,inSlope, inUrbanDensity, 0.0f))
QueueSeed(bp,!major,road_restrict,seedQ);
}
}
} while (front_alive || back_alive);
Point3 c(1,1,0);
if(!major)c.y = 0;
int k = ThinLine(pts, 10.0 * MTR_TO_NM * NM_TO_DEG_LAT, 500 * MTR_TO_NM * NM_TO_DEG_LAT);
// printf("Killed %d points, kept %d points.\n", k, pts.size());
for(list<Point2>::iterator i = pts.begin(); i != pts.end(); ++i)
{
// gMeshPoints.push_back(pair<Point2,Point3>(*i,c));
if(i != pts.begin())
{
list<Point2>::iterator j(i);
--j;
// gMeshLines.push_back(pair<Point2,Point3>(*j,c));
// gMeshLines.push_back(pair<Point2,Point3>(*i,c));
// can't do this - makes a point cloud of roads - TOTALLY gross.
// if(RollDice(max(inUrbanDensity.value_linear(j->x,j->y),inUrbanDensity.value_linear(i->x,i->y))))
roads.push_back(Segment2(*j,*i));
}
}
}
seedQ.pop_front();
// if((ctr%1000)==0)
// printf("Q contains: %d, pts: %d\n", seedQ.size(), gMeshPoints.size());
}
}
{
TIMER(build_real_roads)
Pmwx sub;
sub.unbounded_face()->data().mTerrainType = terrain_Natural;
BulkInsertRoads(roads, sub);
BulkZapRoads(inUrbanDensity, sub);
DebugAssert(sub.is_valid());
// TopoIntegrateMaps(&ioMap, &sub);
// for(Pmwx::Face_iterator sf = sub.faces-begin(); sf != sub.faces_end(); ++sf)
// sf->mTerrainType = terrain_Natural;
DebugAssert(ioMap.is_valid());
DebugAssert(sub.is_valid());
#if SHOW_GENERATED_ROADS
for(Pmwx::Edge_iterator eit = sub.edges_begin(); eit != sub.edges_end(); ++eit)
debug_mesh_line(cgal2ben(eit->source()->point()),cgal2ben(eit->target()->point()),1,0,0, 0,1,0);
#endif
if(!sub.is_empty())
MergeMaps_legacy(ioMap, sub, false, NULL, true, inProg);
}
/**********************************************************************************************************************************
* DEBUG OUTPUT
**********************************************************************************************************************************/
#if OPENGL_MAP
if(inFace != Face_handle() && ioTensorImage)
{
Pmwx::Ccb_halfedge_circulator circ = inFace->outer_ccb();
Pmwx::Ccb_halfedge_circulator start = circ;
t.bounds = Bbox2(cgal2ben(circ->source()->point()));
do {
t.bounds += cgal2ben(circ->source()->point());
++circ;
} while (circ != start);
TensorDDA(*ioTensorImage,Tensor_Func,&t);
outTensorBounds[0] = t.bounds.p1.x();
outTensorBounds[1] = t.bounds.p1.y();
outTensorBounds[2] = t.bounds.p2.x();
outTensorBounds[3] = t.bounds.p2.y();
}
#endif
#if SHOW_ROAD_RESTRICT
gDem[dem_Wizard] = road_restrict;
#endif
}
| 30.643162 | 148 | 0.593369 | rromanchuk |
db718f3da616444ed16544aa1dc149a4b7c3f991 | 3,174 | cpp | C++ | src/infra/ToValue.cpp | murataka/two | f6f9835de844a38687e11f649ff97c3fb4146bbe | [
"Zlib"
] | 578 | 2019-05-04T09:09:42.000Z | 2022-03-27T23:02:21.000Z | src/infra/ToValue.cpp | murataka/two | f6f9835de844a38687e11f649ff97c3fb4146bbe | [
"Zlib"
] | 14 | 2019-05-11T14:34:56.000Z | 2021-02-02T07:06:46.000Z | src/infra/ToValue.cpp | murataka/two | f6f9835de844a38687e11f649ff97c3fb4146bbe | [
"Zlib"
] | 42 | 2019-05-11T16:04:19.000Z | 2022-01-24T02:21:43.000Z | // Copyright (c) 2019 Hugo Amiard [email protected]
// This software is provided 'as-is' under the zlib License, see the LICENSE.txt file.
// This notice and the license may not be removed or altered from any source distribution.
#ifdef TWO_MODULES
module;
#include <infra/Cpp20.h>
module TWO(infra);
#else
#include <cstdlib>
#include <infra/ToValue.h>
#endif
namespace two
{
#ifndef USE_STL
template <> void to_value(const string& str, bool& val) { val = atoi(str.c_str()) != 0; } //str == "true" ? true : false; }
template <> void to_value(const string& str, char& val) { val = char(atoi(str.c_str())); }
template <> void to_value(const string& str, schar& val) { val = schar(atoi(str.c_str())); }
template <> void to_value(const string& str, short& val) { val = short(atoi(str.c_str())); }
template <> void to_value(const string& str, int& val) { val = atoi(str.c_str()); }
template <> void to_value(const string& str, long& val) { val = atoi(str.c_str()); }
template <> void to_value(const string& str, llong& val) { val = atoi(str.c_str()); }
template <> void to_value(const string& str, uchar& val) { val = uchar(atoi(str.c_str())); }
template <> void to_value(const string& str, ushort& val) { val = ushort(atoi(str.c_str())); }
template <> void to_value(const string& str, uint& val) { val = atoi(str.c_str()); }
template <> void to_value(const string& str, ulong& val) { val = atoi(str.c_str()); }
template <> void to_value(const string& str, ullong& val) { val = atoi(str.c_str()); }
template <> void to_value(const string& str, float& val) { val = float(atof(str.c_str())); }
template <> void to_value(const string& str, double& val) { val = atof(str.c_str()); } //sscanf(str.c_str(), "%lf", &val); }
template <> void to_value(const string& str, ldouble& val) { val = atof(str.c_str()); }
#else
template <> void to_value(const string& str, bool& val) { val = std::stoi(str) != 0; } //str == "true" ? true : false; }
template <> void to_value(const string& str, char& val) { val = char(std::stoi(str)); }
template <> void to_value(const string& str, schar& val) { val = schar(std::stoi(str)); }
template <> void to_value(const string& str, short& val) { val = short(std::stoi(str)); }
template <> void to_value(const string& str, int& val) { val = std::stoi(str); }
template <> void to_value(const string& str, long& val) { val = std::stoi(str); }
template <> void to_value(const string& str, llong& val) { val = std::stoi(str); }
template <> void to_value(const string& str, uchar& val) { val = uchar(std::stoi(str)); }
template <> void to_value(const string& str, ushort& val) { val = ushort(std::stoi(str)); }
template <> void to_value(const string& str, uint& val) { val = std::stoi(str); }
template <> void to_value(const string& str, ulong& val) { val = std::stoi(str); }
template <> void to_value(const string& str, ullong& val) { val = std::stoi(str); }
template <> void to_value(const string& str, float& val) { val = std::stof(str); }
template <> void to_value(const string& str, double& val) { val = std::stod(str); }
template <> void to_value(const string& str, ldouble& val) { val = std::stod(str); }
#endif
}
| 63.48 | 125 | 0.660996 | murataka |
db72e8a58c56991009ed2558b84cd8ff6b326bfc | 7,778 | hpp | C++ | neutrino/math/inc/matrix_functions.hpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 1 | 2017-07-14T04:51:54.000Z | 2017-07-14T04:51:54.000Z | neutrino/math/inc/matrix_functions.hpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | 32 | 2017-02-02T14:49:41.000Z | 2019-06-25T19:38:27.000Z | neutrino/math/inc/matrix_functions.hpp | alexiynew/nih_framework | a65335586331daa0ece892f98265bd1d2f8f579f | [
"MIT"
] | null | null | null | #ifndef FRAMEWORK_MATH_DETAILS
#error You should include math/math.hpp instead of matrix_functions.hpp
#endif
#ifndef FRAMEWORK_MATH_INC_MATRIX_FUNCTIONS_HPP
#define FRAMEWORK_MATH_INC_MATRIX_FUNCTIONS_HPP
#include <math/inc/matrix_functions_details.hpp>
#include <math/inc/matrix_type.hpp>
namespace framework::math
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @addtogroup math_matrix_functions
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name transpose
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Calculate the transpose of a Matrix.
///
/// @param value Specifies the Matrix of which to take the transpose.
///
/// @return The transpose of the Matrix.
template <std::size_t C, std::size_t R, typename T>
inline Matrix<R, C, T> transpose(const Matrix<C, R, T>& value)
{
return matrix_functions_details::transpose(value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name component_wise_multiplication
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Perform a component-wise multiplication of two matrices.
///
/// @param lhs Specifies the first Matrix multiplicand.
/// @param rhs Specifies the second Matrix multiplicand.
///
/// @return The component-wise multiplication of two matrices.
template <std::size_t C, std::size_t R, typename T>
inline Matrix<C, R, T> component_wise_multiplication(const Matrix<C, R, T>& lhs, const Matrix<C, R, T>& rhs)
{
Matrix<C, R, T> temp{lhs};
for (std::size_t i = 0; i < C; ++i) {
temp[i] *= rhs[i];
}
return temp;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name outer_product
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Calculate the outer product of a pair of vectors.
///
/// @param lhs Specifies the parameter to be treated as a column vector.
/// @param rhs Specifies the parameter to be treated as a row vector.
///
/// @return The outer product of a pair of vectors.
template <std::size_t C, std::size_t R, typename T>
inline Matrix<C, R, T> outer_product(const Vector<R, T>& lhs, const Vector<C, T>& rhs)
{
return matrix_functions_details::outer_product(lhs, rhs);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name determinant
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Calculate the determinant of a Matrix.
///
/// @param value Specifies the Matrix of which to take the determinant.
///
/// @return The determinant of the Matrix.
template <std::size_t C, std::size_t R, typename T>
inline T determinant(const Matrix<C, R, T>& value)
{
return matrix_functions_details::determinant(value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name inverse
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Calculate the inverse of a Matrix.
///
/// The values in the returned Matrix are undefined if Matrix is singular or
/// poorly-conditioned (nearly singular).
///
/// @param value Specifies the Matrix of which to take the inverse.
///
/// @return The inverse of a Matrix.
template <std::size_t C, std::size_t R, typename T>
inline Matrix<C, R, T> inverse(const Matrix<C, R, T>& value)
{
return matrix_functions_details::inverse(value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name affine_inverse
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Calculate the inverse of a affine Matrix.
///
/// The values in the returned Matrix are undefined if Matrix contains not
/// affine transformations, or Matrix is singular or
/// poorly-conditioned (nearly singular).
///
/// @param value Specifies the Matrix of which to take the inverse.
///
/// @return The inverse of a Matrix.
template <std::size_t C, std::size_t R, typename T>
inline Matrix<C, R, T> affine_inverse(const Matrix<C, R, T>& value)
{
return matrix_functions_details::affine_inverse(value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @name inverse_transpose
/// @{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Calculate the inverse-transpose of a Matrix.
///
/// The values in the returned Matrix are undefined if Matrix is singular
/// or poorly-conditioned (nearly singular).
///
/// @param value Specifies the Matrix of which to take the inverse.
///
/// @return The Matrix which is equivalent to `transpose(inverse(Matrix))`.
template <std::size_t C, std::size_t R, typename T>
inline Matrix<C, R, T> inverse_transpose(const Matrix<C, R, T>& value)
{
return matrix_functions_details::inverse_transpose(value);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace framework::math
#endif
| 44.193182 | 120 | 0.349061 | alexiynew |
db7846efea4d150c6002f9cc48ba392637725477 | 591 | hpp | C++ | include/Engine.hpp | DavidCarlyn/simple_cpp_gui | ba7e58bb231734b38ebb329f9d4142442ce81c0b | [
"MIT"
] | null | null | null | include/Engine.hpp | DavidCarlyn/simple_cpp_gui | ba7e58bb231734b38ebb329f9d4142442ce81c0b | [
"MIT"
] | null | null | null | include/Engine.hpp | DavidCarlyn/simple_cpp_gui | ba7e58bb231734b38ebb329f9d4142442ce81c0b | [
"MIT"
] | null | null | null | #pragma once
#include <SDL.h>
#include <string>
class Engine {
public:
Engine();
SDL_Window* createWindow(const int width, const int height, std::string name = "WINDOW NAME");
SDL_Surface* createSurface(SDL_Window* window);
SDL_Surface* createImageSurface(SDL_Surface* surface, std::string path);
SDL_Renderer* createRenderer(SDL_Window* window);
void freeSurface(SDL_Surface* surface);
void destroyWindow(SDL_Window* window);
void destroyRenderer(SDL_Renderer* renderer);
void close();
private:
}; | 28.142857 | 102 | 0.663283 | DavidCarlyn |
db789037bfac80d89b06b52ad44a23ce54bf584f | 2,312 | cpp | C++ | TerraForge3D/src/Generators/ClearMeshGenerator.cpp | MalikuMane/TerraForge3D | aa0c532cbafe42b7789bb610bae7495211196cd5 | [
"MIT"
] | 434 | 2021-11-03T06:03:07.000Z | 2022-03-31T22:52:19.000Z | TerraForge3D/src/Generators/ClearMeshGenerator.cpp | MalikuMane/TerraForge3D | aa0c532cbafe42b7789bb610bae7495211196cd5 | [
"MIT"
] | 14 | 2021-11-03T12:11:30.000Z | 2022-03-31T16:52:24.000Z | TerraForge3D/src/Generators/ClearMeshGenerator.cpp | MalikuMane/TerraForge3D | aa0c532cbafe42b7789bb610bae7495211196cd5 | [
"MIT"
] | 45 | 2021-11-04T07:34:21.000Z | 2022-03-31T07:06:05.000Z | #include "Generators/ClearMeshGenerator.h"
#include "Utils/Utils.h"
#include "Data/ApplicationState.h"
#include "Profiler.h"
ClearMeshGenerator::ClearMeshGenerator(ApplicationState *as, ComputeKernel *kernels)
{
bool tmp = false;
appState = as;
}
void ClearMeshGenerator::Generate(ComputeKernel *kernels)
{
START_PROFILER();
if(useGPU)
{
if (appState->mode == ApplicationMode::TERRAIN)
{
kernels->SetKernelArg("clear_mesh_terrain", 0, "mesh");
kernels->ExecuteKernel("clear_mesh_terrain", cl::NDRange(1), cl::NDRange(appState->models.coreTerrain->mesh->vertexCount));
}
else if (appState->mode == ApplicationMode::CUSTOM_BASE)
{
kernels->SetKernelArg("clear_mesh_custom_base", 0, "mesh");
kernels->SetKernelArg("clear_mesh_custom_base", 1, "mesh_copy");
kernels->ExecuteKernel("clear_mesh_custom_base", cl::NDRange(1), cl::NDRange(appState->models.customBase->mesh->vertexCount));
}
}
else
{
if (appState->mode == ApplicationMode::TERRAIN)
{
Mesh *mes = appState->models.coreTerrain->mesh;
int vc = mes->vertexCount;
for(int i=0; i<vc; i++)
{
mes->vert[i].normal.x = mes->vert[i].normal.y = mes->vert[i].normal.z = mes->vert[i].position.y = 0.0f;
mes->vert[i].extras1.x = 0.0f;
mes->vert[i].extras1.y = 0.0f;
mes->vert[i].extras1.z = 0.0f;
}
}
else if (appState->mode == ApplicationMode::CUSTOM_BASE)
{
Mesh *mes = appState->models.customBase->mesh;
Mesh *mesC = appState->models.customBaseCopy->mesh;
int vc = mesC->vertexCount;
for(int i=0; i<vc; i++)
{
mes->vert[i].normal.x = mes->vert[i].normal.y = mes->vert[i].normal.z = 0.0f;
mes->vert[i].position = mesC->vert[i].position;
mes->vert[i].extras1.x = 0.0f;
mes->vert[i].extras1.y = 0.0f;
mes->vert[i].extras1.z = 0.0f;
}
}
}
END_PROFILER(time);
}
nlohmann::json ClearMeshGenerator::Save()
{
nlohmann::json data;
data["uiActive"] = uiActive;
data["useGPU"] = useGPU;
return data;
}
void ClearMeshGenerator::Load(nlohmann::json data)
{
uiActive = data["uiActive"];
useGPU = data["useGPU"];
}
void ClearMeshGenerator::ShowSettings()
{
if(ImGui::Checkbox("Use GPU##CMG", &useGPU))
{
}
ImGui::Checkbox("Use GPU For Normals(Flat Shading)##CMG", &appState->states.useGPUForNormals);
ImGui::Text("Time : %lf ms", time);
}
| 25.406593 | 129 | 0.66955 | MalikuMane |
db7c6c9a207927d5cfeb3aa6a0fcff3ad8344de7 | 656 | hpp | C++ | src/hardware/audio/components/length_component.hpp | geaz/emu-gameboy | da8a3e6898a0075dcb4371eb772e31695300ae54 | [
"MIT"
] | 47 | 2019-10-12T14:23:47.000Z | 2022-03-22T03:31:43.000Z | src/hardware/audio/components/length_component.hpp | geaz/emu-gameboy | da8a3e6898a0075dcb4371eb772e31695300ae54 | [
"MIT"
] | null | null | null | src/hardware/audio/components/length_component.hpp | geaz/emu-gameboy | da8a3e6898a0075dcb4371eb772e31695300ae54 | [
"MIT"
] | 2 | 2021-09-20T20:47:21.000Z | 2021-10-12T12:10:46.000Z | #pragma once
#ifndef LENGTHCOMPONENT_H
#define LENGTHCOMPONENT_H
#include <cstdint>
namespace GGB::Hardware::Audio
{
class LengthComponent
{
public:
void setLength(uint16_t value, bool stopAfterLength)
{
length = length == 0 ? value : length;
lengthStop = stopAfterLength;
}
bool tick()
{
length -= length != 0 ? 1 : 0;
return !lengthStop || (length != 0 && lengthStop);
}
private:
bool lengthStop = false;
uint16_t length = 0;
};
}
#endif // LENGTHCOMPONENT_H | 21.866667 | 66 | 0.509146 | geaz |
db7d4727215550b68a5cf3bf5f4bd8e2fc78e565 | 913 | cpp | C++ | Module/HelloWorld_Scratch/kmain.cpp | arkiny/OSwithMSVC | 90cd62ce9bbe8301942e024404f32b04874e7906 | [
"MIT"
] | 1 | 2021-05-09T01:24:05.000Z | 2021-05-09T01:24:05.000Z | Module/HelloWorld_Scratch/kmain.cpp | arkiny/OSwithMSVC | 90cd62ce9bbe8301942e024404f32b04874e7906 | [
"MIT"
] | null | null | null | Module/HelloWorld_Scratch/kmain.cpp | arkiny/OSwithMSVC | 90cd62ce9bbe8301942e024404f32b04874e7906 | [
"MIT"
] | null | null | null | #include "kmain.h"
_declspec(naked) void multiboot_entry(void)
{
__asm {
align 4
multiboot_header:
//멀티부트 헤더 사이즈 : 0X20
dd(MULTIBOOT_HEADER_MAGIC); magic number
dd(MULTIBOOT_HEADER_FLAGS); flags
dd(CHECKSUM); checksum
dd(HEADER_ADRESS); //헤더 주소 KERNEL_LOAD_ADDRESS+ALIGN(0x100064)
dd(KERNEL_LOAD_ADDRESS); //커널이 로드된 가상주소 공간
dd(00); //사용되지 않음
dd(00); //사용되지 않음
dd(HEADER_ADRESS + 0x20); //커널 시작 주소 : 멀티부트 헤더 주소 + 0x20, kernel_entry
kernel_entry :
mov esp, KERNEL_STACK; //스택 설정
push 0; //플래그 레지스터 초기화
popf
//GRUB에 의해 담겨 있는 정보값을 스택에 푸쉬한다.
push ebx; //멀티부트 구조체 포인터
push eax; //매직 넘버
//위의 두 파라메터와 함께 kmain 함수를 호출한다.
call kmain; //C++ 메인 함수 호출
//루프를 돈다. kmain이 리턴되지 않으면 아래 코드는 수행되지 않는다.
halt:
jmp halt;
}
}
void kmain(unsigned long magic, unsigned long addr)
{
SkyConsole::Initialize();
SkyConsole::Print("Hello World!!\n");
for (;;);
} | 20.288889 | 72 | 0.654984 | arkiny |
db7e905e90ad38d210c95b593c49ddc191b9176b | 1,130 | hpp | C++ | src/app/Page.hpp | hilnius/cappella | 555a920330e615793b238d72255274ca7c558467 | [
"MIT"
] | null | null | null | src/app/Page.hpp | hilnius/cappella | 555a920330e615793b238d72255274ca7c558467 | [
"MIT"
] | null | null | null | src/app/Page.hpp | hilnius/cappella | 555a920330e615793b238d72255274ca7c558467 | [
"MIT"
] | null | null | null | #ifndef PAGE_H_INCLUDED
#define PAGE_H_INCLUDED
#include "common/Types.hpp"
#include "core/SQLEntity.hpp"
#include <iostream>
class JSONSerializable;
class Page: public SQLEntity, public JSONSerializable
{
public:
Page();
virtual ~Page();
void setId(INTEGER<12> id) { p_id = id; }
void setName(STRING<255> name) { p_name = name; }
void setUserId(INTEGER<12> userId) { p_userId = userId; }
void setPageViews(INTEGER<12> pageViews) { p_pageViews = pageViews; }
INTEGER<12> getId() { return p_id; }
STRING<255> getName() { return p_name; }
INTEGER<12> getUserId() { return p_userId; }
INTEGER<12> getPageViews() { return p_pageViews; }
private:
INTEGER<12> p_id;
STRING<255> p_name;
INTEGER<12> p_userId;
INTEGER<12> p_pageViews;
protected:
virtual std::map<std::string, const JSONSerializable*> getSerializedData() const
{
std::map<std::string, const JSONSerializable*> result;
result["id"] = &p_id;
result["name"] = &p_name;
result["pageViews"] = &p_pageViews;
return result;
}
};
#endif // PAGE_H_INCLUDED
| 24.565217 | 84 | 0.655752 | hilnius |
db7eb204d7d422870d51397c17162f4b698f1606 | 1,652 | cpp | C++ | Leetcode/Practice/1568.cpp | coderanant/Competitive-Programming | 45076af7894251080ac616c9581fbf2dc49604af | [
"MIT"
] | 4 | 2019-06-04T11:03:38.000Z | 2020-06-19T23:37:32.000Z | Leetcode/Practice/1568.cpp | coderanant/Competitive-Programming | 45076af7894251080ac616c9581fbf2dc49604af | [
"MIT"
] | null | null | null | Leetcode/Practice/1568.cpp | coderanant/Competitive-Programming | 45076af7894251080ac616c9581fbf2dc49604af | [
"MIT"
] | null | null | null | class Solution {
public:
void dfs(vector<vector<int>>& grid, int i, int j)
{
int n = grid.size(), m = grid[0].size();
if(i < 0 || j < 0 || i >= n || j >= m || grid[i][j] == 0)
return ;
grid[i][j] = 0;
int d1[] = {0, 1, 0, -1}, d2[] = {1, 0, -1, 0};
for(int k = 0; k < 4; k++)
dfs(grid, i + d1[k], j + d2[k]);
return ;
}
bool isConn(vector<vector<int>> grid) {
if(grid.size() == 0)
return false;
int n = grid.size(), m = grid[0].size();
int flag = false;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(grid[i][j] == 1)
{
if(flag == false)
{
dfs(grid, i, j);
flag = true;
}
else
return false;
}
}
}
if(flag == false)
return false;
return true;
}
int minDays(vector<vector<int>>& grid) {
if(grid.size() == 0)
return true;
int n = grid.size(), m = grid[0].size();
if(isConn(grid) == false)
return 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(grid[i][j] == 1)
{
grid[i][j] = 0;
if(isConn(grid) == false)
return 1;
grid[i][j] = 1;
}
}
}
return 2;
}
}; | 27.533333 | 65 | 0.311743 | coderanant |
db83eb4b7174151e3f6261ece34cce9b304a7c6c | 6,385 | cpp | C++ | DataStructures/src/streams/DS_Stream.cpp | Kay01010101/PredictVersion | adde9de5dd39b2f22e103f3294d1beab4f327d62 | [
"MIT"
] | null | null | null | DataStructures/src/streams/DS_Stream.cpp | Kay01010101/PredictVersion | adde9de5dd39b2f22e103f3294d1beab4f327d62 | [
"MIT"
] | null | null | null | DataStructures/src/streams/DS_Stream.cpp | Kay01010101/PredictVersion | adde9de5dd39b2f22e103f3294d1beab4f327d62 | [
"MIT"
] | null | null | null | #include "CommonTypeDefines.h"
#include "streams/DS_FileStream.h"
#include "fileUtils/_fileExists.h"
#include <algorithm>
using std::min;
namespace DataStructures
{
//------------------------------------------------------------------- Stream ------------------------------------------------------------------------
#if __WORDSIZE == 64
template <>
size_t Stream::Write(const unsigned int &buffer)
{
if (mForce32bitCompatable)
{
__u32 val = buffer;
return this->Write(&val, sizeof(__u32));
}
else
return this->Write(&buffer, sizeof(unsigned int));
}
template <>
size_t Stream::Write(const int &buffer)
{
if (mForce32bitCompatable)
{
__s32 val = buffer;
return this->Write(&val, sizeof(__s32));
}
else
return this->Write(&buffer, sizeof(int));
}
template <>
size_t Stream::Write(const unsigned long &buffer)
{
if (mForce32bitCompatable)
{
__u32 val = buffer;
return this->Write(&val, sizeof(__u32));
}
else
return this->Write(&buffer, sizeof(unsigned long));
}
template <>
size_t Stream::Write(const long &buffer)
{
if (mForce32bitCompatable)
{
__s32 val = buffer;
return this->Write(&val, sizeof(__s32));
}
else
return this->Write(&buffer, sizeof(long));
}
template <>
bool Stream::Read(unsigned int &dst)
{
if (mForce32bitCompatable)
{
__u32 t;
bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(unsigned int)) == sizeof(unsigned int);
}
template <>
bool Stream::Read(int &dst)
{
if (mForce32bitCompatable)
{
__s32 t;
bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(int)) == sizeof(int);
}
template <>
bool Stream::Read(unsigned long &dst)
{
if (mForce32bitCompatable)
{
__u32 t;
bool res = this->Read(&t, sizeof(__u32)) == sizeof(__u32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(unsigned long)) == sizeof(unsigned long);
}
template <>
bool Stream::Read(long &dst)
{
if (mForce32bitCompatable)
{
__s32 t;
bool res = this->Read(&t, sizeof(__s32)) == sizeof(__s32);
dst = t;
return res;
}
else
return this->Read((void *)&dst, sizeof(long)) == sizeof(long);
}
#endif
size_t Stream::WriteString(const char *buffer, size_t maxsize)
{
if (!CanWrite())
return 0;
__u16 size = min(strlen(buffer), maxsize + sizeof(__u16));
size_t actSize = this->Write(&size, sizeof(size));
actSize += this->Write(buffer, size);
return actSize;
}
size_t Stream::ReadString(char *dst, size_t maxsize)
{
if (Eof() || !dst || !CanRead())
return 0;
__u16 size;
size_t readIn = this->Read(&size, sizeof(size));
readIn += this->Read(dst, min((size_t)size, maxsize));
dst[size] = 0;
return readIn;
}
size_t Stream::CopyFrom(Stream *stream, size_t count)
{
const size_t _max_buffer_size = 0xf0000;
size_t size = count;
if (count == 0)
{
stream->Seek(0, SEEK_SET);
size = stream->Length();
}
size_t result = size;
size_t bufferSize;
if (size > _max_buffer_size)
bufferSize = _max_buffer_size;
else
bufferSize = size;
char *buffer = (char *)malloc(bufferSize);
size_t n;
while (size != 0)
{
if (size > bufferSize)
n = bufferSize;
else
n = size;
stream->Read(buffer, n);
Write(buffer, n);
size -= n;
}
free(buffer);
return result;
}
bool Stream::SaveToStream(Stream *stream)
{
if (!stream)
return false;
__s64 oldPos = Position();
__s64 oldPos1 = stream->Position();
bool res = stream->CopyFrom(this, 0) == Length();
Seek(oldPos, SEEK_SET);
stream->Seek(oldPos1, SEEK_SET);
return res;
}
bool Stream::LoadFromStream(Stream *stream)
{
if (!stream)
return false;
__s64 oldPos = Position();
__s64 oldPos1 = stream->Position();
size_t size = stream->Length();
SetLength(size);
Seek(0, SEEK_SET);
bool res = CopyFrom(stream, 0) == size;
Seek(oldPos, SEEK_SET);
stream->Seek(oldPos1, SEEK_SET);
return res;
}
bool Stream::SaveToFile(const char *fileName)
{
FileStream *stream = new FileStream(fileName, "wb+");
bool result = SaveToStream(stream);
stream->Close();
delete stream;
return result;
}
bool Stream::LoadFromFile(const char *fileName)
{
if (!_fileExists(fileName))
return false;
FileStream *stream = new FileStream(fileName, "rb");
bool result = LoadFromStream(stream);
stream->Close();
delete stream;
return result;
}
__s64 Stream::Length()
{
__s64 oldPos = Seek(0, SEEK_CUR);
__s64 length = Seek(0, SEEK_END);
Seek(oldPos, SEEK_SET);
return length;
}
__s64 Stream::Position()
{
return Seek(0, SEEK_CUR);
}
char *Stream::ReadLine(char *str, int num)
{
if (num <= 0)
return NULL;
char c = 0;
size_t maxCharsToRead = num - 1;
for (size_t i = 0; i < maxCharsToRead; ++i)
{
size_t result = Read(&c, 1);
if (result != 1)
{
str[i] = '\0';
break;
}
if (c == '\n')
{
str[i] = c;
str[i + 1] = '\0';
break;
}
else if(c == '\r')
{
str[i] = c;
// next may be '\n'
size_t pos = Position();
char nextChar = 0;
if (Read(&nextChar, 1) != 1)
{
// no more characters
str[i + 1] = '\0';
break;
}
if (nextChar == '\n')
{
if (i == maxCharsToRead - 1)
{
str[i + 1] = '\0';
break;
}
else
{
str[i + 1] = nextChar;
str[i + 2] = '\0';
break;
}
}
else
{
Seek(pos, SEEK_SET);
str[i + 1] = '\0';
break;
}
}
str[i] = c;
}
return str; // what if first read failed?
}
bool Stream::Eof()
{
return Position() >= Length();
}
bool Stream::Rewind()
{
if (!CanSeek())
return 0;
else
return Seek(0, SEEK_SET) == 0;
}
std::string Stream::GetAsString()
{
char *buffer;
__s64 fileLen = Length();
__s64 oldPosition = Position();
buffer = (char *)malloc(fileLen + 1);
Seek(0, SEEK_SET);
Read(buffer, fileLen);
Seek(oldPosition, SEEK_SET);
buffer[fileLen] = 0;
std::string result(buffer);
free(buffer);
return result;
}
__u32 Stream::GetMemoryCost()
{
//this value is not very accurate because of class HexString's cache using
return static_cast<__u32>(sizeof(*this) + strlen(mFileName));
}
} | 19.829193 | 150 | 0.595771 | Kay01010101 |
db86fd0393e1a6ec76d97b9a5c98076e1fd12e83 | 47,102 | hpp | C++ | src/uavcan/equipment/ice/reciprocating/Status.hpp | bolderflight/dronecan | bf3382ebfad5107077c62ce220e102e1f3f7a67c | [
"MIT"
] | null | null | null | src/uavcan/equipment/ice/reciprocating/Status.hpp | bolderflight/dronecan | bf3382ebfad5107077c62ce220e102e1f3f7a67c | [
"MIT"
] | null | null | null | src/uavcan/equipment/ice/reciprocating/Status.hpp | bolderflight/dronecan | bf3382ebfad5107077c62ce220e102e1f3f7a67c | [
"MIT"
] | null | null | null | /*
* UAVCAN data structure definition for libuavcan.
*
* Autogenerated, do not edit.
*
* Source file: /mnt/c/Users/BrianTaylor/Documents/Software/dronecan/dsdl/uavcan/equipment/ice/reciprocating/1120.Status.uavcan
*/
#ifndef UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED
#define UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED
#include <uavcan/build_config.hpp>
#include <uavcan/node/global_data_type_registry.hpp>
#include <uavcan/marshal/types.hpp>
#include <uavcan/equipment/ice/reciprocating/CylinderStatus.hpp>
/******************************* Source text **********************************
#
# Generic status message of a piston engine control system.
#
# All integer fields are required unless stated otherwise.
# All floating point fields are optional unless stated otherwise; unknown/unapplicable fields should be set to NaN.
#
#
# Abstract engine state. The flags defined below can provide further elaboration.
# This is a required field.
#
uint2 state
#
# The engine is not running. This is the default state.
# Next states: STARTING, FAULT
#
uint2 STATE_STOPPED = 0
#
# The engine is starting. This is a transient state.
# Next states: STOPPED, RUNNING, FAULT
#
uint2 STATE_STARTING = 1
#
# The engine is running normally.
# Some error flags may be set to indicate non-fatal issues, e.g. overheating.
# Next states: STOPPED, FAULT
#
uint2 STATE_RUNNING = 2
#
# The engine can no longer function.
# The error flags may contain additional information about the nature of the fault.
# Next states: STOPPED.
#
uint2 STATE_FAULT = 3
#
# General status flags.
# Note that not all flags are required. Those that aren't are prepended with a validity flag, which is, obviously,
# always required; when the validity flag is set, it is assumed that the relevant flags are set correctly.
# If the validity flag is cleared, then the state of the relevant flags should be ignored.
# All unused bits must be cleared.
#
uint30 flags
#
# General error. This flag is required, and it can be used to indicate an error condition
# that does not fit any of the other flags.
# Note that the vendor may also report additional status information via the vendor specific status code
# field of the NodeStatus message.
#
uint30 FLAG_GENERAL_ERROR = 1
#
# Error of the crankshaft sensor. This flag is optional.
#
uint30 FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED = 2
uint30 FLAG_CRANKSHAFT_SENSOR_ERROR = 4
#
# Temperature levels. These flags are optional; either none of them or all of them are supported.
#
uint30 FLAG_TEMPERATURE_SUPPORTED = 8
uint30 FLAG_TEMPERATURE_BELOW_NOMINAL = 16 # Under-temperature warning
uint30 FLAG_TEMPERATURE_ABOVE_NOMINAL = 32 # Over-temperature warning
uint30 FLAG_TEMPERATURE_OVERHEATING = 64 # Critical overheating
uint30 FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL = 128 # Exhaust gas over-temperature warning
#
# Fuel pressure. These flags are optional; either none of them or all of them are supported.
#
uint30 FLAG_FUEL_PRESSURE_SUPPORTED = 256
uint30 FLAG_FUEL_PRESSURE_BELOW_NOMINAL = 512 # Under-pressure warning
uint30 FLAG_FUEL_PRESSURE_ABOVE_NOMINAL = 1024 # Over-pressure warning
#
# Detonation warning. This flag is optional.
# This warning is cleared immediately after broadcasting is done if detonation is no longer happening.
#
uint30 FLAG_DETONATION_SUPPORTED = 2048
uint30 FLAG_DETONATION_OBSERVED = 4096 # Detonation condition observed warning
#
# Misfire warning. This flag is optional.
# This warning is cleared immediately after broadcasting is done if misfire is no longer happening.
#
uint30 FLAG_MISFIRE_SUPPORTED = 8192
uint30 FLAG_MISFIRE_OBSERVED = 16384 # Misfire condition observed warning
#
# Oil pressure. These flags are optional; either none of them or all of them are supported.
#
uint30 FLAG_OIL_PRESSURE_SUPPORTED = 32768
uint30 FLAG_OIL_PRESSURE_BELOW_NOMINAL = 65536 # Under-pressure warning
uint30 FLAG_OIL_PRESSURE_ABOVE_NOMINAL = 131072 # Over-pressure warning
#
# Debris warning. This flag is optional.
#
uint30 FLAG_DEBRIS_SUPPORTED = 262144
uint30 FLAG_DEBRIS_DETECTED = 524288 # Detection of debris warning
#
# Reserved space
#
void16
#
# Engine load estimate.
# Unit: percent.
# Range: [0, 127].
#
uint7 engine_load_percent
#
# Engine speed.
# Unit: revolutions per minute.
#
uint17 engine_speed_rpm
#
# Spark dwell time.
# Unit: millisecond.
#
float16 spark_dwell_time_ms
#
# Atmospheric (barometric) pressure.
# Unit: kilopascal.
#
float16 atmospheric_pressure_kpa
#
# Engine intake manifold pressure.
# Unit: kilopascal.
#
float16 intake_manifold_pressure_kpa
#
# Engine intake manifold temperature.
# Unit: kelvin.
#
float16 intake_manifold_temperature
#
# Engine coolant temperature.
# Unit: kelvin.
#
float16 coolant_temperature
#
# Oil pressure.
# Unit: kilopascal.
#
float16 oil_pressure
#
# Oil temperature.
# Unit: kelvin.
#
float16 oil_temperature
#
# Fuel pressure.
# Unit: kilopascal.
#
float16 fuel_pressure
#
# Instant fuel consumption estimate.
# The estimated value should be low-pass filtered in order to prevent aliasing effects.
# Unit: (centimeter^3)/minute.
#
float32 fuel_consumption_rate_cm3pm
#
# Estimate of the consumed fuel since the start of the engine.
# This variable MUST be reset when the engine is stopped.
# Unit: centimeter^3.
#
float32 estimated_consumed_fuel_volume_cm3
#
# Throttle position.
# Unit: percent.
#
uint7 throttle_position_percent
#
# The index of the publishing ECU.
#
uint6 ecu_index
#
# Spark plug activity report.
# Can be used during pre-flight tests of the spark subsystem.
#
uint3 spark_plug_usage
#
uint3 SPARK_PLUG_SINGLE = 0
uint3 SPARK_PLUG_FIRST_ACTIVE = 1
uint3 SPARK_PLUG_SECOND_ACTIVE = 2
uint3 SPARK_PLUG_BOTH_ACTIVE = 3
#
# Per-cylinder status information.
#
CylinderStatus[<=16] cylinder_status
******************************************************************************/
/********************* DSDL signature source definition ***********************
uavcan.equipment.ice.reciprocating.Status
saturated uint2 state
saturated uint30 flags
void16
saturated uint7 engine_load_percent
saturated uint17 engine_speed_rpm
saturated float16 spark_dwell_time_ms
saturated float16 atmospheric_pressure_kpa
saturated float16 intake_manifold_pressure_kpa
saturated float16 intake_manifold_temperature
saturated float16 coolant_temperature
saturated float16 oil_pressure
saturated float16 oil_temperature
saturated float16 fuel_pressure
saturated float32 fuel_consumption_rate_cm3pm
saturated float32 estimated_consumed_fuel_volume_cm3
saturated uint7 throttle_position_percent
saturated uint6 ecu_index
saturated uint3 spark_plug_usage
uavcan.equipment.ice.reciprocating.CylinderStatus[<=16] cylinder_status
******************************************************************************/
#undef state
#undef flags
#undef _void_0
#undef engine_load_percent
#undef engine_speed_rpm
#undef spark_dwell_time_ms
#undef atmospheric_pressure_kpa
#undef intake_manifold_pressure_kpa
#undef intake_manifold_temperature
#undef coolant_temperature
#undef oil_pressure
#undef oil_temperature
#undef fuel_pressure
#undef fuel_consumption_rate_cm3pm
#undef estimated_consumed_fuel_volume_cm3
#undef throttle_position_percent
#undef ecu_index
#undef spark_plug_usage
#undef cylinder_status
#undef STATE_STOPPED
#undef STATE_STARTING
#undef STATE_RUNNING
#undef STATE_FAULT
#undef FLAG_GENERAL_ERROR
#undef FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED
#undef FLAG_CRANKSHAFT_SENSOR_ERROR
#undef FLAG_TEMPERATURE_SUPPORTED
#undef FLAG_TEMPERATURE_BELOW_NOMINAL
#undef FLAG_TEMPERATURE_ABOVE_NOMINAL
#undef FLAG_TEMPERATURE_OVERHEATING
#undef FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL
#undef FLAG_FUEL_PRESSURE_SUPPORTED
#undef FLAG_FUEL_PRESSURE_BELOW_NOMINAL
#undef FLAG_FUEL_PRESSURE_ABOVE_NOMINAL
#undef FLAG_DETONATION_SUPPORTED
#undef FLAG_DETONATION_OBSERVED
#undef FLAG_MISFIRE_SUPPORTED
#undef FLAG_MISFIRE_OBSERVED
#undef FLAG_OIL_PRESSURE_SUPPORTED
#undef FLAG_OIL_PRESSURE_BELOW_NOMINAL
#undef FLAG_OIL_PRESSURE_ABOVE_NOMINAL
#undef FLAG_DEBRIS_SUPPORTED
#undef FLAG_DEBRIS_DETECTED
#undef SPARK_PLUG_SINGLE
#undef SPARK_PLUG_FIRST_ACTIVE
#undef SPARK_PLUG_SECOND_ACTIVE
#undef SPARK_PLUG_BOTH_ACTIVE
namespace uavcan
{
namespace equipment
{
namespace ice
{
namespace reciprocating
{
template <int _tmpl>
struct UAVCAN_EXPORT Status_
{
typedef const Status_<_tmpl>& ParameterType;
typedef Status_<_tmpl>& ReferenceType;
struct ConstantTypes
{
typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_STOPPED;
typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_STARTING;
typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_RUNNING;
typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > STATE_FAULT;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_GENERAL_ERROR;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_CRANKSHAFT_SENSOR_ERROR;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_SUPPORTED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_BELOW_NOMINAL;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_ABOVE_NOMINAL;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_OVERHEATING;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_SUPPORTED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_BELOW_NOMINAL;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_FUEL_PRESSURE_ABOVE_NOMINAL;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DETONATION_SUPPORTED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DETONATION_OBSERVED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_MISFIRE_SUPPORTED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_MISFIRE_OBSERVED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_SUPPORTED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_BELOW_NOMINAL;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_OIL_PRESSURE_ABOVE_NOMINAL;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DEBRIS_SUPPORTED;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_DEBRIS_DETECTED;
typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_SINGLE;
typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_FIRST_ACTIVE;
typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_SECOND_ACTIVE;
typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > SPARK_PLUG_BOTH_ACTIVE;
};
struct FieldTypes
{
typedef ::uavcan::IntegerSpec< 2, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > state;
typedef ::uavcan::IntegerSpec< 30, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > flags;
typedef ::uavcan::IntegerSpec< 16, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > _void_0;
typedef ::uavcan::IntegerSpec< 7, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > engine_load_percent;
typedef ::uavcan::IntegerSpec< 17, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > engine_speed_rpm;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > spark_dwell_time_ms;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > atmospheric_pressure_kpa;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > intake_manifold_pressure_kpa;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > intake_manifold_temperature;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > coolant_temperature;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > oil_pressure;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > oil_temperature;
typedef ::uavcan::FloatSpec< 16, ::uavcan::CastModeSaturate > fuel_pressure;
typedef ::uavcan::FloatSpec< 32, ::uavcan::CastModeSaturate > fuel_consumption_rate_cm3pm;
typedef ::uavcan::FloatSpec< 32, ::uavcan::CastModeSaturate > estimated_consumed_fuel_volume_cm3;
typedef ::uavcan::IntegerSpec< 7, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > throttle_position_percent;
typedef ::uavcan::IntegerSpec< 6, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > ecu_index;
typedef ::uavcan::IntegerSpec< 3, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > spark_plug_usage;
typedef ::uavcan::Array< ::uavcan::equipment::ice::reciprocating::CylinderStatus, ::uavcan::ArrayModeDynamic, 16 > cylinder_status;
};
enum
{
MinBitLen
= FieldTypes::state::MinBitLen
+ FieldTypes::flags::MinBitLen
+ FieldTypes::_void_0::MinBitLen
+ FieldTypes::engine_load_percent::MinBitLen
+ FieldTypes::engine_speed_rpm::MinBitLen
+ FieldTypes::spark_dwell_time_ms::MinBitLen
+ FieldTypes::atmospheric_pressure_kpa::MinBitLen
+ FieldTypes::intake_manifold_pressure_kpa::MinBitLen
+ FieldTypes::intake_manifold_temperature::MinBitLen
+ FieldTypes::coolant_temperature::MinBitLen
+ FieldTypes::oil_pressure::MinBitLen
+ FieldTypes::oil_temperature::MinBitLen
+ FieldTypes::fuel_pressure::MinBitLen
+ FieldTypes::fuel_consumption_rate_cm3pm::MinBitLen
+ FieldTypes::estimated_consumed_fuel_volume_cm3::MinBitLen
+ FieldTypes::throttle_position_percent::MinBitLen
+ FieldTypes::ecu_index::MinBitLen
+ FieldTypes::spark_plug_usage::MinBitLen
+ FieldTypes::cylinder_status::MinBitLen
};
enum
{
MaxBitLen
= FieldTypes::state::MaxBitLen
+ FieldTypes::flags::MaxBitLen
+ FieldTypes::_void_0::MaxBitLen
+ FieldTypes::engine_load_percent::MaxBitLen
+ FieldTypes::engine_speed_rpm::MaxBitLen
+ FieldTypes::spark_dwell_time_ms::MaxBitLen
+ FieldTypes::atmospheric_pressure_kpa::MaxBitLen
+ FieldTypes::intake_manifold_pressure_kpa::MaxBitLen
+ FieldTypes::intake_manifold_temperature::MaxBitLen
+ FieldTypes::coolant_temperature::MaxBitLen
+ FieldTypes::oil_pressure::MaxBitLen
+ FieldTypes::oil_temperature::MaxBitLen
+ FieldTypes::fuel_pressure::MaxBitLen
+ FieldTypes::fuel_consumption_rate_cm3pm::MaxBitLen
+ FieldTypes::estimated_consumed_fuel_volume_cm3::MaxBitLen
+ FieldTypes::throttle_position_percent::MaxBitLen
+ FieldTypes::ecu_index::MaxBitLen
+ FieldTypes::spark_plug_usage::MaxBitLen
+ FieldTypes::cylinder_status::MaxBitLen
};
// Constants
static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_STOPPED >::Type STATE_STOPPED; // 0
static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_STARTING >::Type STATE_STARTING; // 1
static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_RUNNING >::Type STATE_RUNNING; // 2
static const typename ::uavcan::StorageType< typename ConstantTypes::STATE_FAULT >::Type STATE_FAULT; // 3
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_GENERAL_ERROR >::Type FLAG_GENERAL_ERROR; // 1
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED >::Type FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED; // 2
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR >::Type FLAG_CRANKSHAFT_SENSOR_ERROR; // 4
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_SUPPORTED >::Type FLAG_TEMPERATURE_SUPPORTED; // 8
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_BELOW_NOMINAL >::Type FLAG_TEMPERATURE_BELOW_NOMINAL; // 16
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_ABOVE_NOMINAL >::Type FLAG_TEMPERATURE_ABOVE_NOMINAL; // 32
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_OVERHEATING >::Type FLAG_TEMPERATURE_OVERHEATING; // 64
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL >::Type FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL; // 128
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_SUPPORTED >::Type FLAG_FUEL_PRESSURE_SUPPORTED; // 256
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_BELOW_NOMINAL >::Type FLAG_FUEL_PRESSURE_BELOW_NOMINAL; // 512
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL >::Type FLAG_FUEL_PRESSURE_ABOVE_NOMINAL; // 1024
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DETONATION_SUPPORTED >::Type FLAG_DETONATION_SUPPORTED; // 2048
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DETONATION_OBSERVED >::Type FLAG_DETONATION_OBSERVED; // 4096
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_MISFIRE_SUPPORTED >::Type FLAG_MISFIRE_SUPPORTED; // 8192
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_MISFIRE_OBSERVED >::Type FLAG_MISFIRE_OBSERVED; // 16384
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_SUPPORTED >::Type FLAG_OIL_PRESSURE_SUPPORTED; // 32768
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_BELOW_NOMINAL >::Type FLAG_OIL_PRESSURE_BELOW_NOMINAL; // 65536
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_OIL_PRESSURE_ABOVE_NOMINAL >::Type FLAG_OIL_PRESSURE_ABOVE_NOMINAL; // 131072
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DEBRIS_SUPPORTED >::Type FLAG_DEBRIS_SUPPORTED; // 262144
static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_DEBRIS_DETECTED >::Type FLAG_DEBRIS_DETECTED; // 524288
static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_SINGLE >::Type SPARK_PLUG_SINGLE; // 0
static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_FIRST_ACTIVE >::Type SPARK_PLUG_FIRST_ACTIVE; // 1
static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_SECOND_ACTIVE >::Type SPARK_PLUG_SECOND_ACTIVE; // 2
static const typename ::uavcan::StorageType< typename ConstantTypes::SPARK_PLUG_BOTH_ACTIVE >::Type SPARK_PLUG_BOTH_ACTIVE; // 3
// Fields
typename ::uavcan::StorageType< typename FieldTypes::state >::Type state;
typename ::uavcan::StorageType< typename FieldTypes::flags >::Type flags;
typename ::uavcan::StorageType< typename FieldTypes::engine_load_percent >::Type engine_load_percent;
typename ::uavcan::StorageType< typename FieldTypes::engine_speed_rpm >::Type engine_speed_rpm;
typename ::uavcan::StorageType< typename FieldTypes::spark_dwell_time_ms >::Type spark_dwell_time_ms;
typename ::uavcan::StorageType< typename FieldTypes::atmospheric_pressure_kpa >::Type atmospheric_pressure_kpa;
typename ::uavcan::StorageType< typename FieldTypes::intake_manifold_pressure_kpa >::Type intake_manifold_pressure_kpa;
typename ::uavcan::StorageType< typename FieldTypes::intake_manifold_temperature >::Type intake_manifold_temperature;
typename ::uavcan::StorageType< typename FieldTypes::coolant_temperature >::Type coolant_temperature;
typename ::uavcan::StorageType< typename FieldTypes::oil_pressure >::Type oil_pressure;
typename ::uavcan::StorageType< typename FieldTypes::oil_temperature >::Type oil_temperature;
typename ::uavcan::StorageType< typename FieldTypes::fuel_pressure >::Type fuel_pressure;
typename ::uavcan::StorageType< typename FieldTypes::fuel_consumption_rate_cm3pm >::Type fuel_consumption_rate_cm3pm;
typename ::uavcan::StorageType< typename FieldTypes::estimated_consumed_fuel_volume_cm3 >::Type estimated_consumed_fuel_volume_cm3;
typename ::uavcan::StorageType< typename FieldTypes::throttle_position_percent >::Type throttle_position_percent;
typename ::uavcan::StorageType< typename FieldTypes::ecu_index >::Type ecu_index;
typename ::uavcan::StorageType< typename FieldTypes::spark_plug_usage >::Type spark_plug_usage;
typename ::uavcan::StorageType< typename FieldTypes::cylinder_status >::Type cylinder_status;
Status_()
: state()
, flags()
, engine_load_percent()
, engine_speed_rpm()
, spark_dwell_time_ms()
, atmospheric_pressure_kpa()
, intake_manifold_pressure_kpa()
, intake_manifold_temperature()
, coolant_temperature()
, oil_pressure()
, oil_temperature()
, fuel_pressure()
, fuel_consumption_rate_cm3pm()
, estimated_consumed_fuel_volume_cm3()
, throttle_position_percent()
, ecu_index()
, spark_plug_usage()
, cylinder_status()
{
::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check
#if UAVCAN_DEBUG
/*
* Cross-checking MaxBitLen provided by the DSDL compiler.
* This check shall never be performed in user code because MaxBitLen value
* actually depends on the nested types, thus it is not invariant.
*/
::uavcan::StaticAssert<1565 == MaxBitLen>::check();
#endif
}
bool operator==(ParameterType rhs) const;
bool operator!=(ParameterType rhs) const { return !operator==(rhs); }
/**
* This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of
* floating point fields at any depth.
*/
bool isClose(ParameterType rhs) const;
static int encode(ParameterType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled);
static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled);
/*
* Static type info
*/
enum { DataTypeKind = ::uavcan::DataTypeKindMessage };
enum { DefaultDataTypeID = 1120 };
static const char* getDataTypeFullName()
{
return "uavcan.equipment.ice.reciprocating.Status";
}
static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature)
{
signature.extend(getDataTypeSignature());
}
static ::uavcan::DataTypeSignature getDataTypeSignature();
};
/*
* Out of line struct method definitions
*/
template <int _tmpl>
bool Status_<_tmpl>::operator==(ParameterType rhs) const
{
return
state == rhs.state &&
flags == rhs.flags &&
engine_load_percent == rhs.engine_load_percent &&
engine_speed_rpm == rhs.engine_speed_rpm &&
spark_dwell_time_ms == rhs.spark_dwell_time_ms &&
atmospheric_pressure_kpa == rhs.atmospheric_pressure_kpa &&
intake_manifold_pressure_kpa == rhs.intake_manifold_pressure_kpa &&
intake_manifold_temperature == rhs.intake_manifold_temperature &&
coolant_temperature == rhs.coolant_temperature &&
oil_pressure == rhs.oil_pressure &&
oil_temperature == rhs.oil_temperature &&
fuel_pressure == rhs.fuel_pressure &&
fuel_consumption_rate_cm3pm == rhs.fuel_consumption_rate_cm3pm &&
estimated_consumed_fuel_volume_cm3 == rhs.estimated_consumed_fuel_volume_cm3 &&
throttle_position_percent == rhs.throttle_position_percent &&
ecu_index == rhs.ecu_index &&
spark_plug_usage == rhs.spark_plug_usage &&
cylinder_status == rhs.cylinder_status;
}
template <int _tmpl>
bool Status_<_tmpl>::isClose(ParameterType rhs) const
{
return
::uavcan::areClose(state, rhs.state) &&
::uavcan::areClose(flags, rhs.flags) &&
::uavcan::areClose(engine_load_percent, rhs.engine_load_percent) &&
::uavcan::areClose(engine_speed_rpm, rhs.engine_speed_rpm) &&
::uavcan::areClose(spark_dwell_time_ms, rhs.spark_dwell_time_ms) &&
::uavcan::areClose(atmospheric_pressure_kpa, rhs.atmospheric_pressure_kpa) &&
::uavcan::areClose(intake_manifold_pressure_kpa, rhs.intake_manifold_pressure_kpa) &&
::uavcan::areClose(intake_manifold_temperature, rhs.intake_manifold_temperature) &&
::uavcan::areClose(coolant_temperature, rhs.coolant_temperature) &&
::uavcan::areClose(oil_pressure, rhs.oil_pressure) &&
::uavcan::areClose(oil_temperature, rhs.oil_temperature) &&
::uavcan::areClose(fuel_pressure, rhs.fuel_pressure) &&
::uavcan::areClose(fuel_consumption_rate_cm3pm, rhs.fuel_consumption_rate_cm3pm) &&
::uavcan::areClose(estimated_consumed_fuel_volume_cm3, rhs.estimated_consumed_fuel_volume_cm3) &&
::uavcan::areClose(throttle_position_percent, rhs.throttle_position_percent) &&
::uavcan::areClose(ecu_index, rhs.ecu_index) &&
::uavcan::areClose(spark_plug_usage, rhs.spark_plug_usage) &&
::uavcan::areClose(cylinder_status, rhs.cylinder_status);
}
template <int _tmpl>
int Status_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode)
{
(void)self;
(void)codec;
(void)tao_mode;
typename ::uavcan::StorageType< typename FieldTypes::_void_0 >::Type _void_0 = 0;
int res = 1;
res = FieldTypes::state::encode(self.state, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::flags::encode(self.flags, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::_void_0::encode(_void_0, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::engine_load_percent::encode(self.engine_load_percent, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::engine_speed_rpm::encode(self.engine_speed_rpm, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::spark_dwell_time_ms::encode(self.spark_dwell_time_ms, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::atmospheric_pressure_kpa::encode(self.atmospheric_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::intake_manifold_pressure_kpa::encode(self.intake_manifold_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::intake_manifold_temperature::encode(self.intake_manifold_temperature, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::coolant_temperature::encode(self.coolant_temperature, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::oil_pressure::encode(self.oil_pressure, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::oil_temperature::encode(self.oil_temperature, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::fuel_pressure::encode(self.fuel_pressure, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::fuel_consumption_rate_cm3pm::encode(self.fuel_consumption_rate_cm3pm, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::estimated_consumed_fuel_volume_cm3::encode(self.estimated_consumed_fuel_volume_cm3, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::throttle_position_percent::encode(self.throttle_position_percent, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::ecu_index::encode(self.ecu_index, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::spark_plug_usage::encode(self.spark_plug_usage, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::cylinder_status::encode(self.cylinder_status, codec, tao_mode);
return res;
}
template <int _tmpl>
int Status_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec,
::uavcan::TailArrayOptimizationMode tao_mode)
{
(void)self;
(void)codec;
(void)tao_mode;
typename ::uavcan::StorageType< typename FieldTypes::_void_0 >::Type _void_0 = 0;
int res = 1;
res = FieldTypes::state::decode(self.state, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::flags::decode(self.flags, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::_void_0::decode(_void_0, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::engine_load_percent::decode(self.engine_load_percent, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::engine_speed_rpm::decode(self.engine_speed_rpm, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::spark_dwell_time_ms::decode(self.spark_dwell_time_ms, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::atmospheric_pressure_kpa::decode(self.atmospheric_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::intake_manifold_pressure_kpa::decode(self.intake_manifold_pressure_kpa, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::intake_manifold_temperature::decode(self.intake_manifold_temperature, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::coolant_temperature::decode(self.coolant_temperature, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::oil_pressure::decode(self.oil_pressure, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::oil_temperature::decode(self.oil_temperature, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::fuel_pressure::decode(self.fuel_pressure, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::fuel_consumption_rate_cm3pm::decode(self.fuel_consumption_rate_cm3pm, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::estimated_consumed_fuel_volume_cm3::decode(self.estimated_consumed_fuel_volume_cm3, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::throttle_position_percent::decode(self.throttle_position_percent, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::ecu_index::decode(self.ecu_index, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::spark_plug_usage::decode(self.spark_plug_usage, codec, ::uavcan::TailArrayOptDisabled);
if (res <= 0)
{
return res;
}
res = FieldTypes::cylinder_status::decode(self.cylinder_status, codec, tao_mode);
return res;
}
/*
* Out of line type method definitions
*/
template <int _tmpl>
::uavcan::DataTypeSignature Status_<_tmpl>::getDataTypeSignature()
{
::uavcan::DataTypeSignature signature(0x5465C0CF37619F32ULL);
FieldTypes::state::extendDataTypeSignature(signature);
FieldTypes::flags::extendDataTypeSignature(signature);
FieldTypes::_void_0::extendDataTypeSignature(signature);
FieldTypes::engine_load_percent::extendDataTypeSignature(signature);
FieldTypes::engine_speed_rpm::extendDataTypeSignature(signature);
FieldTypes::spark_dwell_time_ms::extendDataTypeSignature(signature);
FieldTypes::atmospheric_pressure_kpa::extendDataTypeSignature(signature);
FieldTypes::intake_manifold_pressure_kpa::extendDataTypeSignature(signature);
FieldTypes::intake_manifold_temperature::extendDataTypeSignature(signature);
FieldTypes::coolant_temperature::extendDataTypeSignature(signature);
FieldTypes::oil_pressure::extendDataTypeSignature(signature);
FieldTypes::oil_temperature::extendDataTypeSignature(signature);
FieldTypes::fuel_pressure::extendDataTypeSignature(signature);
FieldTypes::fuel_consumption_rate_cm3pm::extendDataTypeSignature(signature);
FieldTypes::estimated_consumed_fuel_volume_cm3::extendDataTypeSignature(signature);
FieldTypes::throttle_position_percent::extendDataTypeSignature(signature);
FieldTypes::ecu_index::extendDataTypeSignature(signature);
FieldTypes::spark_plug_usage::extendDataTypeSignature(signature);
FieldTypes::cylinder_status::extendDataTypeSignature(signature);
return signature;
}
/*
* Out of line constant definitions
*/
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_STOPPED >::Type
Status_<_tmpl>::STATE_STOPPED = 0U; // 0
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_STARTING >::Type
Status_<_tmpl>::STATE_STARTING = 1U; // 1
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_RUNNING >::Type
Status_<_tmpl>::STATE_RUNNING = 2U; // 2
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::STATE_FAULT >::Type
Status_<_tmpl>::STATE_FAULT = 3U; // 3
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_GENERAL_ERROR >::Type
Status_<_tmpl>::FLAG_GENERAL_ERROR = 1U; // 1
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED >::Type
Status_<_tmpl>::FLAG_CRANKSHAFT_SENSOR_ERROR_SUPPORTED = 2U; // 2
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_CRANKSHAFT_SENSOR_ERROR >::Type
Status_<_tmpl>::FLAG_CRANKSHAFT_SENSOR_ERROR = 4U; // 4
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_SUPPORTED >::Type
Status_<_tmpl>::FLAG_TEMPERATURE_SUPPORTED = 8U; // 8
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_BELOW_NOMINAL >::Type
Status_<_tmpl>::FLAG_TEMPERATURE_BELOW_NOMINAL = 16U; // 16
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_ABOVE_NOMINAL >::Type
Status_<_tmpl>::FLAG_TEMPERATURE_ABOVE_NOMINAL = 32U; // 32
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_OVERHEATING >::Type
Status_<_tmpl>::FLAG_TEMPERATURE_OVERHEATING = 64U; // 64
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL >::Type
Status_<_tmpl>::FLAG_TEMPERATURE_EGT_ABOVE_NOMINAL = 128U; // 128
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_SUPPORTED >::Type
Status_<_tmpl>::FLAG_FUEL_PRESSURE_SUPPORTED = 256U; // 256
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_BELOW_NOMINAL >::Type
Status_<_tmpl>::FLAG_FUEL_PRESSURE_BELOW_NOMINAL = 512U; // 512
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL >::Type
Status_<_tmpl>::FLAG_FUEL_PRESSURE_ABOVE_NOMINAL = 1024U; // 1024
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DETONATION_SUPPORTED >::Type
Status_<_tmpl>::FLAG_DETONATION_SUPPORTED = 2048U; // 2048
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DETONATION_OBSERVED >::Type
Status_<_tmpl>::FLAG_DETONATION_OBSERVED = 4096U; // 4096
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_MISFIRE_SUPPORTED >::Type
Status_<_tmpl>::FLAG_MISFIRE_SUPPORTED = 8192U; // 8192
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_MISFIRE_OBSERVED >::Type
Status_<_tmpl>::FLAG_MISFIRE_OBSERVED = 16384U; // 16384
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_SUPPORTED >::Type
Status_<_tmpl>::FLAG_OIL_PRESSURE_SUPPORTED = 32768U; // 32768
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_BELOW_NOMINAL >::Type
Status_<_tmpl>::FLAG_OIL_PRESSURE_BELOW_NOMINAL = 65536U; // 65536
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_OIL_PRESSURE_ABOVE_NOMINAL >::Type
Status_<_tmpl>::FLAG_OIL_PRESSURE_ABOVE_NOMINAL = 131072U; // 131072
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DEBRIS_SUPPORTED >::Type
Status_<_tmpl>::FLAG_DEBRIS_SUPPORTED = 262144U; // 262144
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::FLAG_DEBRIS_DETECTED >::Type
Status_<_tmpl>::FLAG_DEBRIS_DETECTED = 524288U; // 524288
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_SINGLE >::Type
Status_<_tmpl>::SPARK_PLUG_SINGLE = 0U; // 0
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_FIRST_ACTIVE >::Type
Status_<_tmpl>::SPARK_PLUG_FIRST_ACTIVE = 1U; // 1
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_SECOND_ACTIVE >::Type
Status_<_tmpl>::SPARK_PLUG_SECOND_ACTIVE = 2U; // 2
template <int _tmpl>
const typename ::uavcan::StorageType< typename Status_<_tmpl>::ConstantTypes::SPARK_PLUG_BOTH_ACTIVE >::Type
Status_<_tmpl>::SPARK_PLUG_BOTH_ACTIVE = 3U; // 3
/*
* Final typedef
*/
typedef Status_<0> Status;
namespace
{
const ::uavcan::DefaultDataTypeRegistrator< ::uavcan::equipment::ice::reciprocating::Status > _uavcan_gdtr_registrator_Status;
}
} // Namespace reciprocating
} // Namespace ice
} // Namespace equipment
} // Namespace uavcan
/*
* YAML streamer specialization
*/
namespace uavcan
{
template <>
class UAVCAN_EXPORT YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status >
{
public:
template <typename Stream>
static void stream(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj, const int level);
};
template <typename Stream>
void YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status >::stream(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj, const int level)
{
(void)s;
(void)obj;
(void)level;
if (level > 0)
{
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
}
s << "state: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::state >::stream(s, obj.state, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "flags: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::flags >::stream(s, obj.flags, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "engine_load_percent: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::engine_load_percent >::stream(s, obj.engine_load_percent, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "engine_speed_rpm: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::engine_speed_rpm >::stream(s, obj.engine_speed_rpm, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "spark_dwell_time_ms: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::spark_dwell_time_ms >::stream(s, obj.spark_dwell_time_ms, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "atmospheric_pressure_kpa: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::atmospheric_pressure_kpa >::stream(s, obj.atmospheric_pressure_kpa, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "intake_manifold_pressure_kpa: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::intake_manifold_pressure_kpa >::stream(s, obj.intake_manifold_pressure_kpa, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "intake_manifold_temperature: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::intake_manifold_temperature >::stream(s, obj.intake_manifold_temperature, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "coolant_temperature: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::coolant_temperature >::stream(s, obj.coolant_temperature, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "oil_pressure: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::oil_pressure >::stream(s, obj.oil_pressure, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "oil_temperature: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::oil_temperature >::stream(s, obj.oil_temperature, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "fuel_pressure: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::fuel_pressure >::stream(s, obj.fuel_pressure, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "fuel_consumption_rate_cm3pm: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::fuel_consumption_rate_cm3pm >::stream(s, obj.fuel_consumption_rate_cm3pm, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "estimated_consumed_fuel_volume_cm3: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::estimated_consumed_fuel_volume_cm3 >::stream(s, obj.estimated_consumed_fuel_volume_cm3, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "throttle_position_percent: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::throttle_position_percent >::stream(s, obj.throttle_position_percent, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "ecu_index: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::ecu_index >::stream(s, obj.ecu_index, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "spark_plug_usage: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::spark_plug_usage >::stream(s, obj.spark_plug_usage, level + 1);
s << '\n';
for (int pos = 0; pos < level; pos++)
{
s << " ";
}
s << "cylinder_status: ";
YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status::FieldTypes::cylinder_status >::stream(s, obj.cylinder_status, level + 1);
}
}
namespace uavcan
{
namespace equipment
{
namespace ice
{
namespace reciprocating
{
template <typename Stream>
inline Stream& operator<<(Stream& s, ::uavcan::equipment::ice::reciprocating::Status::ParameterType obj)
{
::uavcan::YamlStreamer< ::uavcan::equipment::ice::reciprocating::Status >::stream(s, obj, 0);
return s;
}
} // Namespace reciprocating
} // Namespace ice
} // Namespace equipment
} // Namespace uavcan
#endif // UAVCAN_EQUIPMENT_ICE_RECIPROCATING_STATUS_HPP_INCLUDED | 41.980392 | 178 | 0.715999 | bolderflight |
db87898b216bae3122a2f3d54dd64e72f4558416 | 2,738 | cpp | C++ | Scripts/PlayerMovement/BombDropSkill.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 10 | 2019-02-25T11:36:23.000Z | 2021-11-03T22:51:30.000Z | Scripts/PlayerMovement/BombDropSkill.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 146 | 2019-02-05T13:57:33.000Z | 2019-11-07T16:21:31.000Z | Scripts/PlayerMovement/BombDropSkill.cpp | FractalPuppy/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 3 | 2019-11-17T20:49:12.000Z | 2020-04-19T17:28:28.000Z | #include "BombDropSkill.h"
#include "PlayerMovement.h"
#include "Application.h"
#include "ModuleNavigation.h"
#include "ModuleTime.h"
#include "GameObject.h"
#include "ComponentTransform.h"
#include "ComponentBoxTrigger.h"
#include "PlayerState.h"
BombDropSkill::BombDropSkill(PlayerMovement* PM, const char* trigger, ComponentBoxTrigger* attackBox) :
MeleeSkill(PM, trigger, attackBox)
{
}
BombDropSkill::~BombDropSkill()
{
path.clear();
}
void BombDropSkill::Start()
{
MeleeSkill::Start();
player->App->navigation->setPlayerBB(player->gameobject->bbox);
if (player->App->navigation->NavigateTowardsCursor(player->gameobject->transform->position, path,
math::float3(player->OutOfMeshCorrectionXZ, player->OutOfMeshCorrectionY, player->OutOfMeshCorrectionXZ),
intersectionPoint, bombDropMaxDistance, PathFindType::NODODGE))
{
pathIndex = 0;
player->gameobject->transform->LookAt(intersectionPoint);
if (bombDropFX)
{
bombDropFX->SetActive(true);
}
player->ResetCooldown(HUD_BUTTON_E);
}
//Create the hitbox
boxSize = math::float3(250.f, 100.f, 250.f);
//attackBoxTrigger.set
// Set delay for hit
hitDelay = 0.5f;
}
void BombDropSkill::UseSkill()
{
if (path.size() > 0 && timer > bombDropPreparationTime && timer < hitDelay)
{
math::float3 currentPosition = player->gameobject->transform->GetPosition();
while (pathIndex < path.size() && currentPosition.DistanceSq(path[pathIndex]) < MINIMUM_PATH_DISTANCE)
{
pathIndex++;
}
if (pathIndex < path.size())
{
player->gameobject->transform->LookAt(path[pathIndex]);
math::float3 direction = (path[pathIndex] - currentPosition).Normalized();
player->gameobject->transform->SetPosition(currentPosition + bombDropSpeed * direction * player->App->time->fullGameDeltaTime);
}
}
if (player->attackBoxTrigger != nullptr && !player->attackBoxTrigger->enabled)
{
// Update hitbox
boxPosition = player->transform->up * 100.f; //this front stuff isnt working well when rotating the chicken
player->attackBoxTrigger->SetBoxPosition(boxPosition.x, boxPosition.y, boxPosition.z + 200.f);
}
}
void BombDropSkill::CheckInput()
{
if (timer > player->currentState->duration) //CAN SWITCH?
{
if (player->IsUsingSkill())
{
player->currentState = (PlayerState*)player->attack;
}
else if (player->IsMovingToAttack())
{
if (player->ThirdStageBoss)
{
player->currentState = (PlayerState*)player->walkToHit3rdBoss;
}
else
{
player->currentState = (PlayerState*)player->walkToHit;
}
}
else if (player->IsMovingToItem())
{
player->currentState = (PlayerState*)player->walkToPickItem;
}
else if (player->IsMoving())
{
player->currentState = (PlayerState*)player->walk;
}
}
}
| 25.351852 | 130 | 0.716216 | solidajenjo |
db9471268d8a19e81c2756bee36f02aab74bd2a0 | 1,391 | cpp | C++ | src/Engine/Thread.cpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 127 | 2018-12-09T18:40:02.000Z | 2022-03-06T00:10:07.000Z | src/Engine/Thread.cpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 267 | 2019-02-26T22:16:48.000Z | 2022-02-09T09:49:22.000Z | src/Engine/Thread.cpp | scemino/engge | 3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f | [
"MIT"
] | 17 | 2019-02-26T20:45:34.000Z | 2021-06-17T15:06:26.000Z | #include <squirrel.h>
#include "engge/System/Locator.hpp"
#include "engge/Engine/EntityManager.hpp"
#include "engge/Engine/Thread.hpp"
#include <utility>
namespace ng {
Thread::Thread(std::string name, bool isGlobal,
HSQUIRRELVM v,
HSQOBJECT thread_obj,
HSQOBJECT env_obj,
HSQOBJECT closureObj,
std::vector<HSQOBJECT> args)
: m_name(std::move(name)), m_v(v), m_threadObj(thread_obj), m_envObj(env_obj), m_closureObj(closureObj), m_args(std::move(args)),
m_isGlobal(isGlobal) {
sq_addref(m_v, &m_threadObj);
sq_addref(m_v, &m_envObj);
sq_addref(m_v, &m_closureObj);
m_id = Locator<EntityManager>::get().getThreadId();
}
Thread::~Thread() {
sq_release(m_v, &m_threadObj);
sq_release(m_v, &m_envObj);
sq_release(m_v, &m_closureObj);
}
std::string Thread::getName() const {
return m_name;
}
HSQUIRRELVM Thread::getThread() const { return m_threadObj._unVal.pThread; }
bool Thread::call() {
auto thread = getThread();
// call the closure in the thread
SQInteger top = sq_gettop(thread);
sq_pushobject(thread, m_closureObj);
sq_pushobject(thread, m_envObj);
for (auto arg : m_args) {
sq_pushobject(thread, arg);
}
if (SQ_FAILED(sq_call(thread, 1 + m_args.size(), SQFalse, SQTrue))) {
sq_settop(thread, top);
return false;
}
return true;
}
} // namespace ng
| 26.75 | 133 | 0.672178 | scemino |
db957aeb96208737a0f832c61bb9b7c15ee33b44 | 11,669 | cpp | C++ | externals/browser/externals/browser/browser/src/vts-libbrowser/camera/altitude.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2021-09-02T08:42:59.000Z | 2021-09-02T08:42:59.000Z | externals/browser/externals/browser/browser/src/vts-libbrowser/camera/altitude.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | null | null | null | externals/browser/externals/browser/browser/src/vts-libbrowser/camera/altitude.cpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (c) 2017 Melown Technologies SE
*
* 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.
*
* 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.
*/
#include "../camera.hpp"
#include "../navigation.hpp"
#include "../traverseNode.hpp"
#include "../coordsManip.hpp"
#include "../mapLayer.hpp"
#include "../mapConfig.hpp"
#include "../map.hpp"
#include "../gpuResource.hpp"
#include "../renderTasks.hpp"
#include <optick.h>
namespace vts
{
using vtslibs::vts::NodeInfo;
namespace
{
double cross(const vec2 &a, const vec2 &b)
{
return a[0] * b[1] - a[1] * b[0];
}
double sign(double a)
{
return a < 0 ? -1 : 1;
}
double lineSolver(const vec2 &p,
const vec2 &a, const vec2 &b,
double av, double bv)
{
vec2 v1 = b - a;
if (dot(v1, v1) < 1e-4)
return av; // degenerated into a point
vec2 v2 = p - a;
double l1 = length(v1);
double l2 = length(v2);
double u = l2 / l1 * sign(dot(v2, v1));
return interpolate(av, bv, u);
}
double triangleSolver(const vec2 &p,
const vec2 &a, const vec2 &b, const vec2 &c,
double av, double bv, double cv)
{
vec2 v0 = b - a;
vec2 v1 = c - a;
vec2 v2 = p - a;
double d00 = dot(v0, v0);
double d01 = dot(v0, v1);
double d11 = dot(v1, v1);
double d20 = dot(v2, v0);
double d21 = dot(v2, v1);
{
// detect degenerated cases (lines)
if (d00 < 1e-4)
return lineSolver(p, a, c, av, cv);
if (d11 < 1e-4)
return lineSolver(p, a, b, av, bv);
vec2 v3 = c - b;
double d33 = dot(v3, v3);
if (d33 < 1e-4)
return lineSolver(p, a, b, av, bv);
}
double invDenom = 1.0 / (d00 * d11 - d01 * d01);
double v = (d11 * d20 - d01 * d21) * invDenom;
double w = (d00 * d21 - d01 * d20) * invDenom;
double u = 1 - v - w;
return u * av + v * bv + w * cv;
}
double bilinearInterpolation(double u, double v,
double av, double bv, double cv, double dv)
{
assert(u >= 0 && u <= 1 && v >= 0 && v <= 1);
double p = interpolate(av, bv, u);
double q = interpolate(cv, dv, u);
return interpolate(p, q, v);
}
double quadrilateralSolver(const vec2 &p,
const vec2 &a, const vec2 &b, const vec2 &c, const vec2 &d,
double av, double bv, double cv, double dv)
{
const vec2 e = b - a;
const vec2 f = c - a;
{
// detect degenerated cases (triangles)
vec2 q3 = b - d;
vec2 q4 = c - d;
if (dot(e, e) < 1e-4)
return triangleSolver(p, a, c, d, av, cv, dv);
if (dot(f, f) < 1e-4)
return triangleSolver(p, a, b, d, av, bv, dv);
if (dot(q3, q3) < 1e-4)
return triangleSolver(p, a, b, c, av, bv, cv);
if (dot(q4, q4) < 1e-4)
return triangleSolver(p, a, b, c, av, bv, cv);
}
vec2 g = a - b + d - c;
vec2 h = p - a;
double k2 = cross(g, f);
if (std::abs(k2) < 1e-7)
{
// rectangle
double u = h[0] / e[0];
double v = h[1] / f[1];
if (v >= 0 && v <= 1 && u >= 0 && u <= 1)
return bilinearInterpolation(u, v, av, bv, cv, dv);
return nan1(); // the query is outside the quadrilateral
}
double k0 = cross(h, e);
double k1 = cross(e, f) + cross(h, g);
double w = k1 * k1 - 4 * k0 * k2;
if (w < 0)
return nan1(); // the quadrilateral has negative area
w = sqrt(w);
double v1 = (-k1 - w) / (2 * k2);
double u1 = (h[0] - f[0] * v1) / (e[0] + g[0] * v1);
double v2 = (-k1 + w) / (2 * k2);
double u2 = (h[0] - f[0] * v2) / (e[0] + g[0] * v2);
if (v1 >= 0 && v1 <= 1 && u1 >= 0 && u1 <= 1)
return bilinearInterpolation(u1, v1, av, bv, cv, dv);
if (v2 >= 0 && v2 <= 1 && u2 >= 0 && u2 <= 1)
return bilinearInterpolation(u2, v2, av, bv, cv, dv);
return nan1(); // the query is outside the quadrilateral
}
double altitudeInterpolation(
const vec2 &query,
const vec2 points[4],
double values[4])
{
return quadrilateralSolver(query,
points[0], points[1], points[2], points[3],
values[0], values[1], values[2], values[3]
);
}
TraverseNode *findTravSds(CameraImpl *camera, TraverseNode *where,
const vec2 &pointSds, uint32 maxLod)
{
assert(where && where->meta);
if (where->id.lod >= maxLod)
return where;
math::Point2 ublasSds = vecToUblas<math::Point2>(pointSds);
for (auto &ci : where->childs)
{
// avoid computing new extents if we already have them
if (ci.meta)
{
if (!math::inside(ci.meta->extents, ublasSds))
continue;
}
else
{
const Extents2 ce = subExtents(
where->meta->extents, where->id, ci.id);
if (!math::inside(ce, ublasSds))
continue;
}
if (!camera->travInit(&ci))
continue;
return findTravSds(camera, &ci, pointSds, maxLod);
}
return where;
}
} // namespace
bool CameraImpl::getSurfaceOverEllipsoid(
double &result, const vec3 &navPos,
double sampleSize, bool renderDebug)
{
OPTICK_EVENT();
assert(map->convertor);
assert(!map->layers.empty());
//std::string s = map->layers.empty() ? "true" : "false";
//LOG(info3) << "map" << std::endl;
//LOG(info3) << map << std::endl;
//LOG(info3) << "map layers 0" << std::endl;
//// LOG(info3) << map->layers << std::endl;
//LOG(info3) << "map->layers.empty() : " << s;
//LOG(info3) << map->layers[0] << std::endl;
//LOG(info3) << "map layers 0 traverseRoot" << std::endl;
//LOG(info3) << map->layers[0]->traverseRoot << std::endl;
//LOG(info3) << "map end" << std::endl;
//if (map->layers[0] == nullptr) {
// return false;
//}
//---------------------------------------crash region --------------------------------------
TraverseNode *root = map->layers[0]->traverseRoot.get();
//-------------------------------------------------------------------------------------------
if (!root || !root->meta)
return false;
if (sampleSize <= 0)
sampleSize = getSurfaceAltitudeSamples();
// find surface division coordinates (and appropriate node info)
vec2 sds;
boost::optional<NodeInfo> info;
uint32 index = 0;
for (const auto &it : map->mapconfig->referenceFrame.division.nodes)
{
struct I {
uint32 &i; I(uint32 &i) : i(i) {} ~I() { ++i; }
} inc(index);
if (it.second.partitioning.mode
!= vtslibs::registry::PartitioningMode::bisection)
continue;
const NodeInfo &ni
= map->mapconfig->referenceDivisionNodeInfos[index];
try
{
sds = vec3to2(map->convertor->convert(navPos,
Srs::Navigation, it.second.srs));
if (!ni.inside(vecToUblas<math::Point2>(sds)))
continue;
info = ni;
break;
}
catch(const std::exception &)
{
// do nothing
}
}
if (!info)
return false;
// desired lod
uint32 desiredLod = std::max(0.0,
-std::log2(sampleSize / info->extents().size()));
// find corner positions
vec2 points[4];
{
NodeInfo i = *info;
while (i.nodeId().lod < desiredLod)
{
for (auto j : vtslibs::vts::children(i.nodeId()))
{
NodeInfo k = i.child(j);
if (!k.inside(vecToUblas<math::Point2>(sds)))
continue;
i = k;
break;
}
}
math::Extents2 ext = i.extents();
vec2 center = vecFromUblas<vec2>(ext.ll + ext.ur) * 0.5;
vec2 size = vecFromUblas<vec2>(ext.ur - ext.ll);
vec2 p = sds;
if (sds(0) < center(0))
p(0) -= size(0);
if (sds(1) < center(1))
p(1) -= size(1);
points[0] = p;
points[1] = p + vec2(size(0), 0);
points[2] = p + vec2(0, size(1));
points[3] = p + size;
// todo periodicity
}
// find the actual corners
TraverseNode *travRoot = findTravById(root, info->nodeId());
if (!travRoot || !travRoot->meta)
return false;
double altitudes[4];
const TraverseNode *nodes[4];
for (int i = 0; i < 4; i++)
{
auto t = findTravSds(this, travRoot, points[i], desiredLod);
if (!t)
return false;
if (!t->meta->surrogateNav)
return false;
const math::Extents2 &ext = t->meta->extents;
points[i] = vecFromUblas<vec2>(ext.ll + ext.ur) * 0.5;
altitudes[i] = *t->meta->surrogateNav;
nodes[i] = t;
}
// interpolate
double res = altitudeInterpolation(sds, points, altitudes);
// debug visualization
if (renderDebug)
{
RenderInfographicsTask task;
task.mesh = map->getMesh("internal://data/meshes/sphere.obj");
task.mesh->priority = inf1();
if (*task.mesh)
{
float c = std::isnan(res) ? 0.0 : 1.0;
task.color = vec4f(c, c, c, 0.7f);
double scaleSum = 0;
for (int i = 0; i < 4; i++)
{
const TraverseNode *t = nodes[i];
double scale = t->meta->extents.size() * 0.035;
task.model = translationMatrix(*t->meta->surrogatePhys)
* scaleMatrix(scale);
draws.infographics.push_back(convert(task));
scaleSum += scale;
}
if (!std::isnan(res))
{
vec3 p = navPos;
p[2] = res;
p = map->convertor->convert(p,
Srs::Navigation, Srs::Physical);
task.model = translationMatrix(p)
* scaleMatrix(scaleSum / 4);
task.color = vec4f(c, c, c, 1.f);
draws.infographics.push_back(convert(task));
}
}
}
// output
if (std::isnan(res))
return false;
result = res;
return true;
}
double CameraImpl::getSurfaceAltitudeSamples()
{
double targetDistance = length(vec3(target - eye));
double viewExtent = targetDistance / (apiProj(1, 1) * 0.5);
double result = viewExtent / options.samplesForAltitudeLodSelection;
if (std::isnan(result))
return 10;
return result;
}
} // namespace vts
| 31.034574 | 97 | 0.537921 | HanochZhu |
db9683b9927669a1c501318a673a228da87a6576 | 5,411 | cpp | C++ | src/internal/ResumeCache.cpp | benjchristensen/rsocket-cpp | 26299669be5c9df67d11fa105deb5f453436803d | [
"BSD-3-Clause"
] | null | null | null | src/internal/ResumeCache.cpp | benjchristensen/rsocket-cpp | 26299669be5c9df67d11fa105deb5f453436803d | [
"BSD-3-Clause"
] | null | null | null | src/internal/ResumeCache.cpp | benjchristensen/rsocket-cpp | 26299669be5c9df67d11fa105deb5f453436803d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2004-present Facebook. All Rights Reserved.
#include "ResumeCache.h"
#include <algorithm>
#include "src/framing/Frame.h"
#include "src/framing/FrameTransport.h"
#include "src/statemachine/RSocketStateMachine.h"
namespace {
using rsocket::FrameType;
bool shouldTrackFrame(const FrameType frameType) {
switch (frameType) {
case FrameType::REQUEST_CHANNEL:
case FrameType::REQUEST_STREAM:
case FrameType::REQUEST_RESPONSE:
case FrameType::REQUEST_FNF:
case FrameType::REQUEST_N:
case FrameType::CANCEL:
case FrameType::ERROR:
case FrameType::PAYLOAD:
return true;
case FrameType::RESERVED:
case FrameType::SETUP:
case FrameType::LEASE:
case FrameType::KEEPALIVE:
case FrameType::METADATA_PUSH:
case FrameType::RESUME:
case FrameType::RESUME_OK:
case FrameType::EXT:
default:
return false;
}
}
} // anonymous
namespace rsocket {
ResumeCache::~ResumeCache() {
clearFrames(position_);
}
void ResumeCache::trackReceivedFrame(
const folly::IOBuf& serializedFrame,
const FrameType frameType,
const StreamId streamId) {
onStreamOpen(streamId, frameType);
if (shouldTrackFrame(frameType)) {
VLOG(6) << "received frame " << frameType;
// TODO(tmont): this could be expensive, find a better way to get length
impliedPosition_ += serializedFrame.computeChainDataLength();
}
}
void ResumeCache::trackSentFrame(
const folly::IOBuf& serializedFrame,
const FrameType frameType,
const folly::Optional<StreamId> streamIdPtr) {
if (streamIdPtr) {
const StreamId streamId = *streamIdPtr;
onStreamOpen(streamId, frameType);
}
if (shouldTrackFrame(frameType)) {
// TODO(tmont): this could be expensive, find a better way to get length
auto frameDataLength = serializedFrame.computeChainDataLength();
// if the frame is too huge, we don't cache it
if (frameDataLength > capacity_) {
resetUpToPosition(position_);
position_ += frameDataLength;
DCHECK(size_ == 0);
return;
}
addFrame(serializedFrame, frameDataLength);
position_ += frameDataLength;
}
}
void ResumeCache::resetUpToPosition(ResumePosition position) {
if (position <= resetPosition_) {
return;
}
if (position > position_) {
position = position_;
}
clearFrames(position);
resetPosition_ = position;
DCHECK(frames_.empty() || frames_.front().first == resetPosition_);
}
bool ResumeCache::isPositionAvailable(ResumePosition position) const {
return (position_ == position) ||
std::binary_search(
frames_.begin(),
frames_.end(),
std::make_pair(position, std::unique_ptr<folly::IOBuf>()),
[](decltype(frames_.back()) pairA,
decltype(frames_.back()) pairB) {
return pairA.first < pairB.first;
});
}
void ResumeCache::addFrame(const folly::IOBuf& frame, size_t frameDataLength) {
size_ += frameDataLength;
while (size_ > capacity_) {
evictFrame();
}
frames_.emplace_back(position_, frame.clone());
stats_->resumeBufferChanged(1, static_cast<int>(frameDataLength));
}
void ResumeCache::evictFrame() {
DCHECK(!frames_.empty());
auto position =
frames_.size() > 1 ? std::next(frames_.begin())->first : position_;
resetUpToPosition(position);
}
void ResumeCache::clearFrames(ResumePosition position) {
if (frames_.empty()) {
return;
}
DCHECK(position <= position_);
DCHECK(position >= resetPosition_);
auto end = std::lower_bound(
frames_.begin(),
frames_.end(),
position,
[](decltype(frames_.back()) pair, ResumePosition pos) {
return pair.first < pos;
});
DCHECK(end == frames_.end() || end->first >= resetPosition_);
auto pos = end == frames_.end() ? position : end->first;
stats_->resumeBufferChanged(
-static_cast<int>(std::distance(frames_.begin(), end)),
-static_cast<int>(pos - resetPosition_));
frames_.erase(frames_.begin(), end);
size_ -= static_cast<decltype(size_)>(pos - resetPosition_);
}
void ResumeCache::sendFramesFromPosition(
ResumePosition position,
FrameTransport& frameTransport) const {
DCHECK(isPositionAvailable(position));
if (position == position_) {
// idle resumption
return;
}
auto found = std::lower_bound(
frames_.begin(),
frames_.end(),
position,
[](decltype(frames_.back()) pair, ResumePosition pos) {
return pair.first < pos;
});
DCHECK(found != frames_.end());
DCHECK(found->first == position);
while (found != frames_.end()) {
frameTransport.outputFrameOrEnqueue(found->second->clone());
found++;
}
}
void ResumeCache::onStreamClosed(StreamId streamId) {
// This is crude. We could try to preserve the stream type in
// RSocketStateMachine and pass it down explicitly here.
activeRequestStreams_.erase(streamId);
activeRequestChannels_.erase(streamId);
activeRequestResponses_.erase(streamId);
}
void ResumeCache::onStreamOpen(StreamId streamId, FrameType frameType) {
if (frameType == FrameType::REQUEST_STREAM) {
activeRequestStreams_.insert(streamId);
} else if (frameType == FrameType::REQUEST_CHANNEL) {
activeRequestChannels_.insert(streamId);
} else if (frameType == FrameType::REQUEST_RESPONSE) {
activeRequestResponses_.insert(streamId);
}
}
} // reactivesocket
| 27.190955 | 79 | 0.685825 | benjchristensen |
db9768afc836e12b07b38ecbbd7ab34cc3d2d96c | 1,865 | cpp | C++ | evolve4src/src/evolve/evolveDoc.cpp | ilyar/Evolve | f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88 | [
"EFL-2.0"
] | null | null | null | evolve4src/src/evolve/evolveDoc.cpp | ilyar/Evolve | f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88 | [
"EFL-2.0"
] | null | null | null | evolve4src/src/evolve/evolveDoc.cpp | ilyar/Evolve | f1aa89ea71fcf8be3ff6eb9ca1d57afd41cc7d88 | [
"EFL-2.0"
] | null | null | null | // evolveDoc.cpp : implementation of the CevolveDoc class
//
#include "stdafx.h"
#include "evolve.h"
#include "evolveDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CevolveDoc
IMPLEMENT_DYNCREATE(CevolveDoc, CDocument)
BEGIN_MESSAGE_MAP(CevolveDoc, CDocument)
END_MESSAGE_MAP()
// CevolveDoc construction/destruction
CevolveDoc::CevolveDoc()
{
universe = NULL;
}
CevolveDoc::~CevolveDoc()
{
if( universe != NULL ) {
Universe_Delete(universe);
universe = NULL;
}
}
BOOL CevolveDoc::OnNewDocument()
{
UNIVERSE *u;
CevolveApp *app;
char errbuf[1000];
NewUniverseOptions *nuo;
if( ! CDocument::OnNewDocument() )
return FALSE;
app = (CevolveApp *) AfxGetApp();
nuo = app->GetNewUniverseOptions();
u = CreateUniverse(nuo, errbuf);
if( u == NULL ) {
AfxMessageBox(errbuf, MB_OK, 0);
return false;
}
SetModifiedFlag(true);
universe = u;
return true;
}
void CevolveDoc::Serialize(CArchive& ar)
{
//
// do nothing as we have arn't using seriaize mechanism
//
return;
}
void CevolveDoc::DeleteContents()
{
if( universe != NULL ) {
Universe_Delete(universe);
universe = NULL;
}
}
BOOL CevolveDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
char errbuf[1000];
UNIVERSE *u;
u = LoadUniverse(lpszPathName, errbuf);
if( u == NULL ) {
AfxMessageBox(errbuf, MB_OK, 0);
universe = NULL;
return false;
}
universe = u;
return true;
}
BOOL CevolveDoc::OnSaveDocument(LPCTSTR lpszPathName)
{
int n;
char errbuf[1000];
n = StoreUniverse(lpszPathName, universe, errbuf);
if( n == 0 ) {
AfxMessageBox(errbuf, MB_OK, 0);
return false;
}
SetModifiedFlag(false);
return true;
}
// CevolveDoc diagnostics
#ifdef _DEBUG
void CevolveDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CevolveDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
// CevolveDoc commands
| 14.236641 | 57 | 0.69866 | ilyar |
db9ca8666ef286a6ed1d50a8ef88bcbb61e3454f | 17,155 | cpp | C++ | src/Mustl/MustlWebLink.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 9 | 2020-11-02T17:20:40.000Z | 2021-12-25T15:35:36.000Z | src/Mustl/MustlWebLink.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 2 | 2020-06-27T23:14:13.000Z | 2020-11-02T17:28:32.000Z | src/Mustl/MustlWebLink.cpp | mushware/adanaxis-core-app | 679ac3e8a122e059bb208e84c73efc19753e87dd | [
"MIT"
] | 1 | 2021-05-12T23:05:42.000Z | 2021-05-12T23:05:42.000Z | //%Header {
/*****************************************************************************
*
* File: src/Mustl/MustlWebLink.cpp
*
* Copyright: Andy Southgate 2002-2007, 2020
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
****************************************************************************/
//%Header } ol7C6mm/6AFh/4txRC+jvA
/*
* $Id: MustlWebLink.cpp,v 1.30 2006/06/29 10:12:36 southa Exp $
* $Log: MustlWebLink.cpp,v $
* Revision 1.30 2006/06/29 10:12:36 southa
* 64 bit compatibility fixes
*
* Revision 1.29 2006/06/01 15:39:55 southa
* DrawArray verification and fixes
*
* Revision 1.28 2005/05/19 13:02:20 southa
* Mac release work
*
* Revision 1.27 2004/09/26 21:07:16 southa
* Mustl compilation fixes
*
* Revision 1.26 2004/01/02 21:13:16 southa
* Source conditioning
*
* Revision 1.25 2004/01/01 21:15:46 southa
* Created XCode project
*
* Revision 1.24 2003/10/06 22:23:45 southa
* Game to GameMustl move
*
* Revision 1.23 2003/09/17 19:40:38 southa
* Source conditioning upgrades
*
* Revision 1.22 2003/08/21 23:09:32 southa
* Fixed file headers
*
* Revision 1.21 2003/01/20 10:45:31 southa
* Singleton tidying
*
* Revision 1.20 2003/01/18 13:34:00 southa
* Created MushcoreSingleton
*
* Revision 1.19 2003/01/17 13:30:41 southa
* Source conditioning and build fixes
*
* Revision 1.18 2003/01/17 12:20:41 southa
* Fixed auto_ptr duplication
*
* Revision 1.17 2003/01/16 15:58:02 southa
* Mustl exception handling
*
* Revision 1.16 2003/01/16 12:03:55 southa
* Platform and invalid socket fixes
*
* Revision 1.15 2003/01/14 20:46:12 southa
* Post data handling
*
* Revision 1.14 2003/01/14 17:38:22 southa
* Mustl web configuration
*
* Revision 1.13 2003/01/13 23:05:22 southa
* Mustl test application
*
* Revision 1.12 2003/01/13 16:50:50 southa
* win32 support
*
* Revision 1.11 2003/01/13 15:01:20 southa
* Fix Mustl command line build
*
* Revision 1.10 2003/01/12 17:33:01 southa
* Mushcore work
*
* Revision 1.9 2003/01/11 17:58:15 southa
* Mustl fixes
*
* Revision 1.8 2003/01/09 14:57:08 southa
* Created Mushcore
*
* Revision 1.7 2003/01/07 17:13:45 southa
* Fixes for gcc 3.1
*
* Revision 1.6 2002/12/29 21:00:00 southa
* More build fixes
*
* Revision 1.5 2002/12/29 20:30:57 southa
* Work for gcc 3.1 build
*
* Revision 1.4 2002/12/20 13:17:46 southa
* Namespace changes, licence changes and source conditioning
*
* Revision 1.3 2002/12/17 12:53:34 southa
* Mustl library
*
* Revision 1.2 2002/12/12 18:38:25 southa
* Mustl separation
*
* Revision 1.14 2002/11/23 14:39:06 southa
* Store ports in network order
*
* Revision 1.13 2002/11/22 11:42:07 southa
* Added developer controls
*
* Revision 1.12 2002/11/18 14:11:04 southa
* win32 support
*
* Revision 1.11 2002/11/15 11:47:56 southa
* Web processing and error handling
*
* Revision 1.10 2002/11/14 11:40:28 southa
* Configuration handling
*
* Revision 1.9 2002/11/12 18:02:13 southa
* POST handling and handlepostvalues command
*
* Revision 1.8 2002/11/12 17:05:01 southa
* Tidied localweb server
*
* Revision 1.7 2002/11/12 11:49:22 southa
* Initial MHTML processing
*
* Revision 1.6 2002/11/08 11:54:40 southa
* Web fixes
*
* Revision 1.5 2002/11/08 11:29:24 southa
* Web fixes and debug
*
* Revision 1.4 2002/11/08 00:15:31 southa
* Fixed errors
*
* Revision 1.3 2002/11/07 00:53:37 southa
* localweb work
*
* Revision 1.2 2002/11/06 14:16:57 southa
* Basic web server
*
* Revision 1.1 2002/11/05 18:15:17 southa
* Web server
*
*/
#include "MustlWebLink.h"
#include "Mustl.h"
#include "MustlHTTP.h"
#include "MustlPlatform.h"
#include "MustlSTL.h"
#include "MustlMushcore.h"
using namespace Mustl;
using namespace std;
MUSHCORE_DATA_INSTANCE(MustlWebLink);
string MustlWebLink::m_webPath="";
MustlWebLink::MustlWebLink(tSocket inSocket) :
m_receiveState(kReceiveInitial),
m_tcpSocket(MustlPlatform::InvalidSocketValueGet()),
m_linkErrors(0),
m_isDead(false)
{
// I am the server end of the link
try
{
m_tcpSocket = inSocket;
MustlPlatform::SocketNonBlockingSet(m_tcpSocket);
}
catch (...)
{
MustlPlatform::SocketClose(inSocket);
throw;
}
m_linkState=kLinkStateNew;
m_currentMsec = MustlTimer::Sgl().CurrentMsecGet();
m_creationMsec=m_currentMsec;
m_lastAccessMsec=m_currentMsec; // Not used
}
MustlWebLink::~MustlWebLink()
{
MustlLog::Sgl().WebLog() << "Closing web link" << endl;
try
{
Disconnect();
}
catch (exception& e)
{
MustlLog::Sgl().WebLog() << "~MustlWebLink exception: " << e.what() << endl;
}
}
void
MustlWebLink::Disconnect(void)
{
if (m_tcpSocket != MustlPlatform::InvalidSocketValueGet())
{
MustlPlatform::SocketClose(m_tcpSocket);
m_tcpSocket=MustlPlatform::InvalidSocketValueGet();
}
m_isDead = true;
}
void
MustlWebLink::Tick(void)
{
m_currentMsec = MustlTimer::Sgl().CurrentMsecGet();
}
bool
MustlWebLink::IsDead(void)
{
m_currentMsec = MustlTimer::Sgl().CurrentMsecGet();
if (m_isDead ||
m_currentMsec > m_creationMsec + kLinkLifetime ||
m_linkErrors > kErrorLimit)
{
return true;
}
return false;
}
bool
MustlWebLink::Receive(string& outStr)
{
if (m_isDead) return false;
U8 byte='-';
int result;
outStr="";
do
{
try
{
result=MustlPlatform::TCPReceive(m_tcpSocket, &byte, 1);
}
catch (MustlPermanentFail &e)
{
(void) e;
Disconnect();
throw;
}
catch (MustlTemporaryFail &e)
{
(void) e;
++m_linkErrors;
throw;
}
if (result == 1)
{
outStr += byte;
if (byte == 0xa) break;
}
} while (result > 0);
// MustlLog::Sgl().WebLog() << "Received " << MustlUtils::MakePrintable(outStr) << endl;
return (outStr.size() != 0);
}
void
MustlWebLink::Send(MustlData& ioData)
{
if (m_isDead)
{
throw(MustlFail("Attempt to send on dead WebLink"));
}
try
{
U32 sendSize = ioData.ReadSizeGet();
MustlPlatform::TCPSend(m_tcpSocket, ioData.ReadPtrGet(), sendSize);
ioData.ReadPosAdd(sendSize);
}
catch (MustlPermanentFail &e)
{
(void) e;
Disconnect();
throw;
}
catch (MustlTemporaryFail &e)
{
(void) e;
++m_linkErrors;
throw;
}
// MustlLog::Sgl().WebLog() << "Sending " << ioData << endl;
}
void
MustlWebLink::Send(const string& inStr)
{
MustlData netData;;
netData.Write(inStr);
Send(netData);
}
void
MustlWebLink::Send(istream& ioStream)
{
MustlData netData;
while (ioStream.good() && !ioStream.eof())
{
netData.PrepareForWrite();
ioStream.read(reinterpret_cast<char *>(netData.WritePtrGet()), netData.WriteSizeGet());
U32 length=ioStream.gcount();
netData.WritePosAdd(length);
if (length == 0) break;
}
Send(netData);
}
void
MustlWebLink::ReceivedProcess(const string& inStr)
{
switch (m_receiveState)
{
case kReceiveInitial:
{
if (inStr.substr(0,3) == "GET")
{
m_requestLine = inStr;
m_requestType = kRequestGet;
}
else if (inStr.substr(0,4) == "POST")
{
m_requestLine = inStr;
m_requestType = kRequestPost;
}
}
m_receiveState = kReceiveHeaders;
break;
case kReceiveHeaders:
{
bool lineEnd=false;
if (inStr.size() > 0 &&
(inStr[0] == 0xd || inStr[0] == 0xa))
{
lineEnd=true;
}
switch (m_requestType)
{
case kRequestGet:
if (lineEnd)
{
GetProcess(m_requestLine.substr(4));
m_receiveState = kReceiveInitial;
}
break;
case kRequestPost:
if (lineEnd)
{
m_receiveState = kReceiveBody;
}
break;
default:
SendErrorPage("Unrecognised request");
break;
}
}
break;
case kReceiveBody:
{
switch (m_requestType)
{
case kRequestGet:
throw(MustlFail("Bad receive state for GET"));
break;
case kRequestPost:
PostProcess(inStr);
GetProcess(m_requestLine.substr(5));
break;
default:
SendErrorPage("Unrecognised request");
break;
}
}
break;
default:
throw(MustlFail("Bad value for m_receiveState"));
break;
}
}
void
MustlWebLink::GetProcess(const string& inFilename)
{
string localFilename;
U32 dotCount=0;
U32 slashCount=0;
MustlLog::Sgl().WebLog() << "Serving fetch request for " << MustlUtils::MakePrintable(inFilename) << endl;
try
{
for (U32 i=0; i<inFilename.size(); ++i)
{
U8 byte=inFilename[i];
if (byte == '.')
{
if (dotCount > 0)
{
throw(MustlFail("Bad filename (dots)"));
}
++dotCount;
localFilename+=byte;
}
if (byte == '/')
{
if (slashCount > 0)
{
throw(MustlFail("Bad filename (slashes)"));
}
++slashCount;
}
if (byte >= 'a' && byte <= 'z')
{
localFilename+=byte;
}
if (byte <= ' ')
{
break;
}
}
if (localFilename == "") localFilename = "index.html";
if (localFilename == "test.html")
{
SendTestPage();
}
else
{
if (m_webPath == "")
{
const MushcoreScalar *pScalar;
if (MushcoreGlobalConfig::Sgl().GetIfExists(pScalar, "MUSTL_WEB_PATH"))
{
m_webPath = pScalar->StringGet();
}
}
if (m_webPath == "")
{
throw(MustlFail("Path to web files (MUSTL_WEB_PATH) not set"));
}
localFilename = m_webPath+"/"+localFilename;
SendFile(localFilename);
}
}
catch (MushcoreNonFatalFail &e)
{
MustlLog::Sgl().WebLog() << "Exception: " << e.what() << endl;
if (!m_isDead)
{
try
{
SendErrorPage(e.what());
}
catch (MushcoreNonFatalFail &e2)
{
MustlLog::Sgl().WebLog() << "Exception sending error page: " << e2.what() << endl;
}
}
}
}
void
MustlWebLink::PostProcess(const string& inValues)
{
try
{
if (inValues.find("'") != inValues.npos)
{
throw(MustlFail("Invalid POST values"));
}
MushcoreCommand command(string("mustlpostvalues('")+inValues+"')");
command.Execute();
}
catch (MushcoreNonFatalFail &e)
{
MustlLog::Sgl().WebLog() << "Exception: " << e.what() << endl;
}
}
void
MustlWebLink::SendFile(const string& inFilename)
{
bool processFile=false;
ifstream fileStream(inFilename.c_str());
if (!fileStream)
{
throw(MustlFail("File not found: "+inFilename));
}
MustlHTTP http;
http.Reply200();
string::size_type dotPos = inFilename.rfind('.');
if (dotPos == string::npos)
{
throw(MustlFail("Unknown file type: "+inFilename));
}
string fileTypeStr = inFilename.substr(dotPos+1);
if (fileTypeStr == "html")
{
http.ContentTypeHTML();
}
else if (fileTypeStr == "mhtml")
{
http.ContentTypeHTML();
processFile=true;
}
else if (fileTypeStr == "jpg" || fileTypeStr == "jpeg")
{
http.AllowCachingSet();
http.ContentType("image/jpeg");
}
else if (fileTypeStr == "tif" || fileTypeStr == "tiff")
{
http.AllowCachingSet();
http.ContentType("image/tiff");
}
else if (fileTypeStr == "png")
{
http.AllowCachingSet();
http.ContentType("image/png");
}
else if (fileTypeStr == "css")
{
http.AllowCachingSet();
http.ContentType("text/css");
}
else
{
throw(MustlFail("Unknown file type: "+fileTypeStr));
}
if (processFile)
{
SendMHTML(fileStream, http);
}
else
{
http.Endl();
MustlData netData;
http.ContentGet(netData);
Send(netData);
Send(fileStream);
}
Disconnect();
}
void
MustlWebLink::SendMHTML(istream& ioStream, MustlHTTP& ioHTTP)
{
MustlData netData;
ioHTTP.Endl();
ioHTTP.ContentGet(netData);
Send(netData);
while (ioStream.good() && !ioStream.eof())
{
string dataStr;
getline(ioStream, dataStr, '\0');
U32 startPos;
while (startPos = dataStr.find("<?mush"), startPos != dataStr.npos)
{
U32 endPos = dataStr.find("?>", startPos);
if (endPos == dataStr.npos)
{
throw(MustlFail("Unterminated <?mush (expecting ?>)"));
}
string content=dataStr.substr(startPos+6, endPos - startPos - 6);
// MustlLog::Sgl().WebLog() << "Found mush command '" << content << "'" << endl;
try
{
MushcoreCommand command(content);
ostringstream commandOutput;
MushcoreEnvOutput envOutput(MushcoreEnv::Sgl(), commandOutput);
command.Execute();
dataStr.replace(startPos, endPos - startPos + 2, commandOutput.str());
}
catch (MushcoreNonFatalFail& e)
{
ostringstream errorOutput;
errorOutput << "<pre>Command '" << content << "' failed: " << e.what() << "</pre>" << endl;
dataStr.replace(startPos, endPos - startPos + 2, errorOutput.str());
}
}
Send(dataStr);
}
}
void
MustlWebLink::SendTestPage(void)
{
MustlHTTP http;
http.Reply200();
http.ContentTypeHTML();
http.Endl();
http.Header();
http.Out() << "Mustl test page";
http.Endl();
http.Footer();
MustlData netData;
http.ContentGet(netData);
Send(netData);
Disconnect();
}
void
MustlWebLink::SendErrorPage(const string& inText)
{
MustlHTTP http;
http.Reply200();
http.ContentTypeHTML();
http.Endl();
http.Header();
http.Out() << "<h1>Error from Mustl web server</h1>";
http.Out() << "<p>" << inText << "</p>";
http.Out() << "<p><a target=\"_top\" href=\"/index.html\">Back to main page</a></p>";
http.Endl();
http.Footer();
MustlData netData;
http.ContentGet(netData);
Send(netData);
Disconnect();
}
void
MustlWebLink::Print(ostream& ioOut) const
{
ioOut << "[";
ioOut << "requestLine=" << m_requestLine;
ioOut << ", requestType=" << m_requestType;
ioOut << ", linkState=" << m_linkState;
ioOut << ", receiveState=" << m_receiveState;
ioOut << ", tcpSocket=" << m_tcpSocket;
ioOut << ", currentMsec=" << m_currentMsec;
ioOut << ", creationMsec=" << m_creationMsec;
ioOut << ", lastAccessMsec=" << m_lastAccessMsec;
ioOut << ", linkErrors=" << m_linkErrors;
ioOut << ", isDead=" << m_isDead;
ioOut << ", webPath=" << m_webPath;
ioOut << "]";
}
| 24.934593 | 110 | 0.556456 | mushware |
dba7f28d32a79d69a3ee8f32882ba02fec1d9bac | 2,841 | cpp | C++ | unreal/Plugins/OceanPlugin/Source/OceanPlugin/Private/Fish/FishManager.cpp | explore-astrum/astrum | 868fa6d28e1c44d0a99a72edc7f6b5b7d818da07 | [
"MIT"
] | 2 | 2019-01-21T17:49:19.000Z | 2019-06-20T03:01:06.000Z | unreal/Plugins/OceanPlugin/Source/OceanPlugin/Private/Fish/FishManager.cpp | explore-astrum/astrum | 868fa6d28e1c44d0a99a72edc7f6b5b7d818da07 | [
"MIT"
] | 1 | 2022-01-27T16:05:47.000Z | 2022-01-27T16:05:47.000Z | unreal/Plugins/OceanPlugin/Source/OceanPlugin/Private/Fish/FishManager.cpp | explore-astrum/astrum | 868fa6d28e1c44d0a99a72edc7f6b5b7d818da07 | [
"MIT"
] | null | null | null | /*=================================================
* FileName: FishManager.cpp
*
* Created by: Komodoman
* Project name: OceanProject
* Unreal Engine version: 4.18.3
* Created on: 2015/03/17
*
* Last Edited on: 2018/03/15
* Last Edited by: Felipe "Zoc" Silveira
*
* -------------------------------------------------
* For parts referencing UE4 code, the following copyright applies:
* Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
*
* Feel free to use this software in any commercial/free game.
* Selling this as a plugin/item, in whole or part, is not allowed.
* See "OceanProject\License.md" for full licensing details.
* =================================================*/
#include "Fish/FishManager.h"
#include "Fish/FlockFish.h"
#include "Classes/Kismet/GameplayStatics.h"
#include "Classes/Engine/World.h"
AFishManager::AFishManager(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
PrimaryActorTick.bCanEverTick = true;
}
void AFishManager::Tick(float val)
{
setup();
if (attachToPlayer)
{
moveToPlayer();
}
}
void AFishManager::moveToPlayer()
{
if (player)
this->SetActorLocation(player->GetActorLocation());
}
float AFishManager::getMinZ()
{
return minZ;
}
float AFishManager::getMaxZ()
{
return maxZ;
}
void AFishManager::setup()
{
if (isSetup == false){
if (!areFishSpawned)
{
maxX = GetActorLocation().X + underwaterBoxLength;
maxY = GetActorLocation().Y + underwaterBoxLength;
minX = GetActorLocation().X - underwaterBoxLength;
minY = GetActorLocation().Y - underwaterBoxLength;
UWorld* const world = GetWorld();
int numFlocks = flockTypes.Num();
for (int i = 0; i < numFlocks; i++)
{
FVector spawnLoc = FVector(FMath::FRandRange(minX, maxX), FMath::FRandRange(minY, maxY), FMath::FRandRange(minZ, maxZ));
AFlockFish *leaderFish = NULL;
for (int j = 0; j < numInFlock[i]; j++)
{
AFlockFish *aFish = Cast<AFlockFish>(world->SpawnActor(flockTypes[i]));
aFish->isLeader = false;
aFish->DebugMode = DebugMode;
aFish->underwaterMax = FVector(maxX, maxY, maxZ);
aFish->underwaterMin = FVector(minX, minY, minZ);
aFish->underwaterBoxLength = underwaterBoxLength;
spawnLoc = FVector(FMath::FRandRange(minX, maxX), FMath::FRandRange(minY, maxY), FMath::FRandRange(minZ, maxZ));
if (j == 0)
{
aFish->isLeader = true;
leaderFish = aFish;
}
else if (leaderFish != NULL)
{
aFish->leader = leaderFish;
}
aFish->SetActorLocation(spawnLoc);
}
}
areFishSpawned = true;
}
if (attachToPlayer)
{
TArray<AActor*> aPlayerList;
UGameplayStatics::GetAllActorsOfClass(this, playerType, aPlayerList);
if (aPlayerList.Num() > 0)
{
player = aPlayerList[0];
isSetup = true;
}
}
else
{
isSetup = true;
}
}
}
| 24.704348 | 124 | 0.641675 | explore-astrum |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.