hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cd61f999a60a7d86ff92a819e7ad00b810dabbbb | 22,190 | cc | C++ | hackt_docker/hackt/src/main/compile.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/main/compile.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | hackt_docker/hackt/src/main/compile.cc | broken-wheel/hacktist | 36e832ae7dd38b27bca9be7d0889d06054dc2806 | [
"MIT"
] | null | null | null | /**
\file "main/compile.cc"
Converts HAC source code to an object file (pre-unrolled).
This file was born from "art++2obj.cc" in earlier revision history.
$Id: compile.cc,v 1.25 2010/08/05 18:25:31 fang Exp $
*/
#define ENABLE_STACKTRACE 0
#include <iostream>
#include <list>
#include <string>
#include <map>
#include <cstdio>
#include "common/config.hh"
#include "main/compile.hh"
#include "main/main_funcs.hh"
#include "main/compile_options.hh"
#include "main/global_options.hh"
#include "lexer/file_manager.hh"
#if COMPILE_USE_OPTPARSE
#include "util/optparse.tcc"
#endif
#include "util/getopt_portable.h"
#include "util/getopt_mapped.hh"
#include "util/attributes.h"
#include "util/stacktrace.hh"
extern HAC::lexer::file_manager
hackt_parse_file_manager;
namespace HAC {
#include "util/using_ostream.hh"
using entity::module;
using std::list;
using std::string;
using lexer::file_manager;
using util::good_bool;
//=============================================================================
#if !COMPILE_USE_OPTPARSE
/**
Entry for options.
*/
struct compile::options_modifier_info {
options_modifier op;
string brief;
options_modifier_info() : op(NULL), brief() { }
options_modifier_info(const options_modifier o, const char* b) :
op(o), brief(b) { }
operator bool () const { return op; }
good_bool
operator () (options& o) const {
NEVER_NULL(op);
return (*op)(o);
}
}; // end struct options_modifier_info
#endif
//=============================================================================
// class compile static initializers
const char
compile::name[] = "compile";
const char
compile::brief_str[] = "Compiles HACKT source to object file.";
#if COMPILE_USE_OPTPARSE
typedef util::options_map_impl<compile_options> options_map_impl_type;
typedef options_map_impl_type::opt_map_type opt_map_type;
static options_map_impl_type options_map_wrapper;
#else
/**
Options modifier map must be initialized before any registrations.
*/
const compile::options_modifier_map_type
compile::options_modifier_map;
#endif
//=============================================================================
static const char default_options_brief[] = "Needs description.";
#if COMPILE_USE_OPTPARSE
class compile::register_options_modifier {
typedef options_map_impl_type::opt_entry opt_entry;
typedef options_map_impl_type::opt_func modifier_type;
const opt_entry& receipt;
public:
register_options_modifier(const string& Mode,
const modifier_type COM,
const string& h = default_options_brief) :
receipt(options_map_wrapper.options_map[Mode] =
opt_entry(COM, NULL, NULL, h)) {
}
register_options_modifier(const string& Mode,
const modifier_type COM,
const char* h) :
receipt(options_map_wrapper.options_map[Mode] =
opt_entry(COM, NULL, NULL, h)) {
}
} __ATTRIBUTE_UNUSED__ ;
#else
/**
Options modification registration interface.
*/
class compile::register_options_modifier {
public:
register_options_modifier(const string& optname,
const options_modifier om,
const char* b = default_options_brief) {
options_modifier_map_type&
omm(const_cast<options_modifier_map_type&>(
options_modifier_map));
NEVER_NULL(om);
options_modifier_info& i(omm[optname]);
INVARIANT(!i);
i.op = om;
i.brief = b;
}
} __ATTRIBUTE_UNUSED__; // end class register_options_modifier
#endif // COMPILE_USE_OPTPARSE
//=============================================================================
// compile::options_modifier declarations and definitions
// Texinfo documentation is below, under -f option.
#if COMPILE_USE_OPTPARSE
#define OPTARG const util::option_value& v,
#define OPTARG_UNUSED const util::option_value&,
#define OPTARG_FWD v,
typedef bool optfun_return_type;
#define OPTFUN_RETURN return false;
#else
#define OPTARG
#define OPTARG_UNUSED
#define OPTARG_FWD
typedef good_bool optfun_return_type;
#define OPTFUN_RETURN return good_bool(true);
#endif
using HAC::parser::parse_options;
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
#define SET_OPT(t,m,v) \
options_map_impl_type::set_member_constant<t, &compile_options::m, v>
#define SET_OPT2(t1,m1,t2,m2,v) \
options_map_impl_type::set_member_member_constant< \
t1, t2, &compile_options::m1, &t1::m2, v>
#define SET_BOOL_OPT(m,v) SET_OPT(bool, m, v)
#define SET_BOOL_OPT2(t1,m1,t2,m2,v) SET_OPT2(t1, m1, bool, m2, v)
#define SET_PARSE_OPT2(t2,m2,v) \
SET_OPT2(parse_options, parse_opts, t2, m2, v)
#endif
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
#define DEFINE_OPTION(type, mem, key, val, str) \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem(key, &SET_OPT(type, mem, val), str);
#define DEFINE_BOOL_OPTION(mem, key, val, str) \
DEFINE_OPTION(bool, mem, key, val, str)
#define DEFINE_OPTION2(type1, mem1, type2, mem2, key, val, str) \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem2 ## _ ## val(key, \
&SET_OPT2(type1, mem1, type2, mem2, val), str);
#define DEFINE_PARSE_OPTION2(type2, mem2, key, val, str) \
DEFINE_OPTION2(parse_options, parse_opts, \
type2, mem2, key, val, str)
#define DEFINE_CREATE_OPTION2(type2, mem2, key, val, str) \
DEFINE_OPTION2(create_options, create_opts, \
type2, mem2, key, val, str)
#endif
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
#define DEFINE_BOOL_OPTION_PAIR(mem, key, truestr, falsestr) \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem(key, &SET_BOOL_OPT(mem, true), truestr), \
compile_opt_mod_no_## mem("no-" key, &SET_BOOL_OPT(mem, false), \
falsestr);
#define DEFINE_BOOL_PARSE_OPTION_PAIR(mem, key, truestr, falsestr) \
DEFINE_PARSE_OPTION2(bool, mem, key, true, truestr) \
DEFINE_PARSE_OPTION2(bool, mem, "no-" key, false, falsestr)
#else
#define DEFINE_BOOL_OPTION_PAIR(mem, key, truestr, falsestr) \
static \
optfun_return_type \
__compile_ ## mem(OPTARG_UNUSED compile::options& cf) { \
cf.mem = true; \
OPTFUN_RETURN \
} \
static \
optfun_return_type \
__compile_no_ ## mem(OPTARG_UNUSED compile::options& cf) { \
cf.mem = false; \
OPTFUN_RETURN \
} \
static const compile::register_options_modifier \
compile_opt_mod_ ## mem(key, &__compile_ ## mem, truestr), \
compile_opt_mod_no_## mem("no-" key, &__compile_no_ ## mem, falsestr);
#endif
//-----------------------------------------------------------------------------
DEFINE_BOOL_OPTION_PAIR(dump_include_paths, "dump-include-paths",
"dumps -I include paths as they are processed",
"suppress feedback of -I include paths")
//-----------------------------------------------------------------------------
DEFINE_BOOL_OPTION_PAIR(dump_object_header, "dump-object-header",
"dumps persistent object header before saving",
"suppress persistent object header dump")
//-----------------------------------------------------------------------------
// dialect flags
// texinfo documentation is below under option-f
DEFINE_PARSE_OPTION2(bool, export_all, "export-all", true,
"treat all definitions as exported")
DEFINE_PARSE_OPTION2(bool, export_all, "export-strict", false,
"only export definitions that are marked as such (default, ACT)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// the following are create-phase options forwarded to the create phase
DEFINE_CREATE_OPTION2(canonicalize_policy, canonicalize_mode,
"canonical-shortest-hier", SHORTEST_HIER_NO_LENGTH,
"prefer aliases by number of hierarchy levels only (default)")
DEFINE_CREATE_OPTION2(canonicalize_policy, canonicalize_mode,
"canonical-shortest-length", SHORTEST_HIER_MIN_LENGTH,
"prefer aliases using overall length as tie-breaker")
DEFINE_CREATE_OPTION2(canonicalize_policy, canonicalize_mode,
"canonical-shortest-stage", SHORTEST_EMULATE_ACT,
"prefer aliases using per-member length as tie-breaker (ACT, unimplemented)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEFINE_BOOL_PARSE_OPTION_PAIR(namespace_instances, "namespace-instances",
"allow instance management outside global namespace (default)",
"forbid instance management outside global namespace (ACT)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEFINE_BOOL_PARSE_OPTION_PAIR(array_internal_nodes, "array-internal-nodes",
"allow implicit arrays of internal nodes in PRS (default)",
"reject implicit arrays of internal nodes in PRS (ACT)")
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if COMPILE_USE_OPTPARSE
template <error_policy parse_options::*mem>
static
bool
__set_policy_member(const util::option_value& opt,
compile_options& c_opt) {
const size_t s = opt.values.size();
if (s >= 1) {
if (s > 1) {
cerr << "Warning: extra arguments passed to \'" << opt.key
<< "\' option ignored." << endl;
}
const string& p(opt.values.front());
if (p == "ignore") {
c_opt.parse_opts.*mem = OPTION_IGNORE;
} else if (p == "warn") {
c_opt.parse_opts.*mem = OPTION_WARN;
} else if (p == "error") {
c_opt.parse_opts.*mem = OPTION_ERROR;
} else {
cerr << "Error: error policy values for option " <<
opt.key << " are [ignore|warn|error]." << endl;
return true;
}
}
return false;
}
static const compile::register_options_modifier
__compile_om_case_collision("case-collision",
&__set_policy_member<&parse_options::case_collision_policy>,
"handle case-insensitive collisions (= ignore|[warn]|error)");
#else
static
good_bool
__compile_case_collision_ignore(compile::options& o) {
o.parse_opts.case_collision_policy = OPTION_IGNORE;
return good_bool(true);
}
static
good_bool
__compile_case_collision_warn(compile::options& o) {
o.parse_opts.case_collision_policy = OPTION_WARN;
return good_bool(true);
}
static
good_bool
__compile_case_collision_error(compile::options& o) {
o.parse_opts.case_collision_policy = OPTION_ERROR;
return good_bool(true);
}
// TODO: actually parse the policy argument using optparse()
static const compile::register_options_modifier
__compile_om_case_collision_ignore("case-collision=ignore",
&__compile_case_collision_ignore,
"ignore case-insensitive collisions"),
__compile_om_case_collision_warn("case-collision=warn",
&__compile_case_collision_warn,
"warn about case-insensitive collisions (default)"),
__compile_om_case_collision_error("case-collision=error",
&__compile_case_collision_error,
"reject case-insensitive collisions");
#endif // COMPILE_USE_OPTPARSE
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
static const compile::register_options_modifier
__compile_om_unknown_spec("unknown-spec",
&__set_policy_member<&parse_options::unknown_spec_policy>,
"handle unknown spec directives (= ignore|warn|[error])");
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
static
optfun_return_type
__compile_ACT(OPTARG_UNUSED compile::options& o) {
#if COMPILE_USE_OPTPARSE
o.parse_opts.export_all = false;
o.parse_opts.namespace_instances = false;
o.parse_opts.array_internal_nodes = false;
#else
__compile_export_strict(o);
__compile_no_namespace_instances(o);
__compile_no_array_internal_nodes(o);
#endif
OPTFUN_RETURN
}
static const compile::register_options_modifier
__compile_om_ACT("ACT", &__compile_ACT,
"preset: all ACT-mode flags maximum compatibility");
//=============================================================================
// class compile method definitions
compile::compile() { }
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
The main program for compiling source to object.
Also parses options and sets flags.
\return negative number for non-error 'exit-now' status,
0 for success, positive number for other error.
TODO: is there a way to return the number of arguments parsed,
or just optind?
*/
int
compile::make_module(int argc, char* argv[], options& opt,
count_ptr<module>& ret) {
STACKTRACE_VERBOSE;
if (parse_command_options(argc, argv, opt)) {
usage();
return 1;
}
argv += optind; // shift
argc -= optind;
const int max_args = opt.use_stdin ? 1 : 2;
const int target_ind = max_args -1;
if (argc > max_args || argc <= 0) {
usage();
return 1;
}
if (!opt.use_stdin) {
opt.source_file = argv[0];
// or use util::memory::excl_ptr<FILE, fclose_tag>
FILE* f = open_source_file(opt.source_file.c_str());
if (!f)
return 1;
fclose(f);
}
// dependency generation setup
if (!opt.have_target()) {
// if not already named by -o, use next non-option argument
if (argc >= max_args) {
opt.target_object = argv[target_ind];
} else {
// default: append 'o' to get object file name
// problem: doesn't automatically strip srcdir
// opt.target_object = opt.source_file + 'o';
}
} // else ignore argv[1], use whatever was set before
// have target by now
if (opt.have_target()) {
if (!check_file_writeable(opt.target_object.c_str()).good)
return 1;
}
// parse it
ret = parse_and_check(
opt.use_stdin ? NULL : opt.source_file.c_str(), opt);
if (!ret) {
return 1;
}
return 0;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int
compile::main(const int argc, char* argv[], const global_options&) {
options opt;
count_ptr<module> mod;
const int err = make_module(argc, argv, opt, mod);
if (err < 0) {
return 1;
} else if (err > 0) {
return err;
}
if (!mod) {
return 1;
}
// if (argc -optind >= 2)
if (opt.have_target()) {
// save_module(*mod, opt.target_object);
// save_module_debug(*mod, opt.target_object);
save_module_debug(*mod, opt.target_object.c_str(),
opt.dump_object_header);
}
if (opt.dump_module)
mod->dump(cerr);
return 0;
}
//-----------------------------------------------------------------------------
/**
\return 0 if is ok to continue, anything else will signal early
termination, an error will cause exit(1).
Set global variable optind to the number of initial tokens to
skip (default = 1).
NOTE: the getopt option string begins with '+' to enforce
POSIXLY correct termination at the first non-option argument.
*/
int
compile::parse_command_options(const int argc, char* argv[], options& opt) {
STACKTRACE_VERBOSE;
static const char* optstring = "+df:hi:I:M:o:pv";
int c;
while ((c = getopt(argc, argv, optstring)) != -1) {
switch (c) {
/***
@texinfo compile/option-d.texi
@defopt -d
Produces text dump of compiled module,
like @command{hacobjdump} in @ref{Objdump}.
@end defopt
@end texinfo
***/
case 'd':
opt.dump_module = true;
break;
// TODO: summarize ACT-compatibility in form of a table
/***
@texinfo compile/option-f.texi
@defopt -f optname
general compile flags (repeatable) where @var{optname} is one of the following:
@itemize
@item @option{dump-include-paths}:
dumps @option{-I} include paths as they are processed
@item @option{dump-object-header}:
(diagnostic) dumps persistent object header before saving
@item @option{no-dump-include-paths}:
suppress feedback of @option{-I} include paths
@item @option{no-dump-object-header}:
suppress persistent object header dump
@item @option{case-collision=[ignore|warn|error]}:
Set the error handling policy for case-insensitive collisions.
@itemize
@item @option{ignore} skips the check altogether
@item @option{warn} issues a warning but continues
@item @option{error} rejects and aborts compiling
@end itemize
@item @option{unknown-spec=[ignore|warn|error]}:
Sets the error handling policy for unknown spec directives.
@end itemize
Dialect flags (for ACT-compatibility):
@itemize
@item @option{export-all}:
Treat all definitions as exported, i.e. no export checking.
@item @option{export-strict}:
Check that definitions are exported for use outside their
respective home namespaces (default, ACT).
@item @option{namespace-instances}
Allow instance management outside global namespace (default).
Negatable with @t{no-} prefixed.
ACT mode: @option{no-namespace-instances}.
@item @option{array-internal-nodes}
Allow implicit arrays of internal nodes in PRS (default).
Negatable with @t{no-} prefixed.
ACT mode: @option{no-array-internal-nodes}.
@end itemize
@option{ACT} is a preset that activates all ACT-mode flags for compatibility.
The following options are forwarded to the create-phase of compilation
by the driver. That is, they do not have any affect until the create phase.
These options must be specified up-front at compile-time and cannot be
overriden at create-time on the command line.
@itemize
@item @option{canonical-shortest-hier}:
Only consider hierarchical depth (number of member-dots) for
choosing canonical alias, no further tiebreaker.
@item @option{canonical-shortest-length}:
In addition to minimizing the hierarchy depth, also use overall
string length as a tiebreaker.
@item @option{canonical-shortest-stage}: (unimplemented)
Considers length of identifiers stage-by-stage when hierarchical
depths are equal.
This is for best compatibility with ACT mode.
@end itemize
@end defopt
@end texinfo
***/
case 'f': {
#if COMPILE_USE_OPTPARSE
typedef opt_map_type::const_iterator const_iterator;
const opt_map_type&
options_modifier_map(options_map_wrapper.options_map);
const util::option_value ov(util::optparse(optarg));
const const_iterator mi(options_modifier_map.find(ov.key));
#else
typedef options_modifier_map_type::mapped_type mapped_type;
typedef options_modifier_map_type::const_iterator const_iterator;
const const_iterator mi(options_modifier_map.find(optarg));
#endif
if (mi == options_modifier_map.end()
#if !COMPILE_USE_OPTPARSE
|| !mi->second
#endif
) {
cerr << "Invalid option argument: " << optarg << endl;
return 1;
}
#if COMPILE_USE_OPTPARSE
else if ((mi->second.func)(ov, opt))
#else
else if (!((mi->second)(opt).good))
#endif
{
return 1;
}
break;
}
/***
@texinfo compile/option-h.texi
@defopt -h
Show usage and exit.
@end defopt
@end texinfo
***/
case 'h':
// return 1;
usage();
exit(0);
break;
/***
@texinfo compile/option-I-upper.texi
@defopt -I path
Adds include path @var{path} for importing other source files (repeatable).
@end defopt
@end texinfo
***/
case 'I':
// no need to check validity of paths yet
opt.include_paths.push_back(optarg);
break;
/***
@texinfo compile/option-i.texi
@defopt -i file
Import @var{file}(s) before processing the main top-level file (repeatable).
All @option{-I} search paths take effect before any of these
files are imported.
@end defopt
@end texinfo
***/
case 'i':
// no need to check validity of paths yet
opt.prepend_files.push_back(optarg);
break;
/***
@texinfo compile/option-M-upper.texi
@defopt -M depfile
Emit import dependencies in file @var{depfile} as a side-effect.
Useful for automatic dynamic dependency-tracking in Makefiles.
@end defopt
@end texinfo
***/
case 'M':
opt.make_depend = true;
opt.make_depend_target = optarg;
break;
/***
@texinfo compile/option-o.texi
@defopt -o objfile
Names @var{objfile} as the output object file to save.
This is an alternative to naming the object file as the second
non-option argument.
@end defopt
@end texinfo
***/
case 'o':
opt.target_object = optarg;
break;
/***
@texinfo compile/option-p.texi
@defopt -p
Expect input to be piped from stdin rather than a named file.
Since the name of the input file is omitted in this case,
the only non-option argument (if any) is interpreted as the name
of the output object file.
@end defopt
@end texinfo
***/
case 'p':
opt.use_stdin = true;
break;
/***
@texinfo compile/option-v.texi
@defopt -v
Show version and build information and exit.
@end defopt
@end texinfo
***/
case 'v':
config::dump_all(cout);
exit(0);
break;
case ':':
cerr << "Expected but missing non-option argument." << endl;
return 1;
case '?':
util::unknown_option(cerr, optopt);
return 1;
default:
abort();
} // end switch
} // end while
/***
Now would be a good time to add include paths
to the parser's file manager.
Don't use a global file_manager, use local variables
and pass as arguments, to allow these main subprograms
to be re-entrant.
Q: Should file_manager be a member of module?
Caution: calling this function multiple times with the
same options object will accumulate duplicate paths.
***/
opt.export_include_paths(hackt_parse_file_manager);
return 0;
}
//-----------------------------------------------------------------------------
/**
Prints summary of options and arguments.
*/
void
compile::usage(void) {
cerr << "compile: compiles input file to module object file" << endl;
cerr << "usage: compile [options] <hackt-source-file> [hackt-obj-file]"
<< endl;
cerr << "options:" << endl;
cerr << " -d: produces text dump of compiled module" << endl <<
" -f <opt> : general compile flags (repeatable)" << endl;
{
#if COMPILE_USE_OPTPARSE
options_map_wrapper.help(cerr, false, false);
#else
typedef options_modifier_map_type::const_iterator const_iterator;
const_iterator i(options_modifier_map.begin());
const const_iterator e(options_modifier_map.end());
for ( ; i!=e; ++i) {
cerr << " " << i->first << ": " <<
i->second.brief << endl;
}
#endif
}
cerr << " -h: gives this usage message and exits" << endl <<
" -I <path> : adds include path (repeatable)" << endl <<
" -i <file> : prepends import file (repeatable)" << endl;
cerr << " -M <dependfile> : produces make dependency to file" << endl;
cerr << " -o <objfile> : option to name output object file" << endl;
cerr << " -p : pipe in source from stdin" << endl;
cerr << " -v : print version information and exit" << endl;
cerr << "If no output object file is given, compiled module will not be saved."
<< endl;
}
//=============================================================================
} // end namespace HAC
| 30.819444 | 80 | 0.672105 | [
"object"
] |
cd68866a7b05112659ad897107233759dac740ed | 12,142 | cpp | C++ | messungen/server_client/corr_client_opencl_17/corr_client_opencl/CorrWorker.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 16 | 2021-04-10T16:28:00.000Z | 2021-12-12T10:15:23.000Z | messungen/server_client/corr_client_opencl_17/corr_client_opencl/CorrWorker.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | null | null | null | messungen/server_client/corr_client_opencl_17/corr_client_opencl/CorrWorker.cpp | tihmstar/gido_public | dcc523603b9a27b37752211715a10e30b51ce812 | [
"Unlicense"
] | 2 | 2021-04-10T16:32:36.000Z | 2021-04-11T14:13:45.000Z | //
// CorrWorker.cpp
// corr_client_opencl
//
// Created by tihmstar on 19.03.20.
// Copyright © 2020 tihmstar. All rights reserved.
//
#include "CorrWorker.hpp"
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdio.h>
#include <signal.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "CPULoader.hpp"
#include <stdlib.h>
//#warning custom point_per_trace
//#define NUMBER_OF_POINTS_OVERWRITE 2000
#define assure(cond) do {if (!(cond)) {printf("ERROR: CorrWorker ASSURE FAILED ON LINE=%d\n",__LINE__); throw(__LINE__); }}while (0)
#define assure_(cond) do {cl_int clret = 0; if ((clret = cond)) {printf("ERROR: CorrWorker ASSURE FAILED ON LINE=%d with err=%d\n",__LINE__,clret); throw(__LINE__);}}while (0)
#ifndef ntohll
uint64_t ntohll(uint64_t in){
volatile uint64_t out[1] = {1};
if ((*(uint8_t*)out) == 1){
//little endian, do swap
((uint8_t*)out)[7] = (in >> 0x00) & 0xff;
((uint8_t*)out)[6] = (in >> 0x08) & 0xff;
((uint8_t*)out)[5] = (in >> 0x10) & 0xff;
((uint8_t*)out)[4] = (in >> 0x18) & 0xff;
((uint8_t*)out)[3] = (in >> 0x20) & 0xff;
((uint8_t*)out)[2] = (in >> 0x28) & 0xff;
((uint8_t*)out)[1] = (in >> 0x30) & 0xff;
((uint8_t*)out)[0] = (in >> 0x38) & 0xff;
}else{
out[0] = in;
}
return out[0];
}
#endif
#define senduint32_t(num) do { uint32_t s = htonl(num);assure(write(_serverFd, &s, sizeof(s)) == sizeof(s)); }while(0)
#define receiveuint32_t() [this]()->uint32_t{ uint32_t s = 0; assure(doread(_serverFd, &s, sizeof(s)) == sizeof(s)); s = htonl(s); return s;}()
#define senduint64_t(num) do { uint64_t s = ntohll(num);assure(write(_serverFd, &s, sizeof(s)) == sizeof(s)); }while(0)
#define receiveuint64_t() [this]()->uint64_t{ uint64_t s = 0; assure(doread(_serverFd, &s, sizeof(s)) == sizeof(s)); s = ntohll(s); return s;}()
using namespace std;
static ssize_t doread(int fd, void *buf, ssize_t size){
ssize_t didread = 0;
do{
ssize_t curdidread = read(fd, static_cast<uint8_t*>(buf)+didread, size-didread);
assure(curdidread>0);
didread += curdidread;
}while (didread<size);
return didread;
}
CorrWorker::CorrWorker(std::string tracesIndir, const char *serverAddress, uint16_t port, std::vector<int> gpus, std::string kernelsource, size_t availableRamSize, float workermultiplier)
: _serverFd(-1), _tracesIndir(tracesIndir), _kernelsource(kernelsource), _availableRamSize(availableRamSize), _point_per_trace(0), _workerThread(NULL),
_workerShouldStop(false), _workerIsRunning(false)
{
struct sockaddr_in servaddr = {};
uint32_t num_of_powermodels = 0;
if (_tracesIndir.c_str()[_tracesIndir.size()-1] != '/') {
_tracesIndir += '/';
}
printf("[CorrWorker] init\n");
assure((_serverFd = socket(AF_INET, SOCK_STREAM, 0)) != -1);
// assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(serverAddress);
servaddr.sin_port = htons(port);
printf("[CorrWorker] connecting to server=%s:%u ...\n",serverAddress,port);
assure(!connect(_serverFd, (struct sockaddr *)&servaddr, sizeof(servaddr)));
printf("[CorrWorker] connected!\n");
/*
init sequence:
--- Server -> Cient ---
send point_per_trace //uint32_t
send num_of_powermodels //uint32_t
send power models seperated by \x00 byte
[
model\x00
model\x00 ...
]
--- Cient -> Server ---
send num_of_gpus //uint32_t
*/
_point_per_trace = receiveuint32_t();
num_of_powermodels = receiveuint32_t();
#ifdef NUMBER_OF_POINTS_OVERWRITE
assure(_point_per_trace == NUMBER_OF_POINTS_OVERWRITE);
#endif
for (int i=0; i<num_of_powermodels; i++) {
char c = 0;
std::string curstr;
do{
read(_serverFd, &c, 1);
curstr += c;
}while(c);
_powermodels.push_back(curstr.substr(0,curstr.size()-1));
}
for (auto &m : _powermodels) {
printf("[CorrWorker] Model=%s\n",m.c_str());
}
printf("[CorrWorker] Got %3lu powerModels!\n",_powermodels.size());
#pragma mark init GPUS
// Get platform and device information
cl_platform_id platform_id = NULL;
cl_uint num_platforms = 0;
cl_uint num_devices = 0;
assure_(clGetPlatformIDs(1, &platform_id, &num_platforms));
assure_(clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, 0, NULL, &num_devices));
{
cl_device_id device_ids[num_devices];
assure_(clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_GPU, num_devices, device_ids, &num_devices));
for (int index : gpus) {
printf("[CorrWorker] Init GPU %d!\n",index);
assure(index < num_devices);
_gpus.push_back(new GPUDevice(index,device_ids[index],kernelsource, _point_per_trace, _powermodels));
}
}
printf("[CorrWorker] All GPUs initialized\n");
uint32_t workers = (uint32_t)gpus.size();
workers *= workermultiplier;
assure(workers != 0);
printf("[CorrWorker] workers=%u\n",workers);
senduint32_t(workers);
}
CorrWorker::~CorrWorker(){
_workerShouldStop = true;
{
int fd = _serverFd;_serverFd = -1;
close(fd);
}
if (_workerThread) _workerThread->join();
if (!_workerIsRunning) raise(SIGINT); //sanity check
if (_workerThread) {
delete _workerThread;
_workerThread = NULL;
}
}
void CorrWorker::worker(uint16_t maxLoaderThreads){
_workerIsRunning = true;
while (!_workerShouldStop) {
uint32_t batchSize = 0;
batchSize = receiveuint32_t();
printf("[CorrWorker] Got batchsize=%u\n",batchSize);
std::vector<std::string> bachFilenames;
for (int i=0; i<batchSize; i++) {
char c = 0;
std::string curstr;
do{
read(_serverFd, &c, 1);
curstr += c;
}while(c);
bachFilenames.push_back(_tracesIndir + curstr.substr(0,curstr.size()-1));
}
for (auto &f : bachFilenames) {
printf("[CorrWorker] Batch Filename=%s\n",f.c_str());
}
senduint32_t(batchSize);
#pragma mark doGPUComputation
CPULoader cloader(bachFilenames, _availableRamSize, maxLoaderThreads);
std::queue<std::thread *> gpuTransferThreads;
#define MIN_TRANSFER_CNT 0
#define MAX_TRANSFER_CNT 25000
for (auto &gpu : _gpus) {
gpuTransferThreads.push(new std::thread([&cloader](GPUDevice *gpu)->void{
LoadFile *toTransfer = NULL;
while (LoadFile *file = cloader.dequeue()) {
if (toTransfer) { //if we have "toTransfer"
if (
toTransfer->tracesInFile() >= MIN_TRANSFER_CNT //if "toTransfer" already large enough
|| toTransfer->tracesInFile() + file->tracesInFile() > MAX_TRANSFER_CNT //or combination would exceed MAX limit
) {
//then transfer the pendin trace
gpu->transferTrace(toTransfer);
delete toTransfer;
toTransfer = NULL;
}
}
if (!toTransfer) { //if we don't have a pending trace anymore, make "file" be our new pending trace
toTransfer = file; file = NULL;
continue;
}
//if we have both: "transferTrace" and "file", then we should combine them now
printf("[DW-%u] combining traces (%5u + %5u = %5u)\n",gpu->deviceNum(),toTransfer->tracesInFile(), file->tracesInFile(), toTransfer->tracesInFile() + file->tracesInFile());
*toTransfer += *file;
//once we combined traces, we can discard "file"
if (file) {
delete file; file = NULL;
}
}
//final transfer
if (toTransfer) {
gpu->transferTrace(toTransfer);
delete toTransfer;
toTransfer = NULL;
}
printf("GPU %d done transfer!\n",gpu->deviceNum());
},gpu));
}
printf("Waiting for gpu transfers to finish (%lu threads)!\n",gpuTransferThreads.size());
while (gpuTransferThreads.size()) {
auto t = gpuTransferThreads.front();
gpuTransferThreads.pop();
t->join();
delete t;
}
printf("All GPU transfers finished, getting results...\n");
std::map<std::string,std::map<std::string,CPUModelResults*>> allmodelresults;
for (auto &gpu : _gpus) {
gpu->getResults(allmodelresults);
}
#pragma mark sendBackResults
/*
Protocol:
--- Client -> Server ---
send allmodelresults.size() //uint32_t
send models
[
modelresultcategory\x00 //terminated by zero byte
[
send allmodelresults[x].size() //uint32_t
modelresultname\x00 //terminated by zero byte
cpumodelresultsize //uint64_t
< raw data >
]
....
]
send 00000000 //uint32_t
*/
srand((unsigned int)time(NULL) ^ rand());
uint32_t myrand = rand();
uint32_t remoteRand = 0;
senduint32_t(myrand);
remoteRand = receiveuint32_t();
senduint32_t(allmodelresults.size());
int allmodelresultsCounter = 0;
for (auto &category : allmodelresults) {
assure(allmodelresultsCounter++ < allmodelresults.size()); //don't send more than we announced
assure(write(_serverFd, category.first.c_str(), category.first.size()+1) == category.first.size()+1); //modelresultcategory\x00 //terminated by zero byte
senduint32_t(category.second.size()); //send allmodelresults[x].size() //uint32_t
int modelresultcategorycounter = 0;
for (auto &mr : category.second) {
assure(modelresultcategorycounter++ < category.second.size()); //don't send more than we announced
assure(write(_serverFd, mr.first.c_str(), mr.first.size()+1) == mr.first.size()+1); // modelresultname\x00 //terminated by zero byte
void *data = NULL;
size_t dataSize = 0;
mr.second->serialize(&data, &dataSize);
uint64_t dataSizeSend = (uint64_t)dataSize;
assure(dataSizeSend == dataSize); //no casting issues here
senduint64_t(dataSizeSend); //cpumodelresultsize //uint64_t
assure(write(_serverFd, data, dataSizeSend) == dataSizeSend); // < raw data >
free(data);
}
}
senduint32_t(myrand ^ remoteRand); //final check
for (auto &gpu : _gpus) {
gpu->resetDevice();
}
for (auto & category : allmodelresults) {
for (auto &model: category.second) {
delete model.second; model.second = NULL;
}
}
}
_workerIsRunning = false;
}
void CorrWorker::startWorker(uint16_t maxLoaderThreads){
_workerThread = new std::thread([this](uint16_t loadthreads){
worker(loadthreads);
}, maxLoaderThreads);
}
void CorrWorker::stopWorker(){
_workerShouldStop = true;
}
| 32.816216 | 192 | 0.558887 | [
"vector",
"model"
] |
cd6c6cfb3c4f8f77fe4b027bf3a3ebf4709db7a6 | 7,814 | cc | C++ | tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification/run_eval.cc | NeerajBhadani/tensorflow | 8c849c65503fef22f49f7ab843803fca9c439bdf | [
"Apache-2.0"
] | 4 | 2020-04-19T11:30:20.000Z | 2020-07-02T07:13:15.000Z | tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification/run_eval.cc | NeerajBhadani/tensorflow | 8c849c65503fef22f49f7ab843803fca9c439bdf | [
"Apache-2.0"
] | 2 | 2021-08-25T16:01:49.000Z | 2022-02-10T01:13:06.000Z | tensorflow/lite/tools/evaluation/tasks/imagenet_image_classification/run_eval.cc | NeerajBhadani/tensorflow | 8c849c65503fef22f49f7ab843803fca9c439bdf | [
"Apache-2.0"
] | 1 | 2021-08-29T09:37:58.000Z | 2021-08-29T09:37:58.000Z | /* Copyright 2019 The TensorFlow 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 <cstdlib>
#include <fstream>
#include <string>
#include <vector>
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/tools/command_line_flags.h"
#include "tensorflow/lite/tools/evaluation/evaluation_delegate_provider.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_config.pb.h"
#include "tensorflow/lite/tools/evaluation/proto/evaluation_stages.pb.h"
#include "tensorflow/lite/tools/evaluation/stages/image_classification_stage.h"
#include "tensorflow/lite/tools/evaluation/utils.h"
namespace tflite {
namespace evaluation {
constexpr char kModelFileFlag[] = "model_file";
constexpr char kGroundTruthImagesPathFlag[] = "ground_truth_images_path";
constexpr char kGroundTruthLabelsFlag[] = "ground_truth_labels";
constexpr char kOutputFilePathFlag[] = "output_file_path";
constexpr char kModelOutputLabelsFlag[] = "model_output_labels";
constexpr char kBlacklistFilePathFlag[] = "blacklist_file_path";
constexpr char kNumImagesFlag[] = "num_images";
constexpr char kInterpreterThreadsFlag[] = "num_interpreter_threads";
constexpr char kDelegateFlag[] = "delegate";
template <typename T>
std::vector<T> GetFirstN(const std::vector<T>& v, int n) {
if (n >= v.size()) return v;
std::vector<T> result(v.begin(), v.begin() + n);
return result;
}
bool EvaluateModel(const std::string& model_file_path,
const std::vector<ImageLabel>& image_labels,
const std::vector<std::string>& model_labels,
std::string delegate, std::string output_file_path,
int num_interpreter_threads,
const DelegateProviders& delegate_providers) {
EvaluationStageConfig eval_config;
eval_config.set_name("image_classification");
auto* classification_params = eval_config.mutable_specification()
->mutable_image_classification_params();
auto* inference_params = classification_params->mutable_inference_params();
inference_params->set_model_file_path(model_file_path);
inference_params->set_num_threads(num_interpreter_threads);
inference_params->set_delegate(ParseStringToDelegateType(delegate));
if (!delegate.empty() &&
inference_params->delegate() == TfliteInferenceParams::NONE) {
LOG(WARNING) << "Unsupported TFLite delegate: " << delegate;
return false;
}
classification_params->mutable_topk_accuracy_eval_params()->set_k(10);
ImageClassificationStage eval(eval_config);
eval.SetAllLabels(model_labels);
if (eval.Init(&delegate_providers) != kTfLiteOk) return false;
const int step = image_labels.size() / 100;
for (int i = 0; i < image_labels.size(); ++i) {
if (step > 1 && i % step == 0) {
LOG(INFO) << "Evaluated: " << i / step << "%";
}
eval.SetInputs(image_labels[i].image, image_labels[i].label);
if (eval.Run() != kTfLiteOk) return false;
}
std::ofstream metrics_ofile;
metrics_ofile.open(output_file_path, std::ios::out);
metrics_ofile << eval.LatestMetrics().DebugString();
metrics_ofile.close();
return true;
}
int Main(int argc, char* argv[]) {
// Command Line Flags.
std::string model_file_path;
std::string ground_truth_images_path;
std::string ground_truth_labels_path;
std::string model_output_labels_path;
std::string blacklist_file_path;
std::string output_file_path;
std::string delegate;
int num_images = 0;
int num_interpreter_threads = 1;
std::vector<tflite::Flag> flag_list = {
tflite::Flag::CreateFlag(kModelFileFlag, &model_file_path,
"Path to test tflite model file."),
tflite::Flag::CreateFlag(
kModelOutputLabelsFlag, &model_output_labels_path,
"Path to labels that correspond to output of model."
" E.g. in case of mobilenet, this is the path to label "
"file where each label is in the same order as the output"
" of the model."),
tflite::Flag::CreateFlag(
kGroundTruthImagesPathFlag, &ground_truth_images_path,
"Path to ground truth images. These will be evaluated in "
"alphabetical order of filename"),
tflite::Flag::CreateFlag(
kGroundTruthLabelsFlag, &ground_truth_labels_path,
"Path to ground truth labels, corresponding to alphabetical ordering "
"of ground truth images."),
tflite::Flag::CreateFlag(
kBlacklistFilePathFlag, &blacklist_file_path,
"Path to blacklist file (optional) where each line is a single "
"integer that is "
"equal to index number of blacklisted image."),
tflite::Flag::CreateFlag(kOutputFilePathFlag, &output_file_path,
"File to output metrics proto to."),
tflite::Flag::CreateFlag(kNumImagesFlag, &num_images,
"Number of examples to evaluate, pass 0 for all "
"examples. Default: 0"),
tflite::Flag::CreateFlag(
kInterpreterThreadsFlag, &num_interpreter_threads,
"Number of interpreter threads to use for inference."),
tflite::Flag::CreateFlag(kDelegateFlag, &delegate,
"Delegate to use for inference, if available. "
"Must be one of {'nnapi', 'gpu'}"),
};
tflite::Flags::Parse(&argc, const_cast<const char**>(argv), flag_list);
DelegateProviders delegate_providers;
delegate_providers.InitFromCmdlineArgs(&argc, const_cast<const char**>(argv));
// Process images in filename-sorted order.
std::vector<std::string> image_files, ground_truth_image_labels;
TF_LITE_ENSURE_STATUS(GetSortedFileNames(
StripTrailingSlashes(ground_truth_images_path), &image_files));
if (!ReadFileLines(ground_truth_labels_path, &ground_truth_image_labels)) {
LOG(ERROR) << "Could not read ground truth labels file";
return EXIT_FAILURE;
}
if (image_files.size() != ground_truth_image_labels.size()) {
LOG(ERROR) << "Number of images and ground truth labels is not same";
return EXIT_FAILURE;
}
std::vector<ImageLabel> image_labels;
image_labels.reserve(image_files.size());
for (int i = 0; i < image_files.size(); i++) {
image_labels.push_back({image_files[i], ground_truth_image_labels[i]});
}
// Filter out blacklisted/unwanted images.
TF_LITE_ENSURE_STATUS(
FilterBlackListedImages(blacklist_file_path, &image_labels));
if (num_images > 0) {
image_labels = GetFirstN(image_labels, num_images);
}
std::vector<std::string> model_labels;
if (!ReadFileLines(model_output_labels_path, &model_labels)) {
LOG(ERROR) << "Could not read model output labels file";
return EXIT_FAILURE;
}
if (!EvaluateModel(model_file_path, image_labels, model_labels, delegate,
output_file_path, num_interpreter_threads,
delegate_providers)) {
LOG(ERROR) << "Could not evaluate model";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
} // namespace evaluation
} // namespace tflite
int main(int argc, char* argv[]) {
return tflite::evaluation::Main(argc, argv);
}
| 41.343915 | 80 | 0.695163 | [
"vector",
"model"
] |
cd703d4b3bb4f7a8e28b01d75e02d24a879ef29d | 7,411 | cpp | C++ | third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/modules/bluetooth/BluetoothError.cpp | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 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 "modules/bluetooth/BluetoothError.h"
#include "core/dom/DOMException.h"
#include "core/dom/ExceptionCode.h"
#include "third_party/WebKit/public/platform/modules/bluetooth/web_bluetooth.mojom-blink.h"
namespace blink {
DOMException* BluetoothError::take(
ScriptPromiseResolver*,
int32_t
webError /* Corresponds to WebBluetoothResult in web_bluetooth.mojom */) {
switch (static_cast<mojom::blink::WebBluetoothResult>(webError)) {
case mojom::blink::WebBluetoothResult::SUCCESS:
ASSERT_NOT_REACHED();
return DOMException::create(UnknownError);
#define MAP_ERROR(enumeration, name, message) \
case mojom::blink::WebBluetoothResult::enumeration: \
return DOMException::create(name, message)
// InvalidModificationErrors:
MAP_ERROR(GATT_INVALID_ATTRIBUTE_LENGTH, InvalidModificationError,
"GATT Error: invalid attribute length.");
// InvalidStateErrors:
MAP_ERROR(SERVICE_NO_LONGER_EXISTS, InvalidStateError,
"GATT Service no longer exists.");
MAP_ERROR(CHARACTERISTIC_NO_LONGER_EXISTS, InvalidStateError,
"GATT Characteristic no longer exists.");
// NetworkErrors:
MAP_ERROR(CONNECT_ALREADY_IN_PROGRESS, NetworkError,
"Connection already in progress.");
MAP_ERROR(CONNECT_ATTRIBUTE_LENGTH_INVALID, NetworkError,
"Write operation exceeds the maximum length of the attribute.");
MAP_ERROR(CONNECT_AUTH_CANCELED, NetworkError,
"Authentication canceled.");
MAP_ERROR(CONNECT_AUTH_FAILED, NetworkError, "Authentication failed.");
MAP_ERROR(CONNECT_AUTH_REJECTED, NetworkError,
"Authentication rejected.");
MAP_ERROR(CONNECT_AUTH_TIMEOUT, NetworkError, "Authentication timeout.");
MAP_ERROR(CONNECT_CONNECTION_CONGESTED, NetworkError,
"Remote device connection is congested.");
MAP_ERROR(CONNECT_INSUFFICIENT_ENCRYPTION, NetworkError,
"Insufficient encryption for a given operation");
MAP_ERROR(
CONNECT_OFFSET_INVALID, NetworkError,
"Read or write operation was requested with an invalid offset.");
MAP_ERROR(CONNECT_READ_NOT_PERMITTED, NetworkError,
"GATT read operation is not permitted.");
MAP_ERROR(CONNECT_REQUEST_NOT_SUPPORTED, NetworkError,
"The given request is not supported.");
MAP_ERROR(CONNECT_UNKNOWN_ERROR, NetworkError,
"Unknown error when connecting to the device.");
MAP_ERROR(CONNECT_UNKNOWN_FAILURE, NetworkError,
"Connection failed for unknown reason.");
MAP_ERROR(CONNECT_UNSUPPORTED_DEVICE, NetworkError,
"Unsupported device.");
MAP_ERROR(CONNECT_WRITE_NOT_PERMITTED, NetworkError,
"GATT write operation is not permitted.");
MAP_ERROR(DEVICE_NO_LONGER_IN_RANGE, NetworkError,
"Bluetooth Device is no longer in range.");
MAP_ERROR(GATT_NOT_PAIRED, NetworkError, "GATT Error: Not paired.");
MAP_ERROR(GATT_OPERATION_IN_PROGRESS, NetworkError,
"GATT operation already in progress.");
MAP_ERROR(UNTRANSLATED_CONNECT_ERROR_CODE, NetworkError,
"Unknown ConnectErrorCode.");
// NotFoundErrors:
MAP_ERROR(WEB_BLUETOOTH_NOT_SUPPORTED, NotFoundError,
"Web Bluetooth is not supported on this platform. For a list "
"of supported platforms see: https://goo.gl/J6ASzs");
MAP_ERROR(NO_BLUETOOTH_ADAPTER, NotFoundError,
"Bluetooth adapter not available.");
MAP_ERROR(CHOSEN_DEVICE_VANISHED, NotFoundError,
"User selected a device that doesn't exist anymore.");
MAP_ERROR(CHOOSER_CANCELLED, NotFoundError,
"User cancelled the requestDevice() chooser.");
MAP_ERROR(CHOOSER_NOT_SHOWN_API_GLOBALLY_DISABLED, NotFoundError,
"Web Bluetooth API globally disabled.");
MAP_ERROR(CHOOSER_NOT_SHOWN_API_LOCALLY_DISABLED, NotFoundError,
"User or their enterprise policy has disabled Web Bluetooth.");
MAP_ERROR(
CHOOSER_NOT_SHOWN_USER_DENIED_PERMISSION_TO_SCAN, NotFoundError,
"User denied the browser permission to scan for Bluetooth devices.");
MAP_ERROR(SERVICE_NOT_FOUND, NotFoundError,
"No Services with specified UUID found in Device.");
MAP_ERROR(NO_SERVICES_FOUND, NotFoundError,
"No Services found in device.");
MAP_ERROR(CHARACTERISTIC_NOT_FOUND, NotFoundError,
"No Characteristics with specified UUID found in Service.");
MAP_ERROR(NO_CHARACTERISTICS_FOUND, NotFoundError,
"No Characteristics found in service.");
MAP_ERROR(BLUETOOTH_LOW_ENERGY_NOT_AVAILABLE, NotFoundError,
"Bluetooth Low Energy not available.");
// NotSupportedErrors:
MAP_ERROR(GATT_UNKNOWN_ERROR, NotSupportedError, "GATT Error Unknown.");
MAP_ERROR(GATT_UNKNOWN_FAILURE, NotSupportedError,
"GATT operation failed for unknown reason.");
MAP_ERROR(GATT_NOT_PERMITTED, NotSupportedError,
"GATT operation not permitted.");
MAP_ERROR(GATT_NOT_SUPPORTED, NotSupportedError,
"GATT Error: Not supported.");
MAP_ERROR(GATT_UNTRANSLATED_ERROR_CODE, NotSupportedError,
"GATT Error: Unknown GattErrorCode.");
// SecurityErrors:
MAP_ERROR(GATT_NOT_AUTHORIZED, SecurityError,
"GATT operation not authorized.");
MAP_ERROR(BLOCKLISTED_CHARACTERISTIC_UUID, SecurityError,
"getCharacteristic(s) called with blocklisted UUID. "
"https://goo.gl/4NeimX");
MAP_ERROR(BLOCKLISTED_READ, SecurityError,
"readValue() called on blocklisted object marked "
"exclude-reads. https://goo.gl/4NeimX");
MAP_ERROR(BLOCKLISTED_WRITE, SecurityError,
"writeValue() called on blocklisted object marked "
"exclude-writes. https://goo.gl/4NeimX");
MAP_ERROR(NOT_ALLOWED_TO_ACCESS_ANY_SERVICE, SecurityError,
"Origin is not allowed to access any service. Tip: Add the "
"service UUID to 'optionalServices' in requestDevice() "
"options. https://goo.gl/HxfxSQ");
MAP_ERROR(NOT_ALLOWED_TO_ACCESS_SERVICE, SecurityError,
"Origin is not allowed to access the service. Tip: Add the "
"service UUID to 'optionalServices' in requestDevice() "
"options. https://goo.gl/HxfxSQ");
MAP_ERROR(REQUEST_DEVICE_WITH_BLOCKLISTED_UUID, SecurityError,
"requestDevice() called with a filter containing a blocklisted "
"UUID. https://goo.gl/4NeimX");
MAP_ERROR(REQUEST_DEVICE_FROM_CROSS_ORIGIN_IFRAME, SecurityError,
"requestDevice() called from cross-origin iframe.");
MAP_ERROR(REQUEST_DEVICE_WITHOUT_FRAME, SecurityError,
"No window to show the requestDevice() dialog.");
#undef MAP_ERROR
}
ASSERT_NOT_REACHED();
return DOMException::create(UnknownError);
}
} // namespace blink
| 50.074324 | 91 | 0.682229 | [
"object"
] |
cd7126406416831a88870677389fb78cb50c9023 | 5,337 | cpp | C++ | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferizePass.cpp | MikeDvorskiy/llvm | 8213321ebb90110bf4f3d04fa0dc8e131a464a19 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferizePass.cpp | MikeDvorskiy/llvm | 8213321ebb90110bf4f3d04fa0dc8e131a464a19 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Linalg/Transforms/ComprehensiveBufferizePass.cpp | MikeDvorskiy/llvm | 8213321ebb90110bf4f3d04fa0dc8e131a464a19 | [
"Apache-2.0"
] | null | null | null | //===- ComprehensiveBufferize.cpp - Single pass bufferization -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "PassDetail.h"
#include "mlir/Dialect/Arithmetic/Transforms/BufferizableOpInterfaceImpl.h"
#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
#include "mlir/Dialect/Linalg/ComprehensiveBufferize/AffineInterfaceImpl.h"
#include "mlir/Dialect/Linalg/ComprehensiveBufferize/LinalgInterfaceImpl.h"
#include "mlir/Dialect/Linalg/ComprehensiveBufferize/ModuleBufferization.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/SCF/BufferizableOpInterfaceImpl.h"
#include "mlir/Dialect/Tensor/Transforms/BufferizableOpInterfaceImpl.h"
#include "mlir/Dialect/Vector/Transforms/BufferizableOpInterfaceImpl.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
#include "mlir/Transforms/Passes.h"
using namespace mlir;
using namespace mlir::bufferization;
using namespace mlir::linalg;
using namespace mlir::linalg::comprehensive_bufferize;
namespace {
struct LinalgComprehensiveModuleBufferize
: public LinalgComprehensiveModuleBufferizeBase<
LinalgComprehensiveModuleBufferize> {
LinalgComprehensiveModuleBufferize() = default;
LinalgComprehensiveModuleBufferize(
const LinalgComprehensiveModuleBufferize &p) = default;
explicit LinalgComprehensiveModuleBufferize(
AnalysisBufferizationOptions options)
: options(options) {}
void runOnOperation() override;
void getDependentDialects(DialectRegistry ®istry) const override {
registry
.insert<bufferization::BufferizationDialect, linalg::LinalgDialect,
memref::MemRefDialect, tensor::TensorDialect,
vector::VectorDialect, scf::SCFDialect,
arith::ArithmeticDialect, StandardOpsDialect, AffineDialect>();
affine_ext::registerBufferizableOpInterfaceExternalModels(registry);
arith::registerBufferizableOpInterfaceExternalModels(registry);
linalg_ext::registerBufferizableOpInterfaceExternalModels(registry);
scf::registerBufferizableOpInterfaceExternalModels(registry);
std_ext::registerModuleBufferizationExternalModels(registry);
tensor::registerBufferizableOpInterfaceExternalModels(registry);
vector::registerBufferizableOpInterfaceExternalModels(registry);
}
private:
llvm::Optional<AnalysisBufferizationOptions> options;
};
} // namespace
static void applyEnablingTransformations(ModuleOp moduleOp) {
RewritePatternSet patterns(moduleOp.getContext());
patterns.add<GeneralizePadOpPattern>(moduleOp.getContext());
(void)applyPatternsAndFoldGreedily(moduleOp, std::move(patterns));
}
static FailureOr<Value> allocationFnUsingAlloca(OpBuilder &b, Location loc,
MemRefType type,
ValueRange dynShape,
unsigned int bufferAlignment) {
Value allocated = b.create<memref::AllocaOp>(
loc, type, dynShape, b.getI64IntegerAttr(bufferAlignment));
return allocated;
}
void LinalgComprehensiveModuleBufferize::runOnOperation() {
AnalysisBufferizationOptions opt;
if (!options) {
// Make new bufferization options if none were provided when creating the
// pass.
if (useAlloca) {
opt.allocationFn = allocationFnUsingAlloca;
opt.deallocationFn = [](OpBuilder &b, Location loc, Value v) {
return success();
};
}
opt.allowReturnMemref = allowReturnMemref;
opt.allowUnknownOps = allowUnknownOps;
opt.analysisFuzzerSeed = analysisFuzzerSeed;
opt.createDeallocs = createDeallocs;
opt.fullyDynamicLayoutMaps = fullyDynamicLayoutMaps;
opt.printConflicts = printConflicts;
opt.testAnalysisOnly = testAnalysisOnly;
if (initTensorElimination) {
opt.addPostAnalysisStep(
linalg_ext::insertSliceAnchoredInitTensorEliminationStep);
}
} else {
opt = *options;
}
// Only certain scf.for ops are supported by the analysis.
opt.addPostAnalysisStep(scf::assertScfForAliasingProperties);
ModuleOp moduleOp = getOperation();
applyEnablingTransformations(moduleOp);
if (failed(runModuleBufferize(moduleOp, opt))) {
signalPassFailure();
return;
}
if (opt.testAnalysisOnly)
return;
OpPassManager cleanupPipeline("builtin.module");
cleanupPipeline.addPass(createCanonicalizerPass());
cleanupPipeline.addPass(createCSEPass());
cleanupPipeline.addPass(createLoopInvariantCodeMotionPass());
(void)runPipeline(cleanupPipeline, moduleOp);
}
std::unique_ptr<Pass> mlir::createLinalgComprehensiveModuleBufferizePass() {
return std::make_unique<LinalgComprehensiveModuleBufferize>();
}
std::unique_ptr<Pass> mlir::createLinalgComprehensiveModuleBufferizePass(
const AnalysisBufferizationOptions &options) {
return std::make_unique<LinalgComprehensiveModuleBufferize>(options);
}
| 38.956204 | 80 | 0.746674 | [
"vector"
] |
cd7271cd465ddee611a44c24ab018ccf55dcd357 | 33,798 | cpp | C++ | 10.02_devices/2_src/uda.cpp | jks-prv/QUniBone | 090b400db2d00694873e0f268a18b8ccf662386e | [
"BSD-2-Clause"
] | null | null | null | 10.02_devices/2_src/uda.cpp | jks-prv/QUniBone | 090b400db2d00694873e0f268a18b8ccf662386e | [
"BSD-2-Clause"
] | null | null | null | 10.02_devices/2_src/uda.cpp | jks-prv/QUniBone | 090b400db2d00694873e0f268a18b8ccf662386e | [
"BSD-2-Clause"
] | null | null | null | /*
uda.cpp: Implementation of the MSCP port (qunibus interface).
Copyright Vulcan Inc. 2019 via Living Computers: Museum + Labs, Seattle, WA.
Contributed under the BSD 2-clause license.
This provides logic for the UDA50's SA and IP registers,
the four-step initialization handshake, DMA transfers to and
from the Qbus/Unibus, and the command/response ring protocols.
While the name "UDA" is used here, this is not a strict emulation
of a real UDA50 -- it is a general MSCP implementation and can be
thought of as the equivalent of the third-party MSCP controllers
from Emulex, CMD, etc. that were available.
At this time this class acts as the port for an MSCP controller.
It would be trivial to extend this to TMSCP at a future date.
*/
#include <string.h>
#include <assert.h>
#include "logger.hpp"
#include "gpios.hpp" // debug pin
#include "qunibus.h"
#include "qunibusadapter.hpp"
#include "qunibusdevice.hpp"
#include "storagecontroller.hpp"
#include "mscp_drive.hpp"
#include "uda.hpp"
uda_c::uda_c() :
storagecontroller_c(),
_server(nullptr),
_ringBase(0),
_commandRingLength(0),
_responseRingLength(0),
_commandRingPointer(0),
_responseRingPointer(0),
_interruptVector(0),
_interruptEnable(false),
_purgeInterruptEnable(false),
_step1Value(0),
_initStep(InitializationStep::Uninitialized),
_next_step(false)
{
name.value = "uda";
type_name.value = "UDA50";
log_label = "uda";
// base addr, intr-vector, intr level
set_default_bus_params(0772150, 20, 0154, 5) ;
// The UDA50 controller has two registers.
register_count = 2;
IP_reg = &(this->registers[0]); // @ base addr
strcpy(IP_reg->name, "IP");
IP_reg->active_on_dati = true;
IP_reg->active_on_dato = true;
IP_reg->reset_value = 0;
IP_reg->writable_bits = 0xffff;
SA_reg = &(this->registers[1]); // @ base addr + 2
strcpy(SA_reg->name, "SA");
SA_reg->active_on_dati = false;
SA_reg->active_on_dato = true;
SA_reg->reset_value = 0;
SA_reg->writable_bits = 0xffff;
_server.reset(new mscp_server(this));
//
// Initialize drives. We support up to eight attached drives.
//
drivecount = DRIVE_COUNT;
for (uint32_t i=0; i<drivecount; i++)
{
mscp_drive_c *drive = new mscp_drive_c(this, i);
drive->unitno.value = i;
drive->name.value = name.value + std::to_string(i);
drive->log_label = drive->name.value;
drive->parent = this;
storagedrives.push_back(drive);
}
}
uda_c::~uda_c()
{
for(uint32_t i=0; i<drivecount; i++)
{
delete storagedrives[i];
}
storagedrives.clear();
}
bool uda_c::on_param_changed(parameter_c *param) {
// no own parameter or "enable" logic
if (param == &priority_slot) {
dma_request.set_priority_slot(priority_slot.new_value);
intr_request.set_priority_slot(priority_slot.new_value);
} else if (param == &intr_level) {
intr_request.set_level(intr_level.new_value);
} else if (param == &intr_vector) {
intr_request.set_vector(intr_vector.new_value);
}
return storagecontroller_c::on_param_changed(param) ; // more actions (for enable)
}
//
// Reset():
// Resets the UDA controller state.
// Resets the attached MSCP server, which may take
// significant time.
//
void uda_c::Reset(void)
{
DEBUG("UDA reset");
_server->Reset();
_ringBase = 0;
_commandRingLength = 0;
_responseRingLength = 0;
_commandRingPointer = 0;
_responseRingPointer = 0;
_interruptVector = 0;
intr_vector.value = 0;
_interruptEnable = false;
_purgeInterruptEnable = false;
}
//
// GetDriveCount():
// Returns the number of drives that can be attached to this controller.
//
uint32_t uda_c::GetDriveCount(void)
{
return drivecount;
}
//
// GetDrive():
// Returns a pointer to an mscp_drive_c object for the specified drive number.
// This pointer is owned by the UDA class.
//
mscp_drive_c* uda_c::GetDrive(
uint32_t driveNumber)
{
assert(driveNumber < drivecount);
return dynamic_cast<mscp_drive_c*>(storagedrives[driveNumber]);
}
//
// StateTransition():
// Transitions the UDA initialization state machine to the specified step,
// atomically.
//
void uda_c::StateTransition(
InitializationStep nextStep)
{
pthread_mutex_lock(&on_after_register_access_mutex);
_initStep = nextStep;
_next_step = true;
pthread_cond_signal(&on_after_register_access_cond);
pthread_mutex_unlock(&on_after_register_access_mutex);
}
//
// worker():
// Implements the initialization state machine.
//
void uda_c::worker(unsigned instance)
{
UNUSED(instance) ; // only one
worker_init_realtime_priority(rt_device);
timeout_c timeout;
while (!workers_terminate)
{
//
// Wait to be awoken.
//
pthread_mutex_lock(&on_after_register_access_mutex);
while (!_next_step)
{
pthread_cond_wait(
&on_after_register_access_cond,
&on_after_register_access_mutex);
}
_next_step = false;
pthread_mutex_unlock(&on_after_register_access_mutex);
switch (_initStep)
{
case InitializationStep::Uninitialized:
DEBUG("Transition to Init state Uninitialized.");
// SA should already be zero but we'll be extra sure here.
update_SA(0x0);
// Reset the controller: This may take some time as we must
// wait for the MSCP server to wrap up its current workitem.
Reset();
StateTransition(InitializationStep::Step1);
break;
case InitializationStep::Step1:
timeout.wait_us(500);
DEBUG("Transition to Init state S1.");
//
// S1 is set, all other bits zero. This indicates that we
// support a host-settable interrupt vector, that we do not
// implement enhanced diagnostics, and that no errors have
// occurred.
//
update_SA(0x0800);
break;
case InitializationStep::Step2:
timeout.wait_us(500);
DEBUG("Transition to Init state S2.");
// Update the SA read value for step 2:
// S2 is set, qunibus port type (0), SA bits 15-8 written
// by the host in step 1.
Interrupt(0x1000 | ((_step1Value >> 8) & 0xff));
break;
case InitializationStep::Step3:
timeout.wait_us(500);
DEBUG("Transition to Init state S3.");
// Update the SA read value for step 3:
// S3 set, plus SA bits 7-0 written by the host in step 1.
Interrupt(0x2000 | (_step1Value & 0xff));
break;
case InitializationStep::Step4:
timeout.wait_us(100);
// Clear communications area, set SA
DEBUG("Clearing comm area at 0x%x. Purge header: %d", _ringBase, _purgeInterruptEnable);
DEBUG("resp 0x%x comm 0x%x", _responseRingLength, _commandRingLength);
{
int headerSize = _purgeInterruptEnable ? 8 : 4;
for(uint32_t i = 0;
i < (_responseRingLength + _commandRingLength) * sizeof(Descriptor) + headerSize;
i += 2)
{
DMAWriteWord(_ringBase + i - headerSize, 0x0);
}
}
//
// Set the ownership bit on all descriptors in the response ring
// to indicate that the port owns them.
//
Descriptor blankDescriptor;
blankDescriptor.Word0.Word0 = 0;
blankDescriptor.Word1.Word1 = 0;
blankDescriptor.Word1.Fields.Ownership = 1;
for(uint32_t i = 0; i < _responseRingLength; i++)
{
DMAWrite(
GetResponseDescriptorAddress(i),
sizeof(Descriptor),
reinterpret_cast<uint8_t*>(&blankDescriptor));
}
DEBUG("Transition to Init state S4, comm area initialized.");
// Update the SA read value for step 4:
// Bits 7-0 indicating our control microcode version.
Interrupt(UDA50_ID); // UDA50 ID, makes RSTS happy
break;
case InitializationStep::Complete:
DEBUG("Initialization complete.");
break;
}
}
}
//
// on_after_register_access():
// Handles register accesses for the IP and SA registers.
//
void
uda_c::on_after_register_access(
qunibusdevice_register_t *device_reg,
uint8_t unibus_control
)
{
switch (device_reg->index)
{
case 0: // IP - read / write
if (QUNIBUS_CYCLE_DATO == unibus_control)
{
// "When written with any value, it causes a hard initialization
// of the port and the device controller."
DEBUG("Reset due to IP read");
update_SA(0x0);
StateTransition(InitializationStep::Uninitialized);
}
else
{
// "When read while the port is operating, it causes the controller
// to initiate polling..."
if (_initStep == InitializationStep::Complete)
{
DEBUG("Request to start polling.");
_server->InitPolling();
}
}
break;
case 1: // SA - write only
uint16_t value = SA_reg->active_dato_flipflops;
switch (_initStep)
{
case InitializationStep::Uninitialized:
// Should not occur, we treat it like step1 here.
DEBUG("Write to SA in Uninitialized state.");
case InitializationStep::Step1:
// Host writes the following:
// 15 13 11 10 8 7 6 0
// +-+-+-----+-----+-+-------------+
// |1|W|c rng|r rng|I| int vector |
// | |R| lng | lng |E|(address / 4)|
// +-+-+-----+-----+-+-------------+
// WR = 1 tells the port to enter diagnostic wrap
// mode (which we ignore).
//
// c rng lng is the number of slots (32 bits each)
// in the command ring, expressed as a power of two.
//
// r rng lng is as above, but for the response ring.
//
// IE=1 means the host is requesting an interrupt
// at the end of the completion of init steps 1-3.
//
// int vector determines if interrupts will be generated
// by the port. If this field is non-zero, interupts will
// be generated during normal operation and, if IE=1,
// during initialization.
_step1Value = value;
_interruptVector = ((value & 0x7f) << 2);
intr_request.set_vector(_interruptVector);
_interruptEnable = !!(value & 0x80);
_responseRingLength = (1 << ((value & 0x700) >> 8));
_commandRingLength = (1 << ((value & 0x3800) >> 11));
DEBUG("Step1: 0x%x", value);
DEBUG("resp ring 0x%x", _responseRingLength);
DEBUG("cmd ring 0x%x", _commandRingLength);
DEBUG("vector 0x%x", _interruptVector);
DEBUG("ie %d", _interruptEnable);
// Move to step 2.
StateTransition(InitializationStep::Step2);
break;
case InitializationStep::Step2:
// Host writes the following:
// 15 1 0
// +-----------------------------+-+
// | ringbase low |P|
// | (address) |I|
// +-----------------------------+-+
// ringbase low is the low-order portion of word
// [ringbase+0] of the communications area. This is a
// 16-bit byte address whose low-order bit is zero implicitly.
//
_ringBase = value & 0xfffe;
_purgeInterruptEnable = !!(value & 0x1);
DEBUG("Step2: rb 0x%x pi %d", _ringBase, _purgeInterruptEnable);
// Move to step 3 and interrupt as necessary.
StateTransition(InitializationStep::Step3);
break;
case InitializationStep::Step3:
// Host writes the following:
// 15 0
// +-+-----------------------------+
// |P| ringbase hi |
// |P| (address) |
// +-+-----------------------------+
// PP = 1 means the host is requesting execution of
// purge and poll tests, which we ignore because we can.
//
// ringbase hi is the high-order portion of the address
// [ringbase+0].
_ringBase |= ((value & 0x7fff) << 16);
DEBUG("Step3: ringbase 0x%x", _ringBase);
// Move to step 4 and interrupt as necessary.
StateTransition(InitializationStep::Step4);
break;
case InitializationStep::Step4:
// Host writes the following:
// 15 8 7 1 0
// +---------------+-----------+-+-+
// | reserved | burst |L|G|
// | | |F|O|
// +---------------+-----------+-+-+
// Burst is one less than the max. number of longwords
// the host is willing to allow per DMA transfer.
// If zero, the port uses its default burst count.
//
// LF=1 means that the host wants a "last fail" response
// packet when initialization is complete.
//
// GO=1 means that the controller should enter its functional
// microcode as soon as initialization completes.
//
// Note that if GO=0 when initialization completes, the port
// will continue to read SA until the host forces SA bit 0 to
// make the transition 0->1.
//
// There is no explicit interrupt at the end of Step 4.
//
// TODO: For now we ignore burst settings.
// We also ignore Last Fail report requests since we aren't
// supporting onboard diagnostics and there's nothing to
// report.
//
DEBUG("Step4: 0x%x", value);
if (value & 0x1)
{
//
// GO is set, move to the Complete state. The worker will
// start the controller running.
//
StateTransition(InitializationStep::Complete);
// The VMS bootstrap expects SA to be zero IMMEDIATELY
// after completion.
update_SA(0x0);
}
else
{
// GO unset, wait until it is.
}
break;
case InitializationStep::Complete:
// "When zeroed by the host during both initialization and normal
// operation, it signals the port that the host has successfully
// completed a bus adapter purge in response to a port-initiated
// purge request.
// We don't deal with bus adapter purges, yet.
break;
}
break;
}
}
//
// update_SA():
// Updates the SA register value exposed by the Unibone.
//
void
uda_c::update_SA(uint16_t value)
{
set_register_dati_value(
SA_reg,
value,
"update_SA");
}
//
// GetNextCommand():
// Attempts to pull the next command from the command ring, if any
// are available.
// If successful, returns a pointer to a Message struct; this pointer
// is owned by the caller.
// On failure, nullptr is returned. This indicates that the ring is
// empty or that an attempt to access non-existent memory occurred.
// TODO: Need to handle NXM cases properly.
//
Message*
uda_c::GetNextCommand(void)
{
timeout_c timer;
// Grab the next descriptor being pointed to
uint32_t descriptorAddress =
GetCommandDescriptorAddress(_commandRingPointer);
DEBUG("Next descriptor (ring ptr 0x%x) address is o%o",
_commandRingPointer,
descriptorAddress);
std::unique_ptr<Descriptor> cmdDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
descriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
// TODO: if NULL is returned after retry assume a bus error and handle it appropriately.
assert(cmdDescriptor != nullptr);
// Check owner bit: if set, ownership has been passed to us, in which case
// we can attempt to pull the actual message from memory.
if (cmdDescriptor->Word1.Fields.Ownership)
{
bool doInterrupt = false;
uint32_t messageAddress =
cmdDescriptor->Word0.EnvelopeLow |
(cmdDescriptor->Word1.Fields.EnvelopeHigh << 16);
DEBUG("Next message address is o%o, flag %d",
messageAddress, cmdDescriptor->Word1.Fields.Flag);
//
// Grab the message length; this is at messageAddress - 4
//
bool success = false;
uint16_t messageLength =
DMAReadWord(
messageAddress - 4,
success);
assert(messageLength > 0 && messageLength < MAX_MESSAGE_LENGTH);
std::unique_ptr<Message> cmdMessage(
reinterpret_cast<Message*>(
DMARead(
messageAddress - 4,
messageLength + 4,
sizeof(Message))));
//
// Handle Ring Transitions (from full to not-full) and associated
// interrupts.
// If the previous entry in the ring is owned by the Port then that indicates
// that the ring was previously full (i.e. the descriptor we're now returning
// is the first free entry.)
//
if (cmdDescriptor->Word1.Fields.Flag)
{
//
// Flag is set, host is requesting a transition interrupt.
// Check the previous entry in the ring.
//
if (_commandRingLength == 1)
{
// Degenerate case: If the ring is of size 1 we always interrupt.
doInterrupt = true;
}
else
{
uint32_t previousDescriptorAddress =
GetCommandDescriptorAddress(
(_commandRingPointer - 1) % _commandRingLength);
std::unique_ptr<Descriptor> previousDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
previousDescriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
if (previousDescriptor->Word1.Fields.Ownership)
{
// We own the previous descriptor, so the ring was previously
// full.
doInterrupt = true;
}
}
}
//
// Message retrieved; reset the Owner bit of the command descriptor,
// set the Flag bit (to indicate that we've processed it)
// and return a pointer to the message.
//
cmdDescriptor->Word1.Fields.Ownership = 0;
cmdDescriptor->Word1.Fields.Flag = 1;
DMAWrite(
descriptorAddress,
sizeof(Descriptor),
reinterpret_cast<uint8_t*>(cmdDescriptor.get()));
//
// Move to the next descriptor in the ring for next time.
_commandRingPointer = (_commandRingPointer + 1) % _commandRingLength;
// Post an interrupt as necessary.
if (doInterrupt)
{
//
// Set ring base - 4 to non-zero to indicate a transition.
//
DMAWriteWord(_ringBase - 4, 0x1);
Interrupt();
}
return cmdMessage.release();
}
DEBUG("No descriptor found. 0x%x 0x%x", cmdDescriptor->Word0.Word0, cmdDescriptor->Word1.Word1);
// No descriptor available.
return nullptr;
}
//
// PostResponse():
// Posts the provided Message to the response ring.
// Returns true on success, false otherwise.
// TODO: Need to handle NXM, as above.
//
bool
uda_c::PostResponse(
Message* response
)
{
bool res = false;
// Grab the next descriptor.
uint32_t descriptorAddress = GetResponseDescriptorAddress(_responseRingPointer);
std::unique_ptr<Descriptor> cmdDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
descriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
// TODO: if NULL is returned assume a bus error and handle it appropriately.
//
// Check owner bit: if set, ownership has been passed to us, in which case
// we can use this descriptor and fill in the response buffer it points to.
// If not, we return false to indicate to the caller the need to try again later.
//
if (cmdDescriptor->Word1.Fields.Ownership)
{
bool doInterrupt = false;
uint32_t messageAddress =
cmdDescriptor->Word0.EnvelopeLow |
(cmdDescriptor->Word1.Fields.EnvelopeHigh << 16);
//
// Read the buffer length the host has allocated for this response.
//
// TODO:
// If it is shorter than the buffer we're writing then we will need to
// split the response into multiple responses. I have never seen this happen,
// however and I'm curious if the documentation (AA-L621A-TK) is simply incorrect:
// "Note that if a controller's responses are less than or equal to 60 bytes,
// then the controller need not check the size of the response slot."
// All of the MSCP response messages are shorter than 60 bytes, so this is always
// the case. I'll also note that the spec states "The minimum acceptable size
// is 60 bytes of message text" for the response buffer set up by the host and this
// is *definitely* not followed by host drivers.
//
// The doc is also not exactly clear what a fragmented set of responses looks like...
//
// Message length is at messageAddress - 4 -- this is the size of the command
// not including the two header words.
//
bool success = false;
uint16_t messageLength =
DMAReadWord(
messageAddress - 4,
success);
DEBUG("response address o%o length o%o", messageAddress, response->MessageLength);
assert(reinterpret_cast<uint16_t*>(response)[0] > 0);
if (messageLength == 0)
{
// A lot of bootstraps appear to set up response buffers of length 0.
// We just log the behavior.
DEBUG("Host response buffer size is zero.");
}
else if (messageLength < response->MessageLength)
{
//
// If this happens it's likely fatal since we're not fragmenting responses (see the big comment
// block above). So eat flaming death.
// Note: the VMS bootstrap does this, so we'll just log the issue.
//
DEBUG("Response buffer 0x%x > host buffer length 0x%x", response->MessageLength, messageLength);
}
//
// This will fit; simply copy the response message over the top
// of the buffer allocated on the host -- this updates the header fields
// as necessary and provides the actual response data to the host.
//
DMAWrite(
messageAddress - 4,
response->MessageLength + 4,
reinterpret_cast<uint8_t*>(response));
//
// Check if a transition from empty to non-empty occurred, interrupt if requested.
//
// If the previous entry in the ring is owned by the Port then that indicates
// that the ring was previously empty (i.e. the descriptor we're now returning
// is the first entry returned to the ring by the Port.)
//
if (cmdDescriptor->Word1.Fields.Flag)
{
//
// Flag is set, host is requesting a transition interrupt.
// Check the previous entry in the ring.
//
if (_responseRingLength == 1)
{
// Degenerate case: If the ring is of size 1 we always interrupt.
doInterrupt = true;
}
else
{
uint32_t previousDescriptorAddress =
GetResponseDescriptorAddress(
(_responseRingPointer - 1) % _responseRingLength);
std::unique_ptr<Descriptor> previousDescriptor(
reinterpret_cast<Descriptor*>(
DMARead(
previousDescriptorAddress,
sizeof(Descriptor),
sizeof(Descriptor))));
if (previousDescriptor->Word1.Fields.Ownership)
{
// We own the previous descriptor, so the ring was previously
// full.
doInterrupt = true;
}
}
}
//
// Message posted; reset the Owner bit of the response descriptor,
// and set the Flag bit (to indicate that we've processed it).
//
cmdDescriptor->Word1.Fields.Ownership = 0;
cmdDescriptor->Word1.Fields.Flag = 1;
DMAWrite(
descriptorAddress,
sizeof(Descriptor),
reinterpret_cast<uint8_t*>(cmdDescriptor.get()));
// Post an interrupt as necessary.
if (doInterrupt)
{
DEBUG("Response ring no longer empty, interrupting.");
//
// Set ring base - 2 to non-zero to indicate a transition.
//
DMAWriteWord(_ringBase - 2, 0x1);
Interrupt();
}
res = true;
// Move to the next descriptor in the ring for next time.
_responseRingPointer = (_responseRingPointer + 1) % _responseRingLength;
}
return res;
}
//
// GetControllerIdentifier():
// Returns the ID used by SET CONTROLLER CHARACTERISTICS.
// This should be unique per controller.
//
uint32_t
uda_c::GetControllerIdentifier()
{
// TODO: make this not hardcoded
// ID 0x12345678
return 0x12345678;
}
//
// GetControllerClassModel():
// Returns the Class and Model information used by SET CONTROLLER CHARACTERISTICS.
//
uint16_t
uda_c::GetControllerClassModel()
{
return 0x0102; // Class 1 (mass storage), model 2 (UDA50)
}
//
// Interrupt():
// Invokes a Qbus/Unibus interrupt if interrupts are enabled and the interrupt
// vector is non-zero. Updates SA to the specified value atomically.
//
void
uda_c::Interrupt(uint16_t sa_value)
{
if ((_interruptEnable || _initStep == InitializationStep::Complete) && _interruptVector != 0)
{
qunibusadapter->INTR(intr_request, SA_reg, sa_value);
}
else
{
update_SA(sa_value);
}
}
//
// Interrupt():
// Invokes a Qbus/Unibus interrupt if interrupts are enabled and the interrupt
// vector is non-zero.
//
void
uda_c::Interrupt(void)
{
if ((_interruptEnable || _initStep == InitializationStep::Complete) && _interruptVector != 0)
{
qunibusadapter->INTR(intr_request, NULL, 0);
}
}
//
// on_power_changed():
// Resets the controller and all attached drives.
//
// after QBUS/UNIBUS install, device is reset by DCLO/DCOK cycle
void
uda_c::on_power_changed(signal_edge_enum aclo_edge, signal_edge_enum dclo_edge)
{
storagecontroller_c::on_power_changed(aclo_edge, dclo_edge);
if (dclo_edge == SIGNAL_EDGE_RAISING)
{
DEBUG("Reset due to power change");
StateTransition(InitializationStep::Uninitialized);
}
}
//
// on_init_changed():
// Resets the controller and all attached drives.
//
void
uda_c::on_init_changed(void)
{
if (init_asserted)
{
DEBUG("Reset due to INIT");
StateTransition(InitializationStep::Uninitialized);
}
storagecontroller_c::on_init_changed();
}
//
// on_drive_status_changed():
// A no-op. The controller doesn't require any drive notifications.
//
void
uda_c::on_drive_status_changed(storagedrive_c *drive)
{
UNUSED(drive);
}
//
// GetCommandDescriptorAddress():
// Returns the address of the given command descriptor in the command ring.
//
uint32_t
uda_c::GetCommandDescriptorAddress(
size_t index
)
{
return _ringBase + _responseRingLength * sizeof(Descriptor) +
index * sizeof(Descriptor);
}
//
// GetResponseDescriptorAddress():
// Returns the address of the given response descriptor in the response ring.
//
uint32_t
uda_c::GetResponseDescriptorAddress(
size_t index
)
{
return _ringBase + index * sizeof(Descriptor);
}
//
// DMAWriteWord():
// Writes a single word to Qbus/Unibus memory. Returns true
// on success; if false is returned this is due to an NXM condition.
//
bool
uda_c::DMAWriteWord(
uint32_t address,
uint16_t word)
{
return DMAWrite(
address,
sizeof(uint16_t),
reinterpret_cast<uint8_t*>(&word));
}
//
// DMAReadWord():
// Read a single word from Qbus/Unibus memory. Returns the word read on success.
// the success field indicates the success or failure of the read.
//
uint16_t
uda_c::DMAReadWord(
uint32_t address,
bool& success)
{
uint8_t* buffer = DMARead(
address,
sizeof(uint16_t),
sizeof(uint16_t));
if (buffer)
{
success = true;
uint16_t retval = *reinterpret_cast<uint16_t *>(buffer);
delete[] buffer;
return retval;
}
else
{
success = false;
return 0;
}
}
//
// DMAWrite():
// Write data from the provided buffer to Qbus/Unibus memory. Returns true
// on success; if false is returned this is due to an NXM condition.
// The address specified in 'address' must be word-aligned and the
// length must be even.
//
bool
uda_c::DMAWrite(
uint32_t address,
size_t lengthInBytes,
uint8_t* buffer)
{
assert ((lengthInBytes % 2) == 0);
// if (address >= 0x40000)
// logger->dump(logger->default_filepath) ;
assert (address < 2* qunibus->addr_space_word_count); // exceeds address space? test for IOpage too?
// assert (address < 0x40000);
qunibusadapter->DMA(dma_request, true,
QUNIBUS_CYCLE_DATO,
address,
reinterpret_cast<uint16_t*>(buffer),
lengthInBytes >> 1);
return dma_request.success ;
}
//
// DMARead():
// Read data from Qbus/Unibus memory into the returned buffer.
// Buffer returned is nullptr if memory could not be read.
// Caller is responsible for freeing the buffer when done.
// The address specified in 'address' must be word-aligned
// and the length must be even.
//
uint8_t*
uda_c::DMARead(
uint32_t address,
size_t lengthInBytes,
size_t bufferSize)
{
assert (bufferSize >= lengthInBytes);
assert((lengthInBytes % 2) == 0);
assert (address < 2* qunibus->addr_space_word_count); // exceeds address space? test for IOpage too?
// assert (address < 0x40000);
uint16_t* buffer = new uint16_t[bufferSize >> 1];
assert(buffer);
memset(reinterpret_cast<uint8_t*>(buffer), 0xc3, bufferSize);
qunibusadapter->DMA(dma_request, true,
QUNIBUS_CYCLE_DATI,
address,
buffer,
lengthInBytes >> 1);
if (dma_request.success)
{
return reinterpret_cast<uint8_t*>(buffer);
}
else
{
return nullptr;
}
}
| 33.005859 | 108 | 0.553287 | [
"object",
"vector",
"model"
] |
cd73302619a9061162fa3559d39677c452c24197 | 12,115 | hpp | C++ | src/benchmarks/clsparse-bench/functions/clfunc_xSpMSpM.hpp | xfong/clSPARSE | fa026dcb99a374678624530dff041322d67e0630 | [
"Apache-2.0"
] | 164 | 2015-08-03T21:53:40.000Z | 2022-03-31T14:58:11.000Z | src/benchmarks/clsparse-bench/functions/clfunc_xSpMSpM.hpp | xfong/clSPARSE | fa026dcb99a374678624530dff041322d67e0630 | [
"Apache-2.0"
] | 94 | 2015-08-04T15:49:30.000Z | 2021-02-01T14:28:35.000Z | src/benchmarks/clsparse-bench/functions/clfunc_xSpMSpM.hpp | xfong/clSPARSE | fa026dcb99a374678624530dff041322d67e0630 | [
"Apache-2.0"
] | 76 | 2015-08-04T00:00:44.000Z | 2021-09-17T17:53:06.000Z | /* ************************************************************************
* Copyright 2015 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ************************************************************************ */
#pragma once
#ifndef CLSPARSE_BENCHMARK_SpM_SpM_HXX
#define CLSPARSE_BENCHMARK_SpM_SpM_HXX
#include "clSPARSE.h"
#include "clfunc_common.hpp"
// Dummy Code to be deleted later
clsparseStatus clsparseDcsrSpGemm(const clsparseCsrMatrix* sparseMatA, const clsparseCsrMatrix* sparseMatB, clsparseCsrMatrix* sparseMatC, const clsparseControl control)
{
std::cout << "sparseMat A dimensions = \n";
std::cout << " rows = " << sparseMatA->num_rows << std::endl;
std::cout << " cols = " << sparseMatA->num_cols << std::endl;
std::cout << "nnz = " << sparseMatA->num_nonzeros << std::endl;
std::cout << "sparseMat B dimensions = \n";
std::cout << " rows = " << sparseMatB->num_rows << std::endl;
std::cout << " cols = " << sparseMatB->num_cols << std::endl;
std::cout << "nnz = " << sparseMatB->num_nonzeros << std::endl;
return clsparseSuccess;
}//
// Dummy code ends
template <typename T>
class xSpMSpM : public clsparseFunc {
public:
xSpMSpM(PFCLSPARSETIMER sparseGetTimer, size_t profileCount, cl_device_type devType, cl_bool keep_explicit_zeroes = true) : clsparseFunc(devType, CL_QUEUE_PROFILING_ENABLE), gpuTimer(nullptr), cpuTimer(nullptr)
{
// Create and initialize our timer class, if the external timer shared library loaded
if (sparseGetTimer)
{
gpuTimer = sparseGetTimer(CLSPARSE_GPU);
gpuTimer->Reserve(1, profileCount);
gpuTimer->setNormalize(true);
cpuTimer = sparseGetTimer(CLSPARSE_CPU);
cpuTimer->Reserve(1, profileCount);
cpuTimer->setNormalize(true);
gpuTimerID = gpuTimer->getUniqueID("GPU xSpMSpM", 0);
cpuTimerID = cpuTimer->getUniqueID("CPU xSpMSpM", 0);
}
clsparseEnableAsync(control, false);
explicit_zeroes = keep_explicit_zeroes;
}
~xSpMSpM() {}
void call_func()
{
if (gpuTimer && cpuTimer)
{
gpuTimer->Start(gpuTimerID);
cpuTimer->Start(cpuTimerID);
xSpMSpM_Function(false);
cpuTimer->Stop(cpuTimerID);
gpuTimer->Stop(gpuTimerID);
}
else
{
xSpMSpM_Function(false);
}
}//
double gflops()
{
return 0.0;
}
std::string gflops_formula()
{
return "N/A";
}
double bandwidth() // Need to modify this later **********
{
// Assuming that accesses to the vector always hit in the cache after the first access
// There are NNZ integers in the cols[ ] array
// You access each integer value in row_delimiters[ ] once.
// There are NNZ float_types in the vals[ ] array
// You read num_cols floats from the vector, afterwards they cache perfectly.
// Finally, you write num_rows floats out to DRAM at the end of the kernel.
return (sizeof(clsparseIdx_t)*(csrMtx.num_nonzeros + csrMtx.num_rows) + sizeof(T) * (csrMtx.num_nonzeros + csrMtx.num_cols + csrMtx.num_rows)) / time_in_ns();
} // end of function
std::string bandwidth_formula()
{
return "GiB/s";
}// end of function
void setup_buffer(double pAlpha, double pBeta, const std::string& path)
{
sparseFile = path;
alpha = static_cast<T>(pAlpha);
beta = static_cast<T>(pBeta);
// Read sparse data from file and construct a COO matrix from it
clsparseIdx_t nnz, row, col;
clsparseStatus fileError = clsparseHeaderfromFile(&nnz, &row, &col, sparseFile.c_str());
if (fileError != clsparseSuccess)
throw clsparse::io_exception("Could not read matrix market header from disk");
// Now initialize a CSR matrix from the COO matrix
clsparseInitCsrMatrix(&csrMtx);
csrMtx.num_nonzeros = nnz;
csrMtx.num_rows = row;
csrMtx.num_cols = col;
//clsparseCsrMetaSize(&csrMtx, control);
cl_int status;
csrMtx.values = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
csrMtx.num_nonzeros * sizeof(T), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.values");
csrMtx.col_indices = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
csrMtx.num_nonzeros * sizeof(clsparseIdx_t), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.col_indices");
csrMtx.row_pointer = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
(csrMtx.num_rows + 1) * sizeof(clsparseIdx_t), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.row_pointer");
#if 0
csrMtx.rowBlocks = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
csrMtx.rowBlockSize * sizeof(cl_ulong), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer csrMtx.rowBlocks");
#endif
if (typeid(T) == typeid(float))
fileError = clsparseSCsrMatrixfromFile( &csrMtx, sparseFile.c_str(), control, explicit_zeroes );
else if (typeid(T) == typeid(double))
fileError = clsparseDCsrMatrixfromFile( &csrMtx, sparseFile.c_str(), control, explicit_zeroes );
else
fileError = clsparseInvalidType;
if (fileError != clsparseSuccess)
throw clsparse::io_exception("Could not read matrix market data from disk");
// Initilize the output CSR Matrix
clsparseInitCsrMatrix(&csrMtxC);
// Initialize the scalar alpha & beta parameters
clsparseInitScalar(&a);
a.value = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
1 * sizeof(T), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer a.value");
clsparseInitScalar(&b);
b.value = ::clCreateBuffer(ctx, CL_MEM_READ_ONLY,
1 * sizeof(T), NULL, &status);
CLSPARSE_V(status, "::clCreateBuffer b.value");
//std::cout << "Flops = " << xSpMSpM_Getflopcount() << std::endl;
flopCnt = xSpMSpM_Getflopcount();
}// end of function
void initialize_cpu_buffer()
{
}
void initialize_gpu_buffer()
{
CLSPARSE_V(::clEnqueueFillBuffer(queue, a.value, &alpha, sizeof(T), 0,
sizeof(T) * 1, 0, NULL, NULL), "::clEnqueueFillBuffer alpha.value");
CLSPARSE_V(::clEnqueueFillBuffer(queue, b.value, &beta, sizeof(T), 0,
sizeof(T) * 1, 0, NULL, NULL), "::clEnqueueFillBuffer beta.value");
}// end of function
void reset_gpu_write_buffer()
{
// Every call to clsparseScsrSpGemm() allocates memory to csrMtxC, therefore freeing the memory
CLSPARSE_V(::clReleaseMemObject(csrMtxC.values), "clReleaseMemObject csrMtxC.values");
CLSPARSE_V(::clReleaseMemObject(csrMtxC.col_indices), "clReleaseMemObject csrMtxC.col_indices");
CLSPARSE_V(::clReleaseMemObject(csrMtxC.row_pointer), "clReleaseMemObject csrMtxC.row_pointer");
// Initilize the output CSR Matrix
clsparseInitCsrMatrix(&csrMtxC);
}// end of function
void read_gpu_buffer()
{
}
void cleanup()
{
if (gpuTimer && cpuTimer)
{
std::cout << "clSPARSE matrix: " << sparseFile << std::endl;
cpuTimer->pruneOutliers(3.0);
cpuTimer->Print(flopCnt, "GFlop/s");
cpuTimer->Reset();
gpuTimer->pruneOutliers(3.0);
gpuTimer->Print(flopCnt, "GFlop/s");
gpuTimer->Reset();
}
//this is necessary since we are running a iteration of tests and calculate the average time. (in client.cpp)
//need to do this before we eventually hit the destructor
CLSPARSE_V(::clReleaseMemObject(csrMtx.values), "clReleaseMemObject csrMtx.values");
CLSPARSE_V(::clReleaseMemObject(csrMtx.col_indices), "clReleaseMemObject csrMtx.col_indices");
CLSPARSE_V(::clReleaseMemObject(csrMtx.row_pointer), "clReleaseMemObject csrMtx.row_pointer");
//CLSPARSE_V(::clReleaseMemObject(csrMtx.rowBlocks), "clReleaseMemObject csrMtx.rowBlocks");
if (csrMtxC.values != nullptr)
CLSPARSE_V(::clReleaseMemObject(csrMtxC.values), "clReleaseMemObject csrMtxC.values");
if (csrMtxC.col_indices != nullptr)
CLSPARSE_V(::clReleaseMemObject(csrMtxC.col_indices), "clReleaseMemObject csrMtxC.col_indices");
if (csrMtxC.row_pointer != nullptr)
CLSPARSE_V(::clReleaseMemObject(csrMtxC.row_pointer), "clReleaseMemObject csrMtxC.row_pointer");
//CLSPARSE_V(::clReleaseMemObject(csrMtxC.rowBlocks), "clReleaseMemObject csrMtxC.rowBlocks");
CLSPARSE_V(::clReleaseMemObject(a.value), "clReleaseMemObject alpha.value");
CLSPARSE_V(::clReleaseMemObject(b.value), "clReleaseMemObject beta.value");
}
private:
void xSpMSpM_Function(bool flush);
clsparseIdx_t xSpMSpM_Getflopcount(void)
{
// C = A * B
// But here C = A* A, the A & B matrices are same
clsparseIdx_t nnzA = csrMtx.num_nonzeros;
clsparseIdx_t Browptrlen = csrMtx.num_rows + 1; // Number of row offsets
std::vector<clsparseIdx_t> colIdxA(nnzA, 0);
std::vector<clsparseIdx_t> rowptrB(Browptrlen, 0);
cl_int run_status = 0;
run_status = clEnqueueReadBuffer(queue,
csrMtx.col_indices,
CL_TRUE, 0,
nnzA*sizeof(clsparseIdx_t),
colIdxA.data(), 0, nullptr, nullptr);
CLSPARSE_V(run_status, "Reading col_indices from GPU failed");
// copy rowptrs
run_status = clEnqueueReadBuffer(queue,
csrMtx.row_pointer,
CL_TRUE, 0,
Browptrlen*sizeof(clsparseIdx_t),
rowptrB.data(), 0, nullptr, nullptr);
CLSPARSE_V(run_status, "Reading row offsets from GPU failed");
clsparseIdx_t flop = 0;
for (clsparseIdx_t i = 0; i < nnzA; i++)
{
clsparseIdx_t colIdx = colIdxA[i]; // Get colIdx of A
flop += rowptrB[colIdx + 1] - rowptrB[colIdx]; // nnz in 'colIdx'th row of B
}
flop = 2 * flop; // Two operations - Multiply & Add
return flop;
}// end of function
// Timers we want to keep
clsparseTimer* gpuTimer;
clsparseTimer* cpuTimer;
size_t gpuTimerID;
size_t cpuTimerID;
std::string sparseFile;
//device values
clsparseCsrMatrix csrMtx; // input matrix
clsparseCsrMatrix csrMtxC; // Output CSR MAtrix
clsparseScalar a;
clsparseScalar b;
// host values
T alpha;
T beta;
clsparseIdx_t flopCnt; // Indicates total number of floating point operations
cl_bool explicit_zeroes;
// OpenCL state
//cl_command_queue_properties cqProp;
}; // class xSpMSpM
template<> void
xSpMSpM<float>::xSpMSpM_Function(bool flush)
{
clsparseStatus status = clsparseScsrSpGemm(&csrMtx, &csrMtx, &csrMtxC, control);
if (flush)
clFinish(queue);
}// end of single precision function
template<> void
xSpMSpM<double>::xSpMSpM_Function(bool flush)
{
clsparseStatus status = clsparseDcsrSpGemm(&csrMtx, &csrMtx, &csrMtxC, control);
if (flush)
clFinish(queue);
}
#endif // CLSPARSE_BENCHMARK_SpM_SpM_HXX
| 36.935976 | 214 | 0.625175 | [
"vector"
] |
cd768c1fbd80cfd522bb710bdaf8d2865ec27434 | 1,290 | hpp | C++ | src/webots/user_commands/WbResizeCommand.hpp | yjf18340/webots | 60d441c362031ab8fde120cc0cd97bdb1a31a3d5 | [
"Apache-2.0"
] | 1 | 2019-11-13T08:12:02.000Z | 2019-11-13T08:12:02.000Z | src/webots/user_commands/WbResizeCommand.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | null | null | null | src/webots/user_commands/WbResizeCommand.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | 1 | 2020-09-25T02:01:45.000Z | 2020-09-25T02:01:45.000Z | // Copyright 1996-2019 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef WB_RESIZE_COMMAND_HPP
#define WB_RESIZE_COMMAND_HPP
//
// Description: Representation of 'resize' and 'rescale' actions on geometries
// and definition of respective undo and redo functions
//
#include "WbVector3.hpp"
#include <QtWidgets/QUndoCommand>
class WbGeometry;
class WbResizeCommand : public QUndoCommand {
public:
WbResizeCommand(WbGeometry *geometry, const WbVector3 &scale, QUndoCommand *parent = 0);
~WbResizeCommand() {}
void undo() override;
void redo() override;
protected:
bool mIsFirstCall;
WbGeometry *mGeometry;
const WbVector3 mScale;
const WbVector3 mInvScale;
private:
void resetValue(const WbVector3 &scale);
};
#endif
| 26.875 | 90 | 0.747287 | [
"geometry"
] |
cd77d471ba082206c95bac673127485ad8d035ff | 5,643 | cc | C++ | example/speech-demo/python_wrap/ctypes.cc | axbaretto/mxnet | 5f593885356ff6d14f5519fa18e79b944beb51cd | [
"Apache-2.0"
] | 36 | 2018-02-10T07:14:27.000Z | 2021-09-03T09:11:59.000Z | example/speech-demo/python_wrap/ctypes.cc | yanghaojin/BMXNet | 102f8d0ed59529bbd162c37bf07ae58ad6c4caa1 | [
"Apache-2.0"
] | 3 | 2017-07-10T21:49:18.000Z | 2017-07-12T22:40:06.000Z | example/speech-demo/python_wrap/ctypes.cc | yanghaojin/BMXNet | 102f8d0ed59529bbd162c37bf07ae58ad6c4caa1 | [
"Apache-2.0"
] | 15 | 2017-09-20T15:24:53.000Z | 2018-01-11T11:14:03.000Z | #include <iostream>
#include "util/table-types.h"
#include "hmm/posterior.h"
#include "nnet/nnet-nnet.h"
#include "cudamatrix/cu-device.h"
class Foo{
public:
Foo() {
x[0] = 0.5f;
x[1] = 1.5f;
x[2] = 2.5f;
x[3] = 3.5f;
x[4] = 4.5f;
}
void bar(){
std::cout << "Hello" << std::endl;
}
float * getx() {
return x;
}
int sizex() {
return sizeof(x) / sizeof(float);
}
private:
float x[5];
};
namespace kaldi {
typedef SequentialBaseFloatMatrixReader SBFMReader;
typedef Matrix<BaseFloat> MatrixF;
typedef RandomAccessPosteriorReader RAPReader;
namespace nnet1 {
typedef class Nnet_t_ {
public:
Nnet nnet_transf;
CuMatrix<BaseFloat> feats_transf;
MatrixF buf;
} Nnet_t;
}
}
extern "C" {
Foo* Foo_new(){ return new Foo(); }
void Foo_bar(Foo* foo){ foo->bar(); }
float * Foo_getx(Foo* foo) { return foo->getx(); }
int Foo_sizex(Foo* foo) { return foo->sizex(); }
using namespace kaldi;
using namespace kaldi::nnet1;
/****************************** SBFMReader ******************************/
//SequentialTableReader(): impl_(NULL) { }
SBFMReader* SBFMReader_new() {
return new SBFMReader();
}
//SequentialTableReader(const std::string &rspecifier);
SBFMReader* SBFMReader_new_char(char * rspecifier) {
return new SBFMReader(rspecifier);
}
//bool Open(const std::string &rspecifier);
int SBFMReader_Open(SBFMReader* r, char * rspecifier) {
return r->Open(rspecifier);
}
//inline bool Done();
int SBFMReader_Done(SBFMReader* r) {
return r->Done();
}
//inline std::string Key();
const char * SBFMReader_Key(SBFMReader* r) {
return r->Key().c_str();
}
//void FreeCurrent();
void SBFMReader_FreeCurrent(SBFMReader* r) {
r->FreeCurrent();
}
//const T &Value();
const MatrixF * SBFMReader_Value(SBFMReader* r) {
return &r->Value(); //despite how dangerous this looks, this is safe because holder maintains object (it's not stack allocated)
}
//void Next();
void SBFMReader_Next(SBFMReader* r) {
r->Next();
}
//bool IsOpen() const;
int SBFMReader_IsOpen(SBFMReader* r) {
return r->IsOpen();
}
//bool Close();
int SBFMReader_Close(SBFMReader* r) {
return r->Close();
}
//~SequentialTableReader();
void SBFMReader_Delete(SBFMReader* r) {
delete r;
}
/****************************** MatrixF ******************************/
//NumRows ()
int MatrixF_NumRows(MatrixF *m) {
return m->NumRows();
}
//NumCols ()
int MatrixF_NumCols(MatrixF *m) {
return m->NumCols();
}
//Stride ()
int MatrixF_Stride(MatrixF *m) {
return m->Stride();
}
void MatrixF_cpy_to_ptr(MatrixF *m, float * dst, int dst_stride) {
int num_rows = m->NumRows();
int num_cols = m->NumCols();
int src_stride = m->Stride();
int bytes_per_row = num_cols * sizeof(float);
float * src = m->Data();
for (int r=0; r<num_rows; r++) {
memcpy(dst, src, bytes_per_row);
src += src_stride;
dst += dst_stride;
}
}
//SizeInBytes ()
int MatrixF_SizeInBytes(MatrixF *m) {
return m->SizeInBytes();
}
//Data (), Real is usually float32
const float * MatrixF_Data(MatrixF *m) {
return m->Data();
}
/****************************** RAPReader ******************************/
RAPReader* RAPReader_new_char(char * rspecifier) {
return new RAPReader(rspecifier);
}
//bool HasKey (const std::string &key)
int RAPReader_HasKey(RAPReader* r, char * key) {
return r->HasKey(key);
}
//const T & Value (const std::string &key)
int * RAPReader_Value(RAPReader* r, char * key) {
//return &r->Value(key);
const Posterior p = r->Value(key);
int num_rows = p.size();
if (num_rows == 0) {
return NULL;
}
//std::cout << "num_rows " << num_rows << std::endl;
int * vals = new int[num_rows];
for (int row=0; row<num_rows; row++) {
int num_cols = p.at(row).size();
if (num_cols != 1) {
std::cout << "num_cols != 1: " << num_cols << std::endl;
delete vals;
return NULL;
}
std::pair<int32, BaseFloat> pair = p.at(row).at(0);
if (pair.second != 1) {
std::cout << "pair.second != 1: " << pair.second << std::endl;
delete vals;
return NULL;
}
vals[row] = pair.first;
}
return vals;
}
void RAPReader_DeleteValue(RAPReader* r, int * vals) {
delete vals;
}
//~RandomAccessTableReader ()
void RAPReader_Delete(RAPReader* r) {
delete r;
}
/****************************** Nnet_t ******************************/
Nnet_t* Nnet_new(char * filename, float dropout_retention, int crossvalidate) {
//std::cout << "dropout_retention " << dropout_retention << " crossvalidate " << crossvalidate << std::endl;
Nnet_t * nnet = new Nnet_t();
if(strcmp(filename, "") != 0) {
nnet->nnet_transf.Read(filename);
}
if (dropout_retention > 0.0) {
nnet->nnet_transf.SetDropoutRate(dropout_retention);
}
if (crossvalidate) {
nnet->nnet_transf.SetDropoutRate(1.0);
}
return nnet;
}
const MatrixF * Nnet_Feedforward(Nnet_t* nnet, MatrixF * inputs) {
nnet->nnet_transf.Feedforward(CuMatrix<BaseFloat>(*inputs), &nnet->feats_transf);
nnet->buf.Resize(nnet->feats_transf.NumRows(), nnet->feats_transf.NumCols());
nnet->feats_transf.CopyToMat(&nnet->buf);
return &nnet->buf;
}
void Nnet_Delete(Nnet_t* nnet) {
delete nnet;
}
}
| 24.969027 | 131 | 0.57434 | [
"object"
] |
cd7a7a7bef202c9d9f11519a1b7527bf2de69561 | 14,417 | cpp | C++ | cpp-restsdk/model/Supply.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/Supply.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | cpp-restsdk/model/Supply.cpp | thracesystems/powermeter-api | 7bdab034ff916ee49e986de88f157bd044e981c1 | [
"Apache-2.0"
] | null | null | null | /**
* PowerMeter API
* API
*
* The version of the OpenAPI document: 2021.4.1
*
* NOTE: This class is auto generated by OpenAPI-Generator 4.3.1.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "Supply.h"
namespace powermeter {
namespace model {
Supply::Supply()
{
m_Id = 0;
m_IdIsSet = false;
m_Name = utility::conversions::to_string_t("");
m_NameIsSet = false;
m_Voltage = 0.0;
m_VoltageIsSet = false;
m_Type = utility::conversions::to_string_t("");
m_TypeIsSet = false;
m_Is_power = false;
m_Is_powerIsSet = false;
m_Is_ground = false;
m_Is_groundIsSet = false;
m_Switchable = false;
m_SwitchableIsSet = false;
m_Master_supply = 0;
m_Master_supplyIsSet = false;
m_Color = utility::conversions::to_string_t("");
m_ColorIsSet = false;
m_Instance_count = 0;
m_Instance_countIsSet = false;
}
Supply::~Supply()
{
}
void Supply::validate()
{
// TODO: implement validation
}
web::json::value Supply::toJson() const
{
web::json::value val = web::json::value::object();
if(m_IdIsSet)
{
val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id);
}
if(m_NameIsSet)
{
val[utility::conversions::to_string_t("name")] = ModelBase::toJson(m_Name);
}
if(m_VoltageIsSet)
{
val[utility::conversions::to_string_t("voltage")] = ModelBase::toJson(m_Voltage);
}
if(m_TypeIsSet)
{
val[utility::conversions::to_string_t("type")] = ModelBase::toJson(m_Type);
}
if(m_Is_powerIsSet)
{
val[utility::conversions::to_string_t("is_power")] = ModelBase::toJson(m_Is_power);
}
if(m_Is_groundIsSet)
{
val[utility::conversions::to_string_t("is_ground")] = ModelBase::toJson(m_Is_ground);
}
if(m_SwitchableIsSet)
{
val[utility::conversions::to_string_t("switchable")] = ModelBase::toJson(m_Switchable);
}
if(m_Master_supplyIsSet)
{
val[utility::conversions::to_string_t("master_supply")] = ModelBase::toJson(m_Master_supply);
}
if(m_ColorIsSet)
{
val[utility::conversions::to_string_t("color")] = ModelBase::toJson(m_Color);
}
if(m_Instance_countIsSet)
{
val[utility::conversions::to_string_t("instance_count")] = ModelBase::toJson(m_Instance_count);
}
return val;
}
bool Supply::fromJson(const web::json::value& val)
{
bool ok = true;
if(val.has_field(utility::conversions::to_string_t("id")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id"));
if(!fieldValue.is_null())
{
int32_t refVal_id;
ok &= ModelBase::fromJson(fieldValue, refVal_id);
setId(refVal_id);
}
}
if(val.has_field(utility::conversions::to_string_t("name")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name"));
if(!fieldValue.is_null())
{
utility::string_t refVal_name;
ok &= ModelBase::fromJson(fieldValue, refVal_name);
setName(refVal_name);
}
}
if(val.has_field(utility::conversions::to_string_t("voltage")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("voltage"));
if(!fieldValue.is_null())
{
double refVal_voltage;
ok &= ModelBase::fromJson(fieldValue, refVal_voltage);
setVoltage(refVal_voltage);
}
}
if(val.has_field(utility::conversions::to_string_t("type")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("type"));
if(!fieldValue.is_null())
{
utility::string_t refVal_type;
ok &= ModelBase::fromJson(fieldValue, refVal_type);
setType(refVal_type);
}
}
if(val.has_field(utility::conversions::to_string_t("is_power")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("is_power"));
if(!fieldValue.is_null())
{
bool refVal_is_power;
ok &= ModelBase::fromJson(fieldValue, refVal_is_power);
setIsPower(refVal_is_power);
}
}
if(val.has_field(utility::conversions::to_string_t("is_ground")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("is_ground"));
if(!fieldValue.is_null())
{
bool refVal_is_ground;
ok &= ModelBase::fromJson(fieldValue, refVal_is_ground);
setIsGround(refVal_is_ground);
}
}
if(val.has_field(utility::conversions::to_string_t("switchable")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("switchable"));
if(!fieldValue.is_null())
{
bool refVal_switchable;
ok &= ModelBase::fromJson(fieldValue, refVal_switchable);
setSwitchable(refVal_switchable);
}
}
if(val.has_field(utility::conversions::to_string_t("master_supply")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("master_supply"));
if(!fieldValue.is_null())
{
int32_t refVal_master_supply;
ok &= ModelBase::fromJson(fieldValue, refVal_master_supply);
setMasterSupply(refVal_master_supply);
}
}
if(val.has_field(utility::conversions::to_string_t("color")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("color"));
if(!fieldValue.is_null())
{
utility::string_t refVal_color;
ok &= ModelBase::fromJson(fieldValue, refVal_color);
setColor(refVal_color);
}
}
if(val.has_field(utility::conversions::to_string_t("instance_count")))
{
const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("instance_count"));
if(!fieldValue.is_null())
{
int32_t refVal_instance_count;
ok &= ModelBase::fromJson(fieldValue, refVal_instance_count);
setInstanceCount(refVal_instance_count);
}
}
return ok;
}
void Supply::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(m_IdIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id));
}
if(m_NameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name));
}
if(m_VoltageIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("voltage"), m_Voltage));
}
if(m_TypeIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("type"), m_Type));
}
if(m_Is_powerIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("is_power"), m_Is_power));
}
if(m_Is_groundIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("is_ground"), m_Is_ground));
}
if(m_SwitchableIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("switchable"), m_Switchable));
}
if(m_Master_supplyIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("master_supply"), m_Master_supply));
}
if(m_ColorIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("color"), m_Color));
}
if(m_Instance_countIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("instance_count"), m_Instance_count));
}
}
bool Supply::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
bool ok = true;
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(multipart->hasContent(utility::conversions::to_string_t("id")))
{
int32_t refVal_id;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")), refVal_id );
setId(refVal_id);
}
if(multipart->hasContent(utility::conversions::to_string_t("name")))
{
utility::string_t refVal_name;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("name")), refVal_name );
setName(refVal_name);
}
if(multipart->hasContent(utility::conversions::to_string_t("voltage")))
{
double refVal_voltage;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("voltage")), refVal_voltage );
setVoltage(refVal_voltage);
}
if(multipart->hasContent(utility::conversions::to_string_t("type")))
{
utility::string_t refVal_type;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("type")), refVal_type );
setType(refVal_type);
}
if(multipart->hasContent(utility::conversions::to_string_t("is_power")))
{
bool refVal_is_power;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("is_power")), refVal_is_power );
setIsPower(refVal_is_power);
}
if(multipart->hasContent(utility::conversions::to_string_t("is_ground")))
{
bool refVal_is_ground;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("is_ground")), refVal_is_ground );
setIsGround(refVal_is_ground);
}
if(multipart->hasContent(utility::conversions::to_string_t("switchable")))
{
bool refVal_switchable;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("switchable")), refVal_switchable );
setSwitchable(refVal_switchable);
}
if(multipart->hasContent(utility::conversions::to_string_t("master_supply")))
{
int32_t refVal_master_supply;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("master_supply")), refVal_master_supply );
setMasterSupply(refVal_master_supply);
}
if(multipart->hasContent(utility::conversions::to_string_t("color")))
{
utility::string_t refVal_color;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("color")), refVal_color );
setColor(refVal_color);
}
if(multipart->hasContent(utility::conversions::to_string_t("instance_count")))
{
int32_t refVal_instance_count;
ok &= ModelBase::fromHttpContent(multipart->getContent(utility::conversions::to_string_t("instance_count")), refVal_instance_count );
setInstanceCount(refVal_instance_count);
}
return ok;
}
int32_t Supply::getId() const
{
return m_Id;
}
void Supply::setId(int32_t value)
{
m_Id = value;
m_IdIsSet = true;
}
bool Supply::idIsSet() const
{
return m_IdIsSet;
}
void Supply::unsetId()
{
m_IdIsSet = false;
}
utility::string_t Supply::getName() const
{
return m_Name;
}
void Supply::setName(const utility::string_t& value)
{
m_Name = value;
m_NameIsSet = true;
}
bool Supply::nameIsSet() const
{
return m_NameIsSet;
}
void Supply::unsetName()
{
m_NameIsSet = false;
}
double Supply::getVoltage() const
{
return m_Voltage;
}
void Supply::setVoltage(double value)
{
m_Voltage = value;
m_VoltageIsSet = true;
}
bool Supply::voltageIsSet() const
{
return m_VoltageIsSet;
}
void Supply::unsetVoltage()
{
m_VoltageIsSet = false;
}
utility::string_t Supply::getType() const
{
return m_Type;
}
void Supply::setType(const utility::string_t& value)
{
m_Type = value;
m_TypeIsSet = true;
}
bool Supply::typeIsSet() const
{
return m_TypeIsSet;
}
void Supply::unsetType()
{
m_TypeIsSet = false;
}
bool Supply::isIsPower() const
{
return m_Is_power;
}
void Supply::setIsPower(bool value)
{
m_Is_power = value;
m_Is_powerIsSet = true;
}
bool Supply::isPowerIsSet() const
{
return m_Is_powerIsSet;
}
void Supply::unsetIs_power()
{
m_Is_powerIsSet = false;
}
bool Supply::isIsGround() const
{
return m_Is_ground;
}
void Supply::setIsGround(bool value)
{
m_Is_ground = value;
m_Is_groundIsSet = true;
}
bool Supply::isGroundIsSet() const
{
return m_Is_groundIsSet;
}
void Supply::unsetIs_ground()
{
m_Is_groundIsSet = false;
}
bool Supply::isSwitchable() const
{
return m_Switchable;
}
void Supply::setSwitchable(bool value)
{
m_Switchable = value;
m_SwitchableIsSet = true;
}
bool Supply::switchableIsSet() const
{
return m_SwitchableIsSet;
}
void Supply::unsetSwitchable()
{
m_SwitchableIsSet = false;
}
int32_t Supply::getMasterSupply() const
{
return m_Master_supply;
}
void Supply::setMasterSupply(int32_t value)
{
m_Master_supply = value;
m_Master_supplyIsSet = true;
}
bool Supply::masterSupplyIsSet() const
{
return m_Master_supplyIsSet;
}
void Supply::unsetMaster_supply()
{
m_Master_supplyIsSet = false;
}
utility::string_t Supply::getColor() const
{
return m_Color;
}
void Supply::setColor(const utility::string_t& value)
{
m_Color = value;
m_ColorIsSet = true;
}
bool Supply::colorIsSet() const
{
return m_ColorIsSet;
}
void Supply::unsetColor()
{
m_ColorIsSet = false;
}
int32_t Supply::getInstanceCount() const
{
return m_Instance_count;
}
void Supply::setInstanceCount(int32_t value)
{
m_Instance_count = value;
m_Instance_countIsSet = true;
}
bool Supply::instanceCountIsSet() const
{
return m_Instance_countIsSet;
}
void Supply::unsetInstance_count()
{
m_Instance_countIsSet = false;
}
}
}
| 26.897388 | 141 | 0.658944 | [
"object",
"model"
] |
cd7fc19bca89aa8e11c22b70a11fdcb794b7d405 | 8,926 | cc | C++ | thirdparty/glog/src/vlog_is_on.cc | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 47 | 2016-07-27T07:22:06.000Z | 2021-08-17T13:08:19.000Z | src/third_party/glog/src/vlog_is_on.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 1 | 2016-09-24T06:04:39.000Z | 2016-09-25T10:34:19.000Z | src/third_party/glog/src/vlog_is_on.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 13 | 2016-07-27T10:44:35.000Z | 2020-07-01T21:08:33.000Z | // Copyright (c) 1999, 2007, Google 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: Ray Sidney and many others
//
// Broken out from logging.cc by Soren Lassen
// logging_unittest.cc covers the functionality herein
#include "utilities.h"
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <cstdio>
#include <string>
#include "base/commandlineflags.h"
#include "glog/logging.h"
#include "glog/raw_logging.h"
#include "base/googleinit.h"
// glog doesn't have annotation
#define ANNOTATE_BENIGN_RACE(address, description)
using std::string;
GLOG_DEFINE_int32(v, 0, "Show all VLOG(m) messages for m <= this."
" Overridable by --vmodule.");
GLOG_DEFINE_string(vmodule, "", "per-module verbose level."
" Argument is a comma-separated list of <module name>=<log level>."
" <module name> is a glob pattern, matched against the filename base"
" (that is, name ignoring .cc/.h./-inl.h)."
" <log level> overrides any value given by --v.");
_START_GOOGLE_NAMESPACE_
namespace glog_internal_namespace_ {
namespace {
// Implementation of fnmatch that does not need 0-termination
// of arguments and does not allocate any memory,
// but we only support "*" and "?" wildcards, not the "[...]" patterns.
// It's not a static function for the unittest.
GOOGLE_GLOG_DLL_DECL bool SafeFNMatch_(const char* pattern,
size_t patt_len,
const char* str,
size_t str_len) {
size_t p = 0;
size_t s = 0;
while (1) {
if (p == patt_len && s == str_len) return true;
if (p == patt_len) return false;
if (s == str_len) return p+1 == patt_len && pattern[p] == '*';
if (pattern[p] == str[s] || pattern[p] == '?') {
p += 1;
s += 1;
continue;
}
if (pattern[p] == '*') {
if (p+1 == patt_len) return true;
do {
if (SafeFNMatch_(pattern+(p+1), patt_len-(p+1), str+s, str_len-s)) {
return true;
}
s += 1;
} while (s != str_len);
return false;
}
return false;
}
}
} // namespace
} // namespace glog_internal_namespace_
using glog_internal_namespace_::SafeFNMatch_;
int32 kLogSiteUninitialized = 1000;
// List of per-module log levels from FLAGS_vmodule.
// Once created each element is never deleted/modified
// except for the vlog_level: other threads will read VModuleInfo blobs
// w/o locks and we'll store pointers to vlog_level at VLOG locations
// that will never go away.
// We can't use an STL struct here as we wouldn't know
// when it's safe to delete/update it: other threads need to use it w/o locks.
struct VModuleInfo {
string module_pattern;
mutable int32 vlog_level; // Conceptually this is an AtomicWord, but it's
// too much work to use AtomicWord type here
// w/o much actual benefit.
const VModuleInfo* next;
};
// This protects the following global variables.
static Mutex vmodule_lock;
// Pointer to head of the VModuleInfo list.
// It's a map from module pattern to logging level for those module(s).
static VModuleInfo* vmodule_list = 0;
// Boolean initialization flag.
static bool inited_vmodule = false;
// L >= vmodule_lock.
static void VLOG2Initializer() {
vmodule_lock.AssertHeld();
// Can now parse --vmodule flag and initialize mapping of module-specific
// logging levels.
inited_vmodule = false;
const char* vmodule = FLAGS_vmodule.c_str();
const char* sep;
VModuleInfo* head = NULL;
VModuleInfo* tail = NULL;
while ((sep = strchr(vmodule, '=')) != NULL) {
string pattern(vmodule, sep - vmodule);
int module_level;
if (sscanf(sep, "=%d", &module_level) == 1) {
VModuleInfo* info = new VModuleInfo;
info->module_pattern = pattern;
info->vlog_level = module_level;
if (head) tail->next = info;
else head = info;
tail = info;
}
// Skip past this entry
vmodule = strchr(sep, ',');
if (vmodule == NULL) break;
vmodule++; // Skip past ","
}
if (head) { // Put them into the list at the head:
tail->next = vmodule_list;
vmodule_list = head;
}
inited_vmodule = true;
}
// This can be called very early, so we use SpinLock and RAW_VLOG here.
int SetVLOGLevel(const char* module_pattern, int log_level) {
int result = FLAGS_v;
int const pattern_len = strlen(module_pattern);
bool found = false;
MutexLock l(&vmodule_lock); // protect whole read-modify-write
for (const VModuleInfo* info = vmodule_list;
info != NULL; info = info->next) {
if (info->module_pattern == module_pattern) {
if (!found) {
result = info->vlog_level;
found = true;
}
info->vlog_level = log_level;
} else if (!found &&
SafeFNMatch_(info->module_pattern.c_str(),
info->module_pattern.size(),
module_pattern, pattern_len)) {
result = info->vlog_level;
found = true;
}
}
if (!found) {
VModuleInfo* info = new VModuleInfo;
info->module_pattern = module_pattern;
info->vlog_level = log_level;
info->next = vmodule_list;
vmodule_list = info;
}
RAW_VLOG(1, "Set VLOG level for \"%s\" to %d", module_pattern, log_level);
return result;
}
// NOTE: Individual VLOG statements cache the integer log level pointers.
// NOTE: This function must not allocate memory or require any locks.
bool InitVLOG3__(int32** site_flag, int32* site_default,
const char* fname, int32 verbose_level) {
MutexLock l(&vmodule_lock);
bool read_vmodule_flag = inited_vmodule;
if (!read_vmodule_flag) {
VLOG2Initializer();
}
// protect the errno global in case someone writes:
// VLOG(..) << "The last error was " << strerror(errno)
int old_errno = errno;
// site_default normally points to FLAGS_v
int32* site_flag_value = site_default;
// Get basename for file
const char* base = strrchr(fname, '/');
base = base ? (base+1) : fname;
const char* base_end = strchr(base, '.');
size_t base_length = base_end ? size_t(base_end - base) : strlen(base);
// Trim out trailing "-inl" if any
if (base_length >= 4 && (memcmp(base+base_length-4, "-inl", 4) == 0)) {
base_length -= 4;
}
// TODO: Trim out _unittest suffix? Perhaps it is better to have
// the extra control and just leave it there.
// find target in vector of modules, replace site_flag_value with
// a module-specific verbose level, if any.
for (const VModuleInfo* info = vmodule_list;
info != NULL; info = info->next) {
if (SafeFNMatch_(info->module_pattern.c_str(), info->module_pattern.size(),
base, base_length)) {
site_flag_value = &info->vlog_level;
// value at info->vlog_level is now what controls
// the VLOG at the caller site forever
break;
}
}
// Cache the vlog value pointer if --vmodule flag has been parsed.
ANNOTATE_BENIGN_RACE(site_flag,
"*site_flag may be written by several threads,"
" but the value will be the same");
if (read_vmodule_flag) *site_flag = site_flag_value;
// restore the errno in case something recoverable went wrong during
// the initialization of the VLOG mechanism (see above note "protect the..")
errno = old_errno;
return *site_flag_value >= verbose_level;
}
_END_GOOGLE_NAMESPACE_
| 35.141732 | 79 | 0.667488 | [
"vector"
] |
cd811c1e0ec64b95c93a564db4154e0d92450911 | 12,428 | cpp | C++ | DWriteCore/DWriteCoreGallery/DWriteCoreGallery/TextRenderer.cpp | pmpurifoy/Project-Reunion-Samples | 23015cf649c98eaa305921e41eef21e8fe2e48e9 | [
"MIT"
] | 1 | 2021-07-06T14:30:29.000Z | 2021-07-06T14:30:29.000Z | DWriteCore/DWriteCoreGallery/DWriteCoreGallery/TextRenderer.cpp | pmpurifoy/Project-Reunion-Samples | 23015cf649c98eaa305921e41eef21e8fe2e48e9 | [
"MIT"
] | null | null | null | DWriteCore/DWriteCoreGallery/DWriteCoreGallery/TextRenderer.cpp | pmpurifoy/Project-Reunion-Samples | 23015cf649c98eaa305921e41eef21e8fe2e48e9 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "Main.h"
#include "Helpers.h"
#include "TextRenderer.h"
TextRenderer::TextRenderer(HWND hwnd)
{
auto hdc = wil::GetDC(hwnd);
THROW_LAST_ERROR_IF_NULL(hdc);
int dpi = GetDeviceCaps(hdc.get(), LOGPIXELSY);
m_dpiScale = dpi * (1.0f / 96);
THROW_IF_FAILED(g_factory->CreateRenderingParams(&m_renderingParams));
wil::com_ptr<IDWriteGdiInterop> gdiInterop;
THROW_IF_FAILED(g_factory->GetGdiInterop(&gdiInterop));
constexpr SIZE initialSize = { 1024, 256 };
wil::com_ptr<IDWriteBitmapRenderTarget> renderTarget;
THROW_IF_FAILED(gdiInterop->CreateBitmapRenderTarget(hdc.get(), initialSize.cx, initialSize.cy, &renderTarget));
renderTarget.query_to(&m_renderTarget);
m_targetHdc = renderTarget->GetMemoryDC();
m_targetPixelSize = initialSize;
}
IDWriteTextAnalyzer2* TextRenderer::GetTextAnalyzer()
{
if (m_textAnalyzer == nullptr)
{
wil::com_ptr<IDWriteTextAnalyzer> textAnalyzer;
THROW_IF_FAILED(g_factory->CreateTextAnalyzer(&textAnalyzer));
textAnalyzer.query_to(&m_textAnalyzer);
}
return m_textAnalyzer.get();
}
void TextRenderer::Resize(SIZE pixelSize)
{
if (pixelSize.cx > m_targetPixelSize.cx || pixelSize.cy > m_targetPixelSize.cy)
{
int width = std::max(pixelSize.cx, m_targetPixelSize.cx);
int height = std::max(pixelSize.cy, m_targetPixelSize.cy);
THROW_IF_FAILED(m_renderTarget->Resize(width, height));
m_targetPixelSize = { width, height };
}
m_logicalPixelSize = pixelSize;
}
void TextRenderer::Clear(int sysColorIndex)
{
RECT rect = { 0, 0, m_logicalPixelSize.cx, m_logicalPixelSize.cy };
FillRect(m_targetHdc, &rect, GetSysColorBrush(sysColorIndex));
}
void TextRenderer::CopyTo(HDC hdcDest, POINT topLeft)
{
BitBlt(hdcDest, topLeft.x, topLeft.y, m_logicalPixelSize.cx, m_logicalPixelSize.cy, m_targetHdc, 0, 0, SRCCOPY);
}
// IUnknown method
HRESULT STDMETHODCALLTYPE TextRenderer::QueryInterface(REFIID riid, _COM_Outptr_ void** ppvObject) noexcept
{
if (riid == __uuidof(IDWriteTextRenderer1) ||
riid == __uuidof(IDWriteTextRenderer) ||
riid == __uuidof(IDWritePixelSnapping) ||
riid == __uuidof(IUnknown))
{
AddRef();
*ppvObject = this;
return S_OK;
}
else
{
*ppvObject = nullptr;
return E_NOINTERFACE;
}
}
// IUnknown method
ULONG STDMETHODCALLTYPE TextRenderer::AddRef() noexcept
{
return ++m_refCount;
}
// IUnknown method
ULONG STDMETHODCALLTYPE TextRenderer::Release() noexcept
{
uint32_t newCount = --m_refCount;
if (newCount == 0)
{
delete this;
}
return newCount;
}
DWRITE_MATRIX TextRenderer::CombineTransform(DWRITE_MATRIX a, DWRITE_MATRIX b) noexcept
{
return
{
a.m11 * b.m11 + a.m12 * b.m21,
a.m11 * b.m12 + a.m12 * b.m22,
a.m21 * b.m11 + a.m22 * b.m21,
a.m21 * b.m12 + a.m22 * b.m22,
a.dx * b.m11 + a.dy * b.m21 + b.dx,
a.dx * b.m12 + a.dy * b.m22 + b.dy
};
}
TextRenderer::OrientationTransform::OrientationTransform(TextRenderer* renderer,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
bool isSideways,
D2D_POINT_2F origin
)
{
if (orientationAngle != DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES)
{
m_renderTarget = renderer->GetRenderTarget();
THROW_IF_FAILED(m_renderTarget->GetCurrentTransform(&m_oldTransform));
DWRITE_MATRIX orientationTransform;
THROW_IF_FAILED(renderer->GetTextAnalyzer()->GetGlyphOrientationTransform(orientationAngle, isSideways, origin.x, origin.y, &orientationTransform));
DWRITE_MATRIX finalTransform = CombineTransform(m_oldTransform, orientationTransform);
THROW_IF_FAILED(m_renderTarget->SetCurrentTransform(&finalTransform));
}
}
TextRenderer::OrientationTransform::~OrientationTransform()
{
if (m_renderTarget != nullptr)
{
m_renderTarget->SetCurrentTransform(&m_oldTransform);
}
}
// IDWritePixelSnapping method
HRESULT STDMETHODCALLTYPE TextRenderer::IsPixelSnappingDisabled(
_In_opt_ void* clientDrawingContext,
_Out_ BOOL* isDisabled
) noexcept
{
*isDisabled = false;
return S_OK;
}
// IDWritePixelSnapping method
HRESULT STDMETHODCALLTYPE TextRenderer::GetCurrentTransform(
_In_opt_ void* clientDrawingContext,
_Out_ DWRITE_MATRIX* transform
) noexcept
{
*transform = DWRITE_MATRIX{ 1, 0, 0, 1, 0, 0 };
return S_OK;
}
// IDWritePixelSnapping method
HRESULT STDMETHODCALLTYPE TextRenderer::GetPixelsPerDip(
_In_opt_ void* clientDrawingContext,
_Out_ FLOAT* pixelsPerDip
) noexcept
{
*pixelsPerDip = m_dpiScale;
return S_OK;
}
inline BYTE FloatToColorByte(float c)
{
return static_cast<BYTE>(floorf(c * 255 + 0.5f));
}
COLORREF ToCOLORREF(DWRITE_COLOR_F color)
{
return RGB(
FloatToColorByte(color.r),
FloatToColorByte(color.g),
FloatToColorByte(color.b)
);
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawGlyphRun(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_MEASURING_MODE measuringMode,
_In_ DWRITE_GLYPH_RUN const* glyphRun,
_In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
return DrawGlyphRun(
clientDrawingContext,
baselineOriginX,
baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,
measuringMode,
glyphRun,
glyphRunDescription,
clientDrawingEffect
);
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawGlyphRun(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
DWRITE_MEASURING_MODE measuringMode,
_In_ DWRITE_GLYPH_RUN const* glyphRun,
_In_ DWRITE_GLYPH_RUN_DESCRIPTION const* glyphRunDescription,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
try
{
OrientationTransform orentation(
this,
orientationAngle,
!!glyphRun->isSideways,
D2D_POINT_2F{ baselineOriginX, baselineOriginY }
);
HRESULT hr = DWRITE_E_NOCOLOR;
wil::com_ptr<IDWriteColorGlyphRunEnumerator> colorLayers;
wil::com_ptr<IDWriteFontFace2> fontFace2;
if (SUCCEEDED(glyphRun->fontFace->QueryInterface(&fontFace2)))
{
uint32_t paletteCount = fontFace2->GetColorPaletteCount();
if (paletteCount > 0)
{
DWRITE_MATRIX transform;
hr = m_renderTarget->GetCurrentTransform(&transform);
if (FAILED(hr))
{
return hr;
}
transform.m11 *= m_dpiScale;
transform.m12 *= m_dpiScale;
transform.m21 *= m_dpiScale;
transform.m22 *= m_dpiScale;
transform.dx *= m_dpiScale;
transform.dy *= m_dpiScale;
// Perform color translation.
// Fall back to the default palette if the current palette index is out of range.
hr = g_factory->TranslateColorGlyphRun(
baselineOriginX,
baselineOriginY,
glyphRun,
nullptr,
measuringMode,
&transform,
m_colorPaletteIndex < paletteCount ? m_colorPaletteIndex : 0,
& colorLayers
);
}
}
if (hr == DWRITE_E_NOCOLOR)
{
THROW_IF_FAILED(m_renderTarget->DrawGlyphRun(
baselineOriginX,
baselineOriginY,
measuringMode,
glyphRun,
m_renderingParams.get(),
m_textColor
));
}
else
{
THROW_IF_FAILED(hr);
for (;;)
{
BOOL haveRun;
THROW_IF_FAILED(colorLayers->MoveNext(&haveRun));
if (!haveRun)
{
break;
}
DWRITE_COLOR_GLYPH_RUN const* colorRun;
THROW_IF_FAILED(colorLayers->GetCurrentRun(&colorRun));
COLORREF runColor = (colorRun->paletteIndex == 0xFFFF) ? m_textColor : ToCOLORREF(colorRun->runColor);
THROW_IF_FAILED(m_renderTarget->DrawGlyphRun(
colorRun->baselineOriginX,
colorRun->baselineOriginY,
measuringMode,
&colorRun->glyphRun,
m_renderingParams.get(),
runColor
));
}
}
return S_OK;
}
catch (wil::ResultException& e)
{
return e.GetErrorCode();
}
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawUnderline(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
_In_ DWRITE_UNDERLINE const* underline,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawUnderline(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ DWRITE_UNDERLINE const* underline,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawStrikethrough(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
_In_ DWRITE_STRIKETHROUGH const* strikethrough,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawStrikethrough(
_In_opt_ void* clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ DWRITE_STRIKETHROUGH const* strikethrough,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
// TODO - text decorations
return E_NOTIMPL;
}
// IDWriteTextRenderer method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawInlineObject(
_In_opt_ void* clientDrawingContext,
FLOAT originX,
FLOAT originY,
_In_ IDWriteInlineObject* inlineObject,
BOOL isSideways,
BOOL isRightToLeft,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
return DrawInlineObject(
clientDrawingContext,
originX,
originY,
DWRITE_GLYPH_ORIENTATION_ANGLE_0_DEGREES,
inlineObject,
isSideways,
isRightToLeft,
clientDrawingEffect
);
}
// IDWriteTextRenderer1 method
HRESULT STDMETHODCALLTYPE TextRenderer::DrawInlineObject(
_In_opt_ void* clientDrawingContext,
FLOAT originX,
FLOAT originY,
DWRITE_GLYPH_ORIENTATION_ANGLE orientationAngle,
_In_ IDWriteInlineObject* inlineObject,
BOOL isSideways,
BOOL isRightToLeft,
_In_opt_ IUnknown* clientDrawingEffect
) noexcept
{
try
{
OrientationTransform orentation(
this,
orientationAngle,
!!isSideways,
D2D_POINT_2F{ originX, originY }
);
THROW_IF_FAILED(inlineObject->Draw(
clientDrawingContext,
this,
originX,
originY,
isSideways,
isRightToLeft,
clientDrawingEffect
));
return S_OK;
}
catch (wil::ResultException& e)
{
return e.GetErrorCode();
}
}
| 28.702079 | 157 | 0.630914 | [
"transform"
] |
cd87e3cb30d456a01375e5bc61a0e2e171c166b7 | 724 | cpp | C++ | AcWing/LeetCode究极班/210.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | AcWing/LeetCode究极班/210.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | AcWing/LeetCode究极班/210.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | class Solution {
public:
vector<int> findOrder(int n, vector<vector<int>>& edges) {
vector<vector<int>> g(n);
vector<int> d(n);
for (auto& e: edges) {
int b = e[0], a = e[1];
g[a].emplace_back(b);
d[b] ++;
}
queue<int> q;
for (int i = 0; i < n; i ++ )
if (!d[i])
q.push(i);
vector<int> res;
while (q.size()) {
int t = q.front();
q.pop();
res.emplace_back(t);
for (int i: g[t]) {
if (-- d[i] == 0)
q.push(i);
}
}
if (res.size() < n) res = {};
return res;
}
}; | 24.133333 | 62 | 0.348066 | [
"vector"
] |
cd8c48cb0671b4bd5edd352d8ce9cb77f5a0cf27 | 4,361 | cc | C++ | internal/ceres/preprocessor.cc | hitxiaomi/ceres-solver | c3129c3d4a4830d23a310bd78c240898c82b36e9 | [
"Apache-2.0"
] | 2,425 | 2015-01-23T00:02:03.000Z | 2022-03-31T22:15:00.000Z | internal/ceres/preprocessor.cc | hitxiaomi/ceres-solver | c3129c3d4a4830d23a310bd78c240898c82b36e9 | [
"Apache-2.0"
] | 624 | 2015-03-18T14:36:29.000Z | 2022-03-31T16:06:14.000Z | internal/ceres/preprocessor.cc | hitxiaomi/ceres-solver | c3129c3d4a4830d23a310bd78c240898c82b36e9 | [
"Apache-2.0"
] | 989 | 2015-01-14T14:50:27.000Z | 2022-03-30T15:20:06.000Z | // Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameragarwal@google.com (Sameer Agarwal)
#include "ceres/preprocessor.h"
#include "ceres/callbacks.h"
#include "ceres/gradient_checking_cost_function.h"
#include "ceres/line_search_preprocessor.h"
#include "ceres/parallel_for.h"
#include "ceres/problem_impl.h"
#include "ceres/solver.h"
#include "ceres/trust_region_preprocessor.h"
namespace ceres {
namespace internal {
Preprocessor* Preprocessor::Create(MinimizerType minimizer_type) {
if (minimizer_type == TRUST_REGION) {
return new TrustRegionPreprocessor;
}
if (minimizer_type == LINE_SEARCH) {
return new LineSearchPreprocessor;
}
LOG(FATAL) << "Unknown minimizer_type: " << minimizer_type;
return NULL;
}
Preprocessor::~Preprocessor() {}
void ChangeNumThreadsIfNeeded(Solver::Options* options) {
if (options->num_threads == 1) {
return;
}
const int num_threads_available = MaxNumThreadsAvailable();
if (options->num_threads > num_threads_available) {
LOG(WARNING) << "Specified options.num_threads: " << options->num_threads
<< " exceeds maximum available from the threading model Ceres "
<< "was compiled with: " << num_threads_available
<< ". Bounding to maximum number available.";
options->num_threads = num_threads_available;
}
}
void SetupCommonMinimizerOptions(PreprocessedProblem* pp) {
const Solver::Options& options = pp->options;
Program* program = pp->reduced_program.get();
// Assuming that the parameter blocks in the program have been
// reordered as needed, extract them into a contiguous vector.
pp->reduced_parameters.resize(program->NumParameters());
double* reduced_parameters = pp->reduced_parameters.data();
program->ParameterBlocksToStateVector(reduced_parameters);
Minimizer::Options& minimizer_options = pp->minimizer_options;
minimizer_options = Minimizer::Options(options);
minimizer_options.evaluator = pp->evaluator;
if (options.logging_type != SILENT) {
pp->logging_callback.reset(new LoggingCallback(
options.minimizer_type, options.minimizer_progress_to_stdout));
minimizer_options.callbacks.insert(minimizer_options.callbacks.begin(),
pp->logging_callback.get());
}
if (options.update_state_every_iteration) {
pp->state_updating_callback.reset(
new StateUpdatingCallback(program, reduced_parameters));
// This must get pushed to the front of the callbacks so that it
// is run before any of the user callbacks.
minimizer_options.callbacks.insert(minimizer_options.callbacks.begin(),
pp->state_updating_callback.get());
}
}
} // namespace internal
} // namespace ceres
| 41.141509 | 80 | 0.737904 | [
"vector",
"model"
] |
cd8d6e0e10c0df19c6732a0e0934658dd94776cb | 4,478 | cpp | C++ | cnippet/Configuration_C.cpp | ludanpr/psychec | 3b4e057995e103c62d72b50e8fac1088f2b19727 | [
"BSD-3-Clause"
] | null | null | null | cnippet/Configuration_C.cpp | ludanpr/psychec | 3b4e057995e103c62d72b50e8fac1088f2b19727 | [
"BSD-3-Clause"
] | null | null | null | cnippet/Configuration_C.cpp | ludanpr/psychec | 3b4e057995e103c62d72b50e8fac1088f2b19727 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016/17/18/19/20/21/22 Leandro T. C. Melo <ltcmelo@gmail.com>
//
// 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 "Configuration_C.h"
namespace {
const char* const kCStd = "c-std";
const char* const kHostCCompiler = "host-cc";
const char* const kExpandCPPIncludeDirectives = "cpp-includes";
const char* const kDefineCPPMacro = "cpp-D";
const char* const KUndefineCPPMacro = "cpp-U";
const char* const kAddDirToCPPSearchPath = "cpp-I";
}
using namespace cnip;
void ConfigurationForC::extend(cxxopts::Options& cmdLineOpts)
{
cmdLineOpts.add_options()
// https://gcc.gnu.org/onlinedocs/gcc/C-Dialect-Options.html#C-Dialect-Options
(kCStd,
"Specify the C standard.",
cxxopts::value<std::string>()->default_value("c11"),
"<c89|c90|c99|c11|c17>")
(kHostCCompiler,
"Specify a host C compiler.",
cxxopts::value<std::string>()->default_value("gcc"),
"<gcc|clang>")
// https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html
(kExpandCPPIncludeDirectives,
"Expand `#include' directives of the C preprocessor.",
cxxopts::value<bool>()->default_value("false"))
// https://gcc.gnu.org/onlinedocs/gcc/Directory-Options.html
(kAddDirToCPPSearchPath,
"Add a directory to the `#include' search path of the C preprocessor.",
cxxopts::value<std::vector<std::string>>(),
"path")
// https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html
(kDefineCPPMacro,
"Predefine a C preprocessor macro.",
cxxopts::value<std::vector<std::string>>(),
"<name|name=definition>")
(KUndefineCPPMacro,
"Undefine a C preprocessor macro.",
cxxopts::value<std::vector<std::string>>(),
"<name>")
/* Type inference */
("C-infer", "Infer the definition of missing types.")
("o,output", "Specify output file",
cxxopts::value<std::string>()->default_value("a.cstr"))
;
}
ConfigurationForC::ConfigurationForC(const cxxopts::ParseResult& parsedCmdLine)
: Configuration(parsedCmdLine)
{
auto cc_std = parsedCmdLine[kCStd].as<std::string>();
std::for_each(cc_std.begin(),
cc_std.end(),
[] (char& c) { c = ::tolower(c); });
if (cc_std == "c89" || cc_std == "c90")
langStd = LanguageDialect::Std::C89_90;
else if (cc_std == "c99")
langStd = LanguageDialect::Std::C99;
else if (cc_std == "c17" || cc_std == "c18")
langStd = LanguageDialect::Std::C17_18;
else
langStd = LanguageDialect::Std::C11;
hostCompiler = parsedCmdLine[kHostCCompiler].as<std::string>();
expandIncludes = parsedCmdLine[kExpandCPPIncludeDirectives].as<bool>();
if (parsedCmdLine.count(kDefineCPPMacro))
macrosToDefine = parsedCmdLine[kDefineCPPMacro].as<std::vector<std::string>>();
if (parsedCmdLine.count(KUndefineCPPMacro))
macrosToUndef = parsedCmdLine[KUndefineCPPMacro].as<std::vector<std::string>>();
if (parsedCmdLine.count(kAddDirToCPPSearchPath))
headerSearchPaths = parsedCmdLine[kAddDirToCPPSearchPath].as<std::vector<std::string>>();
inferMissingTypes = parsedCmdLine.count("infer");
}
| 42.647619 | 97 | 0.646494 | [
"vector"
] |
cd92b632432d8da8c8c3d3e41c96231cf22efab2 | 6,267 | hpp | C++ | drivers/sick_ldmrs_driver/src/driver/src/tools/SickThread.hpp | alanjclark/autoware.ai | ba97edbbffb6f22e78912bf96400a59ef6a13daf | [
"Apache-2.0"
] | 64 | 2018-11-19T02:34:05.000Z | 2021-12-27T06:19:48.000Z | ros/src/sensing/drivers/lidar/packages/sick/ldmrs/sick_ldmrs_driver/src/driver/src/tools/SickThread.hpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 40 | 2019-06-24T16:56:15.000Z | 2022-02-28T13:41:58.000Z | ros/src/sensing/drivers/lidar/packages/sick/ldmrs/sick_ldmrs_driver/src/driver/src/tools/SickThread.hpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 34 | 2018-11-27T08:57:32.000Z | 2022-02-18T08:06:04.000Z | //
// SickThread.hpp
//
#ifndef SICKTHREAD_HPP
#define SICKTHREAD_HPP
#include "../BasicDatatypes.hpp"
#include <pthread.h>
#include <unistd.h>
extern "C" void* wrapper_prerun(void*);
class ThreadWrapperBase
{
pthread_t t_id;
friend void* wrapper_prerun(void*);
virtual void thread_entry() = 0;
protected:
void* pthis;
public:
ThreadWrapperBase() {pthis = NULL;};
virtual ~ThreadWrapperBase() {};
void run(void* classptr)
{
if (pthis == NULL)
{
pthis = classptr;
pthread_create(&t_id, NULL, wrapper_prerun, this);
}
}
bool isRunning()
{
if (pthis == NULL)
{
return false;
}
return true;
}
void join()
{
pthread_join(t_id, NULL);
pthis = NULL;
}
pthread_t* get_thread_id()
{
return &t_id;
}
};
/// Wrapper class for posix threads
/**
* Usage: Using object must create an instance of this class, and then
* call start() with its callback function as argument (see start()
* for more details). To stop the thread execution, call stop().
*
* Setting the parameter m_beVerbose to true (e.g. via
* enableVerboseDebugOutput in function start()) will turn on *very*
* verbose output that should be useful for debugging.
*
* The thread callback function itself has 2 parameters:
*
* endThisThread: A bool flag that may be set by the callback function
* to "false" in case the thread function decides this thread
* needs to end.
*
* sleepTimeMs: The sleep time, in ms, that will be spent between
* subsequent calls to the callback function. Default is 10 ms, but
* other times may be set. Note that not all operating systems may be
* able to schedule very short sleep times.
*/
template <typename T, void (T::*M)(bool&, UINT16&)>
class SickThread : public ThreadWrapperBase
{
void thread_entry()
{
T* pt = static_cast<T*>(pthis);
m_threadShouldRun = true;
bool endThread = false;
UINT16 sleepTimeMs = 0;
while ((m_threadShouldRun == true) && (endThread == false))
{
usleep(((UINT32)sleepTimeMs) * 1000);
(pt->*M)(endThread, sleepTimeMs);
}
}
public:
void join()
{
m_threadShouldRun = false;
ThreadWrapperBase::join();
}
SickThread(){m_threadShouldRun = true;}
virtual ~SickThread(){};
bool m_threadShouldRun;
};
/*
template <typename T, void (T::*M)()>
class SickThread : public ThreadWrapperBase
{
void thread_entry()
{
T* pt = static_cast<T*>(pthis);
(pt->*M)();
}
public:
SickThread(){}
virtual ~SickThread(){};
};
*/
// class SickThread
// {
// public:
// /**
// * The thread callback function.
// *
// * \param endThisThread A bool flag that may be set by the callback function
// * to "false" in case the thread function decides this thread
// * needs to end.
// *
// * \param sleepTimeMs The sleep time, in ms, that will be spent between
// * subsequent calls to the callback function. Default is 10 ms, but
// * other times may be set. Note that not all operating systems may be
// * able to schedule very short sleep times.
// */
// // int (*comp)(const void *, const void *)
// typedef void (*ThreadFunction) (bool& endThisThread, UINT16& sleepTimeMs);
//
// /**
// * The thread callback function (simpler version).
// *
// * \return True if the thread should continue to run and
// * continuously call this function (after potentially some waiting
// * time). False if this thread should end now.
// */
// // typedef boost::function < bool (void) > ThreadFunctionSimple;
//
// /// Default constructor.
// SickThread();
//
// /// Destructor. Will call stop() if thread is not yet stopped, and
// /// wait for its completion before destructing this object.
// ~SickThread();
//
// /// Start the thread.
// bool start();
//
// /// Start the thread and also set the thread function. \sa start()
// bool start(ThreadFunction function);
//
// /// Returns true if this thread was started and is running.
// bool isRunning() const;
//
// /// Stops this thread and waits for its completion.
// void stop();
//
// /// Set whether we want verbose debug output
// void setVerboseDebugOutput(bool enableVerboseDebugOutput);
//
// /// Set the thread's "run" function
// void setFunction(ThreadFunction threadFunction);
//
// /// Set the thread's "run" function, simpler version
// // void setFunctionSimple(ThreadFunctionSimple threadFunctionSimple);
//
// /// Set the sleep time between subsequent ThreadFunctionSimple calls in [milliseconds]
// void setSleepTimeMilliseconds(unsigned v);
//
// /// Returns the sleep time between subsequent ThreadFunctionSimple
// /// calls in [milliseconds]. (Default value is zero.)
// unsigned getSleepTimeMilliseconds() const { return m_sleepTimeMilliseconds; }
//
// private:
// static void* thread(void* ptr); // The thread function
// void thread2(); // The member thread function
//
// // typedef boost::mutex Mutex;
//
// pthread_mutex_t m_mutex; // = PTHREAD_MUTEX_INITIALIZER;
// // mutable Mutex m_threadMutex;
// // boost::condition m_threadCondition;
// ThreadFunction m_function;
// // ThreadFunctionSimple m_functionSimple;
//
// // boost::scoped_ptr<boost::thread> m_threadPtr;
// bool m_threadShouldRun;
// bool m_threadIsRunning;
// bool m_beVerbose;
// unsigned m_sleepTimeMilliseconds;
//
// // The thread
// pthread_t m_thread;
//
// };
/*
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define NUM_THREADS 5
void *TaskCode(void *argument)
{
int tid;
tid = *((int *) argument);
printf("Hello World! It's me, thread %d!\n", tid);
// optionally: insert more useful stuff here
return NULL;
}
int main(void)
{
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
int rc, i;
// create all threads
for (i=0; i<NUM_THREADS; ++i) {
thread_args[i] = i;
printf("In main: creating thread %d\n", i);
rc = pthread_create(&threads[i], NULL, TaskCode, (void *) &thread_args[i]);
assert(0 == rc);
}
// wait for all threads to complete
for (i=0; i<NUM_THREADS; ++i) {
rc = pthread_join(threads[i], NULL);
assert(0 == rc);
}
exit(EXIT_SUCCESS);
}
*/
#endif // SICKTHREAD_HPP
| 24.196911 | 90 | 0.657252 | [
"object"
] |
cd96871c70f0128ffd49c7f20e8b2d4f701b446d | 3,666 | hpp | C++ | SpaceNotificationsMain.hpp | TerabyteForever/SpaceNotifications | 2f733dc43a23180b9d17de289fc651807e0655d0 | [
"MIT"
] | 1 | 2020-09-28T19:36:43.000Z | 2020-09-28T19:36:43.000Z | SpaceNotificationsMain.hpp | TerabyteForever/SpaceNotifications | 2f733dc43a23180b9d17de289fc651807e0655d0 | [
"MIT"
] | null | null | null | SpaceNotificationsMain.hpp | TerabyteForever/SpaceNotifications | 2f733dc43a23180b9d17de289fc651807e0655d0 | [
"MIT"
] | null | null | null | //This header is the client side API of the SpaceNotifications. It is designed for the client applications that uses SpaceNotifications.
#include <string>
#include <tuple>
#include <vector>
#include <iostream>
#include <fstream>
#include <exception>
#include <ctime>
#include "include/Colorized.hpp"
//Shared memory support
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <cstdlib>
#include <algorithm>
#include <utility>
using namespace boost::interprocess;
struct NotificationType{
int key;
char title[100];
char notificationItself[1000];
};
typedef allocator<NotificationType, managed_shared_memory::segment_manager> ShmemAllocator;
typedef vector<NotificationType, ShmemAllocator> MainVector;
managed_shared_memory segment(open_or_create,"spacenotifications",65536);
const ShmemAllocator alloc_inst (segment.get_segment_manager());
MainVector *notification_holder = segment.find_or_construct<MainVector>("spaceshared")(alloc_inst);
int notificationCounter = 0;
int readNotificationCounter = 0;
std::ofstream outputFile("SpaceNotificationLog.txt",std::ios::trunc);
class SpaceNotifications{
std::string getDateTime(){
struct tm CurTime;
char datetime[80];
time_t CurrentEpoch = time(NULL);
CurTime = *localtime(&CurrentEpoch);
strftime(datetime, sizeof(datetime), "%d-%m-%Y %H:%M:%S", &CurTime);
return datetime;
}
public:
int getNotificationsCount(){
return notification_holder->size();
}
int getUnreadNotificationsCount(){
return notification_holder->size() - readNotificationCounter;
}
void PushNotification(bool isDebug, char title[], char text[]){
NotificationType a;
a.key = notificationCounter;
strcpy(a.title,title);
strcpy(a.notificationItself,text);
notification_holder->push_back(a);
if(isDebug){
outputFile<<"[ "<<getDateTime()<<" ] "<<"Notification has written to the queue "<<notificationCounter<<"."<<std::endl;
outputFile.eof();
}
notificationCounter++;
}
void ReadNotification(int elementKey){
try{
if(elementKey > notification_holder->size()){
throw std::invalid_argument("Invalid key.");
}
else{
std::cout<<std::endl<<std::endl<<WBOLD_YELLOW_COLOR<<notification_holder->at(elementKey).title<<std::endl<<std::endl<<WBOLD_WHITE_COLOR<<notification_holder->at(elementKey).notificationItself<<std::endl;
readNotificationCounter++;
}
}
catch(std::invalid_argument& inv_arg){
std::cout<<std::endl<<inv_arg.what()<<std::endl;
}
}
}; | 25.458333 | 243 | 0.528914 | [
"vector"
] |
cd9a647b4012da0b053f925d38c56d5ad3c8cd84 | 10,619 | cpp | C++ | examples/cpp/simple/src/SimpleExample.cpp | bretzlaff/libicsneo | 1796cf9487ebf04013118cb2b577c0eea2ad8e18 | [
"BSD-3-Clause"
] | 4 | 2019-03-21T20:25:13.000Z | 2020-03-26T13:14:11.000Z | examples/cpp/simple/src/SimpleExample.cpp | bretzlaff/libicsneo | 1796cf9487ebf04013118cb2b577c0eea2ad8e18 | [
"BSD-3-Clause"
] | 1 | 2019-01-10T13:13:56.000Z | 2019-01-10T21:44:14.000Z | examples/cpp/simple/src/SimpleExample.cpp | bretzlaff/libicsneo | 1796cf9487ebf04013118cb2b577c0eea2ad8e18 | [
"BSD-3-Clause"
] | 7 | 2019-04-11T23:22:51.000Z | 2021-03-22T03:33:40.000Z | #include <iostream>
#include <iomanip>
#include <thread>
#include <chrono>
#include "icsneo/icsneocpp.h"
int main() {
// Print version
std::cout << "Running libicsneo " << icsneo::GetVersion() << std::endl;
std::cout<< "Supported devices:" << std::endl;
for(auto& dev : icsneo::GetSupportedDevices())
std::cout << '\t' << dev << std::endl;
std::cout << "\nFinding devices... " << std::flush;
auto devices = icsneo::FindAllDevices(); // This is type std::vector<std::shared_ptr<icsneo::Device>>
// You now hold the shared_ptrs for these devices, you are considered to "own" these devices from a memory perspective
std::cout << "OK, " << devices.size() << " device" << (devices.size() == 1 ? "" : "s") << " found" << std::endl;
// List off the devices
for(auto& device : devices)
std::cout << '\t' << device->getType() << " - " << device->getSerial() << " @ Handle " << device->getNeoDevice().handle << std::endl;
std::cout << std::endl;
for(auto& device : devices) {
std::cout << "Connecting to " << device->getType() << ' ' << device->getSerial() << "... ";
bool ret = device->open();
if(!ret) { // Failed to open
std::cout << "FAIL" << std::endl;
std::cout << icsneo::GetLastError() << std::endl << std::endl;
continue;
}
std::cout << "OK" << std::endl;
std::cout << "\tGetting HSCAN Baudrate... ";
int64_t baud = device->settings->getBaudrateFor(icsneo::Network::NetID::HSCAN);
if(baud < 0)
std::cout << "FAIL" << std::endl;
else
std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl;
std::cout << "\tSetting HSCAN to operate at 125kbit/s... ";
ret = device->settings->setBaudrateFor(icsneo::Network::NetID::HSCAN, 125000);
std::cout << (ret ? "OK" : "FAIL") << std::endl;
// Changes to the settings do not take affect until you call settings->apply()!
// When you get the baudrate here, you're reading what the device is currently operating on
std::cout << "\tGetting HSCAN Baudrate... (expected to be unchanged) ";
baud = device->settings->getBaudrateFor(icsneo::Network::NetID::HSCAN);
if(baud < 0)
std::cout << "FAIL" << std::endl;
else
std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl;
std::cout << "\tGetting HSCANFD Baudrate... ";
baud = device->settings->getFDBaudrateFor(icsneo::Network::NetID::HSCAN);
if(baud < 0)
std::cout << "FAIL" << std::endl;
else
std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl;
std::cout << "\tSetting HSCANFD to operate at 8Mbit/s... ";
ret = device->settings->setFDBaudrateFor(icsneo::Network::NetID::HSCAN, 8000000);
std::cout << (ret ? "OK" : "FAIL") << std::endl;
std::cout << "\tGetting HSCANFD Baudrate... (expected to be unchanged) ";
baud = device->settings->getFDBaudrateFor(icsneo::Network::NetID::HSCAN);
if(baud < 0)
std::cout << "FAIL" << std::endl;
else
std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl;
// Setting settings temporarily does not need to be done before committing to device EEPROM
// It's done here to test both functionalities
// Setting temporarily will keep these settings until another send/commit is called or a power cycle occurs
std::cout << "\tSetting settings temporarily... ";
ret = device->settings->apply(true);
std::cout << (ret ? "OK" : "FAIL") << std::endl;
// Now that we have applied, we expect that our operating baudrates have changed
std::cout << "\tGetting HSCAN Baudrate... ";
baud = device->settings->getBaudrateFor(icsneo::Network::NetID::HSCAN);
if(baud < 0)
std::cout << "FAIL" << std::endl;
else
std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl;
std::cout << "\tGetting HSCANFD Baudrate... ";
baud = device->settings->getFDBaudrateFor(icsneo::Network::NetID::HSCAN);
if(baud < 0)
std::cout << "FAIL" << std::endl;
else
std::cout << "OK, " << (baud/1000) << "kbit/s" << std::endl;
std::cout << "\tSetting settings permanently... ";
ret = device->settings->apply();
std::cout << (ret ? "OK\n\n" : "FAIL\n\n");
// The concept of going "online" tells the connected device to start listening, i.e. ACKing traffic and giving it to us
std::cout << "\tGoing online... ";
ret = device->goOnline();
if(!ret) {
std::cout << "FAIL" << std::endl;
device->close();
continue;
}
std::cout << "OK" << std::endl;
// A real application would just check the result of icsneo_goOnline() rather than calling this
// This function is intended to be called later on if needed
std::cout << "\tChecking online status... ";
ret = device->isOnline();
if(!ret) {
std::cout << "FAIL\n" << std::endl;
device->close();
continue;
}
std::cout << "OK" << std::endl;
// Now we can either register a handler (or multiple) for messages coming in
// or we can enable message polling, and then call device->getMessages periodically
// We're actually going to do both here, so first enable message polling
device->enableMessagePolling();
device->setPollingMessageLimit(100000); // Feel free to set a limit if you like, the default is a conservative 20k
// Keep in mind that 20k messages comes quickly at high bus loads!
// We can also register a handler
std::cout << "\tStreaming messages in for 3 seconds... " << std::endl;
// MessageCallbacks are powerful, and can filter on things like ArbID for you. See the documentation
auto handler = device->addMessageCallback(icsneo::MessageCallback([](std::shared_ptr<icsneo::Message> message) {
switch(message->network.getType()) {
case icsneo::Network::Type::CAN: {
// A message of type CAN is guaranteed to be a CANMessage, so we can static cast safely
auto canMessage = std::static_pointer_cast<icsneo::CANMessage>(message);
std::cout << "\t\tCAN ";
if(canMessage->isCANFD) {
std::cout << "FD ";
if(!canMessage->baudrateSwitch)
std::cout << "(No BRS) ";
}
// Print the Arbitration ID
std::cout << "0x" << std::hex << std::setw(canMessage->isExtended ? 8 : 3) << std::setfill('0') << canMessage->arbid;
// Print the DLC
std::cout << std::dec << " [" << canMessage->data.size() << "] ";
// Print the data
for(auto& databyte : canMessage->data)
std::cout << std::hex << std::setw(2) << (uint32_t)databyte << ' ';
// Print the timestamp
std::cout << std::dec << '(' << canMessage->timestamp << " ns since 1/1/2007)\n";
break;
}
case icsneo::Network::Type::Ethernet: {
auto ethMessage = std::static_pointer_cast<icsneo::EthernetMessage>(message);
std::cout << "\t\t" << ethMessage->network << " Frame - " << std::dec << ethMessage->data.size() << " bytes on wire\n";
std::cout << "\t\t Timestamped:\t"<< ethMessage->timestamp << " ns since 1/1/2007\n";
// The MACAddress may be printed directly or accessed with the `data` member
std::cout << "\t\t Source:\t" << ethMessage->getSourceMAC() << "\n";
std::cout << "\t\t Destination:\t" << ethMessage->getDestinationMAC();
// Print the data
for(size_t i = 0; i < ethMessage->data.size(); i++) {
if(i % 8 == 0)
std::cout << "\n\t\t " << std::hex << std::setw(4) << std::setfill('0') << i << '\t';
std::cout << std::hex << std::setw(2) << (uint32_t)ethMessage->data[i] << ' ';
}
std::cout << std::dec << std::endl;
break;
}
default:
// Ignoring non-network messages
break;
}
}));
std::this_thread::sleep_for(std::chrono::seconds(3));
device->removeMessageCallback(handler); // Removing the callback means it will not be called anymore
// Since we're using message polling, we can also get the messages which have come in for the past 3 seconds that way
// We could simply call getMessages and it would return a vector of message pointers to us
//auto messages = device->getMessages();
// For speed when calling repeatedly, we can also preallocate and continually reuse a vector
std::vector<std::shared_ptr<icsneo::Message>> messages;
messages.reserve(100000);
device->getMessages(messages);
std::cout << "\t\tGot " << messages.size() << " messages while polling" << std::endl;
// If we wanted to make sure it didn't grow and reallocate, we could also pass in a limit
// If there are more messages than the limit, we can call getMessages repeatedly
//device->getMessages(messages, 100);
// You are now the owner (or one of the owners, if multiple handlers are registered) of the shared_ptrs to the messages
// This means that when you let them go out of scope or reuse the vector, the messages will be freed automatically
// We can transmit messages
std::cout << "\tTransmitting an extended CAN FD frame... ";
auto txMessage = std::make_shared<icsneo::CANMessage>();
txMessage->network = icsneo::Network::NetID::HSCAN;
txMessage->arbid = 0x1C5001C5;
txMessage->data.insert(txMessage->data.end(), {0xaa, 0xbb, 0xcc});
// The DLC will come from the length of the data vector
txMessage->isExtended = true;
txMessage->isCANFD = true;
ret = device->transmit(txMessage); // This will return false if the device does not support CAN FD, or does not have HSCAN
std::cout << (ret ? "OK" : "FAIL") << std::endl;
std::cout << "\tTransmitting an ethernet frame on OP (BR) Ethernet 2... ";
auto ethTxMessage = std::make_shared<icsneo::EthernetMessage>();
ethTxMessage->network = icsneo::Network::NetID::OP_Ethernet2;
ethTxMessage->data.insert(ethTxMessage->data.end(), {
0x00, 0xFC, 0x70, 0x00, 0x01, 0x02, /* Destination MAC */
0x00, 0xFC, 0x70, 0x00, 0x01, 0x01, /* Source MAC */
0x00, 0x00, /* Ether Type */
0x01, 0xC5, 0x01, 0xC5 /* Payload (will automatically be padded on transmit unless you set `ethTxMessage->noPadding`) */
});
ret = device->transmit(ethTxMessage); // This will return false if the device does not support OP (BR) Ethernet 2
std::cout << (ret ? "OK" : "FAIL") << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
// Go offline, stop sending and receiving traffic
std::cout << "\tGoing offline... ";
ret = device->goOffline();
std::cout << (ret ? "OK" : "FAIL") << std::endl;
// Apply default settings
std::cout << "\tSetting default settings... ";
ret = device->settings->applyDefaults(); // This will also write to the device
std::cout << (ret ? "OK" : "FAIL") << std::endl;
std::cout << "\tDisconnecting... ";
ret = device->close();
std::cout << (ret ? "OK\n" : "FAIL\n") << std::endl;
}
std::cout << "Press any key to continue..." << std::endl;
std::cin.get();
return 0;
} | 42.818548 | 135 | 0.634052 | [
"vector"
] |
cd9abcf4c70605e94b2b06c73967289772a137bc | 5,126 | cpp | C++ | testing/unit_testing/src/2_ranks/diffusion.cpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 17 | 2018-11-25T19:29:34.000Z | 2021-09-20T04:46:22.000Z | testing/unit_testing/src/2_ranks/diffusion.cpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 1 | 2020-11-12T15:15:58.000Z | 2020-12-29T15:29:24.000Z | testing/unit_testing/src/2_ranks/diffusion.cpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 4 | 2018-10-17T12:18:10.000Z | 2021-05-28T13:24:20.000Z | #include <Python.h> // this has to be the first included header
#include <iostream>
#include <cstdlib>
#include <fstream>
#include "gtest/gtest.h"
#include "arg.h"
#include "opendihu.h"
#include "../utility.h"
// 2D regular fixed
TEST(DiffusionTest, SerialEqualsParallelRegular2DLinear)
{
// run serial problem
std::string pythonConfig = R"(
# Diffusion 2D
nx = 5 # number of elements in x direction
ny = 8 # number of elements in y direction
# initial values
iv = {}
iv[22] = 5.
iv[23] = 4.
iv[27] = 4.
iv[28] = 3.
config = {
"MultipleInstances": {
"nInstances": 1,
"instances": [{
"ranks": [0],
"ExplicitEuler": {
"initialValues": iv,
"numberTimeSteps": 50,
"endTime": 1.0,
"FiniteElementMethod": {
"inputMeshIsGlobal": True,
"nElements": [nx, ny],
"physicalExtent": [2*nx, 2*ny],
"relativeTolerance": 1e-15,
},
"OutputWriter" : [
{"format": "PythonFile", "filename": "out2", "outputInterval": 1, "binary": False}
]
}
}]
}
}
)";
DihuContext settings(argc, argv, pythonConfig);
typedef Control::MultipleInstances<
TimeSteppingScheme::ExplicitEuler<
SpatialDiscretization::FiniteElementMethod<
Mesh::StructuredRegularFixedOfDimension<2>,
BasisFunction::LagrangeOfOrder<1>,
Quadrature::Gauss<2>,
Equation::Dynamic::IsotropicDiffusion
>
>
> ProblemType;
ProblemType problemSerial(settings);
problemSerial.run();
// run parallel problem
std::string pythonConfig2 = R"(
# Diffusion 2D
nx = 5 # number of elements in x direction
ny = 8 # number of elements in y direction
# initial values
iv = {}
iv[22] = 5.
iv[23] = 4.
iv[27] = 4.
iv[28] = 3.
config = {
"MultipleInstances": {
"nInstances": 1,
"instances": [{
"ranks": [0,1],
"ExplicitEuler": {
"initialValues": iv,
"numberTimeSteps": 50,
"endTime": 1.0,
"FiniteElementMethod": {
"inputMeshIsGlobal": True,
"nElements": [nx, ny],
"physicalExtent": [2*nx, 2*ny],
"relativeTolerance": 1e-15,
},
"OutputWriter" : [
{"format": "PythonFile", "filename": "out2", "outputInterval": 1, "binary": False}
]
}
}]
}
}
)";
DihuContext settings2(argc, argv, pythonConfig2);
ProblemType problemParallel(settings2);
problemParallel.run();
std::vector<std::string> outputFilesToCheck = {"out2_0000010.py", "out2_0000010.0.py", "out2_0000010.1.py"};
assertParallelEqualsSerialOutputFiles(outputFilesToCheck);
nFails += ::testing::Test::HasFailure();
}
// 2D structured deformable
TEST(DiffusionTest, SerialEqualsParallelDeformable2DLinear)
{
// run serial problem
std::string pythonConfig = R"(
# Diffusion 2D
nx = 2 # number of elements in x direction
ny = 2 # number of elements in y direction
# initial values
iv = {}
iv[2] = 5.
iv[3] = 4.
iv[7] = 4.
iv[8] = 3.
config = {
"MultipleInstances": {
"nInstances": 1,
"instances": [{
"ranks": [0],
"ExplicitEuler": {
"initialValues": iv,
"numberTimeSteps": 50,
"endTime": 1.0,
"FiniteElementMethod": {
"inputMeshIsGlobal": True,
"nElements": [nx, ny],
"physicalExtent": [2*nx, 2*ny],
"relativeTolerance": 1e-15,
},
"OutputWriter" : [
{"format": "PythonFile", "filename": "out3", "outputInterval": 1, "binary": False}
]
}
}]
}
}
)";
DihuContext settings(argc, argv, pythonConfig);
typedef Control::MultipleInstances<
TimeSteppingScheme::ExplicitEuler<
SpatialDiscretization::FiniteElementMethod<
Mesh::StructuredDeformableOfDimension<2>,
BasisFunction::LagrangeOfOrder<1>,
Quadrature::Gauss<2>,
Equation::Dynamic::IsotropicDiffusion
>
>
> ProblemType;
ProblemType problemSerial(settings);
problemSerial.run();
// run parallel problem
std::string pythonConfig2 = R"(
# Diffusion 2D
nx = 2 # number of elements in x direction
ny = 2 # number of elements in y direction
# initial values
iv = {}
iv[2] = 5.
iv[3] = 4.
iv[7] = 4.
iv[8] = 3.
config = {
"MultipleInstances": {
"nInstances": 1,
"instances": [{
"ranks": [0,1],
"ExplicitEuler": {
"initialValues": iv,
"numberTimeSteps": 50,
"endTime": 1.0,
"FiniteElementMethod": {
"inputMeshIsGlobal": True,
"nElements": [nx, ny],
"physicalExtent": [2*nx, 2*ny],
"relativeTolerance": 1e-15,
},
"OutputWriter" : [
{"format": "PythonFile", "filename": "out3", "outputInterval": 1, "binary": False}
]
}
}]
}
}
)";
DihuContext settings2(argc, argv, pythonConfig2);
ProblemType problemParallel(settings2);
problemParallel.run();
std::vector<std::string> outputFilesToCheck = {"out3_0000010.py", "out3_0000010.0.py", "out3_0000010.1.py"};
assertParallelEqualsSerialOutputFiles(outputFilesToCheck);
nFails += ::testing::Test::HasFailure();
}
| 22.986547 | 110 | 0.599103 | [
"mesh",
"vector"
] |
cda2fa7ea37a4fe4dd4ea52d24eb38143dca1554 | 23,712 | cc | C++ | libcef/browser/devtools/devtools_frontend.cc | emclient/cef | 84117f2d1be1ce54513290d835c4dcb79da750d4 | [
"BSD-3-Clause"
] | 1,686 | 2017-04-02T19:51:57.000Z | 2022-03-31T10:08:40.000Z | libcef/browser/devtools/devtools_frontend.cc | emclient/cef | 84117f2d1be1ce54513290d835c4dcb79da750d4 | [
"BSD-3-Clause"
] | 16 | 2017-04-21T12:05:52.000Z | 2022-03-01T23:15:13.000Z | libcef/browser/devtools/devtools_frontend.cc | emclient/cef | 84117f2d1be1ce54513290d835c4dcb79da750d4 | [
"BSD-3-Clause"
] | 343 | 2017-04-21T11:20:31.000Z | 2022-03-31T07:47:25.000Z | // Copyright 2013 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 "libcef/browser/devtools/devtools_frontend.h"
#include <stddef.h>
#include <iomanip>
#include <utility>
#include "libcef/browser/browser_context.h"
#include "libcef/browser/devtools/devtools_manager_delegate.h"
#include "libcef/browser/net/devtools_scheme_handler.h"
#include "libcef/common/cef_switches.h"
#include "libcef/common/task_runner_manager.h"
#include "base/base64.h"
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/guid.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/json/string_escape.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/file_url_loader.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/shared_cors_origin_access_list.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "content/public/common/url_constants.h"
#include "content/public/common/url_utils.h"
#include "ipc/ipc_channel.h"
#include "net/base/completion_once_callback.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/cpp/simple_url_loader_stream_consumer.h"
#include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "storage/browser/file_system/native_file_util.h"
#if defined(OS_WIN)
#include <windows.h>
#elif defined(OS_POSIX)
#include <time.h>
#endif
namespace {
// This constant should be in sync with the constant in
// chrome/browser/devtools/devtools_ui_bindings.cc.
constexpr size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4;
constexpr int kMaxLogLineLength = 1024;
static std::string GetFrontendURL() {
return base::StringPrintf("%s://%s/devtools_app.html",
content::kChromeDevToolsScheme,
scheme::kChromeDevToolsHost);
}
base::DictionaryValue BuildObjectForResponse(const net::HttpResponseHeaders* rh,
bool success,
int net_error) {
base::DictionaryValue response;
int responseCode = 200;
if (rh) {
responseCode = rh->response_code();
} else if (!success) {
// In case of no headers, assume file:// URL and failed to load
responseCode = 404;
}
response.SetInteger("statusCode", responseCode);
response.SetInteger("netError", net_error);
response.SetString("netErrorName", net::ErrorToString(net_error));
auto headers = std::make_unique<base::DictionaryValue>();
size_t iterator = 0;
std::string name;
std::string value;
// TODO(caseq): this probably needs to handle duplicate header names
// correctly by folding them.
while (rh && rh->EnumerateHeaderLines(&iterator, &name, &value))
headers->SetString(name, value);
response.Set("headers", std::move(headers));
return response;
}
void WriteTimestamp(std::stringstream& stream) {
#if defined(OS_WIN)
SYSTEMTIME local_time;
GetLocalTime(&local_time);
stream << std::setfill('0') << std::setw(2) << local_time.wMonth
<< std::setw(2) << local_time.wDay << '/' << std::setw(2)
<< local_time.wHour << std::setw(2) << local_time.wMinute
<< std::setw(2) << local_time.wSecond << '.' << std::setw(3)
<< local_time.wMilliseconds;
#elif defined(OS_POSIX)
timeval tv;
gettimeofday(&tv, nullptr);
time_t t = tv.tv_sec;
struct tm local_time;
localtime_r(&t, &local_time);
struct tm* tm_time = &local_time;
stream << std::setfill('0') << std::setw(2) << 1 + tm_time->tm_mon
<< std::setw(2) << tm_time->tm_mday << '/' << std::setw(2)
<< tm_time->tm_hour << std::setw(2) << tm_time->tm_min << std::setw(2)
<< tm_time->tm_sec << '.' << std::setw(6) << tv.tv_usec;
#else
#error Unsupported platform
#endif
}
void LogProtocolMessage(const base::FilePath& log_file,
ProtocolMessageType type,
std::string to_log) {
// Track if logging has failed, in which case we don't keep trying.
static bool log_error = false;
if (log_error)
return;
if (storage::NativeFileUtil::EnsureFileExists(log_file, nullptr) !=
base::File::FILE_OK) {
LOG(ERROR) << "Failed to create file " << log_file.value();
log_error = true;
return;
}
std::string type_label;
switch (type) {
case ProtocolMessageType::METHOD:
type_label = "METHOD";
break;
case ProtocolMessageType::RESULT:
type_label = "RESULT";
break;
case ProtocolMessageType::EVENT:
type_label = "EVENT";
break;
}
std::stringstream stream;
WriteTimestamp(stream);
stream << ": " << type_label << ": " << to_log << "\n";
const std::string& str = stream.str();
if (!base::AppendToFile(log_file, base::StringPiece(str))) {
LOG(ERROR) << "Failed to write file " << log_file.value();
log_error = true;
}
}
} // namespace
class CefDevToolsFrontend::NetworkResourceLoader
: public network::SimpleURLLoaderStreamConsumer {
public:
NetworkResourceLoader(int stream_id,
CefDevToolsFrontend* bindings,
std::unique_ptr<network::SimpleURLLoader> loader,
network::mojom::URLLoaderFactory* url_loader_factory,
int request_id)
: stream_id_(stream_id),
bindings_(bindings),
loader_(std::move(loader)),
request_id_(request_id) {
loader_->SetOnResponseStartedCallback(base::BindOnce(
&NetworkResourceLoader::OnResponseStarted, base::Unretained(this)));
loader_->DownloadAsStream(url_loader_factory, this);
}
private:
void OnResponseStarted(const GURL& final_url,
const network::mojom::URLResponseHead& response_head) {
response_headers_ = response_head.headers;
}
void OnDataReceived(base::StringPiece chunk,
base::OnceClosure resume) override {
base::Value chunkValue;
bool encoded = !base::IsStringUTF8(chunk);
if (encoded) {
std::string encoded_string;
base::Base64Encode(chunk, &encoded_string);
chunkValue = base::Value(std::move(encoded_string));
} else {
chunkValue = base::Value(chunk);
}
base::Value id(stream_id_);
base::Value encodedValue(encoded);
bindings_->CallClientFunction("DevToolsAPI", "streamWrite", std::move(id),
std::move(chunkValue),
std::move(encodedValue));
std::move(resume).Run();
}
void OnComplete(bool success) override {
auto response = BuildObjectForResponse(response_headers_.get(), success,
loader_->NetError());
bindings_->SendMessageAck(request_id_, std::move(response));
bindings_->loaders_.erase(bindings_->loaders_.find(this));
}
void OnRetry(base::OnceClosure start_retry) override { NOTREACHED(); }
const int stream_id_;
CefDevToolsFrontend* const bindings_;
std::unique_ptr<network::SimpleURLLoader> loader_;
int request_id_;
scoped_refptr<net::HttpResponseHeaders> response_headers_;
DISALLOW_COPY_AND_ASSIGN(NetworkResourceLoader);
};
// static
CefDevToolsFrontend* CefDevToolsFrontend::Show(
AlloyBrowserHostImpl* inspected_browser,
const CefWindowInfo& windowInfo,
CefRefPtr<CefClient> client,
const CefBrowserSettings& settings,
const CefPoint& inspect_element_at,
base::OnceClosure frontend_destroyed_callback) {
CefBrowserSettings new_settings = settings;
if (!windowInfo.windowless_rendering_enabled &&
CefColorGetA(new_settings.background_color) != SK_AlphaOPAQUE) {
// Use white as the default background color for windowed DevTools instead
// of the CefSettings.background_color value.
new_settings.background_color = SK_ColorWHITE;
}
CefBrowserCreateParams create_params;
if (!inspected_browser->is_views_hosted())
create_params.window_info.reset(new CefWindowInfo(windowInfo));
create_params.client = client;
create_params.settings = new_settings;
create_params.devtools_opener = inspected_browser;
create_params.request_context = inspected_browser->GetRequestContext();
create_params.extra_info = inspected_browser->browser_info()->extra_info();
CefRefPtr<AlloyBrowserHostImpl> frontend_browser =
AlloyBrowserHostImpl::Create(create_params);
content::WebContents* inspected_contents = inspected_browser->web_contents();
// CefDevToolsFrontend will delete itself when the frontend WebContents is
// destroyed.
CefDevToolsFrontend* devtools_frontend = new CefDevToolsFrontend(
static_cast<AlloyBrowserHostImpl*>(frontend_browser.get()),
inspected_contents, inspect_element_at,
std::move(frontend_destroyed_callback));
// Need to load the URL after creating the DevTools objects.
frontend_browser->GetMainFrame()->LoadURL(GetFrontendURL());
return devtools_frontend;
}
void CefDevToolsFrontend::Activate() {
frontend_browser_->ActivateContents(web_contents());
}
void CefDevToolsFrontend::Focus() {
frontend_browser_->SetFocus(true);
}
void CefDevToolsFrontend::InspectElementAt(int x, int y) {
if (inspect_element_at_.x != x || inspect_element_at_.y != y)
inspect_element_at_.Set(x, y);
if (agent_host_)
agent_host_->InspectElement(inspected_contents_->GetFocusedFrame(), x, y);
}
void CefDevToolsFrontend::Close() {
base::PostTask(FROM_HERE, {content::BrowserThread::UI},
base::BindOnce(&AlloyBrowserHostImpl::CloseBrowser,
frontend_browser_.get(), true));
}
CefDevToolsFrontend::CefDevToolsFrontend(
AlloyBrowserHostImpl* frontend_browser,
content::WebContents* inspected_contents,
const CefPoint& inspect_element_at,
base::OnceClosure frontend_destroyed_callback)
: content::WebContentsObserver(frontend_browser->web_contents()),
frontend_browser_(frontend_browser),
inspected_contents_(inspected_contents),
inspect_element_at_(inspect_element_at),
frontend_destroyed_callback_(std::move(frontend_destroyed_callback)),
file_manager_(frontend_browser, GetPrefs()),
protocol_log_file_(
base::CommandLine::ForCurrentProcess()->GetSwitchValuePath(
switches::kDevToolsProtocolLogFile)),
weak_factory_(this) {
DCHECK(!frontend_destroyed_callback_.is_null());
}
CefDevToolsFrontend::~CefDevToolsFrontend() {}
void CefDevToolsFrontend::ReadyToCommitNavigation(
content::NavigationHandle* navigation_handle) {
content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost();
if (navigation_handle->IsInMainFrame()) {
frontend_host_ = content::DevToolsFrontendHost::Create(
frame, base::BindRepeating(
&CefDevToolsFrontend::HandleMessageFromDevToolsFrontend,
base::Unretained(this)));
return;
}
std::string origin = navigation_handle->GetURL().GetOrigin().spec();
auto it = extensions_api_.find(origin);
if (it == extensions_api_.end())
return;
std::string script = base::StringPrintf("%s(\"%s\")", it->second.c_str(),
base::GenerateGUID().c_str());
content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script);
}
void CefDevToolsFrontend::DocumentAvailableInMainFrame(
content::RenderFrameHost* render_frame_host) {
// Don't call AttachClient multiple times for the same DevToolsAgentHost.
// Otherwise it will call AgentHostClosed which closes the DevTools window.
// This may happen in cases where the DevTools content fails to load.
scoped_refptr<content::DevToolsAgentHost> agent_host =
content::DevToolsAgentHost::GetOrCreateFor(inspected_contents_);
if (agent_host != agent_host_) {
if (agent_host_)
agent_host_->DetachClient(this);
agent_host_ = agent_host;
agent_host_->AttachClient(this);
if (!inspect_element_at_.IsEmpty()) {
agent_host_->InspectElement(inspected_contents_->GetFocusedFrame(),
inspect_element_at_.x, inspect_element_at_.y);
}
}
}
void CefDevToolsFrontend::WebContentsDestroyed() {
if (agent_host_) {
agent_host_->DetachClient(this);
agent_host_ = nullptr;
}
std::move(frontend_destroyed_callback_).Run();
delete this;
}
void CefDevToolsFrontend::HandleMessageFromDevToolsFrontend(
base::Value message) {
if (!message.is_dict())
return;
const std::string* method = message.FindStringKey("method");
if (!method)
return;
int request_id = message.FindIntKey("id").value_or(0);
base::Value* params_value = message.FindListKey("params");
// Since we've received message by value, we can take the list.
base::Value::ListStorage params;
if (params_value) {
params = std::move(*params_value).TakeList();
}
if (*method == "dispatchProtocolMessage") {
if (params.size() < 1)
return;
const std::string* protocol_message = params[0].GetIfString();
if (!agent_host_ || !protocol_message)
return;
if (ProtocolLoggingEnabled()) {
LogProtocolMessage(ProtocolMessageType::METHOD, *protocol_message);
}
agent_host_->DispatchProtocolMessage(
this, base::as_bytes(base::make_span(*protocol_message)));
} else if (*method == "loadCompleted") {
web_contents()->GetMainFrame()->ExecuteJavaScriptForTests(
u"DevToolsAPI.setUseSoftMenu(true);", base::NullCallback());
} else if (*method == "loadNetworkResource") {
if (params.size() < 3)
return;
// TODO(pfeldman): handle some of the embedder messages in content.
const std::string* url = params[0].GetIfString();
const std::string* headers = params[1].GetIfString();
absl::optional<const int> stream_id = params[2].GetIfInt();
if (!url || !headers || !stream_id.has_value()) {
return;
}
GURL gurl(*url);
if (!gurl.is_valid()) {
base::DictionaryValue response;
response.SetInteger("statusCode", 404);
response.SetBoolean("urlValid", false);
SendMessageAck(request_id, std::move(response));
return;
}
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation(
"devtools_handle_front_end_messages", R"(
semantics {
sender: "Developer Tools"
description:
"When user opens Developer Tools, the browser may fetch "
"additional resources from the network to enrich the debugging "
"experience (e.g. source map resources)."
trigger: "User opens Developer Tools to debug a web page."
data: "Any resources requested by Developer Tools."
destination: OTHER
}
policy {
cookies_allowed: YES
cookies_store: "user"
setting:
"It's not possible to disable this feature from settings."
chrome_policy {
DeveloperToolsAvailability {
policy_options {mode: MANDATORY}
DeveloperToolsAvailability: 2
}
}
})");
// Based on DevToolsUIBindings::LoadNetworkResource.
auto resource_request = std::make_unique<network::ResourceRequest>();
resource_request->url = gurl;
// TODO(caseq): this preserves behavior of URLFetcher-based
// implementation. We really need to pass proper first party origin from
// the front-end.
resource_request->site_for_cookies = net::SiteForCookies::FromUrl(gurl);
resource_request->headers.AddHeadersFromString(*headers);
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
if (gurl.SchemeIsFile()) {
mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote =
content::CreateFileURLLoaderFactory(
base::FilePath() /* profile_path */,
nullptr /* shared_cors_origin_access_list */);
url_loader_factory = network::SharedURLLoaderFactory::Create(
std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
std::move(pending_remote)));
} else if (content::HasWebUIScheme(gurl)) {
base::DictionaryValue response;
response.SetInteger("statusCode", 403);
SendMessageAck(request_id, std::move(response));
return;
} else {
auto* partition =
web_contents()->GetBrowserContext()->GetStoragePartitionForUrl(gurl);
url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess();
}
auto simple_url_loader = network::SimpleURLLoader::Create(
std::move(resource_request), traffic_annotation);
auto resource_loader = std::make_unique<NetworkResourceLoader>(
*stream_id, this, std::move(simple_url_loader),
url_loader_factory.get(), request_id);
loaders_.insert(std::move(resource_loader));
return;
} else if (*method == "getPreferences") {
SendMessageAck(
request_id,
GetPrefs()->GetDictionary(prefs::kDevToolsPreferences)->Clone());
return;
} else if (*method == "setPreference") {
if (params.size() < 2)
return;
const std::string* name = params[0].GetIfString();
// We're just setting params[1] as a value anyways, so just make sure it's
// the type we want, but don't worry about getting it.
if (!name || !params[1].is_string())
return;
DictionaryPrefUpdate update(GetPrefs(), prefs::kDevToolsPreferences);
update.Get()->SetKey(*name, std::move(params[1]));
} else if (*method == "removePreference") {
const std::string* name = params[0].GetIfString();
if (!name)
return;
DictionaryPrefUpdate update(GetPrefs(), prefs::kDevToolsPreferences);
update.Get()->RemoveKey(*name);
} else if (*method == "requestFileSystems") {
web_contents()->GetMainFrame()->ExecuteJavaScriptForTests(
u"DevToolsAPI.fileSystemsLoaded([]);", base::NullCallback());
} else if (*method == "reattach") {
if (!agent_host_)
return;
agent_host_->DetachClient(this);
agent_host_->AttachClient(this);
} else if (*method == "registerExtensionsAPI") {
if (params.size() < 2)
return;
const std::string* origin = params[0].GetIfString();
const std::string* script = params[1].GetIfString();
if (!origin || !script)
return;
extensions_api_[*origin + "/"] = *script;
} else if (*method == "save") {
if (params.size() < 3)
return;
const std::string* url = params[0].GetIfString();
const std::string* content = params[1].GetIfString();
absl::optional<bool> save_as = params[2].GetIfBool();
if (!url || !content || !save_as.has_value())
return;
file_manager_.SaveToFile(*url, *content, *save_as);
} else if (*method == "append") {
if (params.size() < 2)
return;
const std::string* url = params[0].GetIfString();
const std::string* content = params[1].GetIfString();
if (!url || !content)
return file_manager_.AppendToFile(*url, *content);
} else {
return;
}
if (request_id)
SendMessageAck(request_id, base::Value());
}
void CefDevToolsFrontend::DispatchProtocolMessage(
content::DevToolsAgentHost* agent_host,
base::span<const uint8_t> message) {
if (!frontend_browser_->GetWebContents() ||
frontend_browser_->GetWebContents()->IsBeingDestroyed()) {
return;
}
base::StringPiece str_message(reinterpret_cast<const char*>(message.data()),
message.size());
if (ProtocolLoggingEnabled()) {
// Quick check to avoid parsing the JSON object. Events begin with a
// "method" value whereas method results begin with an "id" value.
LogProtocolMessage(base::StartsWith(str_message, "{\"method\":")
? ProtocolMessageType::EVENT
: ProtocolMessageType::RESULT,
str_message);
}
if (str_message.length() < kMaxMessageChunkSize) {
CallClientFunction("DevToolsAPI", "dispatchMessage",
base::Value(std::string(str_message)));
} else {
size_t total_size = str_message.length();
for (size_t pos = 0; pos < str_message.length();
pos += kMaxMessageChunkSize) {
base::StringPiece str_message_chunk =
str_message.substr(pos, kMaxMessageChunkSize);
CallClientFunction(
"DevToolsAPI", "dispatchMessageChunk",
base::Value(std::string(str_message_chunk)),
base::Value(base::NumberToString(pos ? 0 : total_size)));
}
}
}
void CefDevToolsFrontend::CallClientFunction(
const std::string& object_name,
const std::string& method_name,
base::Value arg1,
base::Value arg2,
base::Value arg3,
base::OnceCallback<void(base::Value)> cb) {
std::string javascript;
web_contents()->GetMainFrame()->AllowInjectingJavaScript();
base::Value arguments(base::Value::Type::LIST);
if (!arg1.is_none()) {
arguments.Append(std::move(arg1));
if (!arg2.is_none()) {
arguments.Append(std::move(arg2));
if (!arg3.is_none()) {
arguments.Append(std::move(arg3));
}
}
}
web_contents()->GetMainFrame()->ExecuteJavaScriptMethod(
base::ASCIIToUTF16(object_name), base::ASCIIToUTF16(method_name),
std::move(arguments), std::move(cb));
}
void CefDevToolsFrontend::SendMessageAck(int request_id, base::Value arg) {
CallClientFunction("DevToolsAPI", "embedderMessageAck",
base::Value(request_id), std::move(arg));
}
bool CefDevToolsFrontend::ProtocolLoggingEnabled() const {
return !protocol_log_file_.empty();
}
void CefDevToolsFrontend::LogProtocolMessage(ProtocolMessageType type,
const base::StringPiece& message) {
DCHECK(ProtocolLoggingEnabled());
std::string to_log(message.substr(0, kMaxLogLineLength));
// Execute in an ordered context that allows blocking.
auto task_runner = CefTaskRunnerManager::Get()->GetBackgroundTaskRunner();
task_runner->PostTask(
FROM_HERE, base::BindOnce(::LogProtocolMessage, protocol_log_file_, type,
std::move(to_log)));
}
void CefDevToolsFrontend::AgentHostClosed(
content::DevToolsAgentHost* agent_host) {
DCHECK(agent_host == agent_host_.get());
agent_host_ = nullptr;
Close();
}
PrefService* CefDevToolsFrontend::GetPrefs() const {
return CefBrowserContext::FromBrowserContext(
frontend_browser_->web_contents()->GetBrowserContext())
->AsProfile()
->GetPrefs();
}
| 36.819876 | 80 | 0.68265 | [
"object"
] |
cda3cc1c7ddab55cf91929e42c13ac3a5f79903d | 6,813 | hpp | C++ | include/oglplus/imports/blend_file/block_data.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | include/oglplus/imports/blend_file/block_data.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | include/oglplus/imports/blend_file/block_data.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | /**
* @file oglplus/imports/blend_file/block_data.hpp
* @brief Helper class providing access to .blend file block data
*
* @author Matus Chochlik
*
* Copyright 2010-2019 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_IMPORTS_BLEND_FILE_BLOCK_DATA_1107121519_HPP
#define OGLPLUS_IMPORTS_BLEND_FILE_BLOCK_DATA_1107121519_HPP
#include <oglplus/imports/blend_file/flattened.hpp>
#include <oglplus/imports/blend_file/type.hpp>
#include <oglplus/imports/blend_file/visitor.hpp>
namespace oglplus {
namespace imports {
/// Class wrapping the data of a file block
class BlendFileBlockData {
private:
// TODO: some kind of caching in BlendFile or BlendFileBlock
// and only a reference to the buffer here
// to make this class more lightweight
std::vector<char> _block_data;
Endian _byte_order;
std::size_t _ptr_size;
std::size_t _struct_size;
friend class BlendFile;
BlendFileBlockData(
std::vector<char>&& block_data,
Endian byte_order,
std::size_t ptr_size,
std::size_t struct_size)
: _block_data(block_data)
, _byte_order(byte_order)
, _ptr_size(ptr_size)
, _struct_size(struct_size) {
}
template <unsigned Level>
BlendFilePointerTpl<Level> _do_make_pointer(
const char* pos, std::size_t type_index) const;
template <unsigned Level>
BlendFilePointerTpl<Level> _do_get_pointer(
std::size_t type_index,
std::size_t field_offset,
std::size_t block_element,
std::size_t field_element,
std::size_t data_offset) const;
template <unsigned Level>
BlendFilePointerTpl<Level> _get_pointer(
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element,
std::size_t field_element,
std::size_t data_offset) const;
public:
BlendFileBlockData(BlendFileBlockData&& tmp)
: _block_data(tmp._block_data)
, _byte_order(tmp._byte_order)
, _ptr_size(tmp._ptr_size)
, _struct_size(tmp._struct_size) {
}
/// Returns the raw data of the block
const char* RawData() const {
return _block_data.data();
}
/// Returns the i-th byte in the block
char RawByte(std::size_t i) const {
assert(i < _block_data.size());
return _block_data[i];
}
/// returns the size (in bytes) of the raw data
std::size_t DataSize() const {
return _block_data.size();
}
/// Returns a pointer at the specified index
BlendFilePointer AsPointerTo(
const BlendFileType& type,
std::size_t index = 0,
std::size_t data_offset = 0) const;
/// Returns the value of the specified field as a pointer
BlendFilePointer GetPointer(
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element = 0,
std::size_t field_element = 0,
std::size_t data_offset = 0) const;
/// Returns the value of the specified field as a pointer to pointer
BlendFilePointerToPointer GetPointerToPointer(
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element = 0,
std::size_t field_element = 0,
std::size_t data_offset = 0) const;
/// Returns the value at the specified offset as an integer
template <typename Int>
Int GetInt(
std::size_t field_offset,
std::size_t block_element,
std::size_t field_element,
std::size_t data_offset) const {
const char* pos = _block_data.data() + data_offset +
block_element * _struct_size +
field_element * sizeof(Int) + field_offset;
return aux::ReorderToNative(
_byte_order, *reinterpret_cast<const Int*>(pos));
}
/// Returns the value of the specified field as an integer
template <typename Int>
Int GetInt(
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element = 0,
std::size_t field_element = 0,
std::size_t data_offset = 0) const {
assert(sizeof(Int) == flat_field.Field().BaseType().Size());
return GetInt<Int>(
flat_field.Offset(), block_element, field_element, data_offset);
}
/// Returns the value at the specified offset as a floating point value
template <typename Float>
Float GetFloat(
std::size_t field_offset,
std::size_t block_element,
std::size_t field_element,
std::size_t data_offset) const {
const char* pos = _block_data.data() + data_offset +
block_element * _struct_size +
field_element * sizeof(Float) + field_offset;
return *reinterpret_cast<const Float*>(pos);
}
/// Returns the value of the specified field as a floating point value
template <typename Float>
Float GetFloat(
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element = 0,
std::size_t field_element = 0,
std::size_t data_offset = 0) const {
assert(sizeof(Float) == flat_field.Field().BaseType().Size());
return GetFloat<Float>(
flat_field.Offset(), block_element, field_element, data_offset);
}
/// Returns the value at the specified offset as a string
std::string GetString(
std::size_t field_size,
std::size_t field_offset,
std::size_t block_element,
std::size_t field_element,
std::size_t data_offset) const;
/// Returns the value of the specified field as a string
std::string GetString(
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element = 0,
std::size_t field_element = 0,
std::size_t data_offset = 0) const {
return GetString(
flat_field.Size(),
flat_field.Offset(),
block_element,
field_element,
data_offset);
}
/// Visits the value of the specified field by a visitor
void ValueVisitRef(
BlendFileVisitor& visitor,
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element = 0,
std::size_t field_element = 0,
std::size_t data_offset = 0) const;
template <typename Visitor>
void ValueVisit(
Visitor visitor,
const BlendFileFlattenedStructField& flat_field,
std::size_t block_element = 0,
std::size_t field_element = 0) const {
ValueVisitRef(visitor, flat_field, block_element, field_element);
}
};
} // namespace imports
} // namespace oglplus
#if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)
#include <oglplus/imports/blend_file/block_data.ipp>
#endif // OGLPLUS_LINK_LIBRARY
#endif // include guard
| 32.598086 | 75 | 0.673712 | [
"vector"
] |
cda8be4428ff08cf9822147370d41cd13f647ec1 | 4,648 | cpp | C++ | lib/leptonAPI/src/LeptonCamera.cpp | clubcapra/LePi | 5235500b83fe807364825811310049afe53b576f | [
"MIT"
] | null | null | null | lib/leptonAPI/src/LeptonCamera.cpp | clubcapra/LePi | 5235500b83fe807364825811310049afe53b576f | [
"MIT"
] | null | null | null | lib/leptonAPI/src/LeptonCamera.cpp | clubcapra/LePi | 5235500b83fe807364825811310049afe53b576f | [
"MIT"
] | null | null | null | /**
* This file is part of the LePi Project:
* https://github.com/cosmac/LePi
*
* MIT License
*
* Copyright (c) 2017 Andrei Claudiu Cosma
*
* 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.
*/
// LePi
#include <LeptonCommon.h>
#include <LeptonUtils.h>
#include <LeptonAPI.h>
#include <LeptonCamera.h>
// C/C++
#include <vector>
#include <thread>
#include <mutex>
#include <iostream>
LeptonCamera::LeptonCamera()
: grabber_thread_(),
run_thread_{false},
has_frame_{false},
lePi_(),
sensor_temperature_{0.0} {
// Open communication with the sensor
if (!lePi_.OpenConnection()) {
std::cerr << "Unable to open communication with the sensor" << std::endl;
throw std::runtime_error("Connection failed.");
}
// Check lepton type
lepton_type_ = lePi_.GetType();
if (LEPTON_UNKNOWN == lepton_type_) {
throw std::runtime_error("Unknown lepton type.");
}
// Prepare buffers
lepton_config_ = LeptonCameraConfig(lepton_type_);
frame_to_read_.resize(lepton_config_.width * lepton_config_.height);
frame_to_write_.resize(lepton_config_.width * lepton_config_.height);
};
LeptonCamera::~LeptonCamera() {
// Stop thread
stop();
// Close communication with the sensor
if (!lePi_.CloseConnection()) {
std::cerr << "Unable to close communication with the sensor" << std::endl;
}
};
void LeptonCamera::start() {
// Avoid starting the thread if already runs
if (false == run_thread_) {
run_thread_ = true;
grabber_thread_ = std::thread(&LeptonCamera::run, this);
}
}
void LeptonCamera::stop() {
// Stop the thread only if there is a thread running
if (true == run_thread_) {
run_thread_ = false;
if (grabber_thread_.joinable()) {
grabber_thread_.join();
}
}
}
void LeptonCamera::run() {
while (run_thread_) {
// Get new frame
try {
sensor_temperature_ = leptonI2C_InternalTemp();
if (!lePi_.GetFrame(frame_to_write_.data(), FRAME_U16)) {
continue;
}
}
catch (...) {
lePi_.RebootSensor();
continue;
}
// Lock resources and swap buffers
lock_.lock();
std::swap(frame_to_write_, frame_to_read_);
has_frame_ = true;
lock_.unlock();
}
}
void LeptonCamera::getFrameU8(std::vector <uint8_t> &frame) {
// Resize output frame
frame.resize(frame_to_read_.size());
// Lock resources
lock_.lock();
// Find frame min and max
uint16_t minValue = 65535;
uint16_t maxValue = 0;
for (size_t i = 0; i < frame_to_read_.size(); i++) {
if (frame_to_read_[i] > maxValue) {
maxValue = frame_to_read_[i];
}
if (frame_to_read_[i] < minValue) {
minValue = frame_to_read_[i];
}
}
// Scale frame range and copy to output
float scale = 255.f / static_cast<float>(maxValue - minValue);
for (size_t i = 0; i < frame_to_read_.size(); i++) {
frame[i] = static_cast<uint8_t>((frame_to_read_[i] - minValue) * scale);
}
has_frame_ = false;
// Release resources
lock_.unlock();
}
void LeptonCamera::getFrameU16(std::vector <uint16_t> &frame) {
// Lock resources
lock_.lock();
std::copy(frame_to_read_.begin(), frame_to_read_.end(), frame.begin());
has_frame_ = false;
// Release resources
lock_.unlock();
}
bool LeptonCamera::sendCommand(LeptonI2CCmd cmd, void *buffer) {
return lePi_.SendCommand(cmd, buffer);
} | 28.691358 | 82 | 0.646299 | [
"vector"
] |
cdaa6207d0ca393edceb21d243f42e0caa5643a7 | 6,068 | cc | C++ | mindspore/ccsrc/minddata/dataset/engine/datasetops/filter_op.cc | mindspore-ai/mindspore | a9fbb25530a2874166ff0045ddcdfc73207bf5eb | [
"Apache-2.0"
] | 3,200 | 2020-02-17T12:45:41.000Z | 2022-03-31T20:21:16.000Z | mindspore/ccsrc/minddata/dataset/engine/datasetops/filter_op.cc | Ascend/mindspore | 1509d3f848e6685660194d9f58646fc73ae0f0f0 | [
"Apache-2.0"
] | 176 | 2020-02-12T02:52:11.000Z | 2022-03-28T22:15:55.000Z | mindspore/ccsrc/minddata/dataset/engine/datasetops/filter_op.cc | mindspore-ai/mindspore | a9fbb25530a2874166ff0045ddcdfc73207bf5eb | [
"Apache-2.0"
] | 621 | 2020-03-09T01:31:41.000Z | 2022-03-30T03:43:19.000Z | /**
* Copyright 2020-2021 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "minddata/dataset/engine/datasetops/filter_op.h"
#include <algorithm>
#include <cstring>
#include <iostream>
#include <memory>
#include <vector>
#include "minddata/dataset/core/config_manager.h"
#include "minddata/dataset/core/global_context.h"
#include "minddata/dataset/core/tensor.h"
#include "minddata/dataset/kernels/tensor_op.h"
#include "minddata/dataset/util/log_adapter.h"
#include "minddata/dataset/util/task_manager.h"
namespace mindspore {
namespace dataset {
FilterOp::FilterOp(const std::vector<std::string> &in_col_names, int32_t num_workers, int32_t op_queue_size,
std::shared_ptr<TensorOp> predicate_func)
: ParallelOp(num_workers, op_queue_size), predicate_func_(std::move(predicate_func)), in_columns_(in_col_names) {
worker_in_queues_.Init(num_workers, op_queue_size);
}
Status FilterOp::operator()() {
RETURN_IF_NOT_OK(RegisterAndLaunchThreads());
// Synchronize with TaskManager.
TaskManager::FindMe()->Post();
child_iterator_ = std::make_unique<ChildIterator>(this, 0, 0);
TensorRow new_row;
RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row));
int64_t cnt = 0;
while (child_iterator_->EofHandled() == false) {
while (new_row.empty() == false) {
RETURN_IF_NOT_OK(worker_in_queues_[cnt % num_workers_]->EmplaceBack(new_row));
cnt++;
RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row));
}
RETURN_IF_NOT_OK(worker_in_queues_[cnt++ % num_workers_]->EmplaceBack(std::move(TensorRow(TensorRow::kFlagEOE))));
RETURN_IF_NOT_OK(child_iterator_->FetchNextTensorRow(&new_row));
}
RETURN_IF_NOT_OK(worker_in_queues_[cnt++ % num_workers_]->EmplaceBack(std::move(TensorRow(TensorRow::kFlagEOF))));
// EOF received, send quit signal to all workers
for (int32_t ind = 0; ind < num_workers_; ind++) {
RETURN_IF_NOT_OK(worker_in_queues_[cnt++ % num_workers_]->EmplaceBack(std::move(TensorRow(TensorRow::kFlagQuit))));
}
return Status::OK();
}
Status FilterOp::EofReceived(int32_t) { return Status::OK(); }
Status FilterOp::EoeReceived(int32_t) { return Status::OK(); }
// Validating if each of the input_columns exists in the column_name_id_map_.
Status FilterOp::ValidateInColumns(const std::vector<std::string> &input_columns) {
for (const auto &inCol : input_columns) {
bool found = column_name_id_map_.find(inCol) != column_name_id_map_.end() ? true : false;
if (!found) {
std::string err_msg = "Invalid parameter, column name: " + inCol + " does not exist in the dataset columns.";
RETURN_STATUS_UNEXPECTED(err_msg);
}
}
return Status::OK();
}
// A print method typically used for debugging.
void FilterOp::Print(std::ostream &out, bool show_all) const {
if (!show_all) {
// Call the super class for displaying any common 1-liner info
ParallelOp::Print(out, show_all);
// Then show any custom derived-internal 1-liner info for this op
out << "\n";
} else {
// Call the super class for displaying any common detailed info
ParallelOp::Print(out, show_all);
// Then show any custom derived-internal stuff
out << "\nInput column names:";
for (size_t i = 0; i < in_columns_.size(); i++) {
out << " " << in_columns_[i];
}
out << "\n\n";
}
}
Status FilterOp::WorkerEntry(int32_t worker_id) {
TaskManager::FindMe()->Post();
TensorRow new_row;
RETURN_IF_NOT_OK(worker_in_queues_[worker_id]->PopFront(&new_row));
while (!new_row.quit()) {
// Getting a TensorRow to work on.
if (new_row.eoe()) {
RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(new_row));
} else if (new_row.eof()) {
RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(new_row));
} else {
RETURN_IF_NOT_OK(ValidateInColumns(in_columns_));
bool result = false;
RETURN_IF_NOT_OK(WorkerCompute(new_row, &result));
if (result) {
RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(new_row));
} else {
RETURN_IF_NOT_OK(worker_out_queues_[worker_id]->EmplaceBack(TensorRow(TensorRow::TensorRowFlags::kFlagSkip)));
}
}
RETURN_IF_NOT_OK(worker_in_queues_[worker_id]->PopFront(&new_row));
}
return Status::OK();
}
Status FilterOp::WorkerCompute(const TensorRow &in_row, bool *out_predicate) {
TensorRow to_process;
if (in_columns_.empty() == true) {
MS_LOG(INFO) << "Input columns in filter operator is empty, will apply to the all column in the current table.";
to_process = in_row;
} else {
(void)std::transform(
in_columns_.begin(), in_columns_.end(), std::back_inserter(to_process),
[&in_row, this](const auto &it) -> std::shared_ptr<Tensor> { return in_row[column_name_id_map_[it]]; });
}
RETURN_IF_NOT_OK(InvokePredicateFunc(to_process, out_predicate));
return Status::OK();
}
Status FilterOp::CheckInput(const TensorRow &input) const {
for (auto &item : input) {
if (item == nullptr) {
RETURN_STATUS_UNEXPECTED("Invalid data, input tensor is null.");
}
}
return Status::OK();
}
Status FilterOp::InvokePredicateFunc(const TensorRow &input, bool *out_predicate) {
RETURN_IF_NOT_OK(CheckInput(input));
TensorRow output;
RETURN_IF_NOT_OK(predicate_func_->Compute(input, &output));
RETURN_IF_NOT_OK(output.at(0)->GetItemAt(out_predicate, {}));
return Status(StatusCode::kSuccess, "FilterOp predicate func call succeed");
}
} // namespace dataset
} // namespace mindspore
| 37.226994 | 119 | 0.716546 | [
"vector",
"transform"
] |
cdaa82023a7f3693b230a9f3fb868a2ab7980acb | 7,059 | cpp | C++ | src/class_Individual.cpp | mikldk/popr | a6a444a5e288fb3f0db99a06b01627e039b7fcf2 | [
"MIT"
] | null | null | null | src/class_Individual.cpp | mikldk/popr | a6a444a5e288fb3f0db99a06b01627e039b7fcf2 | [
"MIT"
] | null | null | null | src/class_Individual.cpp | mikldk/popr | a6a444a5e288fb3f0db99a06b01627e039b7fcf2 | [
"MIT"
] | null | null | null | #include "popr_types.hpp"
#include <stdexcept>
/*
==========================================
Individual
==========================================
*/
Individual::Individual(int pid, bool is_male) {
m_pid = pid;
m_is_male = is_male;
m_children = new std::vector<Individual*>();
}
Individual::~Individual() {
delete m_children;
}
int Individual::get_pid() const {
return m_pid;
}
/*
int Individual::get_pid_m() const {
return m_pid_m;
}
int Individual::get_pid_f() const {
return m_pid_f;
}
*/
bool Individual::get_is_male() const {
return m_is_male;
}
void Individual::add_child(Individual* child) {
m_children->push_back(child);
}
void Individual::set_mother(Individual* i) {
// FIXME: Check sex of i?
m_mother = i;
}
void Individual::set_father(Individual* i) {
// FIXME: Check sex of i?
m_father = i;
}
Individual* Individual::get_mother() const {
return m_mother;
}
Individual* Individual::get_father() const {
return m_father;
}
std::vector<Individual*>* Individual::get_children() const {
return m_children;
}
bool Individual::pedigree_is_set() const {
return (m_pedigree_id != 0);
}
int Individual::get_pedigree_id() const {
return m_pedigree_id;
}
Pedigree* Individual::get_pedigree() const {
return m_pedigree;
}
void Individual::set_pedigree_id(int id, Pedigree* ped, int* pedigree_size) {
if (this->pedigree_is_set()) {
return;
}
m_pedigree = ped;
m_pedigree_id = id;
*pedigree_size += 1;
ped->add_member(this);
if (m_mother != NULL) {
m_mother->set_pedigree_id(id, ped, pedigree_size);
}
if (m_father != NULL) {
m_father->set_pedigree_id(id, ped, pedigree_size);
}
for (auto &child : (*m_children)) {
ped->add_relation(this, child);
child->set_pedigree_id(id, ped, pedigree_size);
}
}
void Individual::set_alive_status(bool is_alive) {
m_is_alive = is_alive;
}
bool Individual::get_alive_status() const {
return m_is_alive;
}
void Individual::set_birth_year(int birth_year) {
m_birth_year = birth_year;
}
int Individual::get_birth_year() const {
return m_birth_year;
}
void Individual::set_location(double etrs89e, double etrs89n) {
m_etrs89e = etrs89e;
m_etrs89n = etrs89n;
m_etrs89set = true;
}
double Individual::get_etrs89e() const {
return m_etrs89e;
}
double Individual::get_etrs89n() const {
return m_etrs89n;
}
bool Individual::location_is_set() const {
return m_etrs89set;
}
void Individual::dijkstra_reset() {
m_dijkstra_visited = false;
m_dijkstra_distance = 0;
}
void Individual::dijkstra_tick_distance(int step) {
m_dijkstra_distance += step;
}
void Individual::dijkstra_set_distance_if_less(int dist) {
if (m_dijkstra_distance < dist) {
m_dijkstra_distance = dist;
}
}
void Individual::dijkstra_mark_visited() {
m_dijkstra_visited = true;
}
int Individual::dijkstra_get_distance() const {
return m_dijkstra_distance;
}
bool Individual::dijkstra_was_visited() const {
return m_dijkstra_visited;
}
/*
void Individual::set_pedigree_id_f(int id, Pedigree* ped, int* pedigree_size) {
if (!(this->get_is_male())) {
return;
}
if (m_pedigree_id_f != 0) {
return;
}
m_pedigree_id_f = id;
*pedigree_size += 1;
ped->add_member(this);
if (m_father != NULL) {
m_father->set_pedigree_id_f(id, ped, pedigree_size);
}
for (auto &child : (*m_children)) {
ped->add_relation(this, child);
child->set_pedigree_id_f(id, ped, pedigree_size);
}
}
*/
// ASSUMES TREE!
//FIXME: Heavily relies on it being a tree, hence there is only one path connecting every pair of nodes
void Individual::meiosis_dist_tree_internal(Individual* dest, int* dist) const {
if (this->get_pid() == dest->get_pid()) {
//FIXME: Heavily relies on it being a tree, hence there is only one path connecting every pair of nodes
*dist = dest->dijkstra_get_distance();
return;
}
if (dest->get_mother() != NULL) {
throw std::invalid_argument("meiosis_dist_tree_internal assumes tree (e.g. Ychr)!");
}
if (dest->dijkstra_was_visited()) {
return;
}
dest->dijkstra_mark_visited();
dest->dijkstra_tick_distance(1);
int m = dest->dijkstra_get_distance();
// FIXME: If not tree, then distance must be somehow checked if shorter and then adjusted
Individual* father = dest->get_father();
if (father != NULL) {
//tree: ok
father->dijkstra_tick_distance(m);
// general? FIXME Correct?
//father->dijkstra_set_distance_if_less(m);
this->meiosis_dist_tree_internal(father, dist);
}
std::vector<Individual*>* children = dest->get_children();
for (auto child : *children) {
//tree: ok
child->dijkstra_tick_distance(m);
// general? FIXME Correct?
//child->dijkstra_set_distance_if_less(m);
this->meiosis_dist_tree_internal(child, dist);
}
}
// ASSUMES TREE!
int Individual::meiosis_dist_tree(Individual* dest) const {
if (!(this->pedigree_is_set())) {
throw std::invalid_argument("!(this->pedigree_is_set())");
}
if (dest == NULL) {
throw std::invalid_argument("dest is NULL");
}
if (!(dest->pedigree_is_set())) {
throw std::invalid_argument("!(dest->pedigree_is_set())");
}
if (this->get_pedigree_id() != dest->get_pedigree_id()) {
return -1;
}
std::vector<Individual*>* inds = this->get_pedigree()->get_all_individuals();
for (auto child : *inds) {
child->dijkstra_reset();
}
// At this point, the individuals this and dest belong to same pedigree
int dist = 0;
this->meiosis_dist_tree_internal(dest, &dist);
return dist;
}
/*
Father haplotype
FIXME mutation_model?
*/
void Individual::father_haplotype_mutate(double mutation_rate) {
if (!m_father_haplotype_set) {
Rcpp::stop("Father haplotype not set yet, so cannot mutate");
}
if (m_father_haplotype_mutated) {
Rcpp::stop("Father haplotype already set and mutated");
}
for (int loc = 0; loc < m_father_haplotype.size(); ++loc) {
if (R::runif(0.0, 1.0) < mutation_rate) {
if (R::runif(0.0, 1.0) < 0.5) {
m_father_haplotype[loc] = m_father_haplotype[loc] - 1;
} else {
m_father_haplotype[loc] = m_father_haplotype[loc] + 1;
}
}
}
}
bool Individual::is_father_haplotype_set() const {
return m_father_haplotype_set;
}
void Individual::set_father_haplotype(std::vector<int> h) {
m_father_haplotype = h;
m_father_haplotype_set = true;
}
std::vector<int> Individual::get_father_haplotype() const {
return m_father_haplotype;
}
void Individual::pass_haplotype_to_children(bool recursive, double mutation_rate) {
for (auto &child : (*m_children)) {
child->set_father_haplotype(m_father_haplotype);
child->father_haplotype_mutate(mutation_rate);
if (recursive) {
child->pass_haplotype_to_children(recursive, mutation_rate);
}
}
}
void Individual::set_include_meioses_dist(bool status) {
m_include_meioses_dist = status;
}
bool Individual::get_include_meioses_dist() const {
return m_include_meioses_dist;
}
| 21.262048 | 107 | 0.6797 | [
"vector"
] |
cdaf559bca574c49c2657af3464a2b60a6893deb | 2,959 | hpp | C++ | include/Lintel/TestUtil.hpp | sbu-fsl/Lintel | b9e603aaec630c8d3fae2f21fc156582d11d84c9 | [
"BSD-3-Clause"
] | null | null | null | include/Lintel/TestUtil.hpp | sbu-fsl/Lintel | b9e603aaec630c8d3fae2f21fc156582d11d84c9 | [
"BSD-3-Clause"
] | 1 | 2020-10-05T21:20:36.000Z | 2020-10-05T21:56:51.000Z | include/Lintel/TestUtil.hpp | sbu-fsl/Lintel | b9e603aaec630c8d3fae2f21fc156582d11d84c9 | [
"BSD-3-Clause"
] | null | null | null | /* -*-C++-*- */
/*
(c) Copyright 2008-2012, Hewlett-Packard Development Company, LP
See the file named COPYING for license details
*/
/** @file
\brief Some help with testing things that throw invariants
*/
#ifndef LINTEL_TESTUTIL_HPP
#define LINTEL_TESTUTIL_HPP
#include <vector>
#include <string>
#include <Lintel/AssertBoost.hpp>
#include <Lintel/StringUtil.hpp>
/// Macro to test whether a particular chunk of code has an invariant
/// with any of a vector of messages; Assumes that you have not set up any
/// AssertBoost functions
#define TEST_INVARIANT_MSGVEC(code, messages) \
AssertBoostFnBefore(AssertBoostThrowExceptionFn); \
try { \
code; \
FATAL_ERROR("no invariant happened"); \
} catch (AssertBoostException &e) { \
AssertBoostClearFns(); \
bool found = false; \
for (std::vector<std::string>::iterator i = messages.begin(); \
i != messages.end(); ++i) { \
if (e.msg == *i) { found = true; break; } \
} \
INVARIANT(found, boost::format("unexpected error message '%s'") % e.msg); \
}
/// One possibility variant of TEST_INVARIANT_MSGVEC
#define TEST_INVARIANT_MSG1(code, message) { \
std::vector<std::string> msgs; msgs.push_back(message); \
TEST_INVARIANT_MSGVEC(code, msgs); \
}
// TODO: remove uses and purge
/// Deprecated, old version of MSG1
#define TEST_INVARIANTMSG(code, message) TEST_INVARIANT_MSG1(code, message)
/// Two possibility variant of TEST_INVARIANT_MSGVEC
#define TEST_INVARIANT_MSG2(code, msg1, msg2) { \
std::vector<std::string> msgs; msgs.push_back(msg1); msgs.push_back(msg2); \
TEST_INVARIANT_MSGVEC(code, msgs); \
}
/// Three possibility variant of TEST_INVARIANT_MSGVEC
#define TEST_INVARIANT_MSG3(code, msg1, msg2, msg3) { \
std::vector<std::string> msgs; msgs.push_back(msg1); msgs.push_back(msg2); msgs.push_back(msg3); \
TEST_INVARIANT_MSGVEC(code, msgs); \
}
namespace lintel {
struct DeptoolInfo {
std::string os; // e.g. debian, ubuntu, centos, fedora, opensuse, scilinux
std::string version; // e.g. 7.0, 11.10, 5.3, 16, 12.1, 6.2
std::string arch; // e.g. i386, x86_64
std::string osVersion() {
return os + "-" + version;
}
std::string osVersionArch() {
return os + "-" + version + "-" + arch;
}
bool haveAllInfo() {
return !(os.empty() || version.empty() || arch.empty());
}
};
// If $BUILD_OS/$UNAME_M are present in the environment, use those values and convert them
// into os/version/arch. Otherwise, run deptool to get those values and return them in the
// structure. If deptool is not present, a structure of all empty strings will be returned.
// This function is useful for whitelisting tests that fail on particular combinations of
// os/version/arch
DeptoolInfo getDeptoolInfo();
}
#endif
| 34.406977 | 102 | 0.650896 | [
"vector"
] |
cdb8e6dc66628004ace48f1ca745aadf285326a9 | 2,824 | cpp | C++ | Chapter05/files.cpp | vyom104/Beginning-Cpp-Programming | 7e1bd74bf5532a1f41b846165206ac7e3a274dd6 | [
"MIT"
] | 35 | 2017-04-29T05:44:49.000Z | 2022-03-19T09:26:49.000Z | Chapter05/files.cpp | vyom104/Beginning-Cpp-Programming | 7e1bd74bf5532a1f41b846165206ac7e3a274dd6 | [
"MIT"
] | null | null | null | Chapter05/files.cpp | vyom104/Beginning-Cpp-Programming | 7e1bd74bf5532a1f41b846165206ac7e3a274dd6 | [
"MIT"
] | 18 | 2017-04-25T02:25:29.000Z | 2022-02-09T11:20:44.000Z | #include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
// need to use operating system calls to access file information
#include <windows.h>
// this contains the size of a file, we could simply convert the
// file size to a unsigned long long, but using this structure
// means that we have to write operators for it
struct file_size
{
unsigned int high;
unsigned int low;
};
using file_info = tuple<string, file_size>;
// print a file_size object on the console
ostream& operator<<(ostream& os, const file_size fs)
{
int flags = os.flags();
unsigned long long ll = fs.low
+ ((unsigned long long)fs.high << 32);
os << hex << ll;
os.setf(flags);
return os;
}
// compare two file_size objects
bool operator>(const file_size& lhs, const file_size& rhs)
{
if (lhs.high > rhs.high) return true;
if (lhs.high == rhs.high)
{
if (lhs.low > rhs.low) return true;
}
return false;
}
// for the folder folderPath put each file in files and
// recurse for each subfolder
void files_in_folder(
const char *folderPath, vector<file_info>& files)
{
// find all items in the folder
string folder(folderPath);
folder += "\\*";
WIN32_FIND_DATAA findfiledata {};
void* hFind = FindFirstFileA(folder.c_str(), &findfiledata);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
// get the full name
string findItem(folderPath);
findItem += "\\";
findItem += findfiledata.cFileName;
if ((findfiledata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
// this is a folder so recurse
string folder(findfiledata.cFileName);
// ignore . and .. directories
if (folder != "." && folder != "..")
{
// get the files the subfolder contains
files_in_folder(findItem.c_str(), files);
}
}
else
{
// this is a file so store information
file_size fs{};
fs.high = findfiledata.nFileSizeHigh;
fs.low = findfiledata.nFileSizeLow;
files.push_back(make_tuple(findItem, fs));
}
} while (FindNextFileA(hFind, &findfiledata));
FindClose(hFind);
}
}
int main(int argc, char* argv[])
{
if (argc < 2) return 1;
// get the files in the specified folder and subfolders
vector<file_info> files;
files_in_folder(argv[1], files);
// sort by file size, smallest first
sort(files.begin(), files.end(),
[](const file_info& lhs, const file_info& rhs)
{ return get<1>(rhs) > get<1>(lhs); } );
for (auto file : files)
{
cout << setw(16) << get<1>(file) << " " << get<0>(file) << endl;
}
return 0;
}
| 25.908257 | 77 | 0.608003 | [
"object",
"vector"
] |
cdbb286ec803e6103e66dbfe93e9c468da064e2d | 4,645 | cpp | C++ | study/cyan/hhkb2020-E.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | study/cyan/hhkb2020-E.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | study/cyan/hhkb2020-E.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | #ifdef _DEBUG
#include "../../../library/src/debug_template.hpp"
#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)
#else
#define DMP(...) ((void)0)
#endif
#include <cassert>
#include <cstdio>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <queue>
#include <numeric>
#include <algorithm>
#include <bitset>
#include <functional>
using namespace std;
using lint = long long;
constexpr int INF = 1010101010;
constexpr lint LINF = 1LL << 60;
struct init {
init() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << fixed << setprecision(10);
}
} init_;
template<const int &Modulo>
struct Mint {
lint val;
constexpr Mint(lint v = 0) noexcept: val(v % Modulo) { if (val < 0) val += Modulo; }
constexpr Mint &operator+=(const Mint &r) noexcept {
val += r.val;
if (val >= Modulo) val -= Modulo;
return *this;
}
constexpr Mint &operator-=(const Mint &r) noexcept {
val -= r.val;
if (val < 0) val += Modulo;
return *this;
}
constexpr Mint &operator*=(const Mint &r) noexcept {
val = val * r.val % Modulo;
return *this;
}
constexpr Mint &operator/=(const Mint &r) noexcept {
lint a{r.val}, b{Modulo}, u{1}, v{0};
assert(gcd(a, b) == 1 && "a and b must be co-prime");
while (b) {
lint t = a / b;
a -= t * b;
a ^= b, b ^= a, a ^= b;
u -= t * v;
u ^= v, v ^= u, u ^= v;
}
val = val * u % Modulo;
if (val < 0) val += Modulo;
return *this;
}
constexpr Mint operator+(const Mint &r) const noexcept { return Mint(*this) += r; }
constexpr Mint operator-(const Mint &r) const noexcept { return Mint(*this) -= r; }
constexpr Mint operator*(const Mint &r) const noexcept { return Mint(*this) *= r; }
constexpr Mint operator/(const Mint &r) const noexcept { return Mint(*this) /= r; }
constexpr Mint operator-() const noexcept { return Mint(-val); }
constexpr bool operator==(const Mint &r) const noexcept { return val == r.val; }
constexpr bool operator!=(const Mint &r) const noexcept { return !((*this) == r); }
constexpr bool operator<(const Mint &r) const noexcept { return val < r.val; }
constexpr friend ostream &operator<<(ostream &os, const Mint<Modulo> &x) noexcept { return os << x.val; }
constexpr friend istream &operator>>(istream &is, Mint<Modulo> &x) noexcept {
lint tmp{};
is >> tmp;
x = Mint(tmp);
return is;
}
[[nodiscard]] constexpr Mint pow(lint n) const noexcept {
Mint res{1}, tmp{*this};
while (n > 0) {
if (n & 1) res *= tmp;
tmp *= tmp;
n >>= 1;
}
return res;
}
};
constexpr int MOD = 1000000007;
using mint = Mint<MOD>;
class UnionFind {
private:
vector<int> data;
public:
explicit UnionFind(int size) : data(size, -1) {}
[[nodiscard]] int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); }
[[nodiscard]] bool is_same(int x, int y) { return root(x) == root(y); }
[[nodiscard]] int size(int x) { return -data[root(x)]; }
bool unify(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (data[y] < data[x]) swap(x, y);
data[x] += data[y];
data[y] = x;
return true;
}
return false;
}
};
int main() {
int H, W, K = 0;
cin >> H >> W;
vector<vector<char>> grid(H, vector<char>(W));
for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) cin >> grid[i][j];
for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) K += '.' == grid[i][j];
UnionFind ufH(H * W), ufW(H * W);
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
const int now = i * W + j;
if (j + 1 < W && grid[i][j] == grid[i][j + 1]) ufH.unify(now, now + 1);
if (i + 1 < H && grid[i][j] == grid[i + 1][j]) ufW.unify(now, now + W);
}
}
vector<mint> pow2(H * W + 1);
pow2[0] = 1;
for (int i = 0; i < H * W; i++) pow2[i + 1] = pow2[i] * 2;
mint ans = 0;
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
if (grid[i][j] == '#') continue;
const int now = i * W + j;
int cnt = (int)ufH.size(now) + (int)ufW.size(now) - 2;
ans += pow2[K - 1] + (pow2[cnt] - 1) * pow2[K - cnt - 1];
}
}
cout << ans << '\n';
return 0;
}
| 28.323171 | 109 | 0.511302 | [
"vector"
] |
cdbe095bb4bf25adac0e593af84c4d9d93714f2b | 5,276 | cpp | C++ | src/ai/npc/curly.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 8 | 2018-04-03T23:06:33.000Z | 2021-12-28T18:04:19.000Z | src/ai/npc/curly.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | null | null | null | src/ai/npc/curly.cpp | sodomon2/Cavestory-nx | a65ce948c820b3c60b5a5252e5baba6b918d9ebd | [
"BSD-2-Clause"
] | 1 | 2020-07-31T00:23:27.000Z | 2020-07-31T00:23:27.000Z | #include "curly.h"
#include "../stdai.h"
#include "../ai.h"
#include "../sym/smoke.h"
#include "../../ObjManager.h"
#include "../../map.h"
#include "../../p_arms.h"
#include "../../game.h"
#include "../../player.h"
#define CURLY_STAND 0
#define CURLY_WALK 3
#define CURLY_WALKING 4
INITFUNC(AIRoutines)
{
ONTICK(OBJ_CURLY, ai_curly);
AFTERMOVE(OBJ_CURLY_CARRIED, aftermove_curly_carried);
ONTICK(OBJ_CURLY_CARRIED_SHOOTING, ai_curly_carried_shooting);
ONTICK(OBJ_CCS_GUN, ai_ccs_gun);
}
/*
void c------------------------------() {}
*/
// regular NPC curly
void ai_curly(Object *o)
{
switch(o->state)
{
case 0: // state 0: stand and do nothing
o->frame = 0;
o->flags |= FLAG_SCRIPTONACTIVATE; // needed for after Almond battle
case 1:
// important that state 1 does not change look-away frame for Drain cutscene
if (o->frame != 12) o->frame = 0;
o->xinertia = 0;
break;
case 3: // state 3: walk forward
case 10: // state 10: walk to player and stop
{
if (o->state == 10) FACEPLAYER;
o->state++;
o->animtimer = 0;
o->frame = 0;
}
case 4:
case 11:
{
if (o->state == 11 && pdistlx(20 * CSFI))
{
o->state = 0;
break;
}
ANIMATE(5, 0, 3);
if (!o->blockd) o->frame = 3;
XMOVE(0x200);
}
break;
// state 5: curly makes a "kaboom", then looks sad.
case 5:
o->state = 6;
SmokeClouds(o, 8, 0, 0);
case 6:
o->frame = 16;
break;
case 20: // face away
o->xinertia = 0;
o->frame = 12;
break;
case 21: // look up
o->xinertia = 0;
o->frame = 4;
break;
case 30: // state 30: curly goes flying through the air and is knocked out
{
o->state = 31;
o->frame = 14;
o->timer2 = 0;
o->yinertia = -0x400;
XMOVE(-0x200);
}
case 31:
{
if (o->blockd && o->yinertia >= 0)
o->state = 32;
else
break;
}
case 32: // state 32: curly is laying knocked out
{
o->frame = 15;
o->xinertia = 0;
}
break;
// walk backwards from collapsing wall during final cutscene
case 70:
{
o->state = 71;
o->timer = 0;
o->frame = 1;
o->animtimer = 0;
}
case 71:
{
XMOVE(-0x100);
ANIMATE(8, 0, 3);
}
break;
}
o->yinertia += 0x40;
LIMITY(0x5ff);
}
// curly being carried by Tow Rope
void aftermove_curly_carried(Object *o)
{
switch(o->state)
{
case 0:
{
o->state = 1;
o->frame = 17;
o->flags &= ~FLAG_SCRIPTONACTIVATE;
// turn on the HVTrigger in Waterway that kills Curly if you haven't
// drained the water out of her
if (game.curmap == STAGE_WATERWAY)
{
Object *t = FindObjectByID2(220);
if (t) t->ChangeType(OBJ_HVTRIGGER);
}
}
case 1:
{ // carried by player
StickToPlayer(o, -2, -13, -18);
}
break;
// floating away after Ironhead battle
case 10:
{
o->xinertia = 0x40;
o->yinertia = -0x20;
o->state = 11;
}
case 11:
{
if (o->y < MAPY(4)) // if in top part of screen, reverse before hitting wall
o->yinertia = 0x20;
}
break;
case 20:
{
o->Delete();
}
break;
}
}
/*
void c------------------------------() {}
*/
void ai_curly_carried_shooting(Object *o)
{
if (o->state == 0)
{
o->x = player->CenterX();
o->y = player->CenterY();
o->state = 1;
o->BringToFront();
Object *gun;
gun = CreateObject(0, 0, OBJ_CCS_GUN);
gun->linkedobject = o;
gun->PushBehind(o);
}
// get player center position--
// coordinates make more sense when figured this way
int px = player->x + (8 * CSFI);
int py = player->y + (8 * CSFI);
o->dir = player->dir ^ 1;
if (player->look)
{
o->xmark = px;
if (player->look == UP)
{
if (player->blockd)
{
o->ymark = py - (12 * CSFI);
o->frame = 1;
}
else
{
o->ymark = py + (8 * CSFI);
o->frame = 2;
}
}
else
{ // player looking down (and implicitly, not blockd)
o->ymark = py - (8 * CSFI);
o->frame = 1;
}
}
else // normal/horizontal
{
if (player->dir == LEFT)
o->xmark = px + (7 * CSFI);
else
o->xmark = px - (7 * CSFI);
o->ymark = py - (3 * CSFI);
o->frame = 0;
}
o->x += (o->xmark - o->x) / 2;
o->y += (o->ymark - o->y) / 2;
// bounce as player walks
if (player->walking && (player->walkanimframe & 1))
o->y -= (1 * CSFI);
}
void ai_ccs_gun(Object *o)
{
Object *curly = o->linkedobject;
if (!curly) return;
o->dir = curly->dir;
o->frame = curly->frame;
switch(o->frame)
{
case 0: // horizontal/normal
{
if (curly->dir == RIGHT)
o->x = curly->x + (8 * CSFI);
else
o->x = curly->x - (8 * CSFI);
o->y = curly->y;
}
break;
case 1: // looking up
{
o->x = curly->x;
o->y = curly->y - (10 * CSFI);
}
break;
case 2: // looking down
{
o->x = curly->x;
o->y = curly->y + (10 * CSFI);
}
break;
}
if (pinputs[FIREKEY] != o->timer2)
{
o->timer2 = pinputs[FIREKEY];
if (pinputs[FIREKEY])
{
if (CountObjectsOfType(OBJ_NEMESIS_SHOT_CURLY) < 2)
{
int shotdir = curly->dir;
if (curly->frame == 1) shotdir = UP;
if (curly->frame == 2) shotdir = DOWN;
Object *shot = CreateObject(0, 0, OBJ_NEMESIS_SHOT_CURLY);
SetupBullet(shot, curly->x, curly->y, B_CURLYS_NEMESIS, shotdir);
}
}
}
}
| 17.298361 | 79 | 0.546247 | [
"object"
] |
02ccd1707d0410284a0e090d29d18822d5a0c1e0 | 7,471 | cpp | C++ | src/tests/test_node2vec.cpp | ykwd/KnightKing | a4646cebbdbbb195eb144565eed6d03b1187f64f | [
"MIT"
] | 1 | 2020-12-23T09:26:57.000Z | 2020-12-23T09:26:57.000Z | src/tests/test_node2vec.cpp | formath/KnightKing | 7e215231b22fb1f2923823eeb21a235050fe8eea | [
"MIT"
] | null | null | null | src/tests/test_node2vec.cpp | formath/KnightKing | 7e215231b22fb1f2923823eeb21a235050fe8eea | [
"MIT"
] | 1 | 2021-03-16T01:29:48.000Z | 2021-03-16T01:29:48.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ke Yang, Tsinghua University
*
* 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 <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <type_traits>
#include <gtest/gtest.h>
#include "storage.hpp"
#include "graph.hpp"
#include "walk.hpp"
#include "util.hpp"
#include "test.hpp"
#include "test_walk.hpp"
#include "../apps/node2vec.hpp"
template<typename edge_data_t>
void get_node2vec_trans_matrix(vertex_id_t v_num, Edge<edge_data_t> *edges, edge_id_t e_num, double p, double q, std::vector<std::vector<double> > &trans_mat)
{
std::vector<std::vector<Edge<edge_data_t> > > graph(v_num);
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
graph[edges[e_i].src].push_back(edges[e_i]);
}
for (vertex_id_t v_i = 0; v_i < v_num; v_i++)
{
std::sort(graph[v_i].begin(), graph[v_i].end(), [](const Edge<edge_data_t> a, const Edge<edge_data_t> b){return a.dst < b.dst;});
}
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
vertex_id_t src = edges[e_i].src;
vertex_id_t dst = edges[e_i].dst;
assert(src != dst);
//must be undirected graph
assert(graph[dst].size() != 0);
for (auto e : graph[dst])
{
if (e.dst == src)
{
trans_mat[e_i][e.dst] += 1 / p * get_edge_trans_weight(e);
} else if (std::binary_search(graph[src].begin(), graph[src].end(), e, [](const Edge<edge_data_t> a, const Edge<edge_data_t> b){return a.dst < b.dst;}))
{
trans_mat[e_i][e.dst] += 1 * get_edge_trans_weight(e);
} else
{
trans_mat[e_i][e.dst] += 1 / q * get_edge_trans_weight(e);
}
}
}
mat_normalization(trans_mat);
}
template<typename edge_data_t>
void check_node2vec_random_walk(vertex_id_t v_num, Edge<edge_data_t> *edges, edge_id_t e_num, double p, double q, std::vector<std::vector<vertex_id_t> > rw_sequences)
{
std::vector<std::vector<double> > trans_mat(e_num);
for (auto &vec : trans_mat)
{
vec.resize(v_num, 0.0);
}
get_node2vec_trans_matrix(v_num, edges, e_num, p, q, trans_mat);
//check if sequences are legal
std::vector<vertex_id_t> out_degree(v_num, 0);
std::vector<std::vector<bool> > adj_mat(v_num);
for (auto &vec : adj_mat)
{
vec.resize(v_num, false);
}
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
adj_mat[edges[e_i].src][edges[e_i].dst] = true;
out_degree[edges[e_i].src]++;
}
for (auto &s : rw_sequences)
{
if (out_degree[s[0]] == 0)
{
for (auto v : s)
{
ASSERT_EQ(v, s[0]);
}
} else
{
for (size_t v_i = 0; v_i + 1 < s.size(); v_i++)
{
if (adj_mat[s[v_i]][s[v_i + 1]] == false)
{
printf("fault %u %u\n", s[v_i], s[v_i + 1]);
}
ASSERT_TRUE(adj_mat[s[v_i]][s[v_i + 1]]);
}
}
}
std::map<std::pair<vertex_id_t, vertex_id_t>, edge_id_t> dict;
for (edge_id_t e_i = 0; e_i < e_num; e_i++)
{
std::pair<vertex_id_t, vertex_id_t> key = std::pair<vertex_id_t, vertex_id_t>(edges[e_i].src, edges[e_i].dst);
assert(dict.find(key) == dict.end());
dict[key] = e_i;
}
std::vector<std::vector<double> > real_trans_mat(e_num);
for (auto &vec : real_trans_mat)
{
vec.resize(v_num, 0.0);
}
for (auto &s : rw_sequences)
{
if (out_degree[s[0]] != 0)
{
for (size_t v_i = 0; v_i + 2 < s.size(); v_i++)
{
real_trans_mat[dict[std::pair<vertex_id_t, vertex_id_t>(s[v_i], s[v_i + 1])]][s[v_i + 2]] += 1;
}
}
}
mat_normalization(real_trans_mat);
cmp_trans_matrix(real_trans_mat, trans_mat, 10.0);
}
template<typename edge_data_t>
void test_node2vec(vertex_id_t v_num, int worker_number)
{
WalkEngine<edge_data_t, Node2vecState> graph;
graph.set_concurrency(worker_number);
graph.load_graph(v_num, test_data_file);
Node2vecConf n2v_conf;
n2v_conf.walk_length = 80 + rand() % 20;
n2v_conf.walker_num = graph.get_vertex_num() * 500 + graph.get_edge_num() * 100 + rand() % 100;
n2v_conf.p = rand() % 4 + 1;
n2v_conf.q = rand() % 4 + 1;
if (rand() % 2 == 0)
{
n2v_conf.p = 1.0 / n2v_conf.p;
}
if (rand() % 2 == 0)
{
n2v_conf.q = 1.0 / n2v_conf.q;
}
MPI_Bcast(&n2v_conf, sizeof(n2v_conf), get_mpi_data_type<char>(), 0, MPI_COMM_WORLD);
node2vec(&graph, n2v_conf);
std::vector<std::vector<vertex_id_t> > rw_sequences;
graph.collect_walk_sequence(rw_sequences);
if (get_mpi_rank() == 0)
{
Edge<edge_data_t> *std_edges;
edge_id_t std_edge_num;
read_graph(test_data_file, 0, 1, std_edges, std_edge_num);
check_node2vec_random_walk(v_num, std_edges, std_edge_num, n2v_conf.p, n2v_conf.q, rw_sequences);
}
}
template<typename edge_data_t>
void test_node2vec()
{
edge_id_t e_nums_arr[] = {100, 200, 400, 556, 888, 1000, 1200, 1500};
vertex_id_t v_num = 100 + rand() % 50;
std::vector<edge_id_t> e_nums(e_nums_arr, e_nums_arr + 8);
/*
size_t e_nums_arr[] = {30};
vertex_id_t v_num = 10;
std::vector<size_t> e_nums(e_nums_arr, e_nums_arr + 1);
*/
MPI_Bcast(&v_num, 1, get_mpi_data_type<vertex_id_t>(), 0, MPI_COMM_WORLD);
for (auto &e_num : e_nums_arr)
{
if (get_mpi_rank() == 0)
{
gen_undirected_graph_file<edge_data_t>(v_num, e_num);
}
MPI_Barrier(MPI_COMM_WORLD);
int worker_number = rand() % 8 + 1;
MPI_Bcast(&worker_number, 1, get_mpi_data_type<int>(), 0, MPI_COMM_WORLD);
test_node2vec<edge_data_t>(v_num, worker_number);
}
if (get_mpi_rank() == 0)
{
rm_test_graph_temp_file();
}
}
TEST(Node2vec, Unbiased)
{
test_node2vec<EmptyData>();
}
TEST(Node2vec, Biased)
{
Node2vecConf n2v_conf;
test_node2vec<real_t>();
}
GTEST_API_ int main(int argc, char *argv[])
{
MPI_Instance mpi_instance(&argc, &argv);
::testing::InitGoogleTest(&argc, argv);
mute_nonroot_gtest_events();
int result = RUN_ALL_TESTS();
return result;
}
| 31.523207 | 166 | 0.612368 | [
"vector"
] |
02d236359037fa8420de42eb64d07cff96bfcf43 | 3,306 | cpp | C++ | src/vex_adx_cp_server.cpp | sga001/vex | fb4e8890ebb307ce35f6d38ef0dc15f0bb046b54 | [
"CC0-1.0"
] | null | null | null | src/vex_adx_cp_server.cpp | sga001/vex | fb4e8890ebb307ce35f6d38ef0dc15f0bb046b54 | [
"CC0-1.0"
] | null | null | null | src/vex_adx_cp_server.cpp | sga001/vex | fb4e8890ebb307ce35f6d38ef0dc15f0bb046b54 | [
"CC0-1.0"
] | null | null | null | #include "vex_adx_cp_server.h"
int
vex_adx_cp_server::find_closest_cp(uint32_t num)
{
int closest = 0;
for (int i = 0; i < cp_; ++i) {
if ((uint32_t) (MAX_BID/cp_) * i <= num)
closest = i;
else
break;
}
return closest;
}
uint32_t
vex_adx_cp_server::find_remaining(uint32_t num, int closest)
{
uint32_t remaining = num - (closest * (MAX_BID/cp_));
if (closest == 0)
remaining++;
return remaining;
}
void
vex_adx_cp_server::init_checkpoint_vault()
{
for (int i = 0; i < cp_num_; ++i) {
std::vector<uint8_t> seed;
std::vector<uint8_t> c; // 1 checkpoint
checkpoints cps; // list of checkpoints
seed.resize(SEED_SIZE);
c.resize(HASH_SIZE);
cps.reserve(cp_);
vex::setup(HASH_SIZE, g_prefix, seed.data(), c.data());
cps.push_back(seed); // idx 0 = seed
for (int j = 0; j < cp_-1; ++j) {
vex::gen_commit((MAX_BID / cp_), c.data(), HASH_SIZE, c.data());
cps.push_back(c); // add checkpoint to list
}
// add list to vault
checkpoint_vault_.push_back(cps);
}
}
void
vex_adx_cp_server::process_va_req(int conn_idx, const va_req &req)
{
// c_req needs to include seed (potentially 1 cp)
c_req creq;
// Create auction context
auction_context ctx;
ctx.id = req.id;
ctx.sig_id = req.sig_id;
ctx.seed_base_idx = vault_idx_;
auctions_ctx_.insert(std::pair<std::vector<uint8_t>, auction_context>(req.id, ctx));
vault_idx_+= conn_.size()-1; // increment the vault idx counter
creq.id = req.id;
creq.sig_id = req.sig_id;
creq.url = req.url;
creq.width = req.width;
creq.height = req.height;
creq.reserve_price = req.reserve_price;
creq.cookie_version = req.cookie_version;
creq.cookie_age_seconds = req.cookie_age_seconds;
creq.cookie_id = req.cookie_id;
creq.user_agent = req.user_agent;
creq.geo_criteria_id = req.geo_criteria_id;
creq.postal_code = req.postal_code;
creq.timezone_offset = req.timezone_offset;
creq.timestamp = req.timestamp;
creq.ip = rand();
creq.seller_network_id = rand();
creq.detected_language = rand();
for (int i = 1; i < (int) conn_.size(); ++i) {
creq.seed = checkpoint_vault_.at((ctx.seed_base_idx + (i-1)) % cp_num_).at(0);
a_write(i, C_REQ, creq);
}
}
bool
vex_adx_cp_server::consistency_check(auction_context *ctx)
{
uint8_t htag[HASH_SIZE];
bool ret = 1;
int seed_idx = ctx->seed_base_idx;
for (int i = 1; i <= (int) ctx->vos.size(); ++i){
// Get checkpoint closest checkpoint
vex_decommitment *dec = &(ctx->vds.at(i));
vex_object *com = &(ctx->vos.at(i));
HASH((uint8_t*) dec->ad_tag.c_str(), dec->ad_tag.size(), htag);
int closest = find_closest_cp(MAX_BID - dec->bid);
uint32_t remaining = find_remaining(MAX_BID - dec->bid, closest);
std::vector<uint8_t> closest_cp = checkpoint_vault_.at(seed_idx % cp_num_).at(closest);
// treat dec->sprime as if it were a salt instead of a seed.
if (!vex::verify_salted_proof(remaining, com->c.data(), com->c.size(),
closest_cp.data(), closest_cp.size(), dec->sprime.data(), dec->sprime.size()) ||
memcmp(com->htag.data(), htag, HASH_SIZE) != 0) {
ctx->invalid.insert(std::pair<int, bool>(i, 1)); // 1 implies wrong
ret = 0;
}
seed_idx++;
}
return ret;
}
| 26.031496 | 91 | 0.650333 | [
"vector"
] |
02d3aa62dc45c8a80c5f9a739ff57d0eb0b73adb | 6,843 | cpp | C++ | C++/Others/CCC 10.2020/level5.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/Others/CCC 10.2020/level5.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/Others/CCC 10.2020/level5.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
template <typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template <typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
using i64 = long long int;
const int INF = INT_MAX, MOD = 1e9 + 7;
const double EPS = 1e-9, PI = acos(-1);
const int dx[] = {0, 0, 0, -1, 1, -1, 1, 1, -1};
const int dy[] = {0, -1, 1, 0, 0, -1, 1, -1, 1};
/**
* Author: Neeecu
* Data structure: Segment Tree (min)
*/
template<typename T>
struct min_segment_tree {
vector<T> tree, lazy, arr;
vector<int> now;
int n;
void init(int l, int r, int pos) {
if (l == r)
tree[pos] = arr[l];
else {
int mid = l + (r - l) / 2;
init(l, mid, 2 * pos + 1);
init(mid + 1, r, 2 * pos + 2);
tree[pos] = min(tree[2 * pos + 1], tree[2 * pos + 2]);
}
}
min_segment_tree(vector<T> _arr) : arr(_arr), n(arr.size()) {
tree.resize(4 * n);
lazy.resize(4 * n, 0);
init(0, n - 1, 0);
}
void add(int idx, T val) {
_update(val, idx, idx, 0, n - 1, 0);
}
void add(int l, int r, T val) {
_update(val, l, r, 0, n - 1, 0);
}
void update(int idx, T val) {
_update(val - query(idx, idx), idx, idx, 0, n - 1, 0);
}
void _update(int val, int l, int r, int li, int ri, int pos) {
if (lazy[pos] != 0) {
tree[pos] += lazy[pos];
if (li != ri) {
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if (ri < l or r < li)
return;
else if (l <= li and ri <= r) {
tree[pos] = val;
if (li != ri) {
lazy[2 * pos + 1] += val;
lazy[2 * pos + 2] += val;
}
} else {
int mi = li + (ri - li) / 2;
_update(val, l, r, li, mi, 2 * pos + 1);
_update(val, l, r, mi + 1, ri, 2 * pos + 2);
tree[pos] = min(tree[2 * pos + 1], tree[2 * pos + 2]);
}
}
T query(int l, int r) {
return _query(l, r, 0, n - 1, 0);
}
T _query(int l, int r, int li, int ri, int pos) {
if (lazy[pos] != 0) {
tree[pos] += lazy[pos];
if (li != ri) {
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if (r < li or ri < l)
return LLONG_MAX;
else if (l <= li and ri <= r)
return tree[pos];
else {
int mi = li + (ri - li) / 2;
return min(_query(l, r, li, mi, 2 * pos + 1), _query(l, r, mi + 1, ri, 2 * pos + 2));
}
}
pair<i64, int> query_index(int l, int r) {
return _query_index(l, r, 0, n - 1, 0);
}
pair<i64, int> _query_index(int l, int r, int li, int ri, int pos) {
if (lazy[pos] != 0) {
tree[pos] += lazy[pos];
if (li != ri) {
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if (r < li or ri < l)
return {LLONG_MAX, INF};
else if (l <= li and ri <= r and li == ri)
return {li, tree[pos]};
else {
int mi = li + (ri - li) / 2;
pair<i64, int> lo = _query_index(l, r, li, mi, 2 * pos + 1);
pair<i64, int> hi = _query_index(l, r, mi + 1, ri, 2 * pos + 2);
return ((lo.second <= hi.second) ? lo : hi);
}
}
pair<i64, int> _query_needed(int l, int r, int conc) {
if (conc == 0) return {-1, -1};
pair<i64, int> idx = query_index(l, r);
pair<i64, int> i1 = _query_needed(l, idx.first - 1, conc - 1);
pair<i64, int> i2 = _query_needed(idx.first + 1, r, conc - 1);
now.push_back(((i1.second < i2.second and i1.second != -1) ? i1.first : i2.first));
return idx;
}
void query_needed(int l, int r, int conc) {
int last = _query_needed(l, r, conc).first;
now.push_back(last);
}
};
struct Task {
i64 id, pw, a, b;
vector<pair<i64, i64>> ans;
Task(int _id, int _pw, int _a, int _b) : id(_id), pw(_pw), a(_a), b(_b) {
ans.resize(0);
}
bool operator<(const Task& other) const {
if (other.b - other.a + 1 == this->b - this->a + 1)
return pw < other.pw;
else return ((b - a + 1) < (other.b - other.a + 1));
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
/// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ifstream cin("../level5_example.txt");
//ifstream cin("../level4_5.in");
ofstream cout("../answer.txt");
i64 n, m, maxPow, maxBill, maxConc, curBill = 0;
cin >> maxPow >> maxBill >> maxConc;
cin >> n;
vector<i64> v(n), used(n, maxPow);
for (int i = 0; i < n; i++) cin >> v[i];
min_segment_tree<i64> seg(v);
cin >> m;
vector<Task> tasks;
vector<vector<pair<i64, i64>>> ans(m + 1);
for (int i = 0; i < m; i++) {
i64 t, pw, a, b;
cin >> t >> pw >> a >> b;
tasks.push_back(Task(t, pw, a, b));
}
sort(tasks.begin(), tasks.end());
for (int t = 0; t < m; t++) {
auto cur = tasks[t];
seg.now.clear();
i64 nowDoing = min(maxConc, cur.pw);
seg.query_needed(cur.a, cur.b, nowDoing);
cout << t << " " << seg.now << "\n";
/*while (cur.pw > 0) {
seg.now.clear();
i64 nowDoing = min(maxConc, cur.pw);
i64 idx = seg.query_index(cur.a, cur.b);
i64 l = 0, r = min(cur.pw + 1, used[idx] + 1);
while (l < r) {
i64 mid = (l + r) >> 1;
if (mid * v[idx] + curBill <= maxBill) l = mid + 1;
else r = mid;
}
ans[cur.id].push_back({idx, l - 1});
cur.pw -= (l - 1);
used[idx] -= (l - 1);
curBill += (l - 1) * v[idx];
if (used[idx] == 0) seg.update(idx, INF);
}*/
}
/* cout << m << "\n";
for (int task = 1; task <= m; task++) {
cout << task << " ";
for (auto it: ans[task]) cout << it.first << " " << it.second << " ";
cout << "\n";
}*/
//cout << curBill;
return 0;
} | 32.278302 | 172 | 0.428175 | [
"vector"
] |
02d428a0da077ba1ffbe3a5bac45926c4d81c3be | 1,700 | cpp | C++ | Signer/DlgComapreEngine.cpp | WhiteGroup/JAV-AV-Engine | c258c1bb283d2cccc358dab5d3a7bacd4fc35790 | [
"MIT"
] | 15 | 2016-11-03T20:39:13.000Z | 2022-01-17T16:00:21.000Z | Signer/DlgComapreEngine.cpp | ZhuHuiBeiShaDiao/JAV-AV-Engine | c258c1bb283d2cccc358dab5d3a7bacd4fc35790 | [
"MIT"
] | null | null | null | Signer/DlgComapreEngine.cpp | ZhuHuiBeiShaDiao/JAV-AV-Engine | c258c1bb283d2cccc358dab5d3a7bacd4fc35790 | [
"MIT"
] | 16 | 2016-11-04T11:40:39.000Z | 2022-02-25T07:25:52.000Z | #include "DlgComapreEngine.h"
#include "ui_GetPtarrenFileInfo.h"
#include "CompareEngineThread.h"
#include "QCompareEngineModel.h"
//-------------------------------------------------------------------------------------------------
DlgComapreEngine::DlgComapreEngine(QDialog *parent , QSqlDatabase &i_qSqlDatabase ,JString &Path ,JString &strDatFile):QDialog (parent) ,ui (new Ui::DlgGetPatternFileInfo)
{
ui->setupUi(this);
m_posQCompareEngineModel = new QCompareEngineModel(this);
ui->TblFileInfo->setModel(m_posQCompareEngineModel);
m_pCompareEngineThread = new CompareEngineThread (i_qSqlDatabase , Path , strDatFile);
connect(m_pCompareEngineThread , SIGNAL(Report( QString , QString ,QString )) , this , SLOT (GetReport( QString , QString ,QString )));
m_pCompareEngineThread->start();
}
//-------------------------------------------------------------------------------------------------
DlgComapreEngine::~DlgComapreEngine(void)
{
}
//-------------------------------------------------------------------------------------------------
void DlgComapreEngine::GetReport(QString FileName , QString SetNamedat ,QString SetNameDb)
{
m_posQCompareEngineModel->insertRows(ui->TblFileInfo->model()->rowCount(),1,QModelIndex());
m_posQCompareEngineModel->setData(m_posQCompareEngineModel->index(ui->TblFileInfo->model()->rowCount()-1,0) ,FileName);
m_posQCompareEngineModel->setData(m_posQCompareEngineModel->index(ui->TblFileInfo->model()->rowCount()-1,1) ,SetNamedat);
m_posQCompareEngineModel->setData(m_posQCompareEngineModel->index(ui->TblFileInfo->model()->rowCount()-1,2) ,SetNameDb);
}
//-------------------------------------------------------------------------------------------------
| 58.62069 | 171 | 0.605882 | [
"model"
] |
02d9a8df3af70ffde441d179a44cc87e108cf35a | 8,195 | cpp | C++ | VFS/RenderPass/ShadowMapPass.cpp | Snowapril/VFS | a366f519c1382cfa2669b56346b67737513d6099 | [
"MIT"
] | 2 | 2022-02-14T16:34:39.000Z | 2022-02-25T06:11:42.000Z | VFS/RenderPass/ShadowMapPass.cpp | Snowapril/vk_voxel_cone_tracing | a366f519c1382cfa2669b56346b67737513d6099 | [
"MIT"
] | null | null | null | VFS/RenderPass/ShadowMapPass.cpp | Snowapril/vk_voxel_cone_tracing | a366f519c1382cfa2669b56346b67737513d6099 | [
"MIT"
] | null | null | null | // Author : Jihong Shin (snowapril)
#include <pch.h>
#include <VulkanFramework/Commands/CommandBuffer.h>
#include <VulkanFramework/Device.h>
#include <VulkanFramework/Descriptors/DescriptorSetLayout.h>
#include <VulkanFramework/Descriptors/DescriptorSet.h>
#include <VulkanFramework/Descriptors/DescriptorPool.h>
#include <VulkanFramework/Images/Image.h>
#include <VulkanFramework/Images/ImageView.h>
#include <VulkanFramework/Images/Sampler.h>
#include <VulkanFramework/RenderPass/Framebuffer.h>
#include <VulkanFramework/RenderPass/RenderPass.h>
#include <VulkanFramework/Pipelines/GraphicsPipeline.h>
#include <VulkanFramework/Pipelines/PipelineLayout.h>
#include <VulkanFramework/Pipelines/PipelineConfig.h>
#include <VulkanFramework/FrameLayout.h>
#include <VulkanFramework/Buffers/Buffer.h>
#include <RenderPass/ShadowMapPass.h>
#include <RenderPass/RenderPassManager.h>
#include <Camera.h>
#include <SceneManager.h>
namespace vfs
{
ShadowMapPass::ShadowMapPass(CommandPoolPtr cmdPool, VkExtent2D resolution)
: RenderPassBase(cmdPool), _shadowMapResolution(resolution)
{
// Do nothing
}
ShadowMapPass::~ShadowMapPass()
{
// Do nothing
}
void ShadowMapPass::onBeginRenderPass(const FrameLayout* frameLayout)
{
CommandBuffer cmdBuffer(frameLayout->commandBuffer);
_pipeline->bindPipeline(frameLayout->commandBuffer);
VkViewport viewport = {};
viewport.x = 0;
viewport.y = 0;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
viewport.width = static_cast<float>(_shadowMapResolution.width);
viewport.height = static_cast<float>(_shadowMapResolution.height);
cmdBuffer.setViewport({ viewport });
VkRect2D scissor = {};
scissor.offset = { 0, 0 };
scissor.extent.width = _shadowMapResolution.width;
scissor.extent.height = _shadowMapResolution.height;
cmdBuffer.setScissor({ scissor });
cmdBuffer.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, _pipelineLayout->getLayoutHandle(), 2,
{ _descriptorSet }, {});
VkClearValue depthClear;
depthClear.depthStencil = { 1.0f, 0 };
cmdBuffer.beginRenderPass(_renderPass, _framebuffer, { depthClear });
}
void ShadowMapPass::onEndRenderPass(const FrameLayout* frameLayout)
{
CommandBuffer cmdBuffer(frameLayout->commandBuffer);
cmdBuffer.endRenderPass();
}
void ShadowMapPass::onUpdate(const FrameLayout* frameLayout)
{
CommandBuffer cmdBuffer(frameLayout->commandBuffer);
SceneManager* sceneManager = _renderPassManager->get<SceneManager>("SceneManager");
sceneManager->cmdDraw(frameLayout->commandBuffer, _pipelineLayout, 0);
}
void ShadowMapPass::drawGUI(void)
{
_directionalLight->drawGUI();
}
ShadowMapPass& ShadowMapPass::setDirectionalLight(std::unique_ptr<DirectionalLight>&& dirLight)
{
// Move framebuffer and directional light to proper storage
_directionalLight = std::move(dirLight);
_debugUtils.setObjectName(_directionalLight->getShadowMap()->getImageHandle(), "ShadowMap");
_debugUtils.setObjectName(_directionalLight->getShadowMapView()->getImageViewHandle(), "ShadowMap View");
// Create framebuffer for depth render target
std::vector<VkImageView> imageViews{ _directionalLight->getShadowMapView()->getImageViewHandle() };
_framebuffer = std::make_shared<Framebuffer>(_device, imageViews, _renderPass->getHandle(), _shadowMapResolution);
// Descriptor set update
_descriptorSet->updateUniformBuffer({ _directionalLight->getViewProjectionBuffer() }, 0, 1);
_renderPassManager->put("DirectionalLight", _directionalLight.get());
return *this;
}
ShadowMapPass& ShadowMapPass::createRenderPass(void)
{
// TODO(snowapril) : check depth attachment format support
VkAttachmentDescription depthDesc = {};
depthDesc.format = VK_FORMAT_D32_SFLOAT;
depthDesc.samples = VK_SAMPLE_COUNT_1_BIT;
depthDesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
depthDesc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
depthDesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
depthDesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
depthDesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
depthDesc.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
std::vector<VkSubpassDependency> subpassDependencies(2, VkSubpassDependency{});
subpassDependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
subpassDependencies[0].dstSubpass = 0;
subpassDependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
subpassDependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
subpassDependencies[0].dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
subpassDependencies[0].dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
subpassDependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
subpassDependencies[1].srcSubpass = 0;
subpassDependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
subpassDependencies[1].srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
subpassDependencies[1].srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
subpassDependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
subpassDependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
subpassDependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
VkAttachmentReference depthAttachmentRef = {};
depthAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
depthAttachmentRef.attachment = 0;
VkSubpassDescription subpassDesc = {};
subpassDesc.pDepthStencilAttachment = &depthAttachmentRef;
subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
_renderPass = std::make_shared<RenderPass>();
assert(_renderPass->initialize(_device, { depthDesc }, subpassDependencies, { subpassDesc }));
return *this;
}
ShadowMapPass& ShadowMapPass::createPipeline(const DescriptorSetLayoutPtr& globalDescLayout)
{
assert(_renderPass != nullptr);
SceneManager* sceneManager = _renderPassManager->get<SceneManager>("SceneManager");
std::vector<VkDescriptorPoolSize> poolSizes = {
{ VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1}
};
_descriptorPool = std::make_shared<DescriptorPool>(_device, poolSizes, 1, 0);
_descriptorLayout = std::make_shared<DescriptorSetLayout>(_device);
_descriptorLayout->addBinding(VK_SHADER_STAGE_VERTEX_BIT, 0, 1, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0);
_descriptorLayout->createDescriptorSetLayout(0);
_descriptorSet = std::make_shared<DescriptorSet>(_device, _descriptorPool, _descriptorLayout, 1);
_pipelineLayout = std::make_shared<PipelineLayout>();
_pipelineLayout->initialize(
_device,
{ globalDescLayout, sceneManager->getDescriptorLayout(), _descriptorLayout },
{ sceneManager->getDefaultPushConstant() }
);
PipelineConfig config;
PipelineConfig::GetDefaultConfig(&config);
const std::vector<VkVertexInputBindingDescription>& bindingDesc = sceneManager->getVertexInputBindingDesc(0);
const std::vector<VkVertexInputAttributeDescription>& attribDescs = sceneManager->getVertexInputAttribDesc(0);
config.vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attribDescs.size());
config.vertexInputInfo.pVertexAttributeDescriptions = attribDescs.data();
config.vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDesc.size());;
config.vertexInputInfo.pVertexBindingDescriptions = bindingDesc.data();
config.inputAseemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
config.rasterizationInfo.cullMode = VK_CULL_MODE_NONE; // VK_CULL_MODE_BACK_BIT;
config.dynamicStates = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
config.dynamicStateInfo.dynamicStateCount = static_cast<uint32_t>(config.dynamicStates.size());
config.dynamicStateInfo.pDynamicStates = config.dynamicStates.data();
config.renderPass = _renderPass->getHandle();
config.pipelineLayout = _pipelineLayout->getLayoutHandle();
_pipeline = std::make_shared<GraphicsPipeline>(_device);
_pipeline->attachShaderModule(VK_SHADER_STAGE_VERTEX_BIT, "Shaders/shadowPass.vert.spv", nullptr);
_pipeline->attachShaderModule(VK_SHADER_STAGE_FRAGMENT_BIT, "Shaders/shadowPass.frag.spv", nullptr);
_pipeline->createPipeline(&config);
return *this;
}
}; | 42.242268 | 116 | 0.79878 | [
"render",
"vector"
] |
02db02d3cdab20488e222160b2ea72f2a3c973d2 | 1,455 | hpp | C++ | src/include/duckdb/planner/filter/conjunction_filter.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 2,816 | 2018-06-26T18:52:52.000Z | 2021-04-06T10:39:15.000Z | src/include/duckdb/planner/filter/conjunction_filter.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 1,310 | 2021-04-06T16:04:52.000Z | 2022-03-31T13:52:53.000Z | src/include/duckdb/planner/filter/conjunction_filter.hpp | AldoMyrtaj/duckdb | 3aa4978a2ceab8df25e4b20c388bcd7629de73ed | [
"MIT"
] | 270 | 2021-04-09T06:18:28.000Z | 2022-03-31T11:55:37.000Z | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/planner/filter/conjunction_filter.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/planner/table_filter.hpp"
#include "duckdb/common/vector.hpp"
namespace duckdb {
class ConjunctionFilter : public TableFilter {
public:
ConjunctionFilter(TableFilterType filter_type_p) : TableFilter(filter_type_p) {
}
virtual ~ConjunctionFilter() {
}
//! The filters of this conjunction
vector<unique_ptr<TableFilter>> child_filters;
public:
virtual FilterPropagateResult CheckStatistics(BaseStatistics &stats) = 0;
virtual string ToString(const string &column_name) = 0;
virtual bool Equals(const TableFilter &other) const {
return TableFilter::Equals(other);
}
};
class ConjunctionOrFilter : public ConjunctionFilter {
public:
ConjunctionOrFilter();
public:
FilterPropagateResult CheckStatistics(BaseStatistics &stats) override;
string ToString(const string &column_name) override;
bool Equals(const TableFilter &other) const override;
};
class ConjunctionAndFilter : public ConjunctionFilter {
public:
ConjunctionAndFilter();
public:
FilterPropagateResult CheckStatistics(BaseStatistics &stats) override;
string ToString(const string &column_name) override;
bool Equals(const TableFilter &other) const override;
};
} // namespace duckdb
| 25.982143 | 80 | 0.685911 | [
"vector"
] |
02db75c45804423936203e32ba3362c05d330d52 | 8,250 | cpp | C++ | Lyfe_Game/Source/Lyfe_Game/Private/Logging.cpp | GameAboutThings/Lyfe | 320a8e27586c327707f36e9a268c84d6d77c6da4 | [
"Unlicense"
] | 2 | 2018-04-30T09:58:48.000Z | 2018-05-14T10:13:42.000Z | Lyfe_Game/Source/Lyfe_Game/Private/Logging.cpp | GameAboutThings/Lyfe | 320a8e27586c327707f36e9a268c84d6d77c6da4 | [
"Unlicense"
] | null | null | null | Lyfe_Game/Source/Lyfe_Game/Private/Logging.cpp | GameAboutThings/Lyfe | 320a8e27586c327707f36e9a268c84d6d77c6da4 | [
"Unlicense"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "Logging.h"
#include "Runtime/Core/Public/Misc/FileHelper.h"
#include "Runtime/Core/Public/HAL/PlatformFilemanager.h"
#include "Runtime/Core/Public/Misc/DateTime.h"
#include "Util.h"
//#include "../Private/Util.cpp"
Logging::Logging()
{
}
Logging::~Logging()
{
}
//String
void Logging::Log(FString inputString, const char comment[], bool bConsole)
{
FDateTime date;
FString log = "[ APPLICATIONTIME : ";
log.Append(date.GetDate().ToString());
log.Append(date.GetTimeOfDay().ToString());
log.Append(" ] -> ");
log.Append(FString(comment));
log.Append(" ");
log.Append(inputString);
log.Append("\r\n");
IPlatformFile& logFile = FPlatformFileManager::Get().GetPlatformFile();
//test id directory exists
if (!logFile.DirectoryExists(*LOG_DIRECTORY))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't find log directory ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Trying to create log directory ..."));
logFile.CreateDirectoryTree(*LOG_DIRECTORY);
if (!logFile.DirectoryExists(*LOG_DIRECTORY))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't create log directory ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Cancelling ..."));
return;
}
}
//test file
if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*LOG_PATH))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't find log file ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Trying to create log file ..."));
FFileHelper::SaveStringToFile(log, *LOG_PATH);
if(!FPlatformFileManager::Get().GetPlatformFile().FileExists(*LOG_PATH))
{
UE_LOG(LogTemp, Warning, TEXT("*** Couldn't create log file ***"));
UE_LOG(LogTemp, Warning, TEXT("*** *** Trying to create log file ..."));
if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*LOG_PATH))
{
UE_LOG(LogTemp, Warning, TEXT("*** *** *** Couldn't create log file ***"));
}
else
{
UE_LOG(LogTemp, Warning, TEXT("*** *** *** Log file created ***"));
}
}
else
{
UE_LOG(LogTemp, Warning, TEXT("*** *** *** Log file created ***"));
}
}
else
{
FString oldLog;
FFileHelper::LoadFileToString(oldLog, *LOG_PATH);
oldLog.Append(log);
FFileHelper::SaveStringToFile(oldLog, *LOG_PATH);
}
if (bConsole)
{
UE_LOG(LogTemp, Warning, TEXT("%c"), *inputString);
}
}
void Logging::Log(FString inputString, bool bConsole)
{
Logging::Log(inputString, "", bConsole);
}
void Logging::Log(FString inputString)
{
Logging::Log(inputString, false);
}
void Logging::Log(FString inputString, const char comment[])
{
Logging::Log(inputString, comment, false);
}
//Char
void Logging::Log(const char inputString[], const char comment[], bool bConsole)
{
Logging::Log(FString(inputString), comment, bConsole);
}
void Logging::Log(const char inputString[], bool bConsole)
{
Logging::Log(inputString, "", bConsole);
}
void Logging::Log(const char inputString[])
{
Logging::Log(inputString, false);
}
void Logging::Log(const char inputString[], const char comment[])
{
Logging::Log(inputString, comment, false);
}
//Vector 3D
void Logging::Log(FVector inputVector, const char comment[], bool bConsole)
{
FString log = " VECTOR : { X: ";
log.Append(FString::SanitizeFloat(inputVector.X));
log.Append(" | Y: ");
log.Append(FString::SanitizeFloat(inputVector.Y));
log.Append(" | Z: ");
log.Append(FString::SanitizeFloat(inputVector.Z));
log.Append(" }");
Log(log, comment, bConsole);
}
void Logging::Log(FVector inputVector, bool bConsole)
{
Logging::Log(inputVector, "", bConsole);
}
void Logging::Log(FVector inputVector)
{
Logging::Log(inputVector, false);
}
void Logging::Log(FVector inputVector, const char comment[])
{
Logging::Log(inputVector, comment, false);
}
//Vector 2D
void Logging::Log(FVector2D inputVector, const char comment[], bool bConsole)
{
FString log = " VECTOR2D : { X: ";
log.Append(FString::SanitizeFloat(inputVector.X));
log.Append(" | Y: ");
log.Append(FString::SanitizeFloat(inputVector.Y));
log.Append(" }");
Logging::Log(log, comment, bConsole);
}
void Logging::Log(FVector2D inputVector, bool bConsole)
{
Logging::Log(inputVector, "", bConsole);
}
void Logging::Log(FVector2D inputVector)
{
Logging::Log(inputVector, false);
}
void Logging::Log(FVector2D inputVector, const char comment[])
{
Logging::Log(inputVector, comment, false);
}
//Float
void Logging::Log(float inputFloat, const char comment[], bool bConsole)
{
FString log = FString(" FLOAT : ").Append(FString::SanitizeFloat(inputFloat));
Logging::Log(log, comment, bConsole);
}
void Logging::Log(float inputFloat, bool bConsole)
{
Logging::Log(inputFloat, "", bConsole);
}
void Logging::Log(float inputFloat)
{
Logging::Log(inputFloat, false);
}
void Logging::Log(float inputFloat, const char comment[])
{
Logging::Log(inputFloat, comment, false);
}
//Integer
void Logging::Log(int inputInt, const char comment[], bool bConsole)
{
FString log = FString(" INTEGER : ").Append(FString::SanitizeFloat(inputInt));
Log(log, comment, bConsole);
}
void Logging::Log(int inputInt, bool bConsole)
{
Log(inputInt, "", bConsole);
}
void Logging::Log(int inputInt)
{
Logging::Log(inputInt, false);
}
void Logging::Log(int inputInt, const char comment[])
{
Logging::Log(inputInt, comment, false);
}
//Compound
void Logging::Log(ECompound inputCompound, const char comment[], bool bConsole)
{
FString log = FString(" ECOMPOUND : ");
log.Append(Util::EnumToString(inputCompound));
//switch (inputCompound)
//{
//case ECompound::EO2:
// log.Append(" O2 ");
// break;
//case ECompound::ECO2:
// log.Append(" CO2 ");
// break;
//case ECompound::EAminoAcid:
// log.Append(" Amino Acid ");
// break;
//case ECompound::EGlucose:
// log.Append(" Glucose ");
// break;
//case ECompound::ELipid:
// log.Append(" Lipid ");
// break;
//case ECompound::ENothing:
// log.Append(" Nothing ");
// break;
//}
Logging::Log(log, comment, bConsole);
}
void Logging::Log(ECompound inputCompound, bool bConsole)
{
Logging::Log(inputCompound, "", bConsole);
}
void Logging::Log(ECompound inputCompound)
{
Logging::Log(inputCompound, false);
}
void Logging::Log(ECompound inputCompound, const char comment[])
{
Logging::Log(inputCompound, comment, false);
}
//Player State
void Logging::Log(EPlayerState inputState, const char comment[], bool bConsole)
{
FString log = FString(" EPLAYERSTATE : ");
log.Append(Util::EnumToString(inputState));
//switch (inputState)
//{
//case EPlayerState::EDead:
// log.Append(" Dead ");
// break;
//case EPlayerState::EAlive:
// log.Append(" Alive ");
// break;
//}
Logging::Log(log, comment, bConsole);
}
void Logging::Log(EPlayerState inputState, bool bConsole)
{
Logging::Log(inputState, "", bConsole);
}
void Logging::Log(EPlayerState inputState)
{
Logging::Log(inputState, false);
}
void Logging::Log(EPlayerState inputState, const char comment[])
{
Logging::Log(inputState, comment, false);
}
//Control Setting
void Logging::Log(EControlSettings inputControls, const char comment[], bool bConsole)
{
FString log = FString(" ECONTROLSETTING : ");
log.Append(Util::EnumToString(inputControls));
//switch (inputControls)
//{
//case EControlSettings::EFollowMouse:
// log.Append(" FollowMouse ");
// break;
//case EControlSettings::EWASD:
// log.Append(" WASD ");
// break;
//case EControlSettings::EClick:
// log.Append(" Click ");
// break;
//}
Logging::Log(log, bConsole);
}
void Logging::Log(EControlSettings inputControls, bool bConsole)
{
Logging::Log(inputControls, "", bConsole);
}
void Logging::Log(EControlSettings inputControls)
{
Logging::Log(inputControls, false);
}
void Logging::Log(EControlSettings inputControls, const char comment[])
{
Logging::Log(inputControls, comment, false);
}
//FColor
void Logging::Log(FColor color, const char comment[], bool bConsole)
{
FString log = FString(" FCOLOR : ");
log.Append(Util::ColorToString(color));
Logging::Log(log, bConsole);
}
void Logging::Log(FColor color, bool bConsole)
{
Logging::Log(color, "", bConsole);
}
void Logging::Log(FColor color)
{
Logging::Log(color, false);
}
void Logging::Log(FColor color, const char comment[])
{
Logging::Log(color, comment, false);
}
| 22.727273 | 86 | 0.690545 | [
"vector",
"3d"
] |
02e3d0099ea8a5220a6a7bdfc45588dfcd5e6b91 | 20,735 | cpp | C++ | tutorials/LFW/trainer.cpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 119 | 2018-05-30T01:16:36.000Z | 2021-11-08T13:01:07.000Z | tutorials/LFW/trainer.cpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 24 | 2018-08-05T16:50:42.000Z | 2020-10-28T00:38:48.000Z | tutorials/LFW/trainer.cpp | wok1909/WICWIU-OSSLab-Final-Project | ea172614c3106de3a8e203acfac8f0dd4eca7c7c | [
"Apache-2.0"
] | 35 | 2018-06-29T17:10:13.000Z | 2021-06-05T04:07:48.000Z | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctime>
#include <vector>
#include <float.h>
#include <unistd.h>
#include <Dataset.hpp>
#include <Utils.hpp>
#include "net/my_Facenet.hpp"
#include "LFWDataset.hpp"
#include "LFWSampler.hpp"
#include "../../WICWIU_src/KNearestNeighbor.hpp"
#define NUMBER_OF_CLASS 5749 // for lfw_funneled
//#define NUMBER_OF_CLASS 143 // for lfw_little
#define BATCH 45
//#define EPOCH 500
#define EPOCH 10000
//#define GPUID 0
#define GPUID 1
#define LOG_LENGTH 1
#define LEARNING_RATE_DECAY_RATE 0.1
#define LEARNING_RATE_DECAY_TIMING 100
//#define SAMPLE_PER_CLASS 5
#define SAMPLE_PER_CLASS 3
//#define KNN_K 3
#define KNN_K 1
#define BLOCK_SIZE 360 // block to find positive and negative samples
// #define IMAGE_SIZE 48400 // defined in LFWDataset.hpp (220*220)
// #define INPUT_DIM 145200 // defined in LFWDataset.hpp (3 * 220 * 200)
#define FEATURE_DIM 128
#define ENABLE_TRAINING
#define ENABLE_TEST
void GetReferenceSamples(LFWDataset<float> *dataset, int dim, int noClass, int samplePerClass, std::vector<float*> &vSamples, std::vector<int> &vLabels, std::vector<int> *pvRefIndex = NULL, int startIdx = 0); // designed for k-NN
void FindPostiveNegativeSamples(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, int outDim, int blockSize, int batchSize, int *pPosIndex, int *pNegIndex);
void ExtractFeature(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, std::vector<int> &shuffle, int from, int to, int outDim, float *pFeature[], int batchSize);
int main(int argc, char const *argv[])
{
srand(time(NULL));
time_t startTime = 0;
struct tm *curr_tm = NULL;
double nProcessExcuteTime = 0.;
char filename[] = "another_params";
// create input, label data placeholder -> Tensorholder
Tensorholder<float> *x = new Tensorholder<float>(1, BATCH, 1, 1, 145200, "x");
Tensorholder<float> *label = new Tensorholder<float>(1, BATCH, 1, 1, NUMBER_OF_CLASS, "label");
// ======================= Select net ===================
NeuralNetwork<float> *net = new my_FaceNet<float>(x, label, NUMBER_OF_CLASS);
// net->PrintGraphInformation();
if(access(filename, 00) == 0){
net->Load(filename);
printf("Parameters loaded from %s\n", filename);
fflush(stdout);
}
#ifdef __CUDNN__
net->SetDeviceGPU(GPUID);
#endif // __CUDNN__
// std::cout << "/* Prepare Data */" << '\n';
// ======================= Prepare Data ===================
vision::Compose *transform = new vision::Compose({new vision::Resize(224), new vision::CenterCrop(220)});
// LFWDataset<float> *train_dataset = new LFWDataset<float>("./data", "lfw_little", NUMBER_OF_CLASS, transform);
LFWDataset<float> *train_dataset = new LFWDataset<float>("./data", "lfw_funneled", NUMBER_OF_CLASS, transform);
#ifdef __DEBUG__
LogMessageF("lfw_funneled_label.txt", TRUE, "%d samples\n", train_dataset->GetLength());
for(int i = 0; i < train_dataset->GetLength(); i++)
LogMessageF("lfw_funneled_label.txt", FALSE, "%d\t%d\n", i, train_dataset->GetLabel(i));
for(int i = 0; i < NUMBER_OF_CLASS; i++){
printf("count[%d] = %d\n", i, train_dataset->GetSampleCount(i));
LogMessageF("lfw_funneled_count.txt", FALSE, "count[%d] = %d\n", i, train_dataset->GetSampleCount(i));
}
// MyPause(__FUNCTION__);
#endif // __DEBUG__
DataLoader<float> *train_dataloader = new LFWSampler<float>(NUMBER_OF_CLASS, train_dataset, BATCH, TRUE, 1, FALSE);
std::cout << "test" << '\n';
#ifdef ENABLE_TEST
// get referece idxs for k-NN
std::vector<float*> vRefSamples;
std::vector<int> vRefLabels;
std::vector<int> vPosIndex;
std::vector<int> vNegIndex;
std::cout << "test1" << '\n';
GetReferenceSamples(train_dataset, INPUT_DIM, NUMBER_OF_CLASS, SAMPLE_PER_CLASS, vRefSamples, vRefLabels);
#endif // ENABLE_TEST
std::cout << "test2" << '\n';
// LFWDataset<float> *test_dataset = new LFWDataset<float>("./data", "lfw_Test", 60, transform);
float best_acc = 0.f;
int startEpoch = -1; // epoch starts from startEpoch + 1
// int startEpoch = 2614;
int loop_for_train = (train_dataset->GetLength() - train_dataset->GetNoMinorClass(2))/ BATCH;
float min_lr = 0.000001F;
int pos_neg_cycle = 3;
std::cout << "filename : " << filename << '\n';
std::cout << "best_acc : " << best_acc << '\n';
std::cout << "start epoch : " << startEpoch << '\n';
std::cout << "end epoch : " << EPOCH << '\n';
std::cout << "min_lr : " << min_lr << '\n';
std::cout << "pos_neg_cycle : " << pos_neg_cycle << '\n';
if (startEpoch / LEARNING_RATE_DECAY_TIMING) {
float lr = net->GetOptimizer()->GetLearningRate();
float new_lr = lr * pow(0.1, (int)(startEpoch / LEARNING_RATE_DECAY_TIMING));
if(new_lr < min_lr)
new_lr = min_lr;
net->GetOptimizer()->SetLearningRate(new_lr);
std::cout << "lr : " << new_lr << '\n';
}
for (int epoch = startEpoch + 1; epoch < EPOCH; epoch++) {
std::cout << "epoch : " << epoch << '\n';
float train_avg_loss = 0.f;
float train_cur_loss = 0.f;
#ifdef ENABLE_TRAINING
if(epoch == startEpoch + 1 || (epoch - 1) % pos_neg_cycle == 0){
printf("Searching for positive and negative samples...\n"); fflush(stdout);
LogMessageF("log.txt", FALSE, "Finding positive and negative samples...\n");
train_dataset->GetPositiveIndices().resize(train_dataset->GetLength());
train_dataset->GetNegativeIndices().resize(train_dataset->GetLength());
FindPostiveNegativeSamples(net, INPUT_DIM, *train_dataset, FEATURE_DIM, BLOCK_SIZE, BATCH,
&train_dataset->GetPositiveIndices()[0], &train_dataset->GetNegativeIndices()[0]);
printf("Searching for positive and negative samples... Done.\n"); fflush(stdout);
#ifdef __DEBUG__
for(int i = 0; i < 100; i++)
printf("%d (%s): anchor: %d, pos:%d, neg: %d\n", i, train_dataset->GetImagePath(i).c_str(), train_dataset->GetLabel(i), train_dataset->GetPositiveIndex(i), train_dataset->GetNegativeIndex(i));
// MyPause(__FUNCTION__);
#endif // __DEBUG__
}
startTime = time(NULL);
curr_tm = localtime(&startTime);
std::cout << curr_tm->tm_hour << "\'h " << curr_tm->tm_min << "\'m " << curr_tm->tm_sec << "\'s" << '\n';
float lr = net->GetOptimizer()->GetLearningRate();
if (epoch % LEARNING_RATE_DECAY_TIMING == 0 && lr > min_lr) {
// adjust learning rate
std::cout << "Change learning rate!" << '\n';
float new_lr = lr * LEARNING_RATE_DECAY_RATE;
if(new_lr < min_lr)
new_lr = min_lr;
net->GetOptimizer()->SetLearningRate(new_lr);
std::cout << "lr : " << new_lr << '\n';
} else {
std::cout << "lr : " << lr << '\n';
}
// ======================= Train =======================
net->SetModeTrain();
for (int j = 0; j < loop_for_train; j++) {
std::vector<Tensor<float> *> * temp = train_dataloader->GetDataFromGlobalBuffer();
#ifdef __CUDNN__
(*temp)[0]->SetDeviceGPU(GPUID); // 異뷀썑 ?먮룞???꾩슂
(*temp)[1]->SetDeviceGPU(GPUID);
#endif // __CUDNN__
net->FeedInputTensor(2, (*temp)[0], (*temp)[1]);
delete temp;
temp = NULL;
net->ResetParameterGradient();
net->Train();
train_cur_loss = net->GetLoss();
train_avg_loss += train_cur_loss;
printf("\r%d / %d -> cur_loss : %f", j + 1, loop_for_train, train_avg_loss / (j + 1));
fflush(stdout);
}
printf("\n");
#endif // ENABLE_TRAINING
// ======================= Test ======================
float test_accuracy = 0.f;
// float test_avg_loss = 0.f;
#ifdef ENABLE_TEST
net->SetModeInference();
printf("Start testing...\n"); fflush(stdout);
// LFWDataset<float> &dataset = *test_dataset;
LFWDataset<float> &dataset = *train_dataset; // only for debug
// create k-NN classifier using net and (vRefLabels, vRefSamples)
// printf("Feature fxtraction (reference images)\n"); fflush(stdout);
std::vector<float*> vRefFeatures;
AllocFeatureVector(FEATURE_DIM, vRefSamples.size(), vRefFeatures);
net->InputToFeature(INPUT_DIM, vRefSamples.size(), &vRefSamples[0], FEATURE_DIM, &vRefFeatures[0], BATCH); // convert reference images to feature vectors using CNN
KNearestNeighbor knn(FEATURE_DIM, NUMBER_OF_CLASS, vRefSamples.size(), &vRefLabels[0], &vRefFeatures[0]); // create k-NN classifier
DeleteFeatureVector(vRefFeatures);
// test
int correct = 0;
int noTestSample = dataset.GetLength();
int noBatch = (noTestSample + BATCH - 1) / BATCH;
int remained = noTestSample;
std::vector<float*> vTestSample;
std::vector<float*> vTestFeature;
vPosIndex.resize(dataset.GetLength());
vNegIndex.resize(dataset.GetLength());
printf("Recognizing using knn...\n"); fflush(stdout);
for(int batchIdx = 0; batchIdx < noBatch; batchIdx++){
int curBatch = MIN(remained, BATCH);
// extract feature using CNN
AllocFeatureVector(INPUT_DIM, curBatch, vTestSample);
AllocFeatureVector(FEATURE_DIM, curBatch, vTestFeature);
//printf("\rReading test images (batchIdx = %d)... (%s %d)\n", batchIdx, __FILE__, __LINE__); fflush(stdout);
for(int i = 0; i < curBatch; i++){
// printf("Reading test image (i = %d)... (%s %d)\n", i, __FILE__, __LINE__); fflush(stdout);
dataset.CopyData(batchIdx * BATCH + i, vTestSample[i]);
}
// printf("Extracting feature ... (%s %d)\n", __FILE__, __LINE__); fflush(stdout);
net->InputToFeature(INPUT_DIM, vTestSample.size(), &vTestSample[0], FEATURE_DIM, &vTestFeature[0], BATCH);
// printf("Recognizing test images ... (%s %d)\n", __FILE__, __LINE__); fflush(stdout);
// recognize using k-NN classifier
for(int i = 0; i < curBatch; i++){
int result = knn.Recognize(vTestFeature[i], KNN_K);
if(result == dataset.GetLabel(batchIdx * BATCH + i))
correct++;
}
DeleteFeatureVector(vTestFeature);
DeleteFeatureVector(vTestSample);
remained -= curBatch;
if((batchIdx + 1) % 10 == 0){
printf("batch = %d / %d test accuracy = %f (%d / %d)\n", batchIdx + 1, noBatch, correct / (float)(batchIdx * BATCH + curBatch), correct, batchIdx * BATCH + curBatch);
fflush(stdout);
}
}
test_accuracy = correct / (float)noTestSample;
printf("\repoch = %d, test accuracy = %f (%d / %d)\n", epoch, correct / (float)noTestSample, correct, noTestSample); fflush(stdout);
LogMessageF("log.txt", FALSE, "epoch = %d, lr = %f, training loss = %f, test accuracy = %f (%d / %d)\n", epoch, net->GetOptimizer()->GetLearningRate(), train_avg_loss / (float)loop_for_train, correct / (float)noTestSample, correct, noTestSample);
if(test_accuracy > best_acc){
best_acc = test_accuracy;
printf("Saving best model into %s (best_acc = %f)\n", filename, best_acc);
net->Save(filename);
}
#ifndef ENABLE_TRAINING
break; // if training is disabled, repeating test is meaningless
#endif // ENABLE_TRAINING
#endif // ENABLE_TEST
if(test_accuracy > best_acc){
// save the best model
best_acc = test_accuracy;
net->Save(filename);
printf("Model was saved in %s. (best_acc = %f)\n", filename, best_acc);
fflush(stdout);
}
printf("\n");
}
delete net;
delete train_dataloader;
delete train_dataset;
// delete test_dataset;
return 0;
}
void GetReferenceSamples(LFWDataset<float> *dataset, int dim, int noClass, int samplePerClass, std::vector<float*> &vSamples, std::vector<int> &vLabels, std::vector<int> *pvRefIndex, int startIdx) // designed for k-NN
{
DeleteFeatureVector(vSamples);
vLabels.resize(0);
if(pvRefIndex != NULL)
pvRefIndex->resize(0);
if(startIdx = -1)
startIdx = rand() % dataset->GetLength();
std::vector<int> vCount;
vCount.resize(noClass);
for(int i = 0; i < noClass; i++)
vCount[i] = 0;
int noComplete = 0;
for(int i = 0; i < dataset->GetLength() && noComplete < noClass; i++){
int idx = (startIdx + i) % dataset->GetLength();
int label = dataset->GetLabel(idx);
if(label >= noClass){
printf("Error! label = %d, noClass = %d\n", label, noClass);
printf("Press Enter to continue (%s)...", __FUNCTION__); fflush(stdout);
getchar();
}
if(vCount[label] < samplePerClass){
vLabels.push_back(label);
if(pvRefIndex)
pvRefIndex->push_back(idx);
float *pSample = new float[dim];
if(pSample == NULL){
printf("Failed to allocate memory, dim = %d in %s (%s %d)\n", dim, __FUNCTION__, __FILE__, __LINE__);
exit(-1);
}
dataset->CopyData(idx, pSample);
vSamples.push_back(pSample);
vCount[label]++;
if(vCount[label] == samplePerClass)
noComplete++;
}
}
#ifdef __DEBUG__
for(int i = 0; i < vLabels.size(); i++){
printf("vLabels[%d] = %d\n", i, vLabels[i]);
}
#endif // __DEBUG__
}
void FindPostiveNegativeSamples(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, int outDim, int blockSize, int batchSize, int *pPosIndex, int *pNegIndex)
{
int noSample = dataset.GetLength();
int noBlock = (noSample + blockSize - 1) / blockSize;
std::vector<float*> vBlockFeature;
AllocFeatureVector(outDim, blockSize, vBlockFeature);
std::vector<int> shuffle;
std::vector<float> vMinNegative;
std::vector<float> vMaxPositive;
try {
shuffle.resize(noSample);
vMinNegative.resize(blockSize);
vMaxPositive.resize(blockSize);
} catch(...){
printf("Failed to allocate memory in %s (%s %d)\n", __FUNCTION__, __FILE__, __LINE__);
return;
}
for(int i = 0; i < noSample; i++){
shuffle[i] = i;
pPosIndex[i] = -1;
pNegIndex[i] = -1;
}
// random shuffle
// for(int i = 0; i < noSample; i++){
// int j = rand() % noSample;
// int temp = shuffle[i];
// shuffle[i] = shuffle[j];
// shuffle[j] = temp;
// }
std::random_shuffle(shuffle.begin(), shuffle.end());
int remained = noSample;
for(int block = 0; block < noBlock; block++){
int from = block * blockSize;
if(block % 5 == 0){
printf("\rProcessing block %d / %d\n", block, noBlock);
fflush(stdout);
}
int curBlock = MIN(blockSize, remained);
int to = from + curBlock;
// printf("Extracting feature\n"); fflush(stdout);
ExtractFeature(pNN, inDim, dataset, shuffle, from, to, outDim, &vBlockFeature[0], batchSize);
for(int i = 0; i < curBlock; i++){
vMinNegative[i] = FLT_MAX;
vMaxPositive[i] = -FLT_MAX;
}
//printf("Finding positive and negative samples\n"); fflush(stdout);
for(int i = 0; i < curBlock; i++){
int idx_i = shuffle[from + i];
for(int j = i + 1; j < curBlock; j++){
int idx_j = shuffle[from + j];
int dist2 = GetSquareDistance(outDim, vBlockFeature[i], vBlockFeature[j]);
if(dataset.GetLabel(idx_i) == dataset.GetLabel(idx_j)){ // same label
if(dist2 > vMaxPositive[i]){
pPosIndex[idx_i] = idx_j;
vMaxPositive[i] = dist2;
}
if(dist2 > vMaxPositive[j]){
pPosIndex[idx_j] = idx_i;
vMaxPositive[j] = dist2;
}
if(dataset.GetLabel(idx_i) != dataset.GetLabel(idx_j)){
printf("Error! Wrong positive sample! (%s %d)\n", __FILE__, __LINE__);
MyPause(__FUNCTION__);
}
} else { // different label
if(dist2 < vMinNegative[i]){
pNegIndex[idx_i] = idx_j;
vMinNegative[i] = dist2;
}
if(dist2 < vMinNegative[j]){
pNegIndex[idx_j] = idx_i;
vMinNegative[j] = dist2;
}
if(dataset.GetLabel(idx_i) == dataset.GetLabel(idx_j)){
printf("Error! Wrong negative sample! (%s %d)\n", __FILE__, __LINE__);
MyPause(__FUNCTION__);
}
}
}
}
#ifdef __DEBUG__
for(int i = 0; i < curBlock; i++){
int anchorIdx = shuffle[from + i];
int posIdx = pPosIndex[anchorIdx];
int negIdx = pNegIndex[anchorIdx];
int posLabel = (posIdx >= 0 ? dataset.GetLabel(posIdx) : -1);
int negLabel = (negIdx >= 0 ? dataset.GetLabel(negIdx) : -1);
printf("%d: anchor: %d (%d),\tpos = %d (%d),\tneg = %d (%d)\n", i, anchorIdx, dataset.GetLabel(anchorIdx), posIdx, posLabel, negIdx, negLabel);
// if(dataset.GetLabel(anchorIdx) != dataset.GetLabel(posIdx) || dataset.GetLabel(anchorIdx) == dataset.GetLabel(negIdx)){
// printf("Error! Wrong positive or negative sample! (%s %d)\n", __FILE__, __LINE__);
// MyPause(__FUNCTION__);
// }
}
MyPause(__FUNCTION__);
#endif// __DEBUG__
remained -= blockSize;
//printf("Done\n"); fflush(stdout);
}
DeleteFeatureVector(vBlockFeature);
printf("Done\n"); fflush(stdout);
}
void ExtractFeature(NeuralNetwork<float> *pNN, int inDim, Dataset<float> &dataset, std::vector<int> &shuffle, int from, int to, int outDim, float *pFeature[], int batchSize)
{
from = MIN(from, dataset.GetLength());
to = MIN(to, dataset.GetLength());
if(from == to){
printf("No data to process in %s (%s %d)\n", __FUNCTION__, __FILE__, __LINE__);
return;
}
int noSample = to - from;
batchSize = MIN(batchSize, noSample);
int noBatch = (noSample + batchSize - 1) / batchSize;
int remained = noSample;
// allocate temporary buffers
std::vector<float*> vTmpSample;
std::vector<float*> vTmpFeature;
try {
AllocFeatureVector(inDim, batchSize, vTmpSample);
AllocFeatureVector(outDim, batchSize, vTmpFeature);
} catch (...){
printf("Failed to allocate memory in %s (%s %d)\n", __FUNCTION__, __FILE__, __LINE__);
MyPause(__FUNCTION__);
return;
}
// extract feature using CNN
for(int batchIdx = 0; batchIdx < noBatch; batchIdx++){
int curBatch = MIN(remained, batchSize);
// printf("Reading batch %d\n", batchIdx); fflush(stdout);
for(int i = 0; i < curBatch; i++)
dataset.CopyData(shuffle[from + batchIdx * batchSize + i], vTmpSample[i]);
// printf("Calling InputToFeature()"); fflush(stdout);
AllocFeatureVector(outDim, vTmpSample.size(), vTmpFeature);
pNN->InputToFeature(inDim, vTmpSample.size(), &vTmpSample[0], outDim, &vTmpFeature[0], batchSize);
// printf("Copying feature"); fflush(stdout);
for(int i = 0; i < curBatch; i++)
// memcpy(pFeature[batchIdx * batchSize + i], vTmpFeature[i], outDim * sizeof(vTmpFeature[i][0]));
memcpy(pFeature[batchIdx * batchSize + i], vTmpFeature[i], outDim * sizeof(float));
DeleteFeatureVector(vTmpFeature);
// printf("Done."); fflush(stdout);
remained -= batchSize;
}
DeleteFeatureVector(vTmpSample);
}
| 39.122642 | 256 | 0.57034 | [
"vector",
"model",
"transform"
] |
02eef8ff363572e7ee8a383cb0de59b38c40364d | 935 | cpp | C++ | leetcode/2157/graph.cpp | mkmark/leetcode | 638a9d37fb3223107d2852ce493d831996a7649e | [
"MIT"
] | null | null | null | leetcode/2157/graph.cpp | mkmark/leetcode | 638a9d37fb3223107d2852ce493d831996a7649e | [
"MIT"
] | null | null | null | leetcode/2157/graph.cpp | mkmark/leetcode | 638a9d37fb3223107d2852ce493d831996a7649e | [
"MIT"
] | null | null | null | /*
author: mark@mkmark.net
*/
#include "graph.hpp"
using namespace std;
graph::graph(int n): n(n){
adj.resize(n);
grp.resize(n);
fill_n(grp.begin(), n, -1);
}
graph::graph(int n, vector<int>& val): n(n){
adj.resize(n);
grp.resize(n);
fill_n(grp.begin(), n, -1);
value = val;
}
void graph::group(){
int gid = -1;
for (int i=0; i<n; ++i) {
if (grp[i] == -1) {
++gid;
grp_size.push_back(0);
dfs(i, grp, gid);
}
}
grp_cnt = gid+1;
}
int graph::max_grp_size(){
int res = 0;
for (int i=0; i<grp_cnt; ++i) {
res=max(res, grp_size[i]);
}
return res;
}
void graph::dfs(int i, vector<int>& grp, int gid){
grp[i] = gid;
for (auto j : adj[i]){
if (grp[j] == -1){
dfs(j, grp, gid);
}
}
}
void graph::add_edge(int i, int j){
adj[i].push_back(j);
adj[j].push_back(i);
}
| 16.696429 | 50 | 0.481283 | [
"vector"
] |
02fc03dddde7c1c52aaf382ded9527376cc4a1c0 | 4,483 | ipp | C++ | include/External/stlib/packages/geom/mesh/iss/ISS_SimplexQuery.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/geom/mesh/iss/ISS_SimplexQuery.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | include/External/stlib/packages/geom/mesh/iss/ISS_SimplexQuery.ipp | bxl295/m4extreme | 2a4a20ebb5b4e971698f7c981de140d31a5e550c | [
"BSD-3-Clause"
] | null | null | null | // -*- C++ -*-
#if !defined(__geom_ISS_SimplexQuery_ipp__)
#error This file is an implementation detail of the class ISS_SimplexQuery.
#endif
namespace geom {
template<class ISS>
inline
void
ISS_SimplexQuery<ISS>::
build() {
std::vector<BBox> boxes(_iss.getSimplicesSize());
Simplex simplex;
// For each simplex.
for (std::size_t n = 0; n != _iss.getSimplicesSize(); ++n) {
_iss.getSimplex(n, &simplex);
// Make a bounding box around the simplex.
boxes[n].bound(simplex.begin(), simplex.end());
}
// Build the tree from the bounding boxes.
_bboxTree.build(boxes.begin(), boxes.end());
}
//
// Queries.
//
// Get the indices of the simplices that contain the point.
template<class ISS>
template <typename IntOutIter>
inline
void
ISS_SimplexQuery<ISS>::
computePointQuery(IntOutIter iter, const Vertex& x) const {
std::size_t n;
Simplex s;
std::vector<std::size_t> candidates;
_bboxTree.computePointQuery(std::back_inserter(candidates), x);
for (std::vector<std::size_t>::const_iterator i = candidates.begin();
i != candidates.end(); ++i) {
n = *i;
// Get the simplex.
_iss.getSimplex(n, &s);
if (isIn(s, x)) {
*iter++ = n;
}
}
}
// Get the indices of the simplices that overlap the window.
template<class ISS>
template <typename IntOutIter>
inline
void
ISS_SimplexQuery<ISS>::
computeWindowQuery(IntOutIter iter, const BBox& window) const {
_bboxTree.computeWindowQuery(iter, window);
}
// Return the index of the simplex of minimum distance.
template<class ISS>
inline
int
ISS_SimplexQuery<ISS>::
computeMinimumDistanceAndIndex(const Vertex& x, Number* minDistance) const {
// If there are no simplices.
if (_iss.getSimplicesSize() == 0) {
// Return an invalid index.
return -1;
}
std::size_t n;
Simplex s;
//
// Get the candidates simplices.
//
std::vector<std::size_t> candidates;
_bboxTree.computeMinimumDistanceQuery(std::back_inserter(candidates), x);
//
// Calculate distance to the candidate simplices.
//
std::vector<Number> distances(candidates.size());
const std::size_t i_end = candidates.size();
for (std::size_t i = 0; i != i_end; ++i) {
n = candidates[i];
// Get the simplex.
_iss.getSimplex(n, &s);
// Calculate the signed or unsigned distance to the simplex.
distances[i] = computeDistance(s, x);
// CONTINUE REMOVE
//std::cerr << "simplex = " << s << " d = " << distances[i] << "\n";
}
//
// Choose the one of minimum distance.
//
typename std::vector<Number>::const_iterator minIter =
std::min_element(distances.begin(), distances.end());
assert(minIter != distances.end());
// Record the minimum distance.
*minDistance = *minIter;
// Return the index of the closest simplex.
return candidates[minIter - distances.begin()];
}
// Return the minimum distance to the mesh.
template<class ISS>
inline
typename ISS_SimplexQuery<ISS>::Number
ISS_SimplexQuery<ISS>::
computeMinimumDistance(const Vertex& x) const {
// If there are no simplices.
if (_iss.getSimplicesSize() == 0) {
// Return infinity.
return std::numeric_limits<Number>::max();
}
// REMOVE
//std::cerr << "x = " << x << "\n";
std::size_t n;
Simplex s;
//
// Get the candidates simplices.
//
std::vector<std::size_t> candidates;
// REMOVE
//std::cerr << "start\n";
_bboxTree.computeMinimumDistanceQuery(std::back_inserter(candidates), x);
// REMOVE
//std::cerr << "finish\n";
// REMOVE
//std::cerr << "size = " << candidates.size() << "\n";
//
// Calculate distance to the candidate simplices.
//
Number d;
Number minDist = std::numeric_limits<Number>::max();
const std::size_t iEnd = candidates.size();
for (std::size_t i = 0; i != iEnd; ++i) {
n = candidates[i];
// Get the simplex.
_iss.getSimplex(n, &s);
// Calculate the signed distance to the simplex.
d = computeDistance(s, x);
// REMOVE
//std::cerr << "d = " << d << "\n";
// Update the minimum distance.
if (d < minDist) {
minDist = d;
}
}
assert(minDist != std::numeric_limits<Number>::max());
return minDist;
}
} // namespace geom
| 25.471591 | 77 | 0.60696 | [
"mesh",
"vector"
] |
02febfd874745719d6ce7741cdb8dfd075dd42fe | 2,900 | cpp | C++ | USACO Bronze/US Open 2019 Contest/cow_evolution.cpp | Alecs-Li/Competitive-Programming | 39941ff8e2c8994abbae8c96a1ed0a04b10058b8 | [
"MIT"
] | 1 | 2021-07-06T02:14:03.000Z | 2021-07-06T02:14:03.000Z | USACO Bronze/US Open 2019 Contest/cow_evolution.cpp | Alex01890-creator/competitive-programming | 39941ff8e2c8994abbae8c96a1ed0a04b10058b8 | [
"MIT"
] | null | null | null | USACO Bronze/US Open 2019 Contest/cow_evolution.cpp | Alex01890-creator/competitive-programming | 39941ff8e2c8994abbae8c96a1ed0a04b10058b8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
#include <string>
#include <set>
#include <queue>
#include <map>
using namespace std;
typedef long double ld;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll,ll> pll;
typedef pair<char, char> pc;
typedef pair<string, string> ps;
typedef tuple<int, int, int> ti;
typedef tuple<ll, ll, ll> tll;
typedef tuple<string, string, string> ts;
typedef tuple<char, char, char> tc;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pi> vpi;
typedef vector<pll> vpll;
typedef vector<ti> vti;
typedef vector<bool> vb;
typedef vector<ts> vts;
typedef multiset<int> msi;
typedef multiset<ll> msll;
typedef multiset<string> mss;
typedef multiset<char> mc;
typedef queue<char> qc;
typedef queue<int> qi;
typedef queue<ll> qll;
typedef queue<string> qs;
typedef set<int> si;
typedef set<ll> sll;
typedef set<string> ss;
typedef set<char> sc;
#define FOR(a, b, c) for (int a=(b); a<(c); a++)
#define F0R(i, a) for (int i=0; i<(a); i++)
#define F1R(i, a) for (int i=1; i<(a); i++)
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define popb pop_back
#define f first
#define sec second
#define ub upper_bound
#define lb lower_bound
#define beg begin
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
void setIO(string name = "evolution"){
ios_base::sync_with_stdio(0); cin.tie(0);
if(name.size()){
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
int n;
vs v[25];
vs v2;
bool check(int x, int y){
int c1 = 0, c2 = 0, c3 = 0;
F0R(a, n){
bool A = false, B = false;
F0R(b, sz(v[a])){
if(v[a][b] == v2[x]){
A = true;
}
if(v[a][b] == v2[y]){
B = true;
}
}
if(A && B){
c1++;
} else if(A){
c2++;
} else if(B){
c3++;
}
}
if(c1 > 0 && c2 > 0 && c3 > 0){
return true;
}
return false;
}
void solve(){
cin >> n;
F0R(a, n){
int c;
cin >> c;
F0R(b, c){
string s; cin >> s;
v[a].pb(s);
bool done = false;
F0R(d, v2.size()){
if(v2[d] == s){
done = true;
}
}
if(!done){
v2.pb(s);
}
}
}
string ans = "yes";
F0R(a, v2.size()){
bool done = false;
FOR(b, a+1, v2.size()){
if(check(a, b)){
done = true;
break;
}
}
if(done){
ans = "no";
break;
}
}
cout << ans;
}
int main(){
setIO();
int t = 1;
//cin >> t;
while(t--){
solve();
}
}
| 20.714286 | 54 | 0.502069 | [
"vector"
] |
f3028ee45e2dd344021d3835ada0d8671b90383b | 20,024 | cpp | C++ | Engine/source/T3D/physicalZone.cpp | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 2,113 | 2015-01-01T11:23:01.000Z | 2022-03-28T04:51:46.000Z | Engine/source/T3D/physicalZone.cpp | Ashry00/Torque3D | 33e3e41c8b7eb41c743a589558bc21302207ef97 | [
"MIT"
] | 948 | 2015-01-02T01:50:00.000Z | 2022-02-27T05:56:40.000Z | Engine/source/T3D/physicalZone.cpp | Ashry00/Torque3D | 33e3e41c8b7eb41c743a589558bc21302207ef97 | [
"MIT"
] | 944 | 2015-01-01T09:33:53.000Z | 2022-03-15T22:23:03.000Z | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
// Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
// Copyright (C) 2015 Faust Logic, Inc.
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
#include "T3D/physicalZone.h"
#include "core/stream/bitStream.h"
#include "collision/boxConvex.h"
#include "collision/clippedPolyList.h"
#include "console/consoleTypes.h"
#include "math/mathIO.h"
#include "scene/sceneRenderState.h"
#include "T3D/trigger.h"
#include "gfx/gfxTransformSaver.h"
#include "renderInstance/renderPassManager.h"
#include "gfx/gfxDrawUtil.h"
#include "console/engineAPI.h"
//#include "console/engineTypes.h"
#include "sim/netConnection.h"
IMPLEMENT_CO_NETOBJECT_V1(PhysicalZone);
ConsoleDocClass( PhysicalZone,
"@brief Physical Zones are areas that modify the player's gravity and/or velocity and/or applied force.\n\n"
"The datablock properties determine how the physics, velocity and applied forces affect a player who enters this zone.\n"
"@tsexample\n"
"new PhysicalZone(Team1JumpPad) {\n"
"velocityMod = \"1\";"
"gravityMod = \"0\";\n"
"appliedForce = \"0 0 20000\";\n"
"polyhedron = \"0.0000000 0.0000000 0.0000000 1.0000000 0.0000000 0.0000000 0.0000000 -1.0000000 0.0000000 0.0000000 0.0000000 1.0000000\";\n"
"position = \"273.559 -166.371 249.856\";\n"
"rotation = \"0 0 1 13.0216\";\n"
"scale = \"8 4.95 28.31\";\n"
"isRenderEnabled = \"true\";\n"
"canSaveDynamicFields = \"1\";\n"
"enabled = \"1\";\n"
"};\n"
"@endtsexample\n\n"
"@ingroup enviroMisc\n"
);
bool PhysicalZone::smRenderPZones = false;
DefineEngineMethod(PhysicalZone, activate, void, (),, "Activate the physical zone's effects.\n"
"@tsexample\n"
"// Activate effects for a specific physical zone.\n"
"%thisPhysicalZone.activate();\n"
"@endtsexample\n"
"@ingroup Datablocks\n"
)
{
if (object->isClientObject())
return;
object->activate();
}
DefineEngineMethod(PhysicalZone, deactivate, void, (),, "Deactivate the physical zone's effects.\n"
"@tsexample\n"
"// Deactivate effects for a specific physical zone.\n"
"%thisPhysicalZone.deactivate();\n"
"@endtsexample\n"
"@ingroup Datablocks\n"
)
{
if (object->isClientObject())
return;
object->deactivate();
}
//--------------------------------------------------------------------------
//--------------------------------------
//
PhysicalZone::PhysicalZone()
{
mNetFlags.set(Ghostable | ScopeAlways);
mTypeMask |= PhysicalZoneObjectType;
mVelocityMod = 1.0f;
mGravityMod = 1.0f;
mAppliedForce.set(0, 0, 0);
mConvexList = new Convex;
mActive = true;
force_type = VECTOR;
force_mag = 0.0f;
orient_force = false;
fade_amt = 1.0f;
}
PhysicalZone::~PhysicalZone()
{
delete mConvexList;
mConvexList = NULL;
}
ImplementEnumType( PhysicalZone_ForceType, "Possible physical zone force types.\n" "@ingroup PhysicalZone\n\n" )
{ PhysicalZone::VECTOR, "vector", "..." },
{ PhysicalZone::SPHERICAL, "spherical", "..." },
{ PhysicalZone::CYLINDRICAL, "cylindrical", "..." },
// aliases
{ PhysicalZone::SPHERICAL, "sphere", "..." },
{ PhysicalZone::CYLINDRICAL, "cylinder", "..." },
EndImplementEnumType;
//--------------------------------------------------------------------------
void PhysicalZone::consoleInit()
{
Con::addVariable( "$PhysicalZone::renderZones", TypeBool, &smRenderPZones, "If true, a box will render around the location of all PhysicalZones.\n"
"@ingroup EnviroMisc\n");
}
void PhysicalZone::initPersistFields()
{
addGroup("Misc");
addField("velocityMod", TypeF32, Offset(mVelocityMod, PhysicalZone), "Multiply velocity of objects entering zone by this value every tick.");
addField("gravityMod", TypeF32, Offset(mGravityMod, PhysicalZone), "Gravity in PhysicalZone. Multiplies against standard gravity.");
addField("appliedForce", TypePoint3F, Offset(mAppliedForce, PhysicalZone), "Three-element floating point value representing forces in three axes to apply to objects entering PhysicalZone.");
addField("polyhedron", TypeTriggerPolyhedron, Offset(mPolyhedron, PhysicalZone),
"The polyhedron type is really a quadrilateral and consists of a corner"
"point followed by three vectors representing the edges extending from the corner." );
endGroup("Misc");
addGroup("AFX");
addField("forceType", TYPEID<PhysicalZone::ForceType>(), Offset(force_type, PhysicalZone));
addField("orientForce", TypeBool, Offset(orient_force, PhysicalZone));
endGroup("AFX");
Parent::initPersistFields();
}
//--------------------------------------------------------------------------
bool PhysicalZone::onAdd()
{
if(!Parent::onAdd())
return false;
if (mVelocityMod < -40.0f || mVelocityMod > 40.0f) {
Con::errorf("PhysicalZone: velocity mod out of range. [-40, 40]");
mVelocityMod = mVelocityMod < -40.0f ? -40.0f : 40.0f;
}
if (mGravityMod < -40.0f || mGravityMod > 40.0f) {
Con::errorf("PhysicalZone: GravityMod out of range. [-40, 40]");
mGravityMod = mGravityMod < -40.0f ? -40.0f : 40.0f;
}
static const char* coordString[] = { "x", "y", "z" };
F32* p = mAppliedForce;
for (U32 i = 0; i < 3; i++) {
if (p[i] < -40000.0f || p[i] > 40000.0f) {
Con::errorf("PhysicalZone: applied force: %s out of range. [-40000, 40000]", coordString[i]);
p[i] = p[i] < -40000.0f ? -40000.0f : 40000.0f;
}
}
Polyhedron temp = mPolyhedron;
setPolyhedron(temp);
switch (force_type)
{
case SPHERICAL:
force_mag = mAppliedForce.magnitudeSafe();
break;
case CYLINDRICAL:
{
Point3F force_vec = mAppliedForce;
force_vec.z = 0.0;
force_mag = force_vec.magnitudeSafe();
}
break;
}
addToScene();
return true;
}
void PhysicalZone::onRemove()
{
mConvexList->nukeList();
removeFromScene();
Parent::onRemove();
}
void PhysicalZone::inspectPostApply()
{
Parent::inspectPostApply();
setPolyhedron(mPolyhedron);
setMaskBits(PolyhedronMask | MoveMask | SettingsMask | FadeMask);
}
//------------------------------------------------------------------------------
void PhysicalZone::setTransform(const MatrixF & mat)
{
Parent::setTransform(mat);
MatrixF base(true);
base.scale(Point3F(1.0/mObjScale.x,
1.0/mObjScale.y,
1.0/mObjScale.z));
base.mul(mWorldToObj);
mClippedList.setBaseTransform(base);
if (isServerObject())
setMaskBits(MoveMask);
}
void PhysicalZone::prepRenderImage( SceneRenderState *state )
{
// only render if selected or render flag is set
if ( !smRenderPZones && !isSelected() )
return;
ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
ri->renderDelegate.bind( this, &PhysicalZone::renderObject );
ri->type = RenderPassManager::RIT_Editor;
ri->defaultKey = 0;
ri->defaultKey2 = 0;
state->getRenderPass()->addInst( ri );
}
void PhysicalZone::renderObject(ObjectRenderInst *ri,
SceneRenderState *state,
BaseMatInstance *overrideMat)
{
if (overrideMat)
return;
GFXStateBlockDesc desc;
desc.setZReadWrite(true, false);
desc.setBlend(true);
desc.setCullMode(GFXCullNone);
GFXTransformSaver saver;
GFXDrawUtil *drawer = GFX->getDrawUtil();
Point3F start = getBoxCenter();
Box3F obb = mObjBox; //object bounding box
F32 baseForce = 10000; //roughly the ammount of force needed to push a player back as it walks into a zone. (used for visual scaling)
Point3F forceDir = getForce(&start);
F32 forceLen = forceDir.len()/ baseForce;
forceDir.normalizeSafe();
ColorI guideCol = LinearColorF(mFabs(forceDir.x), mFabs(forceDir.y), mFabs(forceDir.z), 0.125).toColorI();
if (force_type == VECTOR)
{
Point3F endPos = start + (forceDir * mMax(forceLen,0.75f));
drawer->drawArrow(desc, start, endPos, guideCol, 0.05f);
}
MatrixF mat = getRenderTransform();
mat.scale(getScale());
GFX->multWorld(mat);
start = obb.getCenter();
if (force_type == VECTOR)
{
drawer->drawPolyhedron(desc, mPolyhedron, ColorI(0, 255, 0, 45));
}
else if (force_type == SPHERICAL)
{
F32 rad = obb.getBoundingSphere().radius/ 2;
drawer->drawSphere(desc, rad, start, ColorI(0, 255, 0, 45));
rad = (rad + (mAppliedForce.most() / baseForce))/2;
desc.setFillModeWireframe();
drawer->drawSphere(desc, rad, start, ColorI(0, 0, 255, 255));
}
else
{
Point3F bottomPos = start;
bottomPos.z -= obb.len_z() / 2;
Point3F topPos = start;
topPos.z += obb.len_z() / 2;
F32 rad = obb.len_x() / 2;
drawer->drawCylinder(desc, bottomPos, topPos, rad, ColorI(0, 255, 0, 45));
Point3F force_vec = mAppliedForce; //raw relative-applied force here as oposed to derived
F32 hieght = (force_vec.z / baseForce);
if (force_vec.z<0)
bottomPos.z = (bottomPos.z + hieght)/2;
else
topPos.z = (topPos.z + hieght) / 2;
if (force_vec.x > force_vec.y)
rad = (rad + (force_vec.x / baseForce)) / 2;
else
rad = (rad + (force_vec.y / baseForce)) / 2;
desc.setFillModeWireframe();
drawer->drawCylinder(desc, bottomPos, topPos, rad, guideCol);
}
desc.setFillModeWireframe();
drawer->drawPolyhedron(desc, mPolyhedron, ColorI::BLACK);
}
//--------------------------------------------------------------------------
U32 PhysicalZone::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
{
U32 i;
U32 retMask = Parent::packUpdate(con, mask, stream);
if (stream->writeFlag(mask & PolyhedronMask))
{
// Write the polyhedron
stream->write(mPolyhedron.mPointList.size());
for (i = 0; i < mPolyhedron.mPointList.size(); i++)
mathWrite(*stream, mPolyhedron.mPointList[i]);
stream->write(mPolyhedron.mPlaneList.size());
for (i = 0; i < mPolyhedron.mPlaneList.size(); i++)
mathWrite(*stream, mPolyhedron.mPlaneList[i]);
stream->write(mPolyhedron.mEdgeList.size());
for (i = 0; i < mPolyhedron.mEdgeList.size(); i++) {
const Polyhedron::Edge& rEdge = mPolyhedron.mEdgeList[i];
stream->write(rEdge.face[0]);
stream->write(rEdge.face[1]);
stream->write(rEdge.vertex[0]);
stream->write(rEdge.vertex[1]);
}
}
if (stream->writeFlag(mask & MoveMask))
{
stream->writeAffineTransform(mObjToWorld);
mathWrite(*stream, mObjScale);
}
if (stream->writeFlag(mask & SettingsMask))
{
stream->write(mVelocityMod);
stream->write(mGravityMod);
mathWrite(*stream, mAppliedForce);
stream->writeInt(force_type, FORCE_TYPE_BITS);
stream->writeFlag(orient_force);
}
if (stream->writeFlag(mask & FadeMask))
{
U8 fade_byte = (U8)(fade_amt*255.0f);
stream->write(fade_byte);
}
stream->writeFlag(mActive);
return retMask;
}
void PhysicalZone::unpackUpdate(NetConnection* con, BitStream* stream)
{
Parent::unpackUpdate(con, stream);
bool new_ph = false;
if (stream->readFlag()) // PolyhedronMask
{
U32 i, size;
Polyhedron tempPH;
// Read the polyhedron
stream->read(&size);
tempPH.mPointList.setSize(size);
for (i = 0; i < tempPH.mPointList.size(); i++)
mathRead(*stream, &tempPH.mPointList[i]);
stream->read(&size);
tempPH.mPlaneList.setSize(size);
for (i = 0; i < tempPH.mPlaneList.size(); i++)
mathRead(*stream, &tempPH.mPlaneList[i]);
stream->read(&size);
tempPH.mEdgeList.setSize(size);
for (i = 0; i < tempPH.mEdgeList.size(); i++) {
Polyhedron::Edge& rEdge = tempPH.mEdgeList[i];
stream->read(&rEdge.face[0]);
stream->read(&rEdge.face[1]);
stream->read(&rEdge.vertex[0]);
stream->read(&rEdge.vertex[1]);
}
setPolyhedron(tempPH);
new_ph = true;
}
if (stream->readFlag()) // MoveMask
{
MatrixF temp;
stream->readAffineTransform(&temp);
Point3F tempScale;
mathRead(*stream, &tempScale);
//if (!new_ph)
//{
// Polyhedron rPolyhedron = mPolyhedron;
// setPolyhedron(rPolyhedron);
//}
setScale(tempScale);
setTransform(temp);
}
if (stream->readFlag()) //SettingsMask
{
stream->read(&mVelocityMod);
stream->read(&mGravityMod);
mathRead(*stream, &mAppliedForce);
force_type = stream->readInt(FORCE_TYPE_BITS); // AFX
orient_force = stream->readFlag(); // AFX
}
if (stream->readFlag()) //FadeMask
{
U8 fade_byte;
stream->read(&fade_byte);
fade_amt = ((F32)fade_byte)/255.0f;
}
else
fade_amt = 1.0f;
mActive = stream->readFlag();
}
//--------------------------------------------------------------------------
void PhysicalZone::setPolyhedron(const Polyhedron& rPolyhedron)
{
mPolyhedron = rPolyhedron;
if (mPolyhedron.mPointList.size() != 0) {
mObjBox.minExtents.set(1e10, 1e10, 1e10);
mObjBox.maxExtents.set(-1e10, -1e10, -1e10);
for (U32 i = 0; i < mPolyhedron.mPointList.size(); i++) {
mObjBox.minExtents.setMin(mPolyhedron.mPointList[i]);
mObjBox.maxExtents.setMax(mPolyhedron.mPointList[i]);
}
} else {
mObjBox.minExtents.set(-0.5, -0.5, -0.5);
mObjBox.maxExtents.set( 0.5, 0.5, 0.5);
}
MatrixF xform = getTransform();
setTransform(xform);
mClippedList.clear();
mClippedList.mPlaneList = mPolyhedron.mPlaneList;
MatrixF base(true);
base.scale(Point3F(1.0/mObjScale.x,
1.0/mObjScale.y,
1.0/mObjScale.z));
base.mul(mWorldToObj);
mClippedList.setBaseTransform(base);
}
//--------------------------------------------------------------------------
void PhysicalZone::buildConvex(const Box3F& box, Convex* convex)
{
// These should really come out of a pool
mConvexList->collectGarbage();
Box3F realBox = box;
mWorldToObj.mul(realBox);
realBox.minExtents.convolveInverse(mObjScale);
realBox.maxExtents.convolveInverse(mObjScale);
if (realBox.isOverlapped(getObjBox()) == false)
return;
// Just return a box convex for the entire shape...
Convex* cc = 0;
CollisionWorkingList& wl = convex->getWorkingList();
for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) {
if (itr->mConvex->getType() == BoxConvexType &&
itr->mConvex->getObject() == this) {
cc = itr->mConvex;
break;
}
}
if (cc)
return;
// Create a new convex.
BoxConvex* cp = new BoxConvex;
mConvexList->registerObject(cp);
convex->addToWorkingList(cp);
cp->init(this);
mObjBox.getCenter(&cp->mCenter);
cp->mSize.x = mObjBox.len_x() / 2.0f;
cp->mSize.y = mObjBox.len_y() / 2.0f;
cp->mSize.z = mObjBox.len_z() / 2.0f;
}
bool PhysicalZone::testObject(SceneObject* enter)
{
// TODO: This doesn't look like it's testing against the polyhedron at
// all. And whats the point of building a convex if no collision methods
// are implemented?
if (mPolyhedron.mPointList.size() == 0)
return false;
mClippedList.clear();
SphereF sphere;
sphere.center = (mWorldBox.minExtents + mWorldBox.maxExtents) * 0.5;
VectorF bv = mWorldBox.maxExtents - sphere.center;
sphere.radius = bv.len();
enter->buildPolyList(PLC_Collision, &mClippedList, mWorldBox, sphere);
return mClippedList.isEmpty() == false;
}
bool PhysicalZone::testBox( const Box3F &box ) const
{
return mWorldBox.isOverlapped( box );
}
void PhysicalZone::activate()
{
AssertFatal(isServerObject(), "Client objects not allowed in ForceFieldInstance::open()");
if (mActive != true)
setMaskBits(ActiveMask);
mActive = true;
}
void PhysicalZone::deactivate()
{
AssertFatal(isServerObject(), "Client objects not allowed in ForceFieldInstance::close()");
if (mActive != false)
setMaskBits(ActiveMask);
mActive = false;
}
void PhysicalZone::onStaticModified(const char* slotName, const char*newValue)
{
if (dStricmp(slotName, "appliedForce") == 0 || dStricmp(slotName, "forceType") == 0)
{
switch (force_type)
{
case SPHERICAL:
force_mag = mAppliedForce.magnitudeSafe();
break;
case CYLINDRICAL:
{
Point3F force_vec = mAppliedForce;
force_vec.z = 0.0;
force_mag = force_vec.magnitudeSafe();
}
break;
}
}
}
const Point3F& PhysicalZone::getForce(const Point3F* center) const
{
static Point3F force_vec;
if (force_type == VECTOR)
{
if (orient_force)
{
getTransform().mulV(mAppliedForce, &force_vec);
force_vec *= fade_amt;
return force_vec;
}
force_vec = mAppliedForce;
force_vec *= fade_amt;
return force_vec;
}
if (!center)
{
force_vec.zero();
return force_vec;
}
if (force_type == SPHERICAL)
{
force_vec = *center - getPosition();
force_vec.normalizeSafe();
force_vec *= force_mag*fade_amt;
return force_vec;
}
if (orient_force)
{
force_vec = *center - getPosition();
getWorldTransform().mulV(force_vec);
force_vec.z = 0.0f;
force_vec.normalizeSafe();
force_vec *= force_mag;
force_vec.z = mAppliedForce.z;
getTransform().mulV(force_vec);
force_vec *= fade_amt;
return force_vec;
}
force_vec = *center - getPosition();
force_vec.z = 0.0f;
force_vec.normalizeSafe();
force_vec *= force_mag;
force_vec *= fade_amt;
return force_vec;
}
bool PhysicalZone::isExcludedObject(SceneObject* obj) const
{
for (S32 i = 0; i < excluded_objects.size(); i++)
if (excluded_objects[i] == obj)
return true;
return false;
}
void PhysicalZone::registerExcludedObject(SceneObject* obj)
{
if (isExcludedObject(obj))
return;
excluded_objects.push_back(obj);
setMaskBits(FadeMask);
}
void PhysicalZone::unregisterExcludedObject(SceneObject* obj)
{
for (S32 i = 0; i < excluded_objects.size(); i++)
if (excluded_objects[i] == obj)
{
excluded_objects.erase(i);
setMaskBits(FadeMask);
return;
}
}
| 29.403818 | 203 | 0.612465 | [
"render",
"object",
"shape",
"vector",
"3d"
] |
f3077e630e9ae0a049d12fae2a3fdb923b0ea288 | 42,372 | cc | C++ | crawl-ref/source/precision-menu.cc | RojjaCebolla/crawl | fe7b5d5a6f32694e30fd8c926fa81db8cac38c49 | [
"CC0-1.0"
] | null | null | null | crawl-ref/source/precision-menu.cc | RojjaCebolla/crawl | fe7b5d5a6f32694e30fd8c926fa81db8cac38c49 | [
"CC0-1.0"
] | null | null | null | crawl-ref/source/precision-menu.cc | RojjaCebolla/crawl | fe7b5d5a6f32694e30fd8c926fa81db8cac38c49 | [
"CC0-1.0"
] | 2 | 2021-03-07T18:45:13.000Z | 2021-03-08T23:28:57.000Z | /**
* @file
* @brief Deprecated precision menu code.
**/
#include "AppHdr.h"
#include "menu.h"
#include "precision-menu.h"
#include <functional>
#include "libutil.h"
#include "stringutil.h"
/**
* Performs regular rectangular AABB intersection between the given AABB
* rectangle and a item in the menu_entries
* <pre>
* start(x,y)------------
* | |
* ------------end(x,y)
* </pre>
*/
static bool _AABB_intersection(const coord_def& item_start,
const coord_def& item_end,
const coord_def& aabb_start,
const coord_def& aabb_end)
{
// Check for no overlap using equals on purpose to rule out entities
// that only brush the bounding box
if (aabb_start.x >= item_end.x)
return false;
if (aabb_end.x <= item_start.x)
return false;
if (aabb_start.y >= item_end.y)
return false;
if (aabb_end.y <= item_start.y)
return false;
// We have overlap
return true;
}
PrecisionMenu::PrecisionMenu() : m_active_object(nullptr),
m_select_type(PRECISION_SINGLESELECT)
{
}
PrecisionMenu::~PrecisionMenu()
{
clear();
}
void PrecisionMenu::set_select_type(SelectType flag)
{
m_select_type = flag;
}
/**
* Frees all used memory
*/
void PrecisionMenu::clear()
{
// release all the data reserved
deleteAll(m_attached_objects);
}
/**
* Processes user input.
*
* Returns:
* true when a significant event happened, signaling that the player has made a
* menu ending action like selecting an item in singleselect mode
* false otherwise
*/
bool PrecisionMenu::process_key(int key)
{
if (m_active_object == nullptr)
{
if (m_attached_objects.empty())
{
// nothing to process
return true;
}
else
{
// pick the first object possible
for (auto mobj : m_attached_objects)
{
if (mobj->can_be_focused())
{
m_active_object = mobj;
break;
}
}
}
}
#ifdef TOUCH_UI
if (key == CK_TOUCH_DUMMY)
return true; // mouse click in title area, which wouldn't usually be handled
#endif
// Handle CK_MOUSE_CLICK separately
// This signifies a menu ending action
if (key == CK_MOUSE_CLICK)
return true;
bool focus_find = false;
PrecisionMenu::Direction focus_direction;
MenuObject::InputReturnValue input_ret = m_active_object->process_input(key);
switch (input_ret)
{
case MenuObject::INPUT_NO_ACTION:
break;
case MenuObject::INPUT_SELECTED:
if (m_select_type == PRECISION_SINGLESELECT)
return true;
else
{
// TODO: Handle multiselect somehow
}
break;
case MenuObject::INPUT_DESELECTED:
break;
case MenuObject::INPUT_END_MENU_SUCCESS:
return true;
case MenuObject::INPUT_END_MENU_ABORT:
clear_selections();
return true;
case MenuObject::INPUT_ACTIVE_CHANGED:
break;
case MenuObject::INPUT_FOCUS_RELEASE_UP:
focus_find = true;
focus_direction = PrecisionMenu::UP;
break;
case MenuObject::INPUT_FOCUS_RELEASE_DOWN:
focus_find = true;
focus_direction = PrecisionMenu::DOWN;
break;
case MenuObject::INPUT_FOCUS_RELEASE_LEFT:
focus_find = true;
focus_direction = PrecisionMenu::LEFT;
break;
case MenuObject::INPUT_FOCUS_RELEASE_RIGHT:
focus_find = true;
focus_direction = PrecisionMenu::RIGHT;
break;
default:
die("Malformed return value");
break;
}
if (focus_find)
{
MenuObject* find_object = _find_object_by_direction(m_active_object,
focus_direction);
if (find_object != nullptr)
{
m_active_object->set_active_item((MenuItem*)nullptr);
m_active_object = find_object;
if (focus_direction == PrecisionMenu::UP)
m_active_object->activate_last_item();
else
m_active_object->activate_first_item();
}
}
// Handle selection of other objects items hotkeys
for (MenuObject *obj : m_attached_objects)
{
MenuItem* tmp = obj->select_item_by_hotkey(key);
if (tmp != nullptr)
{
// was it a toggle?
if (!tmp->selected())
continue;
// it was a selection
if (m_select_type == PrecisionMenu::PRECISION_SINGLESELECT)
return true;
}
}
return false;
}
#ifdef USE_TILE_LOCAL
int PrecisionMenu::handle_mouse(const wm_mouse_event &me)
{
// Feed input to each attached object that the mouse is over
// The objects are responsible for processing the input
// This includes, if applicable for instance checking if the mouse
// is over the item or not
for (MenuObject *obj : m_attached_objects)
{
const MenuObject::InputReturnValue input_return = obj->handle_mouse(me);
switch (input_return)
{
case MenuObject::INPUT_SELECTED:
m_active_object = obj;
if (m_select_type == PRECISION_SINGLESELECT)
return CK_MOUSE_CLICK;
break;
case MenuObject::INPUT_ACTIVE_CHANGED:
// Set the active object to be this one
m_active_object = obj;
break;
case MenuObject::INPUT_END_MENU_SUCCESS:
// something got clicked that needs to signal the menu to end
return CK_MOUSE_CLICK;
case MenuObject::INPUT_END_MENU_ABORT:
// XXX: For right-click we use CK_MOUSE_CMD to cancel out of the
// menu, but these mouse-button->key mappings are not very sane.
clear_selections();
return CK_MOUSE_CMD;
case MenuObject::INPUT_FOCUS_LOST:
// The object lost its focus and is no longer the active one
if (obj == m_active_object)
m_active_object = nullptr;
default:
break;
}
}
return 0;
}
#endif
void PrecisionMenu::clear_selections()
{
for (MenuObject *obj : m_attached_objects)
obj->clear_selections();
}
/**
* Finds the closest rectangle to given entry start on a cardinal
* direction from it.
* If no entries are found, nullptr is returned.
*
* TODO: This is exact duplicate of MenuObject::_find_item_by_direction();
* maybe somehow generalize it and detach it from class?
*/
MenuObject* PrecisionMenu::_find_object_by_direction(const MenuObject* start,
Direction dir)
{
if (start == nullptr)
return nullptr;
coord_def aabb_start(0,0);
coord_def aabb_end(0,0);
// construct the aabb
switch (dir)
{
case UP:
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = 0; // top of screen
aabb_end.y = start->get_min_coord().y;
break;
case DOWN:
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = start->get_max_coord().y;
// we choose an arbitrarily large number here, because
// tiles saves entry coordinates in pixels, yet console saves them
// in characters
// basically, we want the AABB to be large enough to extend to the
// bottom of the screen in every possible resolution
aabb_end.y = 32767;
break;
case LEFT:
aabb_start.x = 0; // left of screen
aabb_end.x = start->get_min_coord().x;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
case RIGHT:
aabb_start.x = start->get_max_coord().x;
// we again want a value that is always larger then the width of screen
aabb_end.x = 32767;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
default:
die("Bad direction given");
}
// loop through the entries
// save the currently closest to the index in a variable
MenuObject* closest = nullptr;
for (MenuObject *obj : m_attached_objects)
{
if (!obj->can_be_focused())
{
// this is a noselect entry, skip it
continue;
}
if (!_AABB_intersection(obj->get_min_coord(), obj->get_max_coord(),
aabb_start, aabb_end))
{
continue; // does not intersect, continue loop
}
// intersects
// check if it's closer than current
if (closest == nullptr)
closest = obj;
switch (dir)
{
case UP:
if (obj->get_min_coord().y > closest->get_min_coord().y)
closest = obj;
break;
case DOWN:
if (obj->get_min_coord().y < closest->get_min_coord().y)
closest = obj;
break;
case LEFT:
if (obj->get_min_coord().x > closest->get_min_coord().x)
closest = obj;
break;
case RIGHT:
if (obj->get_min_coord().x < closest->get_min_coord().x)
closest = obj;
}
}
// TODO handle special cases here, like pressing down on the last entry
// to go the the first item in that line
return closest;
}
vector<MenuItem*> PrecisionMenu::get_selected_items()
{
vector<MenuItem*> ret_val;
for (MenuObject *obj : m_attached_objects)
for (MenuItem *item : obj->get_selected_items())
ret_val.push_back(item);
return ret_val;
}
void PrecisionMenu::attach_object(MenuObject* item)
{
ASSERT(item != nullptr);
m_attached_objects.push_back(item);
}
// Predicate for std::find_if
static bool _string_lookup(MenuObject* item, string lookup)
{
return item->get_name().compare(lookup) == 0;
}
MenuObject* PrecisionMenu::get_object_by_name(const string &search)
{
auto it = find_if(begin(m_attached_objects), end(m_attached_objects),
bind(_string_lookup, placeholders::_1, search));
return it != m_attached_objects.end() ? *it : nullptr;
}
MenuItem* PrecisionMenu::get_active_item()
{
if (m_active_object != nullptr)
return m_active_object->get_active_item();
return nullptr;
}
void PrecisionMenu::set_active_object(MenuObject* object)
{
if (object == m_active_object)
return;
// is the object attached?
auto find_val = find(m_attached_objects.begin(), m_attached_objects.end(),
object);
if (find_val != m_attached_objects.end())
{
m_active_object = object;
m_active_object->activate_first_item();
}
}
void PrecisionMenu::draw_menu()
{
for (MenuObject *obj : m_attached_objects)
obj->render();
}
MenuItem::MenuItem(): m_min_coord(0,0), m_max_coord(0,0), m_selected(false),
m_allow_highlight(true), m_dirty(false), m_visible(false),
m_link_left(nullptr), m_link_right(nullptr),
m_link_up(nullptr), m_link_down(nullptr), m_item_id(-1)
{
#ifdef USE_TILE_LOCAL
m_unit_width_pixels = tiles.get_crt_font()->char_width();
m_unit_height_pixels = tiles.get_crt_font()->char_height();
#endif
set_fg_colour(LIGHTGRAY);
set_bg_colour(BLACK);
set_highlight_colour(BLACK);
}
MenuItem::~MenuItem()
{
}
#ifdef USE_TILE_LOCAL
void MenuItem::set_height(const int height)
{
m_unit_height_pixels = height;
}
#endif
/**
* Override this if you use eg funky different sized fonts, tiles etc
*/
void MenuItem::set_bounds(const coord_def& min_coord, const coord_def& max_coord)
{
#ifdef USE_TILE_LOCAL
// these are saved in font dx / dy for mouse to work properly
// remove 1 unit from all the entries because console starts at (1,1)
// but tiles starts at (0,0)
m_min_coord.x = (min_coord.x - 1) * m_unit_width_pixels;
m_min_coord.y = (min_coord.y - 1) * m_unit_height_pixels;
m_max_coord.x = (max_coord.x - 1) * m_unit_width_pixels;
m_max_coord.y = (max_coord.y - 1) * m_unit_height_pixels;
#else
m_min_coord = min_coord;
m_max_coord = max_coord;
#endif
}
/**
* This is handly if you are already working with existing multiplied
* coordinates and modifying them
*/
void MenuItem::set_bounds_no_multiply(const coord_def& min_coord,
const coord_def& max_coord)
{
m_min_coord = min_coord;
m_max_coord = max_coord;
}
void MenuItem::move(const coord_def& delta)
{
m_min_coord += delta;
m_max_coord += delta;
}
// By default, value does nothing. Override for Items needing it.
void MenuItem::select(bool toggle, int /*value*/)
{
select(toggle);
}
void MenuItem::select(bool toggle)
{
m_selected = toggle;
m_dirty = true;
}
bool MenuItem::selected() const
{
return m_selected;
}
void MenuItem::allow_highlight(bool toggle)
{
m_allow_highlight = toggle;
m_dirty = true;
}
bool MenuItem::can_be_highlighted() const
{
return m_allow_highlight;
}
void MenuItem::set_highlight_colour(COLOURS colour)
{
m_highlight_colour = colour;
m_dirty = true;
}
COLOURS MenuItem::get_highlight_colour() const
{
return m_highlight_colour;
}
void MenuItem::set_bg_colour(COLOURS colour)
{
m_bg_colour = colour;
m_dirty = true;
}
void MenuItem::set_fg_colour(COLOURS colour)
{
m_fg_colour = colour;
m_dirty = true;
}
COLOURS MenuItem::get_fg_colour() const
{
return m_fg_colour;
}
COLOURS MenuItem::get_bg_colour() const
{
return static_cast<COLOURS> (m_bg_colour);
}
void MenuItem::set_visible(bool flag)
{
m_visible = flag;
}
bool MenuItem::is_visible() const
{
return m_visible;
}
void MenuItem::add_hotkey(int key)
{
m_hotkeys.push_back(key);
}
void MenuItem::clear_hotkeys()
{
m_hotkeys.clear();
}
const vector<int>& MenuItem::get_hotkeys() const
{
return m_hotkeys;
}
void MenuItem::set_link_left(MenuItem* item)
{
m_link_left = item;
}
void MenuItem::set_link_right(MenuItem* item)
{
m_link_right = item;
}
void MenuItem::set_link_up(MenuItem* item)
{
m_link_up = item;
}
void MenuItem::set_link_down(MenuItem* item)
{
m_link_down = item;
}
MenuItem* MenuItem::get_link_left() const
{
return m_link_left;
}
MenuItem* MenuItem::get_link_right() const
{
return m_link_right;
}
MenuItem* MenuItem::get_link_up() const
{
return m_link_up;
}
MenuItem* MenuItem::get_link_down() const
{
return m_link_down;
}
#ifdef USE_TILE_LOCAL
int MenuItem::get_vertical_offset() const
{
return m_unit_height_pixels / 2 - tiles.get_crt_font()->char_height() / 2;
}
#endif
TextItem::TextItem()
#ifdef USE_TILE_LOCAL
: m_font_buf(tiles.get_crt_font())
#endif
{
}
TextItem::~TextItem()
{
}
/**
* Rewrap the text if bounds changes
*/
void TextItem::set_bounds(const coord_def& min_coord, const coord_def& max_coord)
{
MenuItem::set_bounds(min_coord, max_coord);
_wrap_text();
m_dirty = true;
}
/**
* Rewrap the text if bounds changes
*/
void TextItem::set_bounds_no_multiply(const coord_def& min_coord,
const coord_def& max_coord)
{
MenuItem::set_bounds_no_multiply(min_coord, max_coord);
_wrap_text();
m_dirty = true;
}
void TextItem::render()
{
if (!m_visible)
return;
#ifdef USE_TILE_LOCAL
if (m_dirty)
{
m_font_buf.clear();
// TODO: handle m_bg_colour
m_font_buf.add(m_render_text, term_colours[m_fg_colour],
m_min_coord.x, m_min_coord.y + get_vertical_offset());
m_dirty = false;
}
m_font_buf.draw();
#else
// Clean the drawing area first
// clear_to_end_of_line does not work for us
string white_space(m_max_coord.x - m_min_coord.x, ' ');
textcolour(BLACK);
for (int i = 0; i < (m_max_coord.y - m_min_coord.y); ++i)
{
cgotoxy(m_min_coord.x, m_min_coord.y + i);
cprintf("%s", white_space.c_str());
}
// print each line separately, is there a cleaner solution?
size_t newline_pos = 0;
size_t endline_pos = 0;
for (int i = 0; i < (m_max_coord.y - m_min_coord.y); ++i)
{
endline_pos = m_render_text.find('\n', newline_pos);
cgotoxy(m_min_coord.x, m_min_coord.y + i);
textcolour(m_fg_colour);
textbackground(m_bg_colour);
cprintf("%s", m_render_text.substr(newline_pos,
endline_pos - newline_pos).c_str());
if (endline_pos != string::npos)
newline_pos = endline_pos + 1;
else
break;
}
// clear text background
textbackground(BLACK);
#endif
}
void TextItem::set_text(const string& text)
{
m_text = text;
_wrap_text();
m_dirty = true;
}
const string& TextItem::get_text() const
{
return m_text;
}
/**
* Wraps and chops the #m_text variable and saves the chopped
* text to #m_render_text.
* This is done to preserve the old text in case the text item
* changes size and could fit more text.
* Override if you use font with different sizes than CRTRegion font.
*/
void TextItem::_wrap_text()
{
m_render_text = m_text; // preserve original copy intact
int max_cols;
int max_lines;
max_cols = (m_max_coord.x - m_min_coord.x);
max_lines = (m_max_coord.y - m_min_coord.y);
#ifdef USE_TILE_LOCAL
// Tiles saves coordinates in pixels
max_cols = max_cols / m_unit_width_pixels;
max_lines = max_lines / m_unit_height_pixels;
#endif
if (max_cols == 0 || max_lines == 0)
{
// escape and set render text to nothing
m_render_text = "";
return;
}
int num_linebreaks = linebreak_string(m_render_text, max_cols);
if (num_linebreaks > max_lines)
{
size_t pos = 0;
// find the max_line'th occurrence of '\n'
for (int i = 0; i < max_lines; ++i)
pos = m_render_text.find('\n', pos);
// Chop of all the nonfitting text
m_render_text = m_render_text.substr(pos);
}
// m_render_text now holds the fitting part of the text, ready for render!
}
EditableTextItem::EditableTextItem() : TextItem(),
editable(true), in_edit_mode(false), edit_width(-1),
tag("generic_text_box")
{
}
void EditableTextItem::set_editable(bool e, int width)
{
editable = e;
edit_width = width;
}
/**
* A rudimentary textbox editing mode.
*
* This uses a line_reader to read some text at the location of the TextItem.
* It does not do anything with the edit results! You will need to call this
* function at the right point in the gui, and do something appropriate with
* the results elsewhere.
*
* @param custom_prefill a string to populate the box; if null, this will use
* the current text.
* @param keyproc_fun an optional keyproc for the line_reader
* (see lin_reader::set_keyproc).
*
* @return the result of the editing, including the string and the int
* returned by the line_reader.
*/
edit_result EditableTextItem::edit(const string *custom_prefill,
const line_reader::keyproc keyproc_fun)
{
char buf[80];
if (!editable)
return edit_result(string(m_text), 0);
// this is needed because render will get called during the input loop.
unwind_bool e_mode(in_edit_mode, true);
int e_width;
int box_width = m_max_coord.x - m_min_coord.x;
if (edit_width <= 0)
e_width = box_width;
else
e_width = edit_width;
e_width = min(e_width, (int) sizeof buf - 1);
// TODO: make width not dependent on prefill string
string prefill = make_stringf("%-*s", e_width,
custom_prefill ? custom_prefill->c_str() : m_text.c_str());
strncpy(buf, prefill.c_str(), e_width);
buf[e_width] = 0;
mouse_control mc(MOUSE_MODE_PROMPT);
#ifdef USE_TILE_LOCAL
m_line_buf.clear();
m_line_buf.add_square(m_min_coord.x, m_min_coord.y,
m_max_coord.x, m_max_coord.y, term_colours[RED]);
m_line_buf.draw();
unwind_bool dirty(m_dirty, false);
fontbuf_line_reader reader(buf, e_width+1, m_font_buf, 80);
reader.set_location(coord_def(m_min_coord.x,
m_min_coord.y + get_vertical_offset()));
#else
line_reader reader(buf, e_width+1, 80);
reader.set_location(m_min_coord);
#endif
reader.set_edit_mode(EDIT_MODE_OVERWRITE);
if (keyproc_fun)
reader.set_keyproc(keyproc_fun);
#ifdef USE_TILE_WEB
reader.set_prompt(prompt);
reader.set_tag(tag);
#endif
reader.set_colour(COLOUR_INHERIT, m_highlight_colour);
int result = reader.read_line(false, true);
#ifdef USE_TILE_LOCAL
m_line_buf.clear();
m_line_buf.draw();
#endif
return edit_result(string(buf), result);
}
void EditableTextItem::set_tag(string t)
{
tag = t;
}
void EditableTextItem::set_prompt(string p)
{
prompt = p;
}
bool EditableTextItem::selected() const
{
return false;
}
bool EditableTextItem::can_be_highlighted() const
{
// TODO: make this work better
return false;
}
void EditableTextItem::render()
{
#ifdef USE_TILE_LOCAL
if (in_edit_mode)
{
m_line_buf.add_square(m_min_coord.x, m_min_coord.y,
m_max_coord.x, m_max_coord.y,
term_colours[m_highlight_colour]);
m_line_buf.draw();
// this relies on m_font_buf being modified by the reader
m_font_buf.draw();
}
else
{
m_line_buf.clear();
m_line_buf.draw();
TextItem::render();
}
#else
TextItem::render();
#endif //USE_TILE_LOCAL
}
NoSelectTextItem::NoSelectTextItem()
{
}
NoSelectTextItem::~NoSelectTextItem()
{
}
// Do not allow selection
bool NoSelectTextItem::selected() const
{
return false;
}
// Do not allow highlight
bool NoSelectTextItem::can_be_highlighted() const
{
return false;
}
void FormattedTextItem::render()
{
if (!m_visible)
return;
if (m_max_coord.x == m_min_coord.x || m_max_coord.y == m_min_coord.y)
return;
#ifdef USE_TILE_LOCAL
if (m_dirty)
{
m_font_buf.clear();
// FIXME: m_fg_colour doesn't work here while it works in console.
m_font_buf.add(formatted_string::parse_string(m_render_text,
m_fg_colour),
m_min_coord.x, m_min_coord.y + get_vertical_offset());
m_dirty = false;
}
m_font_buf.draw();
#else
// Clean the drawing area first
// clear_to_end_of_line does not work for us
ASSERT(m_max_coord.x > m_min_coord.x);
ASSERT(m_max_coord.y > m_min_coord.y);
string white_space(m_max_coord.x - m_min_coord.x, ' ');
for (int i = 0; i < (m_max_coord.y - m_min_coord.y); ++i)
{
cgotoxy(m_min_coord.x, m_min_coord.y + i);
cprintf("%s", white_space.c_str());
}
cgotoxy(m_min_coord.x, m_min_coord.y);
textcolour(m_fg_colour);
display_tagged_block(m_render_text);
#endif
}
#ifdef USE_TILE_LOCAL
TextTileItem::TextTileItem()
{
for (int i = 0; i < TEX_MAX; i++)
m_tile_buf[i].set_tex(&tiles.get_image_manager()->m_textures[i]);
m_unit_height_pixels = max<int>(m_unit_height_pixels, TILE_Y);
}
TextTileItem::~TextTileItem()
{
}
void TextTileItem::add_tile(tile_def tile)
{
m_tiles.push_back(tile);
m_dirty = true;
}
void TextTileItem::set_bounds(const coord_def &min_coord, const coord_def &max_coord)
{
// these are saved in font dx / dy for mouse to work properly
// remove 1 unit from all the entries because console starts at (1,1)
// but tiles starts at (0,0)
m_min_coord.x = (min_coord.x - 1) * m_unit_width_pixels;
m_max_coord.x = (max_coord.x - 1) * m_unit_width_pixels + 4;
m_min_coord.y = (min_coord.y - 1) * m_unit_height_pixels;
m_max_coord.y = (max_coord.y - 1) * m_unit_height_pixels + 4;
}
void TextTileItem::render()
{
if (!m_visible)
return;
if (m_dirty)
{
m_font_buf.clear();
for (int t = 0; t < TEX_MAX; t++)
m_tile_buf[t].clear();
for (const tile_def &tdef : m_tiles)
{
int tile = tdef.tile;
TextureID tex = tdef.tex;
m_tile_buf[tex].add_unscaled(tile, m_min_coord.x + 2, m_min_coord.y + 2,
tdef.ymax,
(float)m_unit_height_pixels / TILE_Y);
}
// center the text
// TODO wrap / chop the text
const int tile_offset = m_tiles.empty() ? 0 : (m_unit_height_pixels + 6);
m_font_buf.add(m_text, term_colours[m_fg_colour],
m_min_coord.x + 2 + tile_offset,
m_min_coord.y + 2 + get_vertical_offset());
m_dirty = false;
}
m_font_buf.draw();
for (int i = 0; i < TEX_MAX; i++)
m_tile_buf[i].draw();
}
#endif
MenuObject::MenuObject() : m_dirty(false), m_allow_focus(true), m_min_coord(0,0),
m_max_coord(0,0), m_object_name("unnamed object")
{
#ifdef USE_TILE_LOCAL
m_unit_width_pixels = tiles.get_crt_font()->char_width();
m_unit_height_pixels = tiles.get_crt_font()->char_height();
#endif
}
MenuObject::~MenuObject()
{
}
#ifdef USE_TILE_LOCAL
void MenuObject::set_height(const int height)
{
m_unit_height_pixels = height;
}
#endif
void MenuObject::init(const coord_def& min_coord, const coord_def& max_coord,
const string& name)
{
#ifdef USE_TILE_LOCAL
// these are saved in font dx / dy for mouse to work properly
// remove 1 unit from all the entries because console starts at (1,1)
// but tiles starts at (0,0)
m_min_coord.x = (min_coord.x - 1) * m_unit_width_pixels;
m_min_coord.y = (min_coord.y - 1) * m_unit_height_pixels;
m_max_coord.x = (max_coord.x - 1) * m_unit_width_pixels;
m_max_coord.y = (max_coord.y - 1) * m_unit_height_pixels;
#else
m_min_coord = min_coord;
m_max_coord = max_coord;
#endif
m_object_name = name;
}
bool MenuObject::_is_mouse_in_bounds(const coord_def& pos)
{
// Is the mouse in our bounds?
if (m_min_coord.x > static_cast<int> (pos.x)
|| m_max_coord.x < static_cast<int> (pos.x)
|| m_min_coord.y > static_cast<int> (pos.y)
|| m_max_coord.y < static_cast<int> (pos.y))
{
return false;
}
return true;
}
MenuItem* MenuObject::_find_item_by_mouse_coords(const coord_def& pos)
{
// Is the mouse even in bounds?
if (!_is_mouse_in_bounds(pos))
return nullptr;
// Traverse
for (MenuItem *item : m_entries)
{
if (!item->can_be_highlighted())
{
// this is a noselect entry, skip it
continue;
}
if (!item->is_visible())
{
// this item is not visible, skip it
continue;
}
if (pos.x >= item->get_min_coord().x
&& pos.x <= item->get_max_coord().x
&& pos.y >= item->get_min_coord().y
&& pos.y <= item->get_max_coord().y)
{
// We're inside
return item;
}
}
// nothing found
return nullptr;
}
MenuItem* MenuObject::find_item_by_hotkey(int key)
{
// browse through all the Entries
for (MenuItem *item : m_entries)
for (int hotkey : item->get_hotkeys())
if (key == hotkey)
return item;
return nullptr;
}
MenuItem* MenuObject::select_item_by_hotkey(int key)
{
MenuItem* item = find_item_by_hotkey(key);
if (item)
select_item(item);
return item;
}
vector<MenuItem*> MenuObject::get_selected_items()
{
vector<MenuItem *> result;
for (MenuItem *item : m_entries)
if (item->selected())
result.push_back(item);
return result;
}
void MenuObject::clear_selections()
{
for (MenuItem *item : m_entries)
item->select(false);
}
void MenuObject::allow_focus(bool toggle)
{
m_allow_focus = toggle;
}
bool MenuObject::can_be_focused()
{
if (m_entries.empty())
{
// Do not allow focusing empty containers by default
return false;
}
return m_allow_focus;
}
void MenuObject::set_visible(bool flag)
{
m_visible = flag;
}
bool MenuObject::is_visible() const
{
return m_visible;
}
MenuFreeform::MenuFreeform(): m_active_item(nullptr), m_default_item(nullptr)
{
}
MenuFreeform::~MenuFreeform()
{
deleteAll(m_entries);
}
void MenuFreeform::set_default_item(MenuItem* item)
{
m_default_item = item;
}
void MenuFreeform::activate_default_item()
{
m_active_item = m_default_item;
}
MenuObject::InputReturnValue MenuFreeform::process_input(int key)
{
if (!m_allow_focus || !m_visible)
return INPUT_NO_ACTION;
if (m_active_item == nullptr)
{
if (m_entries.empty())
{
// nothing to process
return MenuObject::INPUT_NO_ACTION;
}
else if (m_default_item == nullptr)
{
// pick the first item possible
for (auto mentry : m_entries)
{
if (mentry->can_be_highlighted())
{
m_active_item = mentry;
break;
}
}
}
}
if (m_active_item == nullptr && m_default_item != nullptr)
{
switch (key)
{
case CK_UP:
case CK_DOWN:
case CK_LEFT:
case CK_RIGHT:
case CK_ENTER:
set_active_item(m_default_item);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
}
MenuItem* find_entry = nullptr;
switch (key)
{
case CK_ENTER:
if (m_active_item == nullptr)
return MenuObject::INPUT_NO_ACTION;
select_item(m_active_item);
if (m_active_item->selected())
return MenuObject::INPUT_SELECTED;
else
return MenuObject::INPUT_DESELECTED;
break;
case CK_UP:
find_entry = _find_item_by_direction(m_active_item, UP);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_UP;
break;
case CK_DOWN:
find_entry = _find_item_by_direction(m_active_item, DOWN);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_DOWN;
break;
case CK_LEFT:
find_entry = _find_item_by_direction(m_active_item, LEFT);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_LEFT;
break;
case CK_RIGHT:
find_entry = _find_item_by_direction(m_active_item, RIGHT);
if (find_entry != nullptr)
{
set_active_item(find_entry);
return MenuObject::INPUT_ACTIVE_CHANGED;
}
else
return MenuObject::INPUT_FOCUS_RELEASE_RIGHT;
break;
default:
find_entry = select_item_by_hotkey(key);
if (find_entry != nullptr)
{
if (find_entry->selected())
return MenuObject::INPUT_SELECTED;
else
return MenuObject::INPUT_DESELECTED;
}
break;
}
return MenuObject::INPUT_NO_ACTION;
}
#ifdef USE_TILE_LOCAL
MenuObject::InputReturnValue MenuFreeform::handle_mouse(const wm_mouse_event& me)
{
if (!m_allow_focus || !m_visible)
return INPUT_NO_ACTION;
if (!_is_mouse_in_bounds(coord_def(me.px, me.py)))
{
if (m_active_item != nullptr)
{
_set_active_item(nullptr);
return INPUT_FOCUS_LOST;
}
else
return INPUT_NO_ACTION;
}
MenuItem* find_item = _find_item_by_mouse_coords(coord_def(me.px, me.py));
if (find_item && find_item->handle_mouse(me))
return MenuObject::INPUT_SELECTED; // The object handled the event
else if (me.event == wm_mouse_event::MOVE)
{
if (find_item == nullptr)
{
if (m_active_item != nullptr)
{
_set_active_item(nullptr);
return INPUT_NO_ACTION;
}
}
else
{
if (m_active_item != find_item)
{
set_active_item(find_item);
return INPUT_ACTIVE_CHANGED;
}
}
return INPUT_NO_ACTION;
}
InputReturnValue ret = INPUT_NO_ACTION;
if (me.event == wm_mouse_event::PRESS)
{
if (me.button == wm_mouse_event::LEFT)
{
if (find_item != nullptr)
{
select_item(find_item);
if (find_item->selected())
ret = INPUT_SELECTED;
else
ret = INPUT_DESELECTED;
}
}
else if (me.button == wm_mouse_event::RIGHT)
ret = INPUT_END_MENU_ABORT;
}
// all the other Mouse Events are uninteresting and are ignored
return ret;
}
#endif
void MenuFreeform::render()
{
if (!m_visible)
return;
if (m_dirty)
_place_items();
for (MenuItem *item : m_entries)
item->render();
}
/**
* Handle all the dirtyness here that the MenuItems themselves do not handle
*/
void MenuFreeform::_place_items()
{
m_dirty = false;
}
MenuItem* MenuFreeform::get_active_item()
{
return m_active_item;
}
/**
* Sets item by ID
* Clears active item if ID not found
*/
void MenuFreeform::set_active_item(int ID)
{
auto it = find_if(m_entries.begin(), m_entries.end(),
[=](const MenuItem* item) { return item->get_id() == ID; });
m_active_item = (it != m_entries.end()) ? *it : nullptr;
m_dirty = true;
}
/**
* Sets active item based on index
* This function is for internal use if object does not have ID set
*/
void MenuFreeform::_set_active_item(MenuItem* item)
{
ASSERT(!item || item->can_be_highlighted());
m_active_item = item;
m_dirty = true;
}
void MenuFreeform::set_active_item(MenuItem* item)
{
bool present = find(m_entries.begin(), m_entries.end(), item) != m_entries.end();
m_active_item = (present && item->can_be_highlighted()) ? item : nullptr;
m_dirty = true;
}
void MenuFreeform::activate_first_item()
{
auto el = find_if(m_entries.begin(), m_entries.end(),
[=](const MenuItem* item) { return item->can_be_highlighted(); });
if (el != m_entries.end())
_set_active_item(*el);
}
void MenuFreeform::activate_last_item()
{
auto el = find_if(m_entries.rbegin(), m_entries.rend(),
[=](const MenuItem* item) { return item->can_be_highlighted(); });
if (el != m_entries.rend())
_set_active_item(*el);
}
bool MenuFreeform::select_item(int index)
{
if (index >= 0 && index < static_cast<int> (m_entries.size()))
{
// Flip the selection flag
m_entries.at(index)->select(!m_entries.at(index)->selected());
}
return m_entries.at(index)->selected();
}
bool MenuFreeform::select_item(MenuItem* item)
{
ASSERT(item != nullptr);
// Is the given item in menu?
auto find_val = find(m_entries.begin(), m_entries.end(), item);
if (find_val != m_entries.end())
{
// Flip the selection flag
item->select(!item->selected());
}
return item->selected();
}
bool MenuFreeform::attach_item(MenuItem* item)
{
// is the item inside boundaries?
if ( item->get_min_coord().x < m_min_coord.x
|| item->get_min_coord().x > m_max_coord.x
|| item->get_min_coord().y < m_min_coord.y
|| item->get_min_coord().y > m_max_coord.y
|| item->get_max_coord().x < m_min_coord.x
|| item->get_max_coord().x > m_max_coord.x
|| item->get_max_coord().y < m_min_coord.y
|| item->get_max_coord().y > m_max_coord.y)
{
return false;
}
// It's inside boundaries
m_entries.push_back(item);
return true;
}
/**
* Finds the closest rectangle to given entry begin_index on a caardinal
* direction from it.
* if no entries are found, -1 is returned
*/
MenuItem* MenuFreeform::_find_item_by_direction(const MenuItem* start,
MenuObject::Direction dir)
{
if (start == nullptr)
return nullptr;
coord_def aabb_start(0,0);
coord_def aabb_end(0,0);
// construct the aabb
switch (dir)
{
case UP:
if (start->get_link_up())
return start->get_link_up();
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = 0; // top of screen
aabb_end.y = start->get_min_coord().y;
break;
case DOWN:
if (start->get_link_down())
return start->get_link_down();
aabb_start.x = start->get_min_coord().x;
aabb_end.x = start->get_max_coord().x;
aabb_start.y = start->get_max_coord().y;
// we choose an arbitrarily large number here, because
// tiles saves entry coordinates in pixels, yet console saves them
// in characters
// basically, we want the AABB to be large enough to extend to the
// bottom of the screen in every possible resolution
aabb_end.y = 32767;
break;
case LEFT:
if (start->get_link_left())
return start->get_link_left();
aabb_start.x = 0; // left of screen
aabb_end.x = start->get_min_coord().x;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
case RIGHT:
if (start->get_link_right())
return start->get_link_right();
aabb_start.x = start->get_max_coord().x;
// we again want a value that is always larger then the width of screen
aabb_end.x = 32767;
aabb_start.y = start->get_min_coord().y;
aabb_end.y = start->get_max_coord().y;
break;
default:
die("Bad direction given");
}
// loop through the entries
// save the currently closest to the index in a variable
MenuItem* closest = nullptr;
for (MenuItem *item : m_entries)
{
if (!item->can_be_highlighted())
{
// this is a noselect entry, skip it
continue;
}
if (!item->is_visible())
{
// this item is not visible, skip it
continue;
}
if (!_AABB_intersection(item->get_min_coord(), item->get_max_coord(),
aabb_start, aabb_end))
{
continue; // does not intersect, continue loop
}
// intersects
// check if it's closer than current
if (closest == nullptr)
closest = item;
switch (dir)
{
case UP:
if (item->get_min_coord().y > closest->get_min_coord().y)
closest = item;
break;
case DOWN:
if (item->get_min_coord().y < closest->get_min_coord().y)
closest = item;
break;
case LEFT:
if (item->get_min_coord().x > closest->get_min_coord().x)
closest = item;
break;
case RIGHT:
if (item->get_min_coord().x < closest->get_min_coord().x)
closest = item;
}
}
// TODO handle special cases here, like pressing down on the last entry
// to go the the first item in that line
return closest;
}
BoxMenuHighlighter::BoxMenuHighlighter(PrecisionMenu *parent): m_parent(parent),
m_active_item(nullptr)
{
ASSERT(parent != nullptr);
}
BoxMenuHighlighter::~BoxMenuHighlighter()
{
}
vector<MenuItem*> BoxMenuHighlighter::get_selected_items()
{
vector<MenuItem*> ret_val;
return ret_val;
}
MenuObject::InputReturnValue BoxMenuHighlighter::process_input(int /*key*/)
{
// just in case we somehow end up processing input of this item
return MenuObject::INPUT_NO_ACTION;
}
#ifdef USE_TILE_LOCAL
MenuObject::InputReturnValue BoxMenuHighlighter::handle_mouse(const wm_mouse_event &/*me*/)
{
// we have nothing interesting to do on mouse events because render()
// always checks if the active has changed
return MenuObject::INPUT_NO_ACTION;
}
#endif
void BoxMenuHighlighter::render()
{
if (!m_visible)
return;
if (!m_visible)
return;
_place_items();
#ifdef USE_TILE_LOCAL
m_line_buf.draw();
m_shape_buf.draw();
#else
if (m_active_item != nullptr)
m_active_item->render();
#endif
}
void BoxMenuHighlighter::_place_items()
{
MenuItem* tmp = m_parent->get_active_item();
if (tmp == m_active_item)
return;
#ifdef USE_TILE_LOCAL
m_line_buf.clear();
m_shape_buf.clear();
if (tmp != nullptr)
{
const VColour& c = term_colours[tmp->get_highlight_colour()];
const VColour bg_colour(c.r, c.g, c.b, 80);
const VColour line_colour(c.r, c.g, c.b, 127);
const coord_def tl = tmp->get_min_coord() + coord_def(1, 1);
const coord_def br = tmp->get_max_coord();
m_line_buf.add_square(tl.x, tl.y, br.x, br.y, line_colour);
m_shape_buf.add(tl.x, tl.y, br.x, br.y, bg_colour);
}
#else
// we had an active item before
if (m_active_item != nullptr)
{
// clear the background highlight trickery
m_active_item->set_bg_colour(m_old_bg_colour);
// redraw the old item
m_active_item->render();
}
if (tmp != nullptr)
{
m_old_bg_colour = tmp->get_bg_colour();
tmp->set_bg_colour(tmp->get_highlight_colour());
}
#endif
m_active_item = tmp;
}
| 26.187886 | 91 | 0.613282 | [
"render",
"object",
"vector"
] |
f30b2414a86ed894af5076d7698a16704e0f7602 | 9,536 | cpp | C++ | Prototype/src/libsbml-5.10.0/src/sbml/packages/groups/extension/test/TestReadGroupsExtension.cpp | Cosmo-Tech/biopredyn | 0f5bcd4cb1f723bfdea07d4973e46e676f4175e8 | [
"BSD-3-Clause"
] | null | null | null | Prototype/src/libsbml-5.10.0/src/sbml/packages/groups/extension/test/TestReadGroupsExtension.cpp | Cosmo-Tech/biopredyn | 0f5bcd4cb1f723bfdea07d4973e46e676f4175e8 | [
"BSD-3-Clause"
] | 95 | 2015-03-06T12:14:06.000Z | 2015-03-20T11:15:54.000Z | Prototype/src/libsbml-5.10.0/src/sbml/packages/groups/extension/test/TestReadGroupsExtension.cpp | Cosmo-Tech/biopredyn | 0f5bcd4cb1f723bfdea07d4973e46e676f4175e8 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file TestReadGroupsExtension.cpp
* @brief Unit tests of writing GroupsExtension
* @author Akiya Jouraku
*
* $Id: $
* $HeadURL: $
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2009-2011 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library 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. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ---------------------------------------------------------------------- -->*/
#include <limits>
#include <iostream>
#include <check.h>
#include <sbml/SBMLTypes.h>
#include <sbml/common/extern.h>
#include <sbml/extension/SBMLExtensionRegistry.h>
#include <sbml/packages/groups/common/GroupsExtensionTypes.h>
#include <string>
/** @cond doxygenIgnored */
using namespace std;
LIBSBML_CPP_NAMESPACE_USE
/** @endcond doxygenIgnored */
CK_CPPSTART
extern char *TestDataDirectory;
START_TEST (test_GroupsExtension_read_L3V1V1)
{
char *filename = safe_strcat(TestDataDirectory, "groups-example1.xml");
SBMLDocument *document = readSBMLFromFile(filename);
fail_unless(document->getPackageName() == "core");
Model *model = document->getModel();
fail_unless(model != NULL);
fail_unless(model->getPackageName() == "core");
fail_unless(document->getNumErrors() == 0);
// get the Group
GroupsModelPlugin* mplugin = static_cast<GroupsModelPlugin*>(model->getPlugin("groups"));
fail_unless(mplugin != NULL);
fail_unless(mplugin->getNumGroups() == 1);
fail_unless(mplugin->getListOfGroups()->getPackageName() == "groups");
Group* group = mplugin->getGroup(0);
fail_unless(group->getId() == "ATP");
fail_unless(group->getSBOTermID() == "SBO:0000252");
fail_unless(group->getKind() == GROUP_KIND_CLASSIFICATION);
fail_unless(group->getNumMembers() == 2);
fail_unless(group->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getPackageName() == "groups");
Member* member = group->getMember(0);
fail_unless(member->getIdRef() == "ATPc");
fail_unless(member->getPackageName() == "groups");
member = group->getMember(1);
fail_unless(member->getIdRef() == "ATPm");
fail_unless(member->getPackageName() == "groups");
delete document;
}
END_TEST
START_TEST (test_GroupsExtension_read_L3V1V1_defaultNS)
{
char *filename = safe_strcat(TestDataDirectory, "groups-example1-defaultNS.xml");
SBMLDocument *document = readSBMLFromFile(filename);
fail_unless(document->getPackageName() == "core");
Model *model = document->getModel();
document->printErrors();
fail_unless(model != NULL);
fail_unless(document->getNumErrors() == 0);
// get the Group
GroupsModelPlugin* mplugin = static_cast<GroupsModelPlugin*>(model->getPlugin("groups"));
fail_unless(mplugin != NULL);
fail_unless(mplugin->getNumGroups() == 1);
fail_unless(mplugin->getListOfGroups()->getPackageName() == "groups");
Group* group = mplugin->getGroup(0);
fail_unless(group->getId() == "ATP");
fail_unless(group->getSBOTermID() == "SBO:0000252");
fail_unless(group->getKind() == GROUP_KIND_CLASSIFICATION);
fail_unless(group->isSetKind() == true);
fail_unless(!strcmp(GroupKind_toString(group->getKind()), "classification"));
fail_unless(group->getNumMembers() == 2);
fail_unless(group->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getPackageName() == "groups");
Member* member = group->getMember(0);
fail_unless(member->getIdRef() == "ATPc");
fail_unless(member->getPackageName() == "groups");
member = group->getMember(1);
fail_unless(member->getIdRef() == "ATPm");
fail_unless(member->getPackageName() == "groups");
delete document;
}
END_TEST
START_TEST (test_GroupsExtension_read_L3V1V1_unknown_elements)
{
const char* s1 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<sbml xmlns=\"http://www.sbml.org/sbml/level3/version1/core\" xmlns:groups=\"http://www.sbml.org/sbml/level3/version1/groups/version1\" level=\"3\" version=\"1\" groups:required=\"false\">\n"
" <model>\n"
" <listOfCompartments>\n"
" <compartment id=\"cytosol\" constant=\"true\"/>\n"
" <compartment id=\"mitochon\" constant=\"true\"/>\n"
" </listOfCompartments>\n"
" <listOfSpecies>\n"
" <species id=\"ATPc\" compartment=\"cytosol\" initialConcentration=\"1\" hasOnlySubstanceUnits=\"false\" boundaryCondition=\"false\" constant=\"false\"/>\n"
" <species id=\"ATPm\" compartment=\"mitochon\" initialConcentration=\"2\" hasOnlySubstanceUnits=\"false\" boundaryCondition=\"false\" constant=\"false\"/>\n"
" </listOfSpecies>\n"
" <groups:listOfGroups>\n"
" <groups:group sboTerm=\"SBO:0000252\" groups:kind=\"partonomy\" groups:id=\"ATP\" groups:unknown=\"unknown\" >\n"
" <groups:listOfMembers>\n"
" <groups:member groups:idRef=\"ATPc\" groups:unknown=\"unknown\"/>\n"
" <groups:member groups:idRef=\"ATPm\"/>\n"
" </groups:listOfMembers>\n"
" <groups:unknown>\n"
" </groups:unknown>\n"
" </groups:group>\n"
" </groups:listOfGroups>\n"
" </model>\n"
"</sbml>\n"
;
SBMLDocument *document = readSBMLFromString(s1);
Model *model = document->getModel();
fail_unless(model != NULL);
fail_unless(document->getNumErrors() == 4);
delete document;
}
END_TEST
START_TEST (test_GroupsExtension_read_memberConstraints)
{
char *filename = safe_strcat(TestDataDirectory, "groups_speciestype_example.xml");
SBMLDocument *document = readSBMLFromFile(filename);
fail_unless(document->getPackageName() == "core");
Model *model = document->getModel();
fail_unless(model != NULL);
fail_unless(model->getPackageName() == "core");
fail_unless(document->getNumErrors() == 0);
// get the Group
GroupsModelPlugin* mplugin = static_cast<GroupsModelPlugin*>(model->getPlugin("groups"));
fail_unless(mplugin != NULL);
fail_unless(mplugin->getNumGroups() == 1);
fail_unless(mplugin->getListOfGroups()->getPackageName() == "groups");
Group* group = mplugin->getGroup(0);
fail_unless(group->getId() == "ATP");
fail_unless(group->getKind() == GROUP_KIND_CLASSIFICATION);
fail_unless(group->getNumMembers() == 2);
fail_unless(group->getNumMemberConstraints() == 3);
fail_unless(group->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getPackageName() == "groups");
fail_unless(group->getListOfMembers()->getSBOTermID() == "SBO:0000248");
Member* member = group->getMember(0);
fail_unless(member->getIdRef() == "ATPc");
fail_unless(member->getPackageName() == "groups");
member = group->getMember(1);
fail_unless(member->getIdRef() == "ATPm");
fail_unless(member->getPackageName() == "groups");
ListOfMemberConstraints* lomcs = group->getListOfMemberConstraints();
fail_unless(lomcs->getPackageName() == "groups");
fail_unless(lomcs->isSetMembersShareType() == true);
fail_unless(lomcs->getMembersShareType() == true);
MemberConstraint* mc = group->getMemberConstraint(0);
fail_unless(mc->isSetDistinctAttribute() == true);
fail_unless(mc->isSetIdenticalAttribute() == false);
fail_unless(mc->getDistinctAttribute() == "compartment");
fail_unless(mc->getPackageName() == "groups");
mc = group->getMemberConstraint(1);
fail_unless(mc->isSetDistinctAttribute() == false);
fail_unless(mc->isSetIdenticalAttribute() == true);
fail_unless(mc->getIdenticalAttribute() == "initialConcentration");
fail_unless(mc->getPackageName() == "groups");
mc = group->getMemberConstraint(2);
fail_unless(mc->isSetDistinctAttribute() == false);
fail_unless(mc->isSetIdenticalAttribute() == true);
fail_unless(mc->getIdenticalAttribute() == "constant");
fail_unless(mc->getPackageName() == "groups");
delete document;
}
END_TEST
Suite *
create_suite_ReadGroupsExtension (void)
{
Suite *suite = suite_create("ReadGroupsExtension");
TCase *tcase = tcase_create("ReadGroupsExtension");
tcase_add_test( tcase, test_GroupsExtension_read_L3V1V1);
tcase_add_test( tcase, test_GroupsExtension_read_L3V1V1_defaultNS);
tcase_add_test( tcase, test_GroupsExtension_read_L3V1V1_unknown_elements);
tcase_add_test( tcase, test_GroupsExtension_read_memberConstraints);
suite_add_tcase(suite, tcase);
return suite;
}
CK_CPPEND
| 35.715356 | 197 | 0.663276 | [
"model"
] |
f30d92053e37da70e960906bcfe6c7be0fc14145 | 3,176 | cpp | C++ | MS1/Date.cpp | dtnguyen22/OOP244SFF | 7a5e3eee5817f56b19f855818021317ce91c6b8d | [
"Unlicense"
] | null | null | null | MS1/Date.cpp | dtnguyen22/OOP244SFF | 7a5e3eee5817f56b19f855818021317ce91c6b8d | [
"Unlicense"
] | null | null | null | MS1/Date.cpp | dtnguyen22/OOP244SFF | 7a5e3eee5817f56b19f855818021317ce91c6b8d | [
"Unlicense"
] | null | null | null | // Final Project Milestone 1
// Date.cpp
// Date 2019-07-11
// Author DucTai Nguyen - dtnguyen22@myseneca.ca - 147942171
/////////////////////////////////////////////////////////////////
#include <iostream>
#include "Date.h"
using namespace std;
namespace aid {
int Date::mdays(int year, int mon) {
int days[] = {31,28,31,30,31,30,31,31,30,31,30,31,-1};
int month = mon >= 1 && mon <= 12 ? mon : 13;
month--;
return days[month] + int((month == 1)*((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}
void Date::errCode(int err) {
this->m_err = err;
}
int Date::errCode() const{
return (this->m_err);
}
bool Date::bad() const{
return (this->m_err); // 0 will be false otherwise true
}
Date::Date() {
this->m_year = 0;
this->m_day = 0;
this->m_month = 0;
this->m_compare = 0;
this->errCode(NO_ERROR);
}
Date::Date(int year, int month, int day) {
int comp = year*372 + month * 31 + day;
if ( year < min_year || year > max_year ||
month > 12 || month < 1 ||
day < 1 || day > mdays(year, month) ||
comp < min_date ){
*this = Date();
}
else {
this->m_year = year;
this->m_day = day;
this->m_month = month;
this->m_compare = comp;
this->errCode(NO_ERROR);
}
}
istream& Date::read(istream& istr) {
int year, mon, day;
char dim = '/';
istr >> year >> dim >> mon >> dim >> day;
if(istr.fail()){
this->errCode(CIN_FAILED);
istr.ignore(2000);
}
else if (year > max_year || year < min_year) {
this->errCode(YEAR_ERROR);
}
else if (mon > 12 || mon < 1) {
this->errCode(MON_ERROR);
}
else if (day > Date::mdays(year, mon) || day < 1) {
this->errCode(DAY_ERROR);
}
else if (!Date::isValid(year, mon, day)) {
this->errCode(PAST_ERROR);
}
else {
*this = Date(year, mon, day);
}
return istr;
}
istream& operator>>(istream& is, Date& rhs) {
rhs.read(is);
return is;
}
ostream& Date::write(ostream& ostr) const{
if (this->m_compare == 0) { // empty object
ostr << "0/00/00";
}
else {
ostr << this->m_year << '/';
ostr.width(2);
ostr.fill('0');
ostr << this->m_month << '/' << this->m_day;
}
return ostr;
}
ostream& operator<<(ostream& os, const Date& rhs) {
rhs.write(os);
return os;
}
bool Date::operator!=(const Date & rhs) const{
return (this->m_compare != rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator==(const Date & rhs) const
{
return (this->m_compare == rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator<(const Date & rhs) const
{
return (this->m_compare < rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator>(const Date & rhs) const
{
return (this->m_compare > rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator<=(const Date & rhs) const
{
return (this->m_compare <= rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::operator>=(const Date & rhs) const
{
return (this->m_compare >= rhs.m_compare) && this->m_compare && rhs.m_compare;
}
bool Date::isValid(int year, int mon, int day)const { //private
return (year * 372 + mon * 31 + day) > min_date;
}
} | 24.620155 | 101 | 0.586272 | [
"object"
] |
f31a954cf9bdefd0809dc749e95e8cb628605387 | 15,595 | cpp | C++ | src/blas/backends/rocblas/rocblas_extensions.cpp | andrewtbarker/oneMKL | 722f6c51b528a2bc09bf549b1097f7d8fdc37826 | [
"Apache-2.0"
] | null | null | null | src/blas/backends/rocblas/rocblas_extensions.cpp | andrewtbarker/oneMKL | 722f6c51b528a2bc09bf549b1097f7d8fdc37826 | [
"Apache-2.0"
] | null | null | null | src/blas/backends/rocblas/rocblas_extensions.cpp | andrewtbarker/oneMKL | 722f6c51b528a2bc09bf549b1097f7d8fdc37826 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright (C) Codeplay Software Limited
* Copyright (C) 2022 Heidelberg University, Engineering Mathematics and Computing Lab (EMCL) and Computing Centre (URZ)
*
* 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
*
* For your convenience, a copy of the License has been included in this
* repository.
*
* 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 "rocblas_helper.hpp"
#include "rocblas_task.hpp"
#include "oneapi/mkl/exceptions.hpp"
#include "oneapi/mkl/blas/detail/rocblas/onemkl_blas_rocblas.hpp"
namespace oneapi {
namespace mkl {
namespace blas {
namespace rocblas {
namespace column_major {
// Buffer APIs
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, float alpha, sycl::buffer<float, 1> &a, int64_t lda,
sycl::buffer<float, 1> &b, int64_t ldb, float beta, sycl::buffer<float, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, double alpha, sycl::buffer<double, 1> &a, int64_t lda,
sycl::buffer<double, 1> &b, int64_t ldb, double beta, sycl::buffer<double, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<float> alpha, sycl::buffer<std::complex<float>, 1> &a,
int64_t lda, sycl::buffer<std::complex<float>, 1> &b, int64_t ldb,
std::complex<float> beta, sycl::buffer<std::complex<float>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<double> alpha, sycl::buffer<std::complex<double>, 1> &a,
int64_t lda, sycl::buffer<std::complex<double>, 1> &b, int64_t ldb,
std::complex<double> beta, sycl::buffer<std::complex<double>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
// USM APIs
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, float alpha, const float *a, int64_t lda, const float *b,
int64_t ldb, float beta, float *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, double alpha, const double *a, int64_t lda, const double *b,
int64_t ldb, double beta, double *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<float> alpha, const std::complex<float> *a,
int64_t lda, const std::complex<float> *b, int64_t ldb, std::complex<float> beta,
std::complex<float> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<double> alpha, const std::complex<double> *a,
int64_t lda, const std::complex<double> *b, int64_t ldb,
std::complex<double> beta, std::complex<double> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for column_major layout");
}
} // namespace column_major
namespace row_major {
// Buffer APIs
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<int8_t, 1> &a, int64_t lda,
int8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<int8_t, 1> &b, int64_t ldb, int8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc, int64_t m,
int64_t n, int64_t k, float alpha, sycl::buffer<uint8_t, 1> &a, int64_t lda,
uint8_t ao, sycl::buffer<uint8_t, 1> &b, int64_t ldb, uint8_t bo, float beta,
sycl::buffer<int32_t, 1> &c, int64_t ldc, sycl::buffer<int32_t, 1> &co) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, float alpha, sycl::buffer<float, 1> &a, int64_t lda,
sycl::buffer<float, 1> &b, int64_t ldb, float beta, sycl::buffer<float, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, double alpha, sycl::buffer<double, 1> &a, int64_t lda,
sycl::buffer<double, 1> &b, int64_t ldb, double beta, sycl::buffer<double, 1> &c,
int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<float> alpha, sycl::buffer<std::complex<float>, 1> &a,
int64_t lda, sycl::buffer<std::complex<float>, 1> &b, int64_t ldb,
std::complex<float> beta, sycl::buffer<std::complex<float>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
void gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb, int64_t n,
int64_t k, std::complex<double> alpha, sycl::buffer<std::complex<double>, 1> &a,
int64_t lda, sycl::buffer<std::complex<double>, 1> &b, int64_t ldb,
std::complex<double> beta, sycl::buffer<std::complex<double>, 1> &c, int64_t ldc) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
// USM APIs
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const int8_t *a, int64_t lda,
int8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const int8_t *b, int64_t ldb, int8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemm_bias(sycl::queue &queue, transpose transa, transpose transb, offset offsetc,
int64_t m, int64_t n, int64_t k, float alpha, const uint8_t *a, int64_t lda,
uint8_t ao, const uint8_t *b, int64_t ldb, uint8_t bo, float beta, int32_t *c,
int64_t ldc, const int32_t *co,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemm_bias", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, float alpha, const float *a, int64_t lda, const float *b,
int64_t ldb, float beta, float *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, double alpha, const double *a, int64_t lda, const double *b,
int64_t ldb, double beta, double *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<float> alpha, const std::complex<float> *a,
int64_t lda, const std::complex<float> *b, int64_t ldb, std::complex<float> beta,
std::complex<float> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
sycl::event gemmt(sycl::queue &queue, uplo upper_lower, transpose transa, transpose transb,
int64_t n, int64_t k, std::complex<double> alpha, const std::complex<double> *a,
int64_t lda, const std::complex<double> *b, int64_t ldb,
std::complex<double> beta, std::complex<double> *c, int64_t ldc,
const std::vector<sycl::event> &dependencies) {
throw unimplemented("blas", "gemmt", "for row_major layout");
}
} // namespace row_major
} // namespace rocblas
} // namespace blas
} // namespace mkl
} // namespace oneapi
| 54.719298 | 120 | 0.634883 | [
"vector"
] |
f31e25a9962d2c06df845a18bbe5da980a08888d | 610 | cpp | C++ | CppPrimer/CppPrimer-Exercises/CppPrimer-Ch10/Exercise10.20.cpp | alaxion/Learning | 4b12b1603419252103cd933fdbfc4b2faffb6d00 | [
"MIT"
] | null | null | null | CppPrimer/CppPrimer-Exercises/CppPrimer-Ch10/Exercise10.20.cpp | alaxion/Learning | 4b12b1603419252103cd933fdbfc4b2faffb6d00 | [
"MIT"
] | null | null | null | CppPrimer/CppPrimer-Exercises/CppPrimer-Ch10/Exercise10.20.cpp | alaxion/Learning | 4b12b1603419252103cd933fdbfc4b2faffb6d00 | [
"MIT"
] | null | null | null | // Exercise10.20.cpp
// Ad
// Use count_if to rewrite the portion of our program that counted how many words are greater than length 6.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
// -----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
std::vector<std::string> svec{"a", "asdfghj", "123", "uoiwersss"};
size_t sz{6};
auto cnt{count_if(svec.begin(), svec.end(), [sz](const std::string &s) { return s.size() > sz; })};
std::cout << cnt << std::endl;
// pause
system("pause");
return 0;
} | 27.727273 | 108 | 0.547541 | [
"vector"
] |
f31efa9f1dfd9f1456963d537ca347f8f3b00f69 | 2,970 | cpp | C++ | src/uri/fetchers/hadoop.cpp | julien-faye/mesos | 5ffb3e40eb4d9234778cc1a96141539258e994bf | [
"Apache-2.0"
] | 4,537 | 2015-01-01T03:26:40.000Z | 2022-03-31T03:07:00.000Z | src/uri/fetchers/hadoop.cpp | julien-faye/mesos | 5ffb3e40eb4d9234778cc1a96141539258e994bf | [
"Apache-2.0"
] | 227 | 2015-01-29T02:21:39.000Z | 2022-03-29T13:35:50.000Z | src/uri/fetchers/hadoop.cpp | julien-faye/mesos | 5ffb3e40eb4d9234778cc1a96141539258e994bf | [
"Apache-2.0"
] | 1,992 | 2015-01-05T12:29:19.000Z | 2022-03-31T03:07:07.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stout/path.hpp>
#include <stout/strings.hpp>
#include <stout/os/mkdir.hpp>
#include "uri/fetchers/hadoop.hpp"
using std::vector;
using std::set;
using std::string;
using process::Failure;
using process::Future;
using process::Owned;
namespace mesos {
namespace uri {
HadoopFetcherPlugin::Flags::Flags()
{
add(&Flags::hadoop_client,
"hadoop_client",
"The path to the hadoop client\n");
add(&Flags::hadoop_client_supported_schemes,
"hadoop_client_supported_schemes",
"A comma-separated list of the schemes supported by the hadoop client.\n",
"hdfs,hftp,s3,s3n");
}
const char HadoopFetcherPlugin::NAME[] = "hadoop";
Try<Owned<Fetcher::Plugin>> HadoopFetcherPlugin::create(const Flags& flags)
{
Try<Owned<HDFS>> hdfs = HDFS::create(flags.hadoop_client);
if (hdfs.isError()) {
return Error("Failed to create HDFS client: " + hdfs.error());
}
vector<string> schemes = strings::tokenize(
flags.hadoop_client_supported_schemes, ",");
return Owned<Fetcher::Plugin>(new HadoopFetcherPlugin(
hdfs.get(),
set<string>(schemes.begin(), schemes.end())));
}
set<string> HadoopFetcherPlugin::schemes() const
{
return schemes_;
}
string HadoopFetcherPlugin::name() const
{
return NAME;
}
Future<Nothing> HadoopFetcherPlugin::fetch(
const URI& uri,
const string& directory,
const Option<string>& data,
const Option<string>& outputFileName) const
{
// TODO(jieyu): Validate the given URI.
if (!uri.has_path()) {
return Failure("URI path is not specified");
}
Try<Nothing> mkdir = os::mkdir(directory);
if (mkdir.isError()) {
return Failure(
"Failed to create directory '" +
directory + "': " + mkdir.error());
}
// NOTE: We ignore the scheme prefix if the host in URI is not
// specified. This is the case when the host is set using the hadoop
// configuration file.
//
// TODO(jieyu): Allow user to specify the name of the output file.
return hdfs->copyToLocal(
(uri.has_host() ? stringify(uri) : uri.path()),
path::join(directory, Path(uri.path()).basename()));
}
} // namespace uri {
} // namespace mesos {
| 27 | 80 | 0.698316 | [
"vector"
] |
f321a91802158625da4653a34d6f543af8f78014 | 23,047 | cpp | C++ | tools/editor/addon_editor_plugin.cpp | aoighost/godot | 6e86a0535050855d5c4e4d63002eea084f2e3ebf | [
"CC-BY-3.0",
"MIT"
] | null | null | null | tools/editor/addon_editor_plugin.cpp | aoighost/godot | 6e86a0535050855d5c4e4d63002eea084f2e3ebf | [
"CC-BY-3.0",
"MIT"
] | null | null | null | tools/editor/addon_editor_plugin.cpp | aoighost/godot | 6e86a0535050855d5c4e4d63002eea084f2e3ebf | [
"CC-BY-3.0",
"MIT"
] | null | null | null | #include "addon_editor_plugin.h"
#include "editor_node.h"
void EditorAssetLibraryItem::configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost) {
title->set_text(p_title);
asset_id=p_asset_id;
category->set_text(p_category);
category_id=p_category_id;
author->set_text(p_author);
author_id=p_author_id;
price->set_text(p_cost);
for(int i=0;i<5;i++) {
if (i>2)
stars[i]->set_texture(get_icon("RatingNoStar","EditorIcons"));
else
stars[i]->set_texture(get_icon("RatingStar","EditorIcons"));
}
}
void EditorAssetLibraryItem::set_image(int p_type,int p_index,const Ref<Texture>& p_image) {
ERR_FAIL_COND(p_type!=EditorAddonLibrary::IMAGE_QUEUE_ICON);
ERR_FAIL_COND(p_index!=0);
icon->set_normal_texture(p_image);
}
void EditorAssetLibraryItem::_notification(int p_what) {
if (p_what==NOTIFICATION_ENTER_TREE) {
icon->set_normal_texture(get_icon("GodotAssetDefault","EditorIcons"));
category->add_color_override("font_color", Color(0.5,0.5,0.5) );
author->add_color_override("font_color", Color(0.5,0.5,0.5) );
}
}
void EditorAssetLibraryItem::_asset_clicked() {
emit_signal("asset_selected",asset_id);
}
void EditorAssetLibraryItem::_category_clicked(){
emit_signal("category_selected",category_id);
}
void EditorAssetLibraryItem::_author_clicked(){
emit_signal("author_selected",author_id);
}
void EditorAssetLibraryItem::_bind_methods() {
ObjectTypeDB::bind_method("set_image",&EditorAssetLibraryItem::set_image);
ObjectTypeDB::bind_method("_asset_clicked",&EditorAssetLibraryItem::_asset_clicked);
ObjectTypeDB::bind_method("_category_clicked",&EditorAssetLibraryItem::_category_clicked);
ObjectTypeDB::bind_method("_author_clicked",&EditorAssetLibraryItem::_author_clicked);
ADD_SIGNAL( MethodInfo("asset_selected"));
ADD_SIGNAL( MethodInfo("category_selected"));
ADD_SIGNAL( MethodInfo("author_selected"));
}
EditorAssetLibraryItem::EditorAssetLibraryItem() {
Ref<StyleBoxEmpty> border;
border.instance();
/*border->set_default_margin(MARGIN_LEFT,5);
border->set_default_margin(MARGIN_RIGHT,5);
border->set_default_margin(MARGIN_BOTTOM,5);
border->set_default_margin(MARGIN_TOP,5);*/
add_style_override("panel",border);
HBoxContainer *hb = memnew( HBoxContainer );
add_child(hb);
icon = memnew( TextureButton );
icon->set_default_cursor_shape(CURSOR_POINTING_HAND);
icon->connect("pressed",this,"_asset_clicked");
hb->add_child(icon);
VBoxContainer *vb = memnew( VBoxContainer );
hb->add_child(vb);
vb->set_h_size_flags(SIZE_EXPAND_FILL);
title = memnew( LinkButton );
title->set_text("My Awesome Addon");
title->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
title->connect("pressed",this,"_asset_clicked");
vb->add_child(title);
category = memnew( LinkButton );
category->set_text("Editor Tools");
category->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
title->connect("pressed",this,"_category_clicked");
vb->add_child(category);
author = memnew( LinkButton );
author->set_text("Johny Tolengo");
author->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
title->connect("pressed",this,"_author_clicked");
vb->add_child(author);
HBoxContainer *rating_hb = memnew( HBoxContainer );
vb->add_child(rating_hb);
for(int i=0;i<5;i++) {
stars[i]=memnew(TextureFrame);
rating_hb->add_child(stars[i]);
}
price = memnew( Label );
price->set_text("Free");
vb->add_child(price);
set_custom_minimum_size(Size2(250,100));
set_h_size_flags(SIZE_EXPAND_FILL);
set_stop_mouse(false);
}
//////////////////////////////////////////////////////////////////////////////
void EditorAddonLibraryItemDescription::set_image(int p_type,int p_index,const Ref<Texture>& p_image) {
switch(p_type) {
case EditorAddonLibrary::IMAGE_QUEUE_ICON: {
item->call("set_image",p_type,p_index,p_image);
} break;
case EditorAddonLibrary::IMAGE_QUEUE_THUMBNAIL: {
for(int i=0;i<preview_images.size();i++) {
if (preview_images[i].id==p_index) {
preview_images[i].button->set_icon(p_image);
}
}
//item->call("set_image",p_type,p_index,p_image);
} break;
case EditorAddonLibrary::IMAGE_QUEUE_SCREENSHOT: {
for(int i=0;i<preview_images.size();i++) {
if (preview_images[i].id==p_index && preview_images[i].button->is_pressed()) {
preview->set_texture(p_image);
}
}
//item->call("set_image",p_type,p_index,p_image);
} break;
}
}
void EditorAddonLibraryItemDescription::_bind_methods() {
ObjectTypeDB::bind_method(_MD("set_image"),&EditorAddonLibraryItemDescription::set_image);
}
void EditorAddonLibraryItemDescription::configure(const String& p_title,int p_asset_id,const String& p_category,int p_category_id,const String& p_author,int p_author_id,int p_rating,const String& p_cost,const String& p_description) {
item->configure(p_title,p_asset_id,p_category,p_category_id,p_author,p_author_id,p_rating,p_cost);
description->parse_bbcode(p_description);
set_title(p_title);
}
void EditorAddonLibraryItemDescription::add_preview(int p_id, bool p_video,const String& p_url){
Preview preview;
preview.id=p_id;
preview.video_link=p_url;
preview.button = memnew( Button );
preview.button->set_flat(true);
preview.button->set_icon(get_icon("ThumbnailWait","EditorIcons"));
preview.button->set_toggle_mode(true);
preview_hb->add_child(preview.button);
if (preview_images.size()==0)
preview.button->set_pressed(true);
preview_images.push_back(preview);
}
EditorAddonLibraryItemDescription::EditorAddonLibraryItemDescription() {
VBoxContainer *vbox = memnew( VBoxContainer );
add_child(vbox);
set_child_rect(vbox);
HBoxContainer *hbox = memnew( HBoxContainer);
vbox->add_child(hbox);
vbox->add_constant_override("separation",15);
VBoxContainer *desc_vbox = memnew( VBoxContainer );
hbox->add_child(desc_vbox);
hbox->add_constant_override("separation",15);
item = memnew( EditorAssetLibraryItem );
desc_vbox->add_child(item);
desc_vbox->set_custom_minimum_size(Size2(300,0));
PanelContainer * desc_bg = memnew( PanelContainer );
desc_vbox->add_child(desc_bg);
desc_bg->set_v_size_flags(SIZE_EXPAND_FILL);
description = memnew( RichTextLabel );
//desc_vbox->add_child(description);
desc_bg->add_child(description);
desc_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
preview = memnew( TextureFrame );
preview->set_custom_minimum_size(Size2(640,345));
hbox->add_child(preview);
PanelContainer * previews_bg = memnew( PanelContainer );
vbox->add_child(previews_bg);
previews_bg->set_custom_minimum_size(Size2(0,85));
previews_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
previews = memnew( ScrollContainer );
previews_bg->add_child(previews);
previews->set_enable_v_scroll(false);
previews->set_enable_h_scroll(true);
preview_hb = memnew( HBoxContainer );
preview_hb->set_v_size_flags(SIZE_EXPAND_FILL);
previews->add_child(preview_hb);
get_ok()->set_text("Install");
get_cancel()->set_text("Close");
}
////////////////////////////////////////////////////////////////////////////////
void EditorAddonLibrary::_notification(int p_what) {
if (p_what==NOTIFICATION_READY) {
_api_request("api/configure");
}
if (p_what==NOTIFICATION_PROCESS) {
}
}
const char* EditorAddonLibrary::sort_key[SORT_MAX]={
"rating",
"downloads",
"name",
"cost",
"updated"
};
const char* EditorAddonLibrary::sort_text[SORT_MAX]={
"Rating",
"Downloads",
"Name",
"Cost",
"Updated"
};
void EditorAddonLibrary::_select_author(int p_id) {
//opemn author window
}
void EditorAddonLibrary::_select_category(int p_id){
for(int i=0;i<categories->get_item_count();i++) {
if (i==0)
continue;
int id = categories->get_item_metadata(i);
if (id==p_id) {
categories->select(i);
_search();
break;
}
}
}
void EditorAddonLibrary::_select_asset(int p_id){
_api_request("api/asset","?id="+itos(p_id));
/*
if (description) {
memdelete(description);
}
description = memnew( EditorAddonLibraryItemDescription );
add_child(description);
description->popup_centered_minsize();*/
}
void EditorAddonLibrary::_image_request_completed(int p_status, int p_code, const StringArray& headers, const ByteArray& p_data,int p_queue_id) {
ERR_FAIL_COND( !image_queue.has(p_queue_id) );
if (p_status==HTTPRequest::RESULT_SUCCESS) {
print_line("GOT IMAGE YAY!");
Object *obj = ObjectDB::get_instance(image_queue[p_queue_id].target);
if (obj) {
int len=p_data.size();
ByteArray::Read r=p_data.read();
Image image(r.ptr(),len);
if (!image.empty()) {
Ref<ImageTexture> tex;
tex.instance();
tex->create_from_image(image);
obj->call("set_image",image_queue[p_queue_id].image_type,image_queue[p_queue_id].image_index,tex);
}
}
} else {
WARN_PRINTS("Error getting PNG file for asset id "+itos(image_queue[p_queue_id].asset_id));
}
image_queue[p_queue_id].request->queue_delete();;
image_queue.erase(p_queue_id);
_update_image_queue();
}
void EditorAddonLibrary::_update_image_queue() {
int max_images=2;
int current_images=0;
List<int> to_delete;
for (Map<int,ImageQueue>::Element *E=image_queue.front();E;E=E->next()) {
if (!E->get().active && current_images<max_images) {
String api;
switch(E->get().image_type) {
case IMAGE_QUEUE_ICON: api="api/icon/icon.png"; break;
case IMAGE_QUEUE_SCREENSHOT: api="api/screenshot/screenshot.png"; break;
case IMAGE_QUEUE_THUMBNAIL: api="api/thumbnail/thumbnail.png"; break;
}
print_line("REQUEST ICON FOR: "+itos(E->get().asset_id));
Error err = E->get().request->request(host+"/"+api+"?asset_id="+itos(E->get().asset_id)+"&index="+itos(E->get().image_index));
if (err!=OK) {
to_delete.push_back(E->key());
} else {
E->get().active=true;
}
current_images++;
} else if (E->get().active) {
current_images++;
}
}
while(to_delete.size()) {
image_queue[to_delete.front()->get()].request->queue_delete();
image_queue.erase(to_delete.front()->get());
to_delete.pop_front();
}
}
void EditorAddonLibrary::_request_image(ObjectID p_for,int p_asset_id,ImageType p_type,int p_image_index) {
ImageQueue iq;
iq.asset_id=p_asset_id;
iq.image_index=p_image_index;
iq.image_type=p_type;
iq.request = memnew( HTTPRequest );
iq.target=p_for;
iq.queue_id=++last_queue_id;
iq.active=false;
iq.request->connect("request_completed",this,"_image_request_completed",varray(iq.queue_id));
image_queue[iq.queue_id]=iq;
add_child(iq.request);
_update_image_queue();
}
void EditorAddonLibrary::_search(int p_page) {
String args;
args=String()+"?sort="+sort_key[sort->get_selected()];
if (categories->get_selected()>0) {
args+="&category="+itos(categories->get_item_metadata(categories->get_selected()));
}
if (filter->get_text()!=String()) {
args+="&filter="+filter->get_text().http_escape();
}
if (p_page>0) {
args+="&page="+itos(p_page);
}
_api_request("api/search",args);
}
HBoxContainer* EditorAddonLibrary::_make_pages(int p_page,int p_max_page,int p_page_len,int p_total_items,int p_current_items) {
HBoxContainer * hbc = memnew( HBoxContainer );
//do the mario
int from = p_page-5;
if (from<0)
from=0;
int to = from+10;
if (to>p_max_page)
to=p_max_page;
Color gray = Color(0.65,0.65,0.65);
hbc->add_spacer();
hbc->add_constant_override("separation",10);
LinkButton *first = memnew( LinkButton );
first->set_text("first");
first->add_color_override("font_color", gray );
first->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
first->connect("pressed",this,"_search",varray(0));
hbc->add_child(first);
if (p_page>0) {
LinkButton *prev = memnew( LinkButton );
prev->set_text("prev");
prev->add_color_override("font_color", gray );
prev->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
prev->connect("pressed",this,"_search",varray(p_page-1));
hbc->add_child(prev);
}
for(int i=from;i<=to;i++) {
if (i==p_page) {
Label *current = memnew(Label);
current->set_text(itos(i));
hbc->add_child(current);
} else {
LinkButton *current = memnew( LinkButton );
current->add_color_override("font_color", gray );
current->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
current->set_text(itos(i));
current->connect("pressed",this,"_search",varray(i));
hbc->add_child(current);
}
}
if (p_page<p_max_page) {
LinkButton *next = memnew( LinkButton );
next->set_text("next");
next->add_color_override("font_color", gray );
next->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
next->connect("pressed",this,"_search",varray(p_page+1));
hbc->add_child(next);
}
LinkButton *last = memnew( LinkButton );
last->set_text("last");
last->add_color_override("font_color", gray );
last->set_underline_mode(LinkButton::UNDERLINE_MODE_ON_HOVER);
hbc->add_child(last);
last->connect("pressed",this,"_search",varray(p_max_page));
Label *totals = memnew( Label );
totals->set_text("( "+itos(from*p_page_len)+" - "+itos(from*p_page_len+p_current_items-1)+" / "+itos(p_total_items)+" )");
hbc->add_child(totals);
hbc->add_spacer();
return hbc;
}
void EditorAddonLibrary::_api_request(const String& p_request,const String& p_arguments) {
if (requesting!=REQUESTING_NONE) {
request->cancel_request();
}
current_request=p_request;
request->request(host+"/"+p_request+p_arguments);
}
void EditorAddonLibrary::_http_request_completed(int p_status, int p_code, const StringArray& headers, const ByteArray& p_data) {
String str;
{
int datalen=p_data.size();
ByteArray::Read r = p_data.read();
str.parse_utf8((const char*)r.ptr(),datalen);
}
print_line("response: "+itos(p_status)+" code: "+itos(p_code));
Dictionary d;
d.parse_json(str);
print_line(Variant(d).get_construct_string());
if (current_request=="api/configure") {
categories->clear();
categories->add_item("All");
categories->set_item_metadata(0,0);
if (d.has("categories")) {
Array clist = d["categories"];
for(int i=0;i<clist.size();i++) {
Dictionary cat = clist[i];
if (!cat.has("name") || !cat.has("id"))
continue;
String name=cat["name"];
int id=cat["id"];
categories->add_item(name);
categories->set_item_metadata( categories->get_item_count() -1, id);
}
}
_search();
} else if (current_request=="api/search") {
if (asset_items) {
memdelete(asset_items);
}
if (asset_top_page) {
memdelete(asset_top_page);
}
if (asset_bottom_page) {
memdelete(asset_bottom_page);
}
int page=0;
int pages=1;
int page_len=10;
int total_items=1;
Array result;
if (d.has("page")) {
page=d["page"];
}
if (d.has("pages")) {
pages=d["pages"];
}
if (d.has("page_length")) {
page_len=d["page_length"];
}
if (d.has("total")) {
total_items=d["total"];
}
if (d.has("result")) {
result=d["result"];
}
asset_top_page = _make_pages(page,pages,page_len,total_items,result.size());
library_vb->add_child(asset_top_page);
asset_items = memnew( GridContainer );
asset_items->set_columns(2);
asset_items->add_constant_override("hseparation",10);
asset_items->add_constant_override("vseparation",10);
library_vb->add_child(asset_items);
asset_bottom_page = _make_pages(page,pages,page_len,total_items,result.size());
library_vb->add_child(asset_bottom_page);
for(int i=0;i<result.size();i++) {
Dictionary r = result[i];
ERR_CONTINUE(!r.has("title"));
ERR_CONTINUE(!r.has("asset_id"));
ERR_CONTINUE(!r.has("author"));
ERR_CONTINUE(!r.has("author_id"));
ERR_CONTINUE(!r.has("category"));
ERR_CONTINUE(!r.has("category_id"));
ERR_CONTINUE(!r.has("rating"));
ERR_CONTINUE(!r.has("cost"));
EditorAssetLibraryItem *item = memnew( EditorAssetLibraryItem );
asset_items->add_child(item);
item->configure(r["title"],r["asset_id"],r["category"],r["category_id"],r["author"],r["author_id"],r["rating"],r["cost"]);
item->connect("asset_selected",this,"_select_asset");
item->connect("author_selected",this,"_select_author");
item->connect("category_selected",this,"_category_selected");
_request_image(item->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_ICON,0);
}
} else if (current_request=="api/asset") {
ERR_FAIL_COND(!d.has("info"));
Dictionary r = d["info"];
ERR_FAIL_COND(!r.has("title"));
ERR_FAIL_COND(!r.has("asset_id"));
ERR_FAIL_COND(!r.has("author"));
ERR_FAIL_COND(!r.has("author_id"));
ERR_FAIL_COND(!r.has("category"));
ERR_FAIL_COND(!r.has("category_id"));
ERR_FAIL_COND(!r.has("rating"));
ERR_FAIL_COND(!r.has("cost"));
ERR_FAIL_COND(!r.has("description"));
if (description) {
memdelete(description);
}
description = memnew( EditorAddonLibraryItemDescription );
add_child(description);
description->popup_centered_minsize();
description->configure(r["title"],r["asset_id"],r["category"],r["category_id"],r["author"],r["author_id"],r["rating"],r["cost"],r["description"]);
/*item->connect("asset_selected",this,"_select_asset");
item->connect("author_selected",this,"_select_author");
item->connect("category_selected",this,"_category_selected");*/
_request_image(description->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_ICON,0);
if (d.has("previews")) {
Array previews = d["previews"];
for(int i=0;i<previews.size();i++) {
Dictionary p=previews[i];
ERR_CONTINUE(!p.has("id"));
bool is_video=p.has("type") && String(p["type"])=="video";
String video_url;
if (is_video && p.has("link")) {
video_url="link";
}
int id=p["id"];
description->add_preview(id,is_video,video_url);
_request_image(description->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_THUMBNAIL,id);
if (i==0) {
_request_image(description->get_instance_ID(),r["asset_id"],IMAGE_QUEUE_SCREENSHOT,id);
}
}
}
}
}
void EditorAddonLibrary::_bind_methods() {
ObjectTypeDB::bind_method("_http_request_completed",&EditorAddonLibrary::_http_request_completed);
ObjectTypeDB::bind_method("_select_asset",&EditorAddonLibrary::_select_asset);
ObjectTypeDB::bind_method("_select_author",&EditorAddonLibrary::_select_author);
ObjectTypeDB::bind_method("_select_category",&EditorAddonLibrary::_select_category);
ObjectTypeDB::bind_method("_image_request_completed",&EditorAddonLibrary::_image_request_completed);
ObjectTypeDB::bind_method("_search",&EditorAddonLibrary::_search,DEFVAL(0));
}
EditorAddonLibrary::EditorAddonLibrary() {
tabs = memnew( TabContainer );
tabs->set_v_size_flags(SIZE_EXPAND_FILL);
add_child(tabs);
installed = memnew( EditorPluginSettings );
installed->set_name("Installed");
tabs->add_child(installed);
Ref<StyleBoxEmpty> border;
border.instance();
border->set_default_margin(MARGIN_LEFT,15);
border->set_default_margin(MARGIN_RIGHT,15);
border->set_default_margin(MARGIN_BOTTOM,15);
border->set_default_margin(MARGIN_TOP,15);
PanelContainer *margin_panel = memnew( PanelContainer );
margin_panel->set_name("Online");
margin_panel->add_style_override("panel",border);
tabs->add_child(margin_panel);
VBoxContainer *library_main = memnew( VBoxContainer );
margin_panel->add_child(library_main);
HBoxContainer *search_hb = memnew( HBoxContainer );
library_main->add_child(search_hb);
library_main->add_constant_override("separation",20);
search_hb->add_child( memnew( Label("Search: ")));
filter =memnew( LineEdit );
search_hb->add_child(filter);
filter->set_h_size_flags(SIZE_EXPAND_FILL);
filter->connect("text_entered",this,"_search");
search = memnew( Button("Search"));
search->connect("pressed",this,"_search");
search_hb->add_child(search);
library_vb->add_child(search_hb);
HBoxContainer *search_hb2 = memnew( HBoxContainer );
library_main->add_child(search_hb2);
search_hb2->add_child( memnew( Label("Sort: ")));
sort = memnew( OptionButton );
for(int i=0;i<SORT_MAX;i++) {
sort->add_item(sort_text[i]);
}
search_hb2->add_child(sort);
sort->set_h_size_flags(SIZE_EXPAND_FILL);
reverse = memnew( CheckBox);
reverse->set_text("Reverse");
search_hb2->add_child(reverse);
search_hb2->add_child(memnew(VSeparator));
//search_hb2->add_spacer();
search_hb2->add_child( memnew( Label("Category: ")));
categories = memnew( OptionButton );
categories->add_item("All");
search_hb2->add_child(categories);
categories->set_h_size_flags(SIZE_EXPAND_FILL);
//search_hb2->add_spacer();
search_hb2->add_child(memnew(VSeparator));
search_hb2->add_child( memnew( Label("Site: ")));
repository = memnew( OptionButton );
repository->add_item("Godot");
search_hb2->add_child(repository);
repository->set_h_size_flags(SIZE_EXPAND_FILL);
/////////
PanelContainer * library_scroll_bg = memnew( PanelContainer );
library_main->add_child(library_scroll_bg);
library_scroll_bg->add_style_override("panel",get_stylebox("normal","TextEdit"));
library_scroll_bg->set_v_size_flags(SIZE_EXPAND_FILL);
library_scroll = memnew( ScrollContainer );
library_scroll->set_enable_v_scroll(true);
library_scroll->set_enable_h_scroll(false);
library_scroll_bg->add_child(library_scroll);
Ref<StyleBoxEmpty> border2;
border2.instance();
border2->set_default_margin(MARGIN_LEFT,15);
border2->set_default_margin(MARGIN_RIGHT,35);
border2->set_default_margin(MARGIN_BOTTOM,15);
border2->set_default_margin(MARGIN_TOP,15);
PanelContainer * library_vb_border = memnew( PanelContainer );
library_scroll->add_child(library_vb_border);
library_vb_border->add_style_override("panel",border2);
library_vb_border->set_h_size_flags(SIZE_EXPAND_FILL);
library_vb_border->set_stop_mouse(false);
library_vb = memnew( VBoxContainer );
library_vb->set_h_size_flags(SIZE_EXPAND_FILL);
library_vb_border->add_child(library_vb);
// margin_panel->set_stop_mouse(false);
asset_top_page = memnew( HBoxContainer );
library_vb->add_child(asset_top_page);
asset_items = memnew( GridContainer );
asset_items->set_columns(2);
asset_items->add_constant_override("hseparation",10);
asset_items->add_constant_override("vseparation",10);
library_vb->add_child(asset_items);
asset_bottom_page = memnew( HBoxContainer );
library_vb->add_child(asset_bottom_page);
request = memnew( HTTPRequest );
add_child(request);
request->connect("request_completed",this,"_http_request_completed");
last_queue_id=0;
library_vb->add_constant_override("separation",20);
description = NULL;
host="http://localhost:8000";
}
///////
void AddonEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
addon_library->show();
} else {
addon_library->hide();
}
}
AddonEditorPlugin::AddonEditorPlugin(EditorNode *p_node) {
editor=p_node;
addon_library = memnew( EditorAddonLibrary );
addon_library->set_v_size_flags(Control::SIZE_EXPAND_FILL);
editor->get_viewport()->add_child(addon_library);
addon_library->set_area_as_parent_rect();
addon_library->hide();
}
AddonEditorPlugin::~AddonEditorPlugin() {
}
| 26.279361 | 233 | 0.725908 | [
"object"
] |
f324106c792f1ebd9af2e62cc9939760552a31bf | 11,453 | cc | C++ | tensorflow/core/kernels/range_sampler_test.cc | deepakmuralidharan/tensorflow | f40e41f9c71ef2865f96f3db3cea2909797fe2a3 | [
"Apache-2.0"
] | 23 | 2016-02-04T21:08:43.000Z | 2022-01-14T13:22:33.000Z | tensorflow/core/kernels/range_sampler_test.cc | deepakmuralidharan/tensorflow | f40e41f9c71ef2865f96f3db3cea2909797fe2a3 | [
"Apache-2.0"
] | 2 | 2016-05-31T16:38:55.000Z | 2018-12-30T20:17:05.000Z | tensorflow/core/kernels/range_sampler_test.cc | deepakmuralidharan/tensorflow | f40e41f9c71ef2865f96f3db3cea2909797fe2a3 | [
"Apache-2.0"
] | 20 | 2016-02-15T17:31:02.000Z | 2020-01-12T08:18:48.000Z | /* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <vector>
#include <gtest/gtest.h>
#include "tensorflow/core/kernels/range_sampler.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/public/env.h"
namespace tensorflow {
namespace {
using gtl::ArraySlice;
using gtl::MutableArraySlice;
class RangeSamplerTest : public ::testing::Test {
protected:
void CheckProbabilitiesSumToOne() {
double sum = 0;
for (int i = 0; i < sampler_->range(); i++) {
sum += sampler_->Probability(i);
}
EXPECT_NEAR(sum, 1.0, 1e-4);
}
void CheckHistogram(int num_samples, float tolerance) {
const int range = sampler_->range();
std::vector<int> h(range);
std::vector<int64> a(num_samples);
// Using a fixed random seed to make the test deterministic.
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
sampler_->SampleBatch(&rnd, false, &a);
for (int i = 0; i < num_samples; i++) {
int64 val = a[i];
ASSERT_GE(val, 0);
ASSERT_LT(val, range);
h[val]++;
}
for (int val = 0; val < range; val++) {
EXPECT_NEAR((h[val] + 0.0) / num_samples, sampler_->Probability(val),
tolerance);
}
}
void Update1() {
// Add the value 3 ten times.
std::vector<int64> a(10);
for (int i = 0; i < 10; i++) {
a[i] = 3;
}
sampler_->Update(a);
}
void Update2() {
// Add the value n n times.
int64 a[10];
for (int i = 0; i < 10; i++) {
a[i] = i;
}
for (int64 i = 1; i < 10; i++) {
sampler_->Update(ArraySlice<int64>(a + i, 10 - i));
}
}
std::unique_ptr<RangeSampler> sampler_;
};
TEST_F(RangeSamplerTest, UniformProbabilities) {
sampler_.reset(new UniformSampler(10));
for (int i = 0; i < 10; i++) {
CHECK_EQ(sampler_->Probability(i), sampler_->Probability(0));
}
}
TEST_F(RangeSamplerTest, UniformChecksum) {
sampler_.reset(new UniformSampler(10));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, UniformHistogram) {
sampler_.reset(new UniformSampler(10));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, LogUniformProbabilities) {
int range = 1000000;
sampler_.reset(new LogUniformSampler(range));
for (int i = 100; i < range; i *= 2) {
float ratio = sampler_->Probability(i) / sampler_->Probability(i / 2);
EXPECT_NEAR(ratio, 0.5, 0.1);
}
}
TEST_F(RangeSamplerTest, LogUniformChecksum) {
sampler_.reset(new LogUniformSampler(10));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, LogUniformHistogram) {
sampler_.reset(new LogUniformSampler(10));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, UnigramProbabilities1) {
sampler_.reset(new UnigramSampler(10));
Update1();
EXPECT_NEAR(sampler_->Probability(3), 0.55, 1e-4);
for (int i = 0; i < 10; i++) {
if (i != 3) {
ASSERT_NEAR(sampler_->Probability(i), 0.05, 1e-4);
}
}
}
TEST_F(RangeSamplerTest, UnigramProbabilities2) {
sampler_.reset(new UnigramSampler(10));
Update2();
for (int i = 0; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), (i + 1) / 55.0, 1e-4);
}
}
TEST_F(RangeSamplerTest, UnigramChecksum) {
sampler_.reset(new UnigramSampler(10));
Update1();
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, UnigramHistogram) {
sampler_.reset(new UnigramSampler(10));
Update1();
CheckHistogram(1000, 0.05);
}
static const char kVocabContent[] =
"w1,1\n"
"w2,2\n"
"w3,4\n"
"w4,8\n"
"w5,16\n"
"w6,32\n"
"w7,64\n"
"w8,128\n"
"w9,256";
TEST_F(RangeSamplerTest, FixedUnigramProbabilities) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 9, fname, 0.8, 0, 1, 0));
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 0; i < 9; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, i * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramChecksum) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 9, fname, 0.8, 0, 1, 0));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, FixedUnigramHistogram) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 9, fname, 0.8, 0, 1, 0));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve1) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 10, fname, 0.8, 1, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 1; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 1) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve2) {
Env* env = Env::Default();
string fname = io::JoinPath(testing::TmpDir(), "vocab_file");
TF_CHECK_OK(WriteStringToFile(env, fname, kVocabContent));
sampler_.reset(new FixedUnigramSampler(env, 11, fname, 0.8, 2, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
ASSERT_NEAR(sampler_->Probability(1), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 2; i < 11; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 2) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(9, weights, 0.8, 0, 1, 0));
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 0; i < 9; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, i * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramChecksumFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(9, weights, 0.8, 0, 1, 0));
CheckProbabilitiesSumToOne();
}
TEST_F(RangeSamplerTest, FixedUnigramHistogramFromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(9, weights, 0.8, 0, 1, 0));
CheckHistogram(1000, 0.05);
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve1FromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(10, weights, 0.8, 1, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 1; i < 10; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 1) * 0.8) / 197.05, 1e-4);
}
}
TEST_F(RangeSamplerTest, FixedUnigramProbabilitiesReserve2FromVector) {
std::vector<float> weights = {1, 2, 4, 8, 16, 32, 64, 128, 256};
sampler_.reset(new FixedUnigramSampler(11, weights, 0.8, 2, 1, 0));
ASSERT_NEAR(sampler_->Probability(0), 0, 1e-4);
ASSERT_NEAR(sampler_->Probability(1), 0, 1e-4);
// 1^0.8+2^0.8+4^0.8+...+256^0.8=197.05
for (int i = 2; i < 11; i++) {
ASSERT_NEAR(sampler_->Probability(i), pow(2, (i - 2) * 0.8) / 197.05, 1e-4);
}
}
// AllSampler cannot call Sample or Probability directly.
// We will test SampleBatchGetExpectedCount instead.
TEST_F(RangeSamplerTest, All) {
int batch_size = 10;
sampler_.reset(new AllSampler(10));
std::vector<int64> batch(batch_size);
std::vector<float> batch_expected(batch_size);
std::vector<int64> extras(2);
std::vector<float> extras_expected(2);
extras[0] = 0;
extras[1] = batch_size - 1;
sampler_->SampleBatchGetExpectedCount(nullptr, // no random numbers needed
false, &batch, &batch_expected, extras,
&extras_expected);
for (int i = 0; i < batch_size; i++) {
EXPECT_EQ(i, batch[i]);
EXPECT_EQ(1, batch_expected[i]);
}
EXPECT_EQ(1, extras_expected[0]);
EXPECT_EQ(1, extras_expected[1]);
}
TEST_F(RangeSamplerTest, Unique) {
// We sample num_batches batches, each without replacement.
//
// We check that the returned expected counts roughly agree with each other
// and with the average observed frequencies over the set of batches.
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
const int range = 100;
const int batch_size = 50;
const int num_batches = 100;
sampler_.reset(new LogUniformSampler(range));
std::vector<int> histogram(range);
std::vector<int64> batch(batch_size);
std::vector<int64> all_values(range);
for (int i = 0; i < range; i++) {
all_values[i] = i;
}
std::vector<float> expected(range);
// Sample one batch and get the expected counts of all values
sampler_->SampleBatchGetExpectedCount(
&rnd, true, &batch, MutableArraySlice<float>(), all_values, &expected);
// Check that all elements are unique
std::set<int64> s(batch.begin(), batch.end());
CHECK_EQ(batch_size, s.size());
for (int trial = 0; trial < num_batches; trial++) {
std::vector<float> trial_expected(range);
sampler_->SampleBatchGetExpectedCount(&rnd, true, &batch,
MutableArraySlice<float>(),
all_values, &trial_expected);
for (int i = 0; i < range; i++) {
EXPECT_NEAR(expected[i], trial_expected[i], expected[i] * 0.5);
}
for (int i = 0; i < batch_size; i++) {
histogram[batch[i]]++;
}
}
for (int i = 0; i < range; i++) {
// Check that the computed expected count agrees with the average observed
// count.
const float average_count = static_cast<float>(histogram[i]) / num_batches;
EXPECT_NEAR(expected[i], average_count, 0.2);
}
}
TEST_F(RangeSamplerTest, Avoid) {
random::PhiloxRandom philox(123, 17);
random::SimplePhilox rnd(&philox);
sampler_.reset(new LogUniformSampler(100));
std::vector<int64> avoided(2);
avoided[0] = 17;
avoided[1] = 23;
std::vector<int64> batch(98);
// We expect to pick all elements of [0, 100) except the avoided two.
sampler_->SampleBatchGetExpectedCountAvoid(
&rnd, true, &batch, MutableArraySlice<float>(), ArraySlice<int64>(),
MutableArraySlice<float>(), avoided);
int sum = 0;
for (auto val : batch) {
sum += val;
}
const int expected_sum = 100 * 99 / 2 - avoided[0] - avoided[1];
EXPECT_EQ(expected_sum, sum);
}
} // namespace
} // namespace tensorflow
| 34.08631 | 80 | 0.655112 | [
"vector"
] |
f32885e9a97906920d0c4dfcdc4f951bbb4f33a0 | 12,646 | cpp | C++ | src/subcommand/locify_main.cpp | fabbondanza/vg | 86edd831bd76b4c33e4cf51134f557c49736cf2b | [
"MIT"
] | null | null | null | src/subcommand/locify_main.cpp | fabbondanza/vg | 86edd831bd76b4c33e4cf51134f557c49736cf2b | [
"MIT"
] | null | null | null | src/subcommand/locify_main.cpp | fabbondanza/vg | 86edd831bd76b4c33e4cf51134f557c49736cf2b | [
"MIT"
] | null | null | null | /** \file locify_main.cpp
*
* Defines the "vg locify" subcommand
*/
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <iostream>
#include "subcommand.hpp"
#include "../vg.hpp"
#include "../xg.hpp"
#include "../index.hpp"
#include "../convert.hpp"
#include <vg/io/stream.hpp>
#include <vg/io/vpkg.hpp>
#include <bdsg/overlay_helper.hpp>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_locify(char** argv){
cerr << "usage: " << argv[0] << " locify [options] " << endl
<< " -l, --loci FILE input loci over which to locify the alignments" << endl
<< " -a, --aln-idx DIR use this rocksdb alignment index (from vg index -N)" << endl
<< " -x, --xg-idx FILE use this xg index or graph" << endl
<< " -n, --name-alleles generate names for each allele rather than using full Paths" << endl
<< " -f, --forwardize flip alignments on the reverse strand to the forward" << endl
<< " -s, --sorted-loci FILE write the non-nested loci out in their sorted order" << endl
<< " -b, --n-best N keep only the N-best alleles by alignment support" << endl
<< " -o, --out-loci FILE rewrite the loci with only N-best alleles kept" << endl;
// TODO -- add some basic filters that are useful downstream in whatshap
}
int main_locify(int argc, char** argv){
string gam_idx_name;
string loci_file;
Index gam_idx;
string xg_idx_name;
bool name_alleles = false;
bool forwardize = false;
string loci_out, sorted_loci;
int n_best = 0;
if (argc <= 2){
help_locify(argv);
exit(1);
}
int c;
optind = 2; // force optind past command positional argument
while (true) {
static struct option long_options[] =
{
{"help", no_argument, 0, 'h'},
{"gam-idx", required_argument, 0, 'g'},
{"loci", required_argument, 0, 'l'},
{"xg-idx", required_argument, 0, 'x'},
{"name-alleles", no_argument, 0, 'n'},
{"forwardize", no_argument, 0, 'f'},
{"sorted-loci", required_argument, 0, 's'},
{"loci-out", required_argument, 0, 'o'},
{"n-best", required_argument, 0, 'b'},
{0, 0, 0, 0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hl:x:g:nfo:b:s:",
long_options, &option_index);
// Detect the end of the options.
if (c == -1)
break;
switch (c)
{
case 'g':
gam_idx_name = optarg;
break;
case 'l':
loci_file = optarg;
break;
case 'x':
xg_idx_name = optarg;
break;
case 'n':
name_alleles = true;
break;
case 'f':
forwardize = true;
break;
case 'o':
loci_out = optarg;
break;
case 's':
sorted_loci = optarg;
break;
case 'b':
n_best = parse<int>(optarg);
name_alleles = true;
break;
case 'h':
case '?':
help_locify(argv);
exit(1);
break;
default:
abort ();
}
}
if (!gam_idx_name.empty()) {
gam_idx.open_read_only(gam_idx_name);
}
if (xg_idx_name.empty()) {
cerr << "[vg locify] Error: no xg index provided" << endl;
return 1;
}
ifstream xgstream(xg_idx_name);
unique_ptr<PathHandleGraph> path_handle_graph = vg::io::VPKG::load_one<PathHandleGraph>(xgstream);
bdsg::PathPositionOverlayHelper overlay_helper;
PathPositionHandleGraph* xgidx = overlay_helper.apply(path_handle_graph.get());
std::function<vector<string>(string, char)> strsplit = [&](string x, char delim){
vector<string> ret;
stringstream ss;
std::string tok;
while (getline(ss, tok, delim)){
ret.push_back(tok);
}
return ret;
};
vector<string> locus_names;
map<string, map<string, int > > locus_allele_names;
map<string, Alignment> alignments_with_loci;
map<pos_t, set<string> > pos_to_loci;
map<string, set<pos_t> > locus_to_pos;
map<string, map<int, int> > locus_allele_support;
map<string, vector<int> > locus_to_best_n_alleles;
map<string, set<int> > locus_to_keep;
int count = 0;
std::function<void(Locus&)> lambda = [&](Locus& l){
locus_names.push_back(l.name());
set<vg::id_t> nodes_in_locus;
for (int i = 0; i < l.allele_size(); ++i) {
auto& allele = l.allele(i);
for (int j = 0; j < allele.mapping_size(); ++j) {
auto& position = allele.mapping(j).position();
nodes_in_locus.insert(position.node_id());
}
// for position in mapping
map<pos_t, int> ref_positions;
map<pos_t, Edit> edits;
decompose(allele, ref_positions, edits);
// warning: uses only reference positions!!!
for (auto& pos : ref_positions) {
pos_to_loci[pos.first].insert(l.name());
locus_to_pos[l.name()].insert(pos.first);
}
}
// void for_alignment_in_range(int64_t id1, int64_t id2, std::function<void(const Alignment&)> lambda);
std::function<void(const Alignment&)> fill_alns = [&](const Alignment& a){
// TODO reverse complementing alleles ?
// overlap is stranded
//matching
// find the most-matching allele
map<double, vector<int> > matches;
for (int i = 0; i < l.allele_size(); ++i) {
auto& allele = l.allele(i);
matches[overlap(a.path(), allele)].push_back(i);
}
assert(l.allele_size());
int best = matches.rbegin()->second.front();
Locus matching;
matching.set_name(l.name());
if (name_alleles) {
//map<string, map<string, int > > locus_allele_names;
auto& allele = l.allele(best);
string s;
allele.SerializeToString(&s);
auto& l_names = locus_allele_names[l.name()];
auto f = l_names.find(s);
int name_int = 0;
if (f == l_names.end()) {
int next_id = l_names.size() + 1;
l_names[s] = next_id;
name_int = next_id;
} else {
name_int = f->second;
}
string allele_name = vg::convert(name_int);
Path p;
p.set_name(allele_name);
*matching.add_allele() = p;
if (n_best) {
// record support for this allele
// we'll use to filter the locus records later
locus_allele_support[l.name()][name_int]++;
}
} else {
*matching.add_allele() = l.allele(best);
// TODO get quality score relative to this specific allele / alignment
// record in the alignment we'll save
}
if (alignments_with_loci.find(a.name()) == alignments_with_loci.end()) {
alignments_with_loci[a.name()] = a;
}
Alignment& aln = alignments_with_loci[a.name()];
*aln.add_locus() = matching;
};
vector<vg::id_t> nodes_vec;
for (auto& id : nodes_in_locus) nodes_vec.push_back(id);
gam_idx.for_alignment_to_nodes(nodes_vec, fill_alns);
};
if (!loci_file.empty()){
ifstream ifi(loci_file);
vg::io::for_each(ifi, lambda);
} else {
cerr << "[vg locify] Warning: empty locus file given, could not annotate alignments with loci." << endl;
}
// find the non-nested loci
vector<string> non_nested_loci;
for (auto& name : locus_names) {
// is it nested?
auto& positions = locus_to_pos[name];
int min_loci = 0;
for (auto& pos : positions) {
auto& loci = pos_to_loci[pos];
min_loci = (min_loci == 0 ? (int)loci.size() : min(min_loci, (int)loci.size()));
}
if (min_loci == 1) {
// not fully contained in any other locus
non_nested_loci.push_back(name);
}
}
// filter out the non-best alleles
if (n_best) {
// find the n-best
for (auto& supp : locus_allele_support) {
auto& name = supp.first;
auto& alleles = supp.second;
map<int, int> ranked;
for (auto& allele : alleles) {
ranked[allele.second] = allele.first;
}
auto& to_keep = locus_to_keep[name];
for (auto r = ranked.rbegin(); r != ranked.rend(); ++r) {
to_keep.insert(r->second);
if (to_keep.size() == n_best) {
break;
}
}
}
// filter out non-n-best from the alignments
for (auto& a : alignments_with_loci) {
auto& aln = a.second;
vector<Locus> kept;
for (int i = 0; i < aln.locus_size(); ++i) {
auto& allele = aln.locus(i).allele(0);
if (locus_to_keep[aln.locus(i).name()].count(atoi(allele.name().c_str()))) {
kept.push_back(aln.locus(i));
}
}
aln.clear_locus();
for (auto& l : kept) {
*aln.add_locus() = l;
}
}
}
if (n_best && !loci_out.empty()) {
// filter out non-n-best from the loci
if (!loci_file.empty()){
ofstream outloci(loci_out);
vector<Locus> buffer;
std::function<void(Locus&)> lambda = [&](Locus& l){
// remove the alleles which are to filter
//map<string, map<string, int > > locus_allele_names;
auto& allele_names = locus_allele_names[l.name()];
auto& to_keep = locus_to_keep[l.name()];
vector<Path> alleles_to_keep;
for (int i = 0; i < l.allele_size(); ++i) {
auto allele = l.allele(i);
string s; allele.SerializeToString(&s);
auto& name = allele_names[s];
if (to_keep.count(name)) {
allele.set_name(vg::convert(name));
alleles_to_keep.push_back(allele);
}
}
l.clear_allele();
for (auto& allele : alleles_to_keep) {
*l.add_allele() = allele;
}
buffer.push_back(l);
vg::io::write_buffered(outloci, buffer, 100);
};
ifstream ifi(loci_file);
vg::io::for_each(ifi, lambda);
vg::io::write_buffered(outloci, buffer, 0);
outloci.close();
} else {
cerr << "[vg locify] Warning: empty locus file given, could not update loci." << endl;
}
}
// sort them using... ? ids?
sort(non_nested_loci.begin(), non_nested_loci.end(),
[&locus_to_pos](const string& s1, const string& s2) {
return *locus_to_pos[s1].begin() < *locus_to_pos[s2].begin();
});
if (!sorted_loci.empty()) {
ofstream outsorted(sorted_loci);
for (auto& name : non_nested_loci) {
outsorted << name << endl;
}
outsorted.close();
}
vector<Alignment> output_buf;
for (auto& aln : alignments_with_loci) {
// TODO order the loci by their order in the alignments
if (forwardize) {
if (aln.second.path().mapping_size() && aln.second.path().mapping(0).position().is_reverse()) {
output_buf.push_back(reverse_complement_alignment(aln.second,
[&xgidx](int64_t id) { return xgidx->get_length(xgidx->get_handle(id)); }));
} else {
output_buf.push_back(aln.second);
}
} else {
output_buf.push_back(aln.second);
}
vg::io::write_buffered(cout, output_buf, 100);
}
vg::io::write_buffered(cout, output_buf, 0);
return 0;
}
// Register subcommand
static Subcommand vg_locify("locify", "find loci", main_locify);
| 34.551913 | 142 | 0.515183 | [
"vector"
] |
f3288f9ac835c7639674ac716875325f8473f5cf | 872 | cc | C++ | solutions/cpp/283-move-zeroes.cc | PW486/leetcode | c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9 | [
"Unlicense"
] | null | null | null | solutions/cpp/283-move-zeroes.cc | PW486/leetcode | c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9 | [
"Unlicense"
] | null | null | null | solutions/cpp/283-move-zeroes.cc | PW486/leetcode | c8a38265ebc98fc6335b6420fefe0ce2bb3eeae9 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void nextIndex(vector<int> &nums, int &index) {
for (; index < nums.size(); index++) {
if (nums[index] != 0)
break;
}
}
void moveZeroes(vector<int> &nums) {
int index = 1;
nextIndex(nums, index);
for (int zero = 0; zero < nums.size() && index < nums.size(); zero++) {
if (index < zero) {
index = zero;
nextIndex(nums, index);
}
if (nums[zero] == 0) {
swap(nums[index], nums[zero]);
nextIndex(nums, index);
}
}
}
};
int main() {
vector<int> nums = {4, 2, 4, 0, 0, 3, 0, 5, 1, 0};
Solution().moveZeroes(nums);
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << endl;
}
return 0;
}
| 18.166667 | 75 | 0.50344 | [
"vector"
] |
f32ab62415ec8e030f64abeced3624f453cef564 | 8,300 | cpp | C++ | lib/storageblobbuffer.cpp | timmyw/ofsystem | 6f955d53dc3025148763333bea0a11d0bce28c06 | [
"MIT"
] | null | null | null | lib/storageblobbuffer.cpp | timmyw/ofsystem | 6f955d53dc3025148763333bea0a11d0bce28c06 | [
"MIT"
] | null | null | null | lib/storageblobbuffer.cpp | timmyw/ofsystem | 6f955d53dc3025148763333bea0a11d0bce28c06 | [
"MIT"
] | null | null | null | /*
Copyright (C) 1997-2011 by Suntail.com AS, Tim Whelan
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 <ofsys.h>
#include <storageblobbuffer.h>
#if defined(OFOPSYS_SOLARIS)
#include <strings.h>
#endif
StorageBlobBuffer::StorageBlobBuffer( ):
m_blob( NULL ), m_left( -1 ), m_ptr( NULL ), m_dyn( false )
{
}
StorageBlobBuffer::StorageBlobBuffer( unsigned char *aBlob,
int aSize,
bool dynFlag ):
m_blob( aBlob ),
m_left( aSize ),
m_ptr( aBlob ),
m_dyn( dynFlag )
{
}
StorageBlobBuffer::~StorageBlobBuffer( )
{
if ( m_dyn )
delete [] m_blob;
}
void
StorageBlobBuffer::makeEmpty()
{
if ( m_dyn )
delete [] m_blob;
m_blob = m_ptr = NULL;
m_left = -1;
m_dyn = false;
}
void
StorageBlobBuffer::bufferTaken( )
{
m_dyn = false;
}
void
StorageBlobBuffer::setupBlob( unsigned char *aBlob, int aSize )
{
m_ptr = m_blob = new unsigned char [ aSize ];
m_left = aSize;
m_dyn = true;
bcopy( aBlob, m_blob, aSize );
}
bool
StorageBlobBuffer::hasOverflowed( )
{
return m_left < 0;
}
void
StorageBlobBuffer::allocate( )
{
m_left = m_ptr - m_blob;
if ( m_dyn )
delete[] ( m_blob );
m_ptr = m_blob = new unsigned char[m_left];
m_dyn = true;
}
unsigned char *
StorageBlobBuffer::getBlob( )
{
return m_blob;
}
int
StorageBlobBuffer::getSize( )
{
return m_ptr - m_blob;
}
void
StorageBlobBuffer::writeBool( bool aBool )
{
if ( --m_left < 0 )
{
m_ptr++;
return;
}
*m_ptr++ = aBool ? 1 : 0;
}
void
StorageBlobBuffer::writeInt08( ofint32 anInt )
{
if ( ( m_left -- ) < 0 )
{
m_ptr ++;
return;
}
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeInt16( ofint32 anInt )
{
if ( ( m_left -= 2 ) < 0 )
{
m_ptr += 2;
return;
}
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeInt32( ofint32 anInt )
{
if ( ( m_left -= 4 ) < 0 )
{
m_ptr += 4;
return;
}
*m_ptr++ = static_cast < char >( anInt >> 24 );
*m_ptr++ = static_cast < char >( anInt >> 16 );
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeInt64( ofuint64 anInt )
{
if ( ( m_left -= 8 ) < 0 )
{
m_ptr += 8;
return;
}
*m_ptr++ = static_cast < char >( anInt >> 56 );
*m_ptr++ = static_cast < char >( anInt >> 48 );
*m_ptr++ = static_cast < char >( anInt >> 40 );
*m_ptr++ = static_cast < char >( anInt >> 32 );
*m_ptr++ = static_cast < char >( anInt >> 24 );
*m_ptr++ = static_cast < char >( anInt >> 16 );
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeString( const char *aString )
{
int i = strlen( aString ) + 1;
if ( ( m_left -= i ) >= 0 )
OFOS::strcpy( ( char * ) m_ptr, aString );
m_ptr += i;
}
void
StorageBlobBuffer::writeIdentity( const OFIDENTITY * anId )
{
writeInt32( anId->m_flags );
writeInt64( anId->m_id0 );
writeInt64( anId->m_id1 );
}
void
StorageBlobBuffer::readIdentity( OFIDENTITY * anId )
{
anId->m_flags = readInt32( );
anId->m_id0 = readInt64( );
anId->m_id1 = readInt64( );
}
void
StorageBlobBuffer::writeServerIdentity( const SRVIDENTITY * anId )
{
assert( anId );
writeInt64( anId->m_id );
}
void
StorageBlobBuffer::readServerIdentity( SRVIDENTITY * anId )
{
anId->m_id = readInt64( );
}
void
StorageBlobBuffer::writeIdentityList( vector < OFIDENTITY * >*list )
{
writeInt32( list->size( ) );
for ( vector < OFIDENTITY * >::iterator i = list->begin( ); i != list->end( ); i++ )
writeIdentity( *i );
}
void
StorageBlobBuffer::writeDouble( double aDouble )
{
if ( ( m_left -= 8 ) < 0 )
{
m_ptr += 8;
return;
}
ofint64 anInt = *( ofint64 * ) ( &aDouble );
*m_ptr++ = static_cast < char >( anInt >> 56 );
*m_ptr++ = static_cast < char >( anInt >> 48 );
*m_ptr++ = static_cast < char >( anInt >> 40 );
*m_ptr++ = static_cast < char >( anInt >> 32 );
*m_ptr++ = static_cast < char >( anInt >> 24 );
*m_ptr++ = static_cast < char >( anInt >> 16 );
*m_ptr++ = static_cast < char >( anInt >> 8 );
*m_ptr++ = static_cast < char >( anInt );
}
void
StorageBlobBuffer::writeBinary( void *data,
ofuint32 size )
{
if ( ( m_left -= size ) < 0 )
{
m_ptr += size;
return;
}
memcpy( m_ptr, data, size );
m_ptr += size;
}
bool
StorageBlobBuffer::readBool( )
{
return ( *m_ptr++ != 0 );
}
ofint32 StorageBlobBuffer::readInt08( )
{
ofuint32 anInt;
anInt = *m_ptr++;
return anInt;
}
ofint32 StorageBlobBuffer::readInt16( )
{
ofuint32 anInt;
anInt = *m_ptr++ << 8;
anInt |= *m_ptr++;
return anInt;
}
ofint32 StorageBlobBuffer::readInt32( )
{
ofint32 anInt;
anInt = *m_ptr++ << 24;
anInt |= *m_ptr++ << 16;
anInt |= *m_ptr++ << 8;
anInt |= *m_ptr++;
return anInt;
}
ofuint64 StorageBlobBuffer::readInt64( )
{
ofuint64 anInt;
anInt = ( ( ofuint64 ) * m_ptr++ ) << 56;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 48;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 40;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 32;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 24;
anInt |= *m_ptr++ << 16;
anInt |= *m_ptr++ << 8;
anInt |= *m_ptr++;
return anInt;
}
char *
StorageBlobBuffer::readString( )
{
ofint32 len = strlen( ( char * ) m_ptr ) + 1;
char *aString = new char[len];
OFOS::strcpy( aString, ( const char * ) m_ptr );
m_ptr += len;
return aString;
}
char *
StorageBlobBuffer::tempReadString( )
{
ofint32 len = strlen( ( char * ) m_ptr ) + 1;
char *aString = ( char * ) m_ptr;
m_ptr += len;
return aString;
}
void
StorageBlobBuffer::readString( char *aString )
{
OFOS::strcpy( aString, ( const char * ) m_ptr );
m_ptr += strlen( ( char * ) m_ptr ) + 1;
}
void
StorageBlobBuffer::readIdentityList( vector < OFIDENTITY * >*list )
{
ofuint32 count = readInt32( );
for ( ; count; count-- )
{
OFIDENTITY *id = new OFIDENTITY;
readIdentity( id );
list->push_back( id );
}
}
double
StorageBlobBuffer::readDouble( )
{
ofint64 anInt;
anInt = ( ( ofuint64 ) * m_ptr++ ) << 56;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 48;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 40;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 32;
anInt |= ( ( ofuint64 ) * m_ptr++ ) << 24;
anInt |= *m_ptr++ << 16;
anInt |= *m_ptr++ << 8;
anInt |= *m_ptr++;
return *( ( double * ) &anInt );
}
void
StorageBlobBuffer::readBinary( void *data,
ofuint32 size )
{
memcpy( data, m_ptr, size );
m_ptr += size;
}
void
StorageBlobBuffer::setReadPosition( ofuint32 pos )
{
m_ptr = m_blob + pos;
}
void
StorageBlobBuffer::setWritePosition( ofuint32 pos )
{
m_ptr = m_blob + pos;
m_left = 0x7fffffff;
}
ofuint32
StorageBlobBuffer::getCurrentPosition()
{
return m_ptr-m_blob;
}
| 22.015915 | 90 | 0.585542 | [
"vector"
] |
f32dc8fd9126800d4f2496ca11cf82eb03866199 | 7,956 | hpp | C++ | tm_kit/basic/simple_shared_chain/InMemoryWithLockChain.hpp | cd606/tm_basic | ea2d13b561dd640161823a5e377f35fcb7fe5d48 | [
"Apache-2.0"
] | 1 | 2020-05-22T08:47:02.000Z | 2020-05-22T08:47:02.000Z | tm_kit/basic/simple_shared_chain/InMemoryWithLockChain.hpp | cd606/tm_basic | ea2d13b561dd640161823a5e377f35fcb7fe5d48 | [
"Apache-2.0"
] | null | null | null | tm_kit/basic/simple_shared_chain/InMemoryWithLockChain.hpp | cd606/tm_basic | ea2d13b561dd640161823a5e377f35fcb7fe5d48 | [
"Apache-2.0"
] | null | null | null | #ifndef TM_KIT_BASIC_IN_MEMORY_WITH_LOCK_CHAIN_HPP_
#define TM_KIT_BASIC_IN_MEMORY_WITH_LOCK_CHAIN_HPP_
#include <tm_kit/basic/simple_shared_chain/ChainReader.hpp>
#include <tm_kit/basic/simple_shared_chain/ChainWriter.hpp>
#include <tm_kit/basic/ByteData.hpp>
#include <tm_kit/basic/SerializationHelperMacros.hpp>
namespace dev { namespace cd606 { namespace tm { namespace basic { namespace simple_shared_chain {
#define InMemoryWithLockChainItemFields \
((int64_t, revision)) \
((std::string, id)) \
((T, data)) \
((std::string, nextID))
#define InMemoryWithLockChainStorageFields \
((T, data)) \
((std::string, nextID))
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT(((typename, T)), InMemoryWithLockChainItem, InMemoryWithLockChainItemFields);
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT(((typename, T)), InMemoryWithLockChainStorage, InMemoryWithLockChainStorageFields);
}}}}}
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT_SERIALIZE_NO_FIELD_NAMES(((typename, T)), dev::cd606::tm::basic::simple_shared_chain::InMemoryWithLockChainItem, InMemoryWithLockChainItemFields);
TM_BASIC_CBOR_CAPABLE_TEMPLATE_STRUCT_SERIALIZE_NO_FIELD_NAMES(((typename, T)), dev::cd606::tm::basic::simple_shared_chain::InMemoryWithLockChainStorage, InMemoryWithLockChainStorageFields);
namespace dev { namespace cd606 { namespace tm { namespace basic { namespace simple_shared_chain {
template <class T>
class InMemoryWithLockChain {
public:
using StorageIDType = std::string;
using DataType = T;
using MapData = InMemoryWithLockChainStorage<T>;
using TheMap = std::unordered_map<std::string, MapData>;
using ItemType = InMemoryWithLockChainItem<T>;
static constexpr bool SupportsExtraData = true;
private:
std::function<void()> updateTriggerFunc_;
TheMap theMap_;
std::unordered_map<std::string, std::string> extraData_;
std::mutex mutex_;
std::mutex chainActionMutex_;
public:
InMemoryWithLockChain() : updateTriggerFunc_(), theMap_({{"", MapData {}}}), extraData_(), mutex_(), chainActionMutex_() {
}
void setUpdateTriggerFunc(std::function<void()> f) {
if (updateTriggerFunc_) {
throw std::runtime_error("Duplicate attempt to set update trigger function for InMemoryWithLockChain");
}
updateTriggerFunc_ = f;
if (updateTriggerFunc_) {
updateTriggerFunc_();
}
}
ItemType head(void *) {
std::lock_guard<std::mutex> _(mutex_);
auto &x = theMap_[""];
return ItemType {0, "", x.data, x.nextID};
}
ItemType loadUntil(void *, StorageIDType const &id) {
std::lock_guard<std::mutex> _(mutex_);
auto &x = theMap_[id];
return ItemType {0, id, x.data, x.nextID};
}
std::optional<ItemType> fetchNext(ItemType const ¤t) {
std::lock_guard<std::mutex> _(mutex_);
auto iter = theMap_.find(current.id);
if (iter == theMap_.end()) {
return std::nullopt;
}
if (iter->second.nextID == "") {
return std::nullopt;
}
iter = theMap_.find(iter->second.nextID);
if (iter == theMap_.end()) {
return std::nullopt;
}
return ItemType {0, iter->first, iter->second.data, iter->second.nextID};
}
bool idIsAlreadyOnChain(std::string const &id) {
std::lock_guard<std::mutex> _(mutex_);
return (theMap_.find(id) != theMap_.end());
}
bool appendAfter(ItemType const ¤t, ItemType &&toBeWritten) {
std::lock_guard<std::mutex> _(mutex_);
if (theMap_.find(toBeWritten.id) != theMap_.end()) {
return false;
}
auto iter = theMap_.find(current.id);
if (iter == theMap_.end()) {
return false;
}
if (iter->second.nextID != "") {
return false;
}
iter->second.nextID = toBeWritten.id;
theMap_.insert({iter->second.nextID, MapData {std::move(toBeWritten.data), ""}}).first;
if (updateTriggerFunc_) {
updateTriggerFunc_();
}
return true;
}
bool appendAfter(ItemType const ¤t, std::vector<ItemType> &&toBeWritten) {
if (toBeWritten.empty()) {
return true;
}
if (toBeWritten.size() == 1) {
return appendAfter(current, std::move(toBeWritten[0]));
}
std::lock_guard<std::mutex> _(mutex_);
auto const &firstID = toBeWritten[0].id;
if (theMap_.find(firstID) != theMap_.end()) {
return false;
}
auto iter = theMap_.find(current.id);
if (iter == theMap_.end()) {
return false;
}
if (iter->second.nextID != "") {
return false;
}
iter->second.nextID = firstID;
for (auto &&x : toBeWritten) {
theMap_.insert({x.id, MapData {std::move(x.data), std::move(x.nextID)}});
}
if (updateTriggerFunc_) {
updateTriggerFunc_();
}
return true;
}
template <class ExtraData>
void saveExtraData(std::string const &key, ExtraData const &data) {
std::lock_guard<std::mutex> _(mutex_);
extraData_[key] = basic::bytedata_utils::RunSerializer<basic::CBOR<ExtraData>>::apply(
basic::CBOR<ExtraData> {data}
);
}
template <class ExtraData>
std::optional<ExtraData> loadExtraData(std::string const &key) {
std::lock_guard<std::mutex> _(mutex_);
auto iter = extraData_.find(key);
if (iter != extraData_.end()) {
auto d = basic::bytedata_utils::RunDeserializer<basic::CBOR<ExtraData>>::apply(
iter->second
);
if (d) {
return d->value;
} else {
return std::nullopt;
}
} else {
return std::nullopt;
}
}
template <class Env>
static StorageIDType newStorageID() {
return Env::id_to_string(Env::new_id());
}
template <class Env>
static std::string newStorageIDAsString() {
return newStorageID<Env>();
}
static ItemType formChainItem(StorageIDType const &itemID, T &&itemData) {
return ItemType {
0, itemID, std::move(itemData), ""
};
}
static std::vector<ItemType> formChainItems(std::vector<std::tuple<StorageIDType, T>> &&itemDatas) {
std::vector<ItemType> ret;
bool first = true;
for (auto &&x: itemDatas) {
auto *p = (first?nullptr:&(ret.back()));
if (p) {
p->nextID = std::get<0>(x);
}
ret.push_back(formChainItem(std::get<0>(x), std::move(std::get<1>(x))));
first = false;
}
return ret;
}
static StorageIDType extractStorageID(ItemType const &p) {
return p.id;
}
static T const *extractData(ItemType const &p) {
return &(p.data);
}
static std::string_view extractStorageIDStringView(ItemType const &p) {
return std::string_view {p.id};
}
void acquireLock() {
chainActionMutex_.lock();
}
void releaseLock() {
chainActionMutex_.unlock();
}
};
}}}}}
#endif
| 39.192118 | 190 | 0.55455 | [
"vector"
] |
f32f1f6b9749e3fc161c9afddd6915ab34880275 | 14,502 | cpp | C++ | landmark_routing/Astar.cpp | AlexandrosPlessias/GreecePoint-to-PointShortestPaths | 469f2014b3cdc8c5859375e79f73347f5939f20f | [
"MIT"
] | null | null | null | landmark_routing/Astar.cpp | AlexandrosPlessias/GreecePoint-to-PointShortestPaths | 469f2014b3cdc8c5859375e79f73347f5939f20f | [
"MIT"
] | null | null | null | landmark_routing/Astar.cpp | AlexandrosPlessias/GreecePoint-to-PointShortestPaths | 469f2014b3cdc8c5859375e79f73347f5939f20f | [
"MIT"
] | null | null | null | #include "Astar.h"
#include <iostream>
#include <random>
#define K_LMRKS 16
int Astar::run(node_t source, node_t target)
{
Timer _t;
Label f_solution(routing_infty,-1);
f_solution.f_score = routing_infty;
astar_f_heap queue;
map<node_t, Label> nodesLabeled;
set<node_t> is_settled;
Label lb(0,source);
lb.f_score = lb.cost + calc_lmrk_dist(
source,target
,&m_g->landmarks_holder_avoid
,make_pair(m_g->nodes_container.at(source).dist_to_lmrk_avoid.get(),m_g->nodes_container.at(source).dist_from_lmrk_avoid.get())
,make_pair(m_g->nodes_container.at(target).dist_to_lmrk_avoid.get(),m_g->nodes_container.at(target).dist_from_lmrk_avoid.get())
);
queue.push(lb);
nodesLabeled[source] = lb;
while (!queue.empty())
{
Label g_label(queue.top());
if (is_settled.find(g_label.currentNode)==is_settled.end()) {
const Vertex* v = &m_g->nodes_container.at(g_label.currentNode);
is_settled.insert(g_label.currentNode);
queue.pop();
if (g_label.currentNode == target)
{
if (f_solution.f_score > g_label.f_score) {
f_solution = g_label;
}
else {
// solved
std::cout << "\nShortest path found in \033[1;31m" << _t.diff() << "s\033[0m";
std::cout << " with cost \033[32m" << f_solution.cost << "\033[0m" << std::endl;
return 0;
}
}
for (auto it = v->out_edges.begin(); it != v->out_edges.end(); ++it)
{
Label new_label(g_label.cost+it->second.cost,it->first);
new_label.prevNode = g_label.currentNode;
new_label.f_score = new_label.cost + calc_lmrk_dist(
new_label.currentNode,target
,&m_g->landmarks_holder_avoid
,make_pair(
m_g->nodes_container.at(new_label.currentNode).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(new_label.currentNode).dist_from_lmrk_avoid.get())
,make_pair(
m_g->nodes_container.at(target).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(target).dist_from_lmrk_avoid.get())
);
add_in_queue(&new_label,nodesLabeled,queue);
}
}
else {
queue.pop();
}
}
if (f_solution.currentNode != -1) {
// solved
std::cout << "\nShortest path found in \033[1;31m" << _t.diff() << "s\033[0m";
std::cout << " with cost \033[32m" << f_solution.cost << "\033[0m" << std::endl;
return 0;
}
else {
cout << " couldn't find Shortest path for source: " << source << ", target: " << target;
cout << " in: " << _t.diff() << " s\n";
return -1;
}
}
cost_t Astar::calc_lmrk_dist(
node_t curr_node,node_t target
,const vector<node_t>* lmrk_holder
,pair<const map<node_t, cost_t>*,const map<node_t, cost_t>*> lmrk_dists_curr_node
,pair<const map<node_t, cost_t>*,const map<node_t, cost_t>*> lmrk_dists_target)
{
double distance = 0;
if (curr_node==target)
return 0;
for(auto lmrk_it=lmrk_holder->begin();lmrk_it!=lmrk_holder->end();++lmrk_it)
{
double tmp_dist = //abs(
lmrk_dists_target.first->at(*lmrk_it) -
lmrk_dists_curr_node.first->at(*lmrk_it)
// )
;
if ( distance < tmp_dist )
{
distance = tmp_dist;
}
tmp_dist = //abs(
lmrk_dists_curr_node.second->at(*lmrk_it) -
lmrk_dists_target.second->at(*lmrk_it)
// )
;
if(distance < tmp_dist)
{
distance = tmp_dist;
}
}
return distance;
}
void Astar::add_in_queue(const Label* l, map<node_t,Label>& labels, astar_f_heap& q)
{
auto it = labels.find(l->currentNode);
if (it != labels.end()) {
if (it->second.cost > l->cost) {
it->second = *l;
q.push(*l);
}
}
else {
labels[l->currentNode] = *l;
q.push(*l);
}
}
int Astar::avoid(int thres_dist)
{
Timer _t;
vector<node_t> v_gNodes;
for(auto it=m_g->nodes_container.begin();it!=m_g->nodes_container.end();++it)
{
v_gNodes.push_back(it->n);
}
std::random_device rd;
std::mt19937 generator(rd());
vector<double> probabilities(v_gNodes.size(),1);
node_t random_node;
int lmrk_inpath_counter = 0;
while(m_g->landmarks_holder_avoid.size() < K_LMRKS )
{
std::discrete_distribution<node_t> distribution(probabilities.begin(), probabilities.end());
random_node = distribution(generator);
node_t rootNode = v_gNodes.at(random_node);
map<node_t,double> node_weights{{rootNode,0}};
map<node_t,Label> sp_tree;
vector<node_t> leafs;
dijkstra(m_g,rootNode,-1,leafs,sp_tree);
for(auto& node:m_g->nodes_container)
{
if (m_g->landmarks_holder_avoid.size()>0) {
double max_lmrk_dist = calc_lmrk_dist(
rootNode,node.n,&m_g->landmarks_holder_avoid
,make_pair(
m_g->nodes_container.at(rootNode).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(rootNode).dist_to_lmrk_avoid.get())
,make_pair(
m_g->nodes_container.at(node.n).dist_to_lmrk_avoid.get()
,m_g->nodes_container.at(node.n).dist_from_lmrk_avoid.get())
);
node_weights[node.n] = sp_tree.at(node.n).cost-max_lmrk_dist;
}
else {
node_weights[node.n] = sp_tree.at(node.n).cost;
}
}
for (auto& node:m_g->landmarks_holder_avoid) {
node_weights[node] = 0;
}
pair<node_t,double> max_size_node{-1,0};
map<node_t,double> node_size;
for (auto& leaf:leafs) {
node_t curr_node = leaf;
if (max_size_node.second < node_weights.at(curr_node)) {
max_size_node = make_pair(leaf,node_weights.at(curr_node));
}
node_size[curr_node] = node_weights.at(curr_node);
while (curr_node!=rootNode) {
node_t p_node = sp_tree.at(curr_node).prevNode;
if (node_weights.at(curr_node)==0 || node_weights.at(p_node)==0) {
node_size[p_node] = 0;
}
else {
try {
node_size.at(p_node) += node_weights.at(curr_node);
}
catch (out_of_range) {
node_size[p_node] = node_weights.at(p_node) + node_weights.at(curr_node);
}
if (max_size_node.second<node_size.at(p_node)) {
max_size_node = make_pair(p_node,node_size.at(p_node));
}
}
curr_node = p_node;
}
}
if (max_size_node.first>-1) {
bool lmrk_found = false;
set<node_t> settled;
while(!lmrk_found) {
const Vertex* v = &(m_g->nodes_container.at(max_size_node.first));
settled.insert(v->n);
pair<node_t,double> next_node(-1,0);
for (auto it = v->out_edges.begin(); it != v->out_edges.end(); ++it)
{
try {
if (next_node.second<node_size.at(it->first) && settled.find(it->first)==settled.end()) {
next_node = make_pair(it->first,node_size.at(it->first));
}
}
catch (out_of_range) {}
}
if (next_node.first==-1) {
m_g->landmarks_holder_avoid.push_back(max_size_node.first);
lmrk_found = true;
}
else if (find(leafs.begin(),leafs.end(),next_node.first)!=leafs.end()) {
max_size_node = next_node;
m_g->landmarks_holder_avoid.push_back(max_size_node.first);
lmrk_found = true;
}
else {
max_size_node = next_node;
}
}
node_t lmrk = max_size_node.first;
lmrk_dijkstra_dists(lmrk,-1);
lmrk_dijkstra_dists(lmrk,-1,true);
auto v_it = find(v_gNodes.begin(),v_gNodes.end(),lmrk);
probabilities.at(distance(v_gNodes.begin(),v_it)) = 0;
double lmrk_lon = m_g->nodes_container.at(max_size_node.first).lon;
double lmrk_lat = m_g->nodes_container.at(max_size_node.first).lat;
for (auto it=m_g->nodes_container.begin(); it!=m_g->nodes_container.end(); ++it) {
double geodist_to_lmrk = geodist(it->lat,it->lon,lmrk_lat,lmrk_lon,'K');
if ( geodist_to_lmrk>thres_dist) {
auto v_it = find(v_gNodes.begin(),v_gNodes.end(),it->n);
probabilities.at(distance(v_gNodes.begin(),v_it)) = (int)(geodist_to_lmrk/thres_dist);
}
}
}
else {
++lmrk_inpath_counter;
}
}
std::cout << "landmarks found in the path: \033[31m" << lmrk_inpath_counter << "\033[0m times" << std::endl;
std::cout << K_LMRKS << " landmarks selected in \033[31m" << _t.diff() << "\033[0ms: " << std::endl;
return 0;
}
int Astar::lmrk_dijkstra_dists(node_t s, node_t t, bool reverse)
{
f_heap queue;
map<node_t, Label> nodesLabeled;
for (auto it = m_g->nodes_container.begin(); it != m_g->nodes_container.end(); ++it)
{
Label l(routing_infty,it->n);
l.handle = setup_handle(queue.push(l));
nodesLabeled[it->n]=l;
}
nodesLabeled.at(s).cost=0;
nodesLabeled.at(s).prevNode = -1;
*(nodesLabeled.at(s).handle) = nodesLabeled.at(s);
queue.decrease(nodesLabeled.at(s).handle);
while (!queue.empty())
{
Label global_label(queue.top());
const Vertex* v = &(m_g->nodes_container.at(global_label.currentNode));
if ((global_label.cost == routing_infty) || (global_label.currentNode == t))
{
// solved
return 0;
}
map<node_t,Edge>* edges;
if(reverse) {
// (*m_g->nodes_container.at(global_label.currentNode).dist_to_lmrk)[s] = global_label.cost;
m_g->nodes_container.at(global_label.currentNode).add_lmrk_cost(s,global_label.cost);
edges = &v->in_edges;
}
else {
// (*m_g->nodes_container.at(global_label.currentNode).dist_from_lmrk)[s] = global_label.cost;
m_g->nodes_container.at(global_label.currentNode).add_lmrk_cost(s,global_label.cost,true);
edges = &v->out_edges;
}
queue.pop();
for (auto it = edges->begin(); it != edges->end(); ++it)
{
Label* _label = &nodesLabeled.at(it->first);
if (global_label.cost < _label->cost - it->second.cost)
{
_label->cost = global_label.cost + it->second.cost;
_label->prevNode = global_label.currentNode;
*(_label->handle) = *_label;
queue.decrease(_label->handle);
}
}
}
return 1;
}
f_heap::handle_type Astar::setup_handle(f_heap::handle_type &&handle)
{
(*handle).handle = handle;
return handle;
}
int Astar::dijkstra(
const Graph* g, node_t source, node_t target,
vector<node_t>& leafs,map<node_t, Label>& labels
)
{
f_heap queue;
for (auto& node:g->nodes_container) {
Label l(routing_infty,node.n);
labels[node.n] = l;
labels.at(node.n).handle = setup_handle(queue.push(labels.at(node.n)));
}
labels.at(source).cost=0;
labels.at(source).prevNode = -1;
*(labels.at(source).handle) = labels.at(source);
queue.decrease(labels.at(source).handle);
while (!queue.empty())
{
Label global_label(queue.top());
const Vertex* v = &(g->nodes_container.at(global_label.currentNode));
queue.pop();
if (!(global_label.currentNode==target)) {
int edges_opened=0;
for (auto it = v->out_edges.begin(); it != v->out_edges.end(); ++it)
{
if (labels.at(it->first).cost - it->second.cost > global_label.cost ) {
labels.at(it->first).cost = global_label.cost + it->second.cost;
labels.at(it->first).prevNode = global_label.currentNode;
*(labels.at(it->first).handle) = labels.at(it->first);
queue.decrease(labels.at(it->first).handle);
++edges_opened;
}
}
if (edges_opened==0
&& global_label.cost < routing_infty
&& find(leafs.begin(),leafs.end(),global_label.currentNode)==leafs.end())
{
leafs.push_back(global_label.currentNode);
}
}
else {
return 0;
}
}
return 1;
}
#define pi 3.14159265358979323846
double Astar::geodist(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta, dist;
theta = lon1 - lon2;
dist = sin(deg2rad(lat1)) * sin(deg2rad(lat2)) + cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * cos(deg2rad(theta));
dist = acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
switch(unit) {
case 'M':
break;
case 'K':
dist = dist * 1.609344;
break;
case 'N':
dist = dist * 0.8684;
break;
}
return (dist);
}
double Astar::deg2rad(double deg) {
return (deg * pi / 180);
}
double Astar::rad2deg(double rad) {
return (rad * 180 / pi);
}
| 32.370536 | 143 | 0.525583 | [
"vector"
] |
f32f287bb635f9037f06d5e313db34d31b84728f | 1,735 | cpp | C++ | src/loop011.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | 4 | 2016-11-07T12:50:14.000Z | 2020-04-30T19:48:05.000Z | src/loop011.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | 1 | 2017-04-17T12:00:16.000Z | 2017-04-17T12:00:16.000Z | src/loop011.cpp | TannerRogalsky/Demoloops | 13cb7c4b1bba892c24ddb8bbd78f4953b9c9a9d5 | [
"MIT"
] | null | null | null | #include <numeric>
#include "demoloop.h"
#include "graphics/3d_primitives.h"
#include <glm/gtx/rotate_vector.hpp>
#include "hsl.h"
using namespace std;
using namespace demoloop;
static const uint16_t NUM_VERTS = 60;
const uint32_t CYCLE_LENGTH = 3;
static const float RADIUS = 0.3;
class Loop11 : public Demoloop {
public:
Loop11() : Demoloop(CYCLE_LENGTH, 150, 150, 150), mesh(icosahedron(0, 0, 0, RADIUS)) {
gl.getProjection() = glm::perspective((float)DEMOLOOP_M_PI / 4.0f, (float)width / (float)height, 0.1f, 100.0f);
iota(mesh.mIndices.begin(), mesh.mIndices.end(), 0);
}
void Update() {
const float cycle_ratio = getCycleRatio();
for (int i = 0; i < NUM_VERTS; ++i) {
const float t = i;
const float interval_cycle_ratio = fmod(t / NUM_VERTS + cycle_ratio, 1);
auto color = hsl2rgb(interval_cycle_ratio, 1, 0.5);
Vertex &v = mesh.mVertices[i];
v.r = color.r;
v.g = color.g;
v.b = color.b;
v.a = 255;
}
gl.pushTransform();
const float cameraX = 0;//sin(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
// const float cameraY = pow(sin(cycle_ratio * DEMOLOOP_M_PI * 2), 2);
const float cameraY = cos(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
const float cameraZ = 3;//cos(cycle_ratio * DEMOLOOP_M_PI * 2) * 3;
gl.getTransform() = glm::lookAt(glm::vec3(cameraX, cameraY, cameraZ), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));
mesh.buffer();
mesh.draw();
glm::mat4 m;
m = glm::translate(m, {0, sinf(cycle_ratio * DEMOLOOP_M_PI * 2) * RADIUS * 4, 0});
m = glm::scale(m, {0.5, 0.5, 0.5});
mesh.draw(m);
gl.popTransform();
}
private:
Mesh mesh;
};
int main(int, char**){
Loop11 test;
test.Run();
return 0;
}
| 27.539683 | 115 | 0.627666 | [
"mesh"
] |
f3300fa6c486bd8c24437c6fa277135f55c47dfe | 11,905 | cpp | C++ | Source/SupportGLUT/Widget/TransferFunctionEditor.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | Source/SupportGLUT/Widget/TransferFunctionEditor.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | Source/SupportGLUT/Widget/TransferFunctionEditor.cpp | CCSEPBVR/KVS | f6153b3f52aa38904cc96d38d5cd609c5dccfc59 | [
"BSD-3-Clause"
] | null | null | null | #include "TransferFunctionEditor.h"
#include <kvs/DebugNew>
#include <kvs/MouseEvent>
#include <kvs/Math>
#include <kvs/HSVColor>
#include <kvs/RGBColor>
#include <kvs/Date>
#include <kvs/Time>
#include <kvs/glut/GLUT>
#include <kvs/IgnoreUnusedVariable>
#include <kvs/Background>
#include <SupportGLUT/Viewer/KVSKey.h>
#include <SupportGLUT/Viewer/KVSMouseButton.h>
namespace
{
class ResetButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
ResetButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->reset();
}
};
class ApplyButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
ApplyButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->apply();
}
};
class SaveButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
SaveButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->save();
}
};
class UndoButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
UndoButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->undo();
}
};
class RedoButton : public kvs::PushButton
{
kvs::glut::TransferFunctionEditor* m_editor;
public:
RedoButton( kvs::glut::TransferFunctionEditor* editor ):
kvs::PushButton( editor ),
m_editor( editor )
{
}
void released()
{
m_editor->redo();
}
};
} // end of namespace
namespace kvs
{
namespace glut
{
TransferFunctionEditor::TransferFunctionEditor( kvs::ScreenBase* parent ):
m_screen( parent ),
m_color_palette( NULL ),
m_color_map_palette( NULL ),
m_opacity_map_palette( NULL ),
m_histogram( NULL ),
m_reset_button( NULL ),
m_undo_button( NULL ),
m_redo_button( NULL ),
m_save_button( NULL ),
m_apply_button( NULL ),
m_min_value( 0.0f ),
m_max_value( 0.0f )
{
const std::string title = "Transfer Function Editor";
const int x = ( parent != 0 ) ? parent->x() + parent->width() + 5 : 0;
const int y = ( parent != 0 ) ? parent->y() : 0;
const int width = 350;
const int height = 512;
const int margin = 10;
const kvs::RGBColor base_color( 50, 50, 50 );
kvs::Font caption_font;
caption_font.setStyleToBold();
caption_font.setColor( kvs::RGBColor( 180, 180, 180 ) );
SuperClass::setBackgroundColor( base_color );
SuperClass::setTitle( title );
SuperClass::setPosition( x, y );
SuperClass::setSize( width, height );
SuperClass::create();
const size_t resolution = 256;
m_initial_transfer_function.create( resolution );
m_undo_stack.push_front( m_initial_transfer_function );
m_stack_event = new StackEvent( this );
SuperClass::addEvent( m_stack_event );
m_max_stack_size = 10;
m_color_palette = new kvs::ColorPalette( this );
m_color_palette->setCaption( "Color palette" );
m_color_palette->setFont( caption_font );
m_color_palette->setY( -7 );
m_color_palette->setHeight( 170 );
m_color_palette->show();
m_color_map_palette = new kvs::ColorMapPalette( this );
m_color_map_palette->setCaption( "Color map" );
m_color_map_palette->setFont( caption_font );
m_color_map_palette->setColorMap( m_initial_transfer_function.colorMap() );
m_color_map_palette->setX( m_color_palette->x0() );
m_color_map_palette->setY( m_color_palette->y1() - m_color_palette->margin() );
m_color_map_palette->attachColorPalette( m_color_palette );
m_color_map_palette->show();
m_opacity_map_palette = new kvs::OpacityMapPalette( this );
m_opacity_map_palette->setCaption( "Opacity map" );
m_opacity_map_palette->setFont( caption_font );
m_opacity_map_palette->setOpacityMap( m_initial_transfer_function.opacityMap() );
m_opacity_map_palette->setX( m_color_map_palette->x0() );
m_opacity_map_palette->setY( m_color_map_palette->y1() - m_color_map_palette->margin() );
m_opacity_map_palette->show();
m_histogram = new kvs::HistogramBar( this );
m_histogram->setCaption( "Histogram" );
m_histogram->setFont( caption_font );
m_histogram->setX( m_opacity_map_palette->x0() );
m_histogram->setY( m_opacity_map_palette->y1() - m_opacity_map_palette->margin() );
m_histogram->setHeight( 100 );
m_histogram->setGraphColor( kvs::RGBAColor( 100, 100, 100, 1.0f ) );
m_histogram->show();
const size_t button_margin = 5;
const size_t button_width = ( width - 2 * margin - button_margin ) / 2;
m_reset_button = new ::ResetButton( this );
m_reset_button->setCaption( "Reset" );
m_reset_button->setFont( caption_font );
m_reset_button->setX( m_histogram->x0() + m_histogram->margin() );
m_reset_button->setY( m_histogram->y1() + 10 );
m_reset_button->setWidth( button_width );
m_reset_button->setButtonColor( base_color * 1.5 );
m_reset_button->show();
m_undo_button = new ::UndoButton( this );
m_undo_button->setCaption( "Undo" );
m_undo_button->setFont( caption_font );
m_undo_button->setX( m_reset_button->x1() + button_margin );
m_undo_button->setY( m_reset_button->y() );
m_undo_button->setWidth( ( button_width - button_margin ) / 2 );
m_undo_button->setButtonColor( base_color * 1.5 );
m_undo_button->show();
m_redo_button = new ::RedoButton( this );
m_redo_button->setCaption( "Redo" );
m_redo_button->setFont( caption_font );
m_redo_button->setX( m_undo_button->x1() + button_margin );
m_redo_button->setY( m_undo_button->y() );
m_redo_button->setWidth( ( button_width - button_margin ) / 2 );
m_redo_button->setButtonColor( base_color * 1.5 );
m_redo_button->show();
m_save_button = new ::SaveButton( this );
m_save_button->setCaption( "Save" );
m_save_button->setFont( caption_font );
m_save_button->setX( m_reset_button->x0() );
m_save_button->setY( m_reset_button->y1() + button_margin );
m_save_button->setWidth( button_width );
m_save_button->setButtonColor( base_color * 1.5 );
m_save_button->show();
m_apply_button = new ::ApplyButton( this );
m_apply_button->setCaption( "Apply" );
m_apply_button->setFont( caption_font );
m_apply_button->setX( m_save_button->x1() + button_margin );
m_apply_button->setY( m_save_button->y0() );
m_apply_button->setWidth( ( width -margin ) / 2 - m_opacity_map_palette->margin() );
m_apply_button->setButtonColor( base_color * 1.5 );
m_apply_button->show();
}
TransferFunctionEditor::~TransferFunctionEditor()
{
if ( m_stack_event ) { delete m_stack_event; m_stack_event = NULL; }
if ( m_color_palette ) { delete m_color_palette; m_color_palette = NULL; }
if ( m_color_map_palette ) { delete m_color_map_palette; m_color_map_palette = NULL; }
if ( m_opacity_map_palette ) { delete m_opacity_map_palette; m_opacity_map_palette = NULL; }
if ( m_histogram ) { delete m_histogram; m_histogram = NULL; }
if ( m_reset_button ) { delete m_reset_button; m_reset_button = NULL; }
if ( m_undo_button ) { delete m_undo_button; m_undo_button = NULL; }
if ( m_redo_button ) { delete m_redo_button; m_redo_button = NULL; }
if ( m_apply_button ) { delete m_apply_button; m_apply_button = NULL; }
if ( m_save_button ) { delete m_save_button; m_save_button = NULL; }
}
const kvs::TransferFunction TransferFunctionEditor::transferFunction() const
{
kvs::TransferFunction transfer_function( this->colorMap(), this->opacityMap() );
transfer_function.setRange( m_min_value, m_max_value );
return transfer_function;
}
void TransferFunctionEditor::setTransferFunction( const kvs::TransferFunction& transfer_function )
{
const kvs::ColorMap& cmap = transfer_function.colorMap();
const kvs::OpacityMap& omap = transfer_function.opacityMap();
// Deep copy for the initial transfer function.
kvs::ColorMap::Table color_map_table( cmap.table().data(), cmap.table().size() );
kvs::OpacityMap::Table opacity_map_table( omap.table().data(), omap.table().size() );
kvs::ColorMap color_map( color_map_table );
kvs::OpacityMap opacity_map( opacity_map_table );
m_initial_transfer_function.setColorMap( color_map );
m_initial_transfer_function.setOpacityMap( opacity_map );
if ( transfer_function.hasRange() )
{
m_min_value = transfer_function.colorMap().minValue();
m_max_value = transfer_function.colorMap().maxValue();
m_initial_transfer_function.setRange( m_min_value, m_max_value );
}
m_color_map_palette->setColorMap( color_map );
m_opacity_map_palette->setOpacityMap( opacity_map );
m_undo_stack.clear();
m_undo_stack.push_front( m_initial_transfer_function );
}
void TransferFunctionEditor::setVolumeObject( const kvs::VolumeObjectBase* object )
{
if ( !m_initial_transfer_function.hasRange() )
{
m_min_value = object->minValue();
m_max_value = object->maxValue();
}
m_histogram->create( object );
}
void TransferFunctionEditor::reset()
{
m_color_map_palette->setColorMap( m_initial_transfer_function.colorMap() );
m_opacity_map_palette->setOpacityMap( m_initial_transfer_function.opacityMap() );
m_color_map_palette->update();
m_opacity_map_palette->update();
this->redraw();
}
void TransferFunctionEditor::save()
{
const std::string date = kvs::Date().toString("");
const std::string time = kvs::Time().toString("");
const std::string filename = "tfunc_" + date + "_" + time + ".kvsml";
kvs::TransferFunction transfer_function = this->transferFunction();
transfer_function.write( filename );
}
void TransferFunctionEditor::undo()
{
if ( m_undo_stack.size() > 1 )
{
if ( m_redo_stack.size() > m_max_stack_size ) m_redo_stack.pop_back();
m_redo_stack.push_front( m_undo_stack.front() );
m_undo_stack.pop_front();
kvs::TransferFunction& transfer_function = m_undo_stack.front();
m_color_map_palette->setColorMap( transfer_function.colorMap() );
m_opacity_map_palette->setOpacityMap( transfer_function.opacityMap() );
m_color_map_palette->update();
m_opacity_map_palette->update();
this->redraw();
}
}
void TransferFunctionEditor::redo()
{
if ( m_redo_stack.size() > 1 )
{
kvs::TransferFunction& transfer_function = m_redo_stack.front();
m_color_map_palette->setColorMap( transfer_function.colorMap() );
m_opacity_map_palette->setOpacityMap( transfer_function.opacityMap() );
if ( m_undo_stack.size() > m_max_stack_size ) m_undo_stack.pop_back();
m_undo_stack.push_front( m_redo_stack.front() );
m_redo_stack.pop_front();
m_color_map_palette->update();
m_opacity_map_palette->update();
this->redraw();
}
}
TransferFunctionEditor::StackEvent::StackEvent(
kvs::glut::TransferFunctionEditor* editor ):
m_editor( editor )
{
}
void TransferFunctionEditor::StackEvent::update( kvs::MouseEvent* event )
{
if ( m_editor->opacityMapPalette()->palette().isActive() ||
m_editor->colorMapPalette()->palette().isActive() )
{
if ( m_editor->m_undo_stack.size() > m_editor->m_max_stack_size )
{
m_editor->m_undo_stack.pop_back();
}
m_editor->m_undo_stack.push_front( m_editor->transferFunction() );
m_editor->redraw();
}
}
} // end of namespace glut
} // end of namespace kvs
| 31.246719 | 98 | 0.684502 | [
"object"
] |
f33f1b6fc927c50f10134e1d1418ce6d8a815ac0 | 6,273 | cpp | C++ | benchmark/inmemory.cpp | WojciechMula/libflagstats | d3fc296be35223387f6dd440b4cbc32067c0cab4 | [
"Apache-2.0"
] | null | null | null | benchmark/inmemory.cpp | WojciechMula/libflagstats | d3fc296be35223387f6dd440b4cbc32067c0cab4 | [
"Apache-2.0"
] | null | null | null | benchmark/inmemory.cpp | WojciechMula/libflagstats | d3fc296be35223387f6dd440b4cbc32067c0cab4 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <chrono>
#include <memory>
#include <cstdint>
#include <random>
#include <vector>
#include "libalgebra.h" // pospopcnt
// force flagstats to define all implementations
#define STORM_HAVE_AVX2
#define STORM_HAVE_AVX512
#define STORM_HAVE_SSE42
#include "../libflagstats.h" // flagstats
using Clock = std::chrono::high_resolution_clock;
template <typename UNIT = std::chrono::microseconds>
Clock::time_point::rep elapsed(const Clock::time_point& t1, const Clock::time_point& t2) {
return std::chrono::duration_cast<UNIT>(t2 - t1).count();
}
class Application {
private:
const size_t size;
std::unique_ptr<uint16_t[]> flags;
std::ostream& out;
public:
Application(size_t size)
: size(size)
, flags(new uint16_t[size])
, out(std::cout) {
initialize_input();
}
void run() {
#if defined(STORM_HAVE_CPUID)
#if defined(__cplusplus)
/* C++11 thread-safe singleton */
static const int cpuid = STORM_get_cpuid();
#else
static int cpuid_ = -1;
int cpuid = cpuid_;
if (cpuid == -1) {
cpuid = STORM_get_cpuid();
#if defined(_MSC_VER)
_InterlockedCompareExchange(&cpuid_, cpuid, -1);
#else
__sync_val_compare_and_swap(&cpuid_, -1, cpuid);
#endif
}
#endif
#endif
uint32_t scalar[32];
run("scalar", FLAGSTAT_scalar, scalar);
#if defined(STORM_HAVE_SSE42)
if (cpuid & STORM_CPUID_runtime_bit_SSE42) {
uint32_t sse4[32];
const uint64_t time_sse4 = run("SSE4", FLAGSTAT_sse4, sse4);
uint32_t sse4_improved[32];
run("SSE4 improved", FLAGSTAT_sse4_improved, sse4_improved, sse4, time_sse4);
}
#endif
#if defined(STORM_HAVE_AVX2)
if (cpuid & STORM_CPUID_runtime_bit_AVX2) {
uint32_t avx2[32];
const uint64_t time_avx2 = run("AVX2", FLAGSTAT_avx2, avx2);
uint32_t avx2_improved[32];
run("AVX2 improved", FLAGSTAT_avx2_improved, avx2_improved, avx2, time_avx2);
}
#endif
#if defined(STORM_HAVE_AVX512)
if (cpuid & STORM_CPUID_runtime_bit_AVX512BW) {
uint32_t avx512[32];
const uint64_t time_avx512 = run("AVX512", FLAGSTAT_avx512, avx512, scalar);
uint32_t avx512_improved[32];
const uint64_t time_avx512_improved = run("AVX512 improved", FLAGSTAT_avx512_improved, avx512_improved, scalar, time_avx512);
uint32_t avx512_improved2[32];
const uint64_t time_avx512_improved2 = run("AVX512 improved 2", FLAGSTAT_avx512_improved2, avx512_improved2, scalar, time_avx512_improved);
uint32_t avx512_improved3[32];
const uint64_t time_avx512_improved3 = run("AVX512 improved 3", FLAGSTAT_avx512_improved3, avx512_improved3, scalar);
uint32_t avx512_improved4[32];
const uint64_t time_avx512_improved4 = run("AVX512 improved 4", FLAGSTAT_avx512_improved4, avx512_improved4, scalar);
}
#endif
}
private:
void initialize_input() {
std::random_device rd;
std::mt19937 eng(rd());
eng.seed(0); // make the results repeatable
std::uniform_int_distribution<uint16_t> flag(0, 4096 - 1);
for (size_t i=0; i < size; i++)
flags[i] = flag(eng);
}
template <typename FUN>
uint64_t run(const char* name,
FUN function,
uint32_t* stats,
uint32_t* stats_ref = nullptr,
uint64_t time_ref = 0)
{
out << "Running function " << name << ": ";
out << std::flush;
for (int i=0; i < 32; i++) stats[i] = 0;
const auto t1 = Clock::now();
function(flags.get(), size, stats);
const auto t2 = Clock::now();
const uint16_t time_us = elapsed(t1, t2);
out << "time " << time_us << " us";
if (time_ref != 0)
out << " (speedup: " << double(time_ref)/time_us << ")";
out << '\n';
dump_stats(stats);
if (stats_ref != nullptr) {
const bool has_error = compare(stats_ref, stats);
}
return time_us;
}
void dump_array(uint32_t* arr, int size) {
out << '[';
for (int i=0; i < size; i++) {
if (i != 0)
out << ", ";
out << std::setw(6);
out << arr[i];
}
out << ']';
}
void dump_stats(uint32_t* stats) {
out << "statistics are: ";
out << '\n';
for (int i=0; i < 32; i += 8) {
out << " ";
dump_array(stats + i, 8);
out << '\n';
}
}
bool compare(uint32_t* reference, uint32_t* stats) {
bool has_error = false;
// test only the counters actually written by FLAGSTAT_scalar_update
static const std::vector<int> tested_counters{
FLAGSTAT_FQCFAIL_OFF,
FLAGSTAT_FSECONDARY_OFF,
FLAGSTAT_FSUPPLEMENTARY_OFF,
FLAGSTAT_BIT12_OFF,
FLAGSTAT_FREAD1_OFF,
FLAGSTAT_FREAD2_OFF,
FLAGSTAT_BIT13_OFF,
FLAGSTAT_BIT14_OFF,
FLAGSTAT_FUNMAP_OFF,
FLAGSTAT_FDUP_OFF,
FLAGSTAT_FQCFAIL_OFF + 16,
FLAGSTAT_FSECONDARY_OFF + 16,
FLAGSTAT_FSUPPLEMENTARY_OFF + 16,
FLAGSTAT_BIT12_OFF + 16,
FLAGSTAT_FREAD1_OFF + 16,
FLAGSTAT_FREAD2_OFF + 16,
FLAGSTAT_BIT13_OFF + 16,
FLAGSTAT_BIT14_OFF + 16,
FLAGSTAT_FUNMAP_OFF + 16,
FLAGSTAT_FDUP_OFF + 16,
};
for (const int index: tested_counters) {
const uint32_t expected = reference[index];
const uint32_t actual = stats[index];
if (expected != actual) {
out << "Difference at " << index << ": expected = " << expected << ", actual = " << actual << '\n';
has_error = true;
}
}
return has_error;
}
};
int main(int argc, char* argv[]) {
const size_t default_size = 1024 * 100;
size_t size = default_size;
if (argc > 1)
size = atoi(argv[1]);
Application app(size);
app.run();
}
| 29.313084 | 151 | 0.579627 | [
"vector"
] |
f34cd691a5e53e31e236c483927bcae85f983213 | 1,665 | cpp | C++ | solutions/AtCoder/diverta2019/E.cpp | yumeno-ukihashi/competitive-programming | 5cc3a7938b62133d8dc71a179cb11dfe985315d3 | [
"Unlicense"
] | null | null | null | solutions/AtCoder/diverta2019/E.cpp | yumeno-ukihashi/competitive-programming | 5cc3a7938b62133d8dc71a179cb11dfe985315d3 | [
"Unlicense"
] | null | null | null | solutions/AtCoder/diverta2019/E.cpp | yumeno-ukihashi/competitive-programming | 5cc3a7938b62133d8dc71a179cb11dfe985315d3 | [
"Unlicense"
] | null | null | null | #include<bits/stdc++.h>
#define REP(x,y,z) for(int x=y;x<=z;x++)
#define MSET(x,y) memset(x,y,sizeof(x))
#define M 500005
#define MX 1048576
#define MOD 1000000007
using namespace std;
using LL = long long;
int n,in[M];
LL pw[M];
vector<int> pos[MX];
int find_cnt(int p1,int p2,int num) {
auto it1 = upper_bound(pos[num].begin(), pos[num].end(), p1);
auto it2 = lower_bound(pos[num].begin(), pos[num].end(), p2) - 1;
if (it1<=it2) return it2-it1+1;
return 0;
}
int main()
{
pw[0] = 1;
REP(i,1,M-1) pw[i] = (pw[i-1]*2) % MOD;
while (~scanf("%d",&n)) {
REP(i,0,MX-1) pos[i].clear();
REP(i,1,n) scanf("%d", &in[i]);
REP(i,2,n) in[i] ^= in[i-1];
REP(i,1,n) pos[in[i]].push_back(i);
//REP(i,1,n) printf("%d ",in[i]); puts("");
LL ans = 0;
REP(i,1,MX-1) if (in[n]==0 || in[n]==i) {
LL frsum = 0;
LL frdp = 0;
LL dp = 0;
REP(j,0,(int)pos[i].size()-1) {
int fri = j==0 ? 0 : pos[i][j-1];
int c0 = find_cnt(fri, pos[i][j], 0);
frdp = (frdp + frsum * c0) % MOD;
dp = (frdp + 1) % MOD;
frsum = (frsum + dp) % MOD;
}
if (in[n]==0) {
ans += frsum;
ans %= MOD;
} else {
ans += dp;
ans %= MOD;
}
}
if (in[n]==0) {
int len = 0;
REP(i,1,n-1) if(in[i]==0) len++;
ans += pw[len];
ans %= MOD;
}
printf("%lld\n", ans);
}
return 0;
}
| 24.485294 | 69 | 0.404805 | [
"vector"
] |
f34d7545ad45b38fe6a125d0f8d77b1185747e78 | 7,934 | cc | C++ | src/search/initializer.cc | thomaskeller79/exhaustive-mdp | bf52164f96abd13c88870677b8b215f5f79e195a | [
"MIT"
] | 26 | 2019-10-18T16:04:34.000Z | 2022-02-22T13:38:31.000Z | src/search/initializer.cc | thomaskeller79/exhaustive-mdp | bf52164f96abd13c88870677b8b215f5f79e195a | [
"MIT"
] | 69 | 2019-10-18T10:19:13.000Z | 2021-07-19T06:51:51.000Z | src/search/initializer.cc | thomaskeller79/exhaustive-mdp | bf52164f96abd13c88870677b8b215f5f79e195a | [
"MIT"
] | 14 | 2019-12-26T06:17:03.000Z | 2022-01-30T09:18:16.000Z | #include "initializer.h"
#include "thts.h"
#include "utils/logger.h"
#include "utils/math_utils.h"
#include "utils/string_utils.h"
#include "utils/system_utils.h"
/******************************************************************
Search Engine Creation
******************************************************************/
Initializer* Initializer::fromString(std::string& desc, THTS* thts) {
StringUtils::trim(desc);
assert(desc[0] == '[' && desc[desc.size() - 1] == ']');
StringUtils::removeFirstAndLastCharacter(desc);
StringUtils::trim(desc);
Initializer* result = nullptr;
if (desc.find("Expand") == 0) {
desc = desc.substr(6, desc.size());
result = new ExpandNodeInitializer(thts);
} else if (desc.find("Single") == 0) {
desc = desc.substr(6, desc.size());
result = new SingleChildInitializer(thts);
} else {
SystemUtils::abort("Unknown Initializer: " + desc);
}
StringUtils::trim(desc);
while (!desc.empty()) {
std::string param;
std::string value;
StringUtils::nextParamValuePair(desc, param, value);
if (!result->setValueFromString(param, value)) {
SystemUtils::abort("Unused parameter value pair: " + param + " / " +
value);
}
}
return result;
}
bool Initializer::setValueFromString(std::string& param, std::string& value) {
if (param == "-h") {
setHeuristic(SearchEngine::fromString(value));
return true;
} else if (param == "-hw") {
setHeuristicWeight(atof(value.c_str()));
return true;
} else if (param == "-iv") {
setNumberOfInitialVisits(atoi(value.c_str()));
return true;
}
return false;
}
Initializer::~Initializer() {
assert(heuristic);
delete heuristic;
}
/******************************************************************
Search Engine Administration
******************************************************************/
void Initializer::disableCaching() {
assert(heuristic);
heuristic->disableCaching();
}
void Initializer::initSession() {
assert(heuristic);
heuristic->initSession();
}
void Initializer::initRound() {
assert(heuristic);
heuristic->initRound();
}
void Initializer::finishRound() {
assert(heuristic);
heuristic->finishRound();
}
void Initializer::initStep(State const& current) {
assert(heuristic);
heuristic->initStep(current);
}
void Initializer::finishStep() {
assert(heuristic);
heuristic->finishStep();
}
/******************************************************************
Parameter Setter
******************************************************************/
void Initializer::setHeuristic(SearchEngine* _heuristic) {
if (heuristic) {
delete heuristic;
}
heuristic = _heuristic;
heuristic->prependName("THTS heuristic ");
}
void Initializer::setMaxSearchDepth(int maxSearchDepth) {
assert(heuristic);
heuristic->setMaxSearchDepth(maxSearchDepth);
}
/******************************************************************
Print
******************************************************************/
void Initializer::printConfig(std::string indent) const {
Logger::logLine(indent + "Initializer: " + name, Verbosity::VERBOSE);
indent += " ";
Logger::logLine(indent + "Heuristic weight: " +
std::to_string(heuristicWeight), Verbosity::VERBOSE);
Logger::logLine(indent + "Number of initial visits: " +
std::to_string(numberOfInitialVisits), Verbosity::VERBOSE);
assert(heuristic);
heuristic->printConfig(indent);
}
void Initializer::printStepStatistics(std::string indent) const {
assert(heuristic);
heuristic->printStepStatistics(indent);
}
void Initializer::printRoundStatistics(std::string indent) const {
assert(heuristic);
heuristic->printRoundStatistics(indent);
}
/******************************************************************
ExpandNodeInitializer
******************************************************************/
void ExpandNodeInitializer::initialize(SearchNode* node, State const& current) {
// Logger::logLine("initializing state:", Verbosity::DEBUG);
// Logger::logLine(current.toString(), Verbosity::DEBUG);
assert(node->children.empty());
node->children.resize(SearchEngine::numberOfActions, nullptr);
std::vector<int> actionsToExpand = thts->getApplicableActions(current);
std::vector<double> initialQValues(SearchEngine::numberOfActions,
-std::numeric_limits<double>::max());
heuristic->estimateQValues(current, actionsToExpand, initialQValues);
for (unsigned int index = 0; index < node->children.size(); ++index) {
if (actionsToExpand[index] == index) {
node->children[index] = thts->createChanceNode(1.0);
node->children[index]->futureReward =
heuristicWeight * initialQValues[index];
node->children[index]->numberOfVisits = numberOfInitialVisits;
node->children[index]->initialized = true;
node->numberOfVisits += numberOfInitialVisits;
node->futureReward = std::max(node->futureReward,
node->children[index]->futureReward);
// Logger::logLine("Initialized child " +
// SearchEngine::actionStates[index].toCompactString(),
// Verbosity::DEBUG);
// Logger::logLine(node->children[index]->toString(), Verbosity::DEBUG);
}
}
//Logger::logLine("", Verbosity::DEBUG);
node->initialized = true;
}
/******************************************************************
ExpandNodeInitializer
******************************************************************/
void SingleChildInitializer::initialize(SearchNode* node,
State const& current) {
// Logger::logLine("initializing state: ", Verbosity::DEBUG);
// Logger::logLine(current.toString(), Verbosity::DEBUG);
std::vector<int> candidates;
if (node->children.empty()) {
node->children.resize(SearchEngine::numberOfActions, nullptr);
std::vector<int> actionsToExpand = thts->getApplicableActions(current);
for (unsigned int index = 0; index < node->children.size(); ++index) {
if (actionsToExpand[index] == index) {
node->children[index] = thts->createChanceNode(1.0);
candidates.push_back(index);
}
}
} else {
for (unsigned int index = 0; index < node->children.size(); ++index) {
if (node->children[index] &&
MathUtils::doubleIsMinusInfinity(
node->children[index]->futureReward)) {
candidates.push_back(index);
}
}
}
assert(!candidates.empty());
int actionIndex = MathUtils::rnd->randomElement(candidates);
double initialQValue = 0.0;
heuristic->estimateQValue(current, actionIndex, initialQValue);
node->children[actionIndex]->futureReward = heuristicWeight * initialQValue;
node->children[actionIndex]->numberOfVisits = numberOfInitialVisits;
node->children[actionIndex]->initialized = true;
node->numberOfVisits += numberOfInitialVisits;
node->futureReward =
std::max(node->futureReward, node->children[actionIndex]->futureReward);
node->initialized = (candidates.size() == 1);
// Logger::logLine("Initialized child " +
// SearchEngine::actionStates[actionIndex].toCompactString(),
// Verbosity::DEBUG);
// Logger::logLine(node->children[actionIndex]->toString(), Verbosity::DEBUG);
}
| 33.905983 | 84 | 0.555079 | [
"vector"
] |
f34fa203aae4ae6bfe938badacd8485495097ef3 | 51,635 | cpp | C++ | src/test/applications/circuit_preprocessor_test.cpp | juanmanzanero/fastest-lap | e278dd2fd0f9fa30a613b87c5155c5d375f8da69 | [
"MIT"
] | 28 | 2021-11-26T16:03:33.000Z | 2022-02-21T13:51:58.000Z | src/test/applications/circuit_preprocessor_test.cpp | juanmanzanero/fastest-lap | e278dd2fd0f9fa30a613b87c5155c5d375f8da69 | [
"MIT"
] | 1 | 2022-03-01T17:10:39.000Z | 2022-03-01T17:10:39.000Z | src/test/applications/circuit_preprocessor_test.cpp | juanmanzanero/fastest-lap | e278dd2fd0f9fa30a613b87c5155c5d375f8da69 | [
"MIT"
] | 1 | 2022-02-28T12:21:04.000Z | 2022-02-28T12:21:04.000Z | #include "src/core/applications/circuit_preprocessor.h"
#include "gtest/gtest.h"
extern bool is_valgrind;
/*
TEST(Circuit_preprocessor_test, miami_2000)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/miami/miami_left.kml", true);
Xml_document coord_right_kml("./database/tracks/miami/miami_right.kml", true);
Circuit_preprocessor::Options opts;
opts.print_level = 5;
opts.eps_c *= 5.0;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, 2000);
circuit.xml()->save("miami_2000.xml");
Xml_document solution_saved("./database/tracks/miami/miami_1000.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,700);
EXPECT_EQ(circuit.r_centerline.size(),700);
EXPECT_EQ(circuit.theta.size(),700);
EXPECT_EQ(circuit.kappa.size(),700);
EXPECT_EQ(circuit.nl.size(),700);
EXPECT_EQ(circuit.nr.size(),700);
EXPECT_EQ(circuit.dkappa.size(),700);
EXPECT_EQ(circuit.dnl.size(),700);
EXPECT_EQ(circuit.dnr.size(),700);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
*/
TEST(Circuit_preprocessor_test, museo_closed)
{
Xml_document coord_left_kml("./database/tracks/fa_museo/Museo_short_left.kml", true);
Xml_document coord_right_kml("./database/tracks/fa_museo/Museo_short_right.kml", true);
Circuit_preprocessor::Options options;
options.eps_k *= 0.001;
options.eps_n *= 0.001;
options.eps_c *= 0.001;
options.eps_d *= 0.001;
options.maximum_kappa = 1.0;
options.maximum_dkappa = 1.0;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, options, 100);
// Call the xml() method, just to confirm there are no errors/valgrind issues
circuit.xml();
Xml_document solution_saved("./data/museo_short_discrete.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,100);
EXPECT_EQ(circuit.r_centerline.size(),100);
EXPECT_EQ(circuit.theta.size(),100);
EXPECT_EQ(circuit.kappa.size(),100);
EXPECT_EQ(circuit.nl.size(),100);
EXPECT_EQ(circuit.nr.size(),100);
EXPECT_EQ(circuit.dkappa.size(),100);
EXPECT_EQ(circuit.dnl.size(),100);
EXPECT_EQ(circuit.dnr.size(),100);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_chicane)
{
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
Circuit_preprocessor::Coordinates start = {2.261, 41.57455};
Circuit_preprocessor::Coordinates finish = {2.26325, 41.57385};
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, start, finish, 20);
circuit.xml();
Xml_document solution_saved("./data/catalunya_chicane_discrete.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,21);
EXPECT_EQ(circuit.r_centerline.size(),21);
EXPECT_EQ(circuit.theta.size(),21);
EXPECT_EQ(circuit.kappa.size(),21);
EXPECT_EQ(circuit.nl.size(),21);
EXPECT_EQ(circuit.nr.size(),21);
EXPECT_EQ(circuit.dkappa.size(),21);
EXPECT_EQ(circuit.dnl.size(),21);
EXPECT_EQ(circuit.dnr.size(),21);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
}
TEST(Circuit_preprocessor_test, melbourne_700)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/melbourne/melbourne_left.kml", true);
Xml_document coord_right_kml("./database/tracks/melbourne/melbourne_right.kml", true);
Circuit_preprocessor::Options opts;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, 700);
circuit.xml();
Xml_document solution_saved("./database/tracks/melbourne/melbourne_700.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,700);
EXPECT_EQ(circuit.r_centerline.size(),700);
EXPECT_EQ(circuit.theta.size(),700);
EXPECT_EQ(circuit.kappa.size(),700);
EXPECT_EQ(circuit.nl.size(),700);
EXPECT_EQ(circuit.nr.size(),700);
EXPECT_EQ(circuit.dkappa.size(),700);
EXPECT_EQ(circuit.dnl.size(),700);
EXPECT_EQ(circuit.dnr.size(),700);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, melbourne_adapted)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/melbourne/melbourne_left.kml", true);
Xml_document coord_right_kml("./database/tracks/melbourne/melbourne_right.kml", true);
std::vector<scalar> s_bkp = {0.0000000000000000, 215.6155437858050732, 225.6155437858050732, 426.1900513192233007, 436.1900513192233007, 930.0647657741851617, 940.0647657741851617, 1291.0496358314749159, 1301.0496358314749159, 1749.8012415292823789, 1759.8012415292823789, 1975.4167853150893279, 1985.4167853150893279, 3171.1791673798661577, 3181.1791673798661577, 3562.2461099419315360, 3572.2461099419315360, 3945.7925343778033493, 3955.7925343778033493, 4178.9285962898038633, 4188.9285962898038633, 4276.6953319303202079, 4286.6953319303202079, 4690.3238288709662811, 4700.3238288709662811 };
std::vector<scalar> ds_bkp = {14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000, 14.0000000000000000, 6.0000000000000000, 6.0000000000000000, 14.0000000000000000};
Circuit_preprocessor::Options opts;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, s_bkp, ds_bkp);
circuit.xml();
Xml_document solution_saved("./database/tracks/melbourne/melbourne_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,545);
EXPECT_EQ(circuit.r_centerline.size(),545);
EXPECT_EQ(circuit.theta.size(),545);
EXPECT_EQ(circuit.kappa.size(),545);
EXPECT_EQ(circuit.nl.size(),545);
EXPECT_EQ(circuit.nr.size(),545);
EXPECT_EQ(circuit.dkappa.size(),545);
EXPECT_EQ(circuit.dnl.size(),545);
EXPECT_EQ(circuit.dnr.size(),545);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_500)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, 500);
circuit.xml();
Xml_document solution_saved("./database/tracks/catalunya/catalunya_discrete.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,500);
EXPECT_EQ(circuit.r_centerline.size(),500);
EXPECT_EQ(circuit.theta.size(),500);
EXPECT_EQ(circuit.kappa.size(),500);
EXPECT_EQ(circuit.nl.size(),500);
EXPECT_EQ(circuit.nr.size(),500);
EXPECT_EQ(circuit.dkappa.size(),500);
EXPECT_EQ(circuit.dnl.size(),500);
EXPECT_EQ(circuit.dnr.size(),500);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_adapted_by_coords)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
std::vector<std::pair<Circuit_preprocessor::Coordinates,scalar>> ds_breakpoints =
{ {{0.0, 0.0 }, 20.0},
{{2.257193719176818,41.56522599658208}, 8.0},
{{2.254933238159729,41.56471245384411}, 10.0},
{{2.253853158059371,41.56800644695232}, 8.0},
{{2.2547819299335, 41.56663345239372}, 10.0},
{{2.261124403684718,41.57244119725051}, 5.0},
{{2.260173022232699,41.57444062293845}, 3.0},
{{2.263173649148178,41.57388038009333}, 10.0}
};
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, ds_breakpoints);
circuit.xml();
Xml_document solution_saved("./data/catalunya_adapted_by_coords.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,555);
EXPECT_EQ(circuit.r_centerline.size(),555);
EXPECT_EQ(circuit.theta.size(),555);
EXPECT_EQ(circuit.kappa.size(),555);
EXPECT_EQ(circuit.nl.size(),555);
EXPECT_EQ(circuit.nr.size(),555);
EXPECT_EQ(circuit.dkappa.size(),555);
EXPECT_EQ(circuit.dnl.size(),555);
EXPECT_EQ(circuit.dnr.size(),555);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_adapted_by_ds_distribution)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya/Catalunya_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya/Catalunya_right.kml", true);
std::vector<scalar> s_distr = {0.0};
while (s_distr.back() < 4633.0 )
s_distr.push_back(s_distr.back() + 4.5);
std::vector<scalar> ds_distr(s_distr.size());
for (size_t i = 0; i < s_distr.size(); ++i)
{
ds_distr[i] = 9.0;
if (s_distr[i] > 950.0 && s_distr[i] < 1200.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 1150.0 && s_distr[i] < 1418.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 3633.17 && s_distr[i] < 3850.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 4050.0 && s_distr[i] < 4430.0)
ds_distr[i] = 2.5;
}
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, s_distr, ds_distr);
circuit.xml();
Xml_document solution_saved("./database/tracks/catalunya/catalunya_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,697);
EXPECT_EQ(circuit.r_centerline.size(),697);
EXPECT_EQ(circuit.theta.size(),697);
EXPECT_EQ(circuit.kappa.size(),697);
EXPECT_EQ(circuit.nl.size(),697);
EXPECT_EQ(circuit.nr.size(),697);
EXPECT_EQ(circuit.dkappa.size(),697);
EXPECT_EQ(circuit.dnl.size(),697);
EXPECT_EQ(circuit.dnr.size(),697);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, vendrell)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/vendrell/vendrell_left.kml", true);
Xml_document coord_right_kml("./database/tracks/vendrell/vendrell_right.kml", true);
Circuit_preprocessor::Options options;
options.eps_k *= 0.0002;
options.eps_n *= 0.001;
options.eps_c *= 0.001;
options.eps_d *= 0.001;
options.maximum_distance_find = 70.0;
options.maximum_kappa = 4.0;
options.maximum_dkappa = 4.0;
options.maximum_dn = 2.0;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, options, 500);
// Call the xml() method, just to confirm there are no errors/valgrind issues
circuit.xml();
Xml_document solution_saved("./database/tracks/vendrell/vendrell.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,500);
EXPECT_EQ(circuit.r_centerline.size(),500);
EXPECT_EQ(circuit.theta.size(),500);
EXPECT_EQ(circuit.kappa.size(),500);
EXPECT_EQ(circuit.nl.size(),500);
EXPECT_EQ(circuit.nr.size(),500);
EXPECT_EQ(circuit.dkappa.size(),500);
EXPECT_EQ(circuit.dnl.size(),500);
EXPECT_EQ(circuit.dnr.size(),500);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, imola_adapted)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/imola/imola_left.kml", true);
Xml_document coord_right_kml("./database/tracks/imola/imola_right.kml", true);
std::vector<scalar> s_bkp = { 0.0, 2650.0, 2660.0, 2950.0, 2960.0, 3300.0, 3310.0, 3450.0, 3460.0, 7000.0};
std::vector<scalar> ds_bkp = { 8.0, 8.0, 6.0, 6.0, 8.0, 8.0, 4.0, 4.0, 8.0, 8.0};
Circuit_preprocessor::Options opts;
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, opts, s_bkp, ds_bkp);
circuit.xml();
Xml_document solution_saved("./database/tracks/imola/imola_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,643);
EXPECT_EQ(circuit.r_centerline.size(),643);
EXPECT_EQ(circuit.theta.size(),643);
EXPECT_EQ(circuit.kappa.size(),643);
EXPECT_EQ(circuit.nl.size(),643);
EXPECT_EQ(circuit.nr.size(),643);
EXPECT_EQ(circuit.dkappa.size(),643);
EXPECT_EQ(circuit.dnl.size(),643);
EXPECT_EQ(circuit.dnr.size(),643);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
TEST(Circuit_preprocessor_test, catalunya_2022_adapted)
{
#ifndef NDEBUG
GTEST_SKIP();
#endif
if ( is_valgrind ) GTEST_SKIP();
Xml_document coord_left_kml("./database/tracks/catalunya_2022/catalunya_2022_left.kml", true);
Xml_document coord_right_kml("./database/tracks/catalunya_2022/catalunya_2022_right.kml", true);
std::vector<scalar> s_distr = {0.0};
while (s_distr.back() < 5000.0 )
s_distr.push_back(s_distr.back() + 4.5);
std::vector<scalar> ds_distr(s_distr.size());
for (size_t i = 0; i < s_distr.size(); ++i)
{
ds_distr[i] = 9.0;
if (s_distr[i] > 950.0 && s_distr[i] < 1200.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 1150.0 && s_distr[i] < 1418.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 3633.17 && s_distr[i] < 3850.0)
ds_distr[i] = 4.5;
if (s_distr[i] > 4050.0 && s_distr[i] < 4430.0)
ds_distr[i] = 2.5;
}
Circuit_preprocessor circuit(coord_left_kml, coord_right_kml, {}, s_distr, ds_distr);
circuit.xml();
Xml_document solution_saved("./database/tracks/catalunya_2022/catalunya_2022_adapted.xml", true);
const std::vector<scalar> s = solution_saved.get_element("circuit/data/arclength").get_value(std::vector<scalar>());
const std::vector<scalar> x = solution_saved.get_element("circuit/data/centerline/x").get_value(std::vector<scalar>());
const std::vector<scalar> y = solution_saved.get_element("circuit/data/centerline/y").get_value(std::vector<scalar>());
const std::vector<scalar> theta = solution_saved.get_element("circuit/data/theta").get_value(std::vector<scalar>());
const std::vector<scalar> kappa = solution_saved.get_element("circuit/data/kappa").get_value(std::vector<scalar>());
const std::vector<scalar> nl = solution_saved.get_element("circuit/data/nl").get_value(std::vector<scalar>());
const std::vector<scalar> nr = solution_saved.get_element("circuit/data/nr").get_value(std::vector<scalar>());
const std::vector<scalar> dkappa = solution_saved.get_element("circuit/data/dkappa").get_value(std::vector<scalar>());
const std::vector<scalar> dnl = solution_saved.get_element("circuit/data/dnl").get_value(std::vector<scalar>());
const std::vector<scalar> dnr = solution_saved.get_element("circuit/data/dnr").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.n_points,700);
EXPECT_EQ(circuit.r_centerline.size(),700);
EXPECT_EQ(circuit.theta.size(),700);
EXPECT_EQ(circuit.kappa.size(),700);
EXPECT_EQ(circuit.nl.size(),700);
EXPECT_EQ(circuit.nr.size(),700);
EXPECT_EQ(circuit.dkappa.size(),700);
EXPECT_EQ(circuit.dnl.size(),700);
EXPECT_EQ(circuit.dnr.size(),700);
// compare centerline
for (size_t i = 0; i < circuit.n_points; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i].x(), x[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.r_centerline[i].y(), y[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.theta[i] , theta[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.kappa[i] , kappa[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nl[i] , nl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.nr[i] , nr[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dkappa[i] , dkappa[i], 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnl[i] , dnl[i] , 1.0e-8) << " with i = " << i;
EXPECT_NEAR(circuit.dnr[i] , dnr[i] , 1.0e-8) << " with i = " << i;
}
for (size_t i = 0; i < circuit.n_points-1; ++i)
{
EXPECT_NEAR(circuit.r_centerline[i+1].x()-circuit.r_centerline[i].x(),
(circuit.s[i+1]-circuit.s[i])*0.5*(cos(circuit.theta[i])+cos(circuit.theta[i+1])), 1.0e-7);
EXPECT_NEAR(circuit.r_centerline[i+1].y()-circuit.r_centerline[i].y(),
(circuit.s[i+1]-circuit.s[i])*0.5*(sin(circuit.theta[i])+sin(circuit.theta[i+1])), 1.0e-7);
}
// Check that the reference coordinates are recovered
std::vector<scalar> coord_left = coord_left_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
std::vector<scalar> coord_right = coord_right_kml.get_element("kml/Document/Placemark/LineString/coordinates").get_value(std::vector<scalar>());
EXPECT_EQ(circuit.r_left_measured.size()*3, coord_left.size());
EXPECT_EQ(circuit.r_right_measured.size()*3, coord_right.size());
scalar theta0 = coord_right[0];
scalar phi0 = coord_right[1];
for (size_t i = 0; i < circuit.r_left_measured.size(); ++i)
{
scalar lon = coord_left[3*i];
scalar lat = coord_left[3*i+1];
EXPECT_DOUBLE_EQ(lon, circuit.r_left_measured[i].x()/(circuit.R_earth*cos(phi0*DEG))*RAD + theta0);
EXPECT_DOUBLE_EQ(lat, circuit.r_left_measured[i].y()/(circuit.R_earth)*RAD + phi0);
}
}
| 52.635066 | 679 | 0.638346 | [
"vector"
] |
f35048fa2f6571033967ae28dfb389e8de1e7794 | 19,279 | cpp | C++ | com/win32comext/axdebug/src/PyIRemoteDebugApplication.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | 3 | 2020-06-18T16:57:44.000Z | 2020-07-21T17:52:06.000Z | com/win32comext/axdebug/src/PyIRemoteDebugApplication.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | com/win32comext/axdebug/src/PyIRemoteDebugApplication.cpp | huanyin88/Mod-Pywin32-For-Python3.x-DDE | 992931aa534357d54aaac34077f0128d3a740e5e | [
"Apache-2.0"
] | null | null | null | // This file implements the IRemoteDebugApplication Interface and Gateway for Python.
// Generated by makegw.py
#include "stdafx.h"
#include "PyIRemoteDebugApplication.h"
// @doc - This file contains autoduck documentation
// ---------------------------------------------------
//
// Interface Implementation
PyIRemoteDebugApplication::PyIRemoteDebugApplication(IUnknown *pdisp) : PyIUnknown(pdisp) { ob_type = &type; }
PyIRemoteDebugApplication::~PyIRemoteDebugApplication() {}
/* static */ IRemoteDebugApplication *PyIRemoteDebugApplication::GetI(PyObject *self)
{
return (IRemoteDebugApplication *)PyIUnknown::GetI(self);
}
// @pymethod |PyIRemoteDebugApplication|ResumeFromBreakPoint|Continue an application which is currently in a breakpoint.
PyObject *PyIRemoteDebugApplication::ResumeFromBreakPoint(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
// @pyparm <o PyIRemoteDebugApplicationThread>|prptFocus||Description for prptFocus
// @pyparm int|bra||Break resume action
// @pyparm int|era||Error resume action
PyObject *obprptFocus;
BREAKRESUMEACTION bra;
ERRORRESUMEACTION era;
if (!PyArg_ParseTuple(args, "Oii:ResumeFromBreakPoint", &obprptFocus, &bra, &era))
return NULL;
IRemoteDebugApplicationThread *prptFocus;
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obprptFocus, IID_IRemoteDebugApplicationThread, (void **)&prptFocus,
FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->ResumeFromBreakPoint(prptFocus, bra, era);
prptFocus->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |PyIRemoteDebugApplication|CauseBreak|Causes the application to break into the debugger at the earliest
// opportunity.
PyObject *PyIRemoteDebugApplication::CauseBreak(PyObject *self, PyObject *args)
{
// @comm Note that a long time may elapse before the application actually breaks, particularly if
// the application is not currently executing script code.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":CauseBreak"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->CauseBreak();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |PyIRemoteDebugApplication|ConnectDebugger|Connects a debugger to the application.
PyObject *PyIRemoteDebugApplication::ConnectDebugger(PyObject *self, PyObject *args)
{
// @comm Only one debugger may be connected at a
// time; this method fails if there is already a debugger connected.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
// @pyparm <o PyIApplicationDebugger>|pad||Description for pad
PyObject *obpad;
if (!PyArg_ParseTuple(args, "O:ConnectDebugger", &obpad))
return NULL;
IApplicationDebugger *pad;
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obpad, IID_IApplicationDebugger, (void **)&pad, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->ConnectDebugger(pad);
pad->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |PyIRemoteDebugApplication|DisconnectDebugger|Disconnects the current debugger from the application.
PyObject *PyIRemoteDebugApplication::DisconnectDebugger(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":DisconnectDebugger"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->DisconnectDebugger();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyIApplicationDebugger>|PyIRemoteDebugApplication|GetDebugger|Returns the current debugger connected to
// the application.
PyObject *PyIRemoteDebugApplication::GetDebugger(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":GetDebugger"))
return NULL;
IApplicationDebugger *pad;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->GetDebugger(&pad);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(pad, IID_IApplicationDebugger, FALSE);
}
// @pymethod <o PyIUnknown>|PyIRemoteDebugApplication|CreateInstanceAtApplication|Create objects in the application
// process address space.
PyObject *PyIRemoteDebugApplication::CreateInstanceAtApplication(PyObject *self, PyObject *args)
{
// @comm Provides a mechanism for the debugger IDE, running out-of-process to the
// application, to create objects in the application process.
// This method simply delegates to CoCreateInstance.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
// @pyparm <o PyIID>|rclsid||Description for rclsid
// @pyparm <o PyIUnknown>|pUnkOuter||Description for pUnkOuter
// @pyparm int|dwClsContext||Description for dwClsContext
// @pyparm <o PyIID>|riid||Description for riid
PyObject *obrclsid;
PyObject *obpUnkOuter;
DWORD dwClsContext;
PyObject *obriid;
if (!PyArg_ParseTuple(args, "OOiO:CreateInstanceAtApplication", &obrclsid, &obpUnkOuter, &dwClsContext, &obriid))
return NULL;
IID rclsid;
IUnknown *pUnkOuter;
IID riid;
IUnknown *ppvObject;
BOOL bPythonIsHappy = TRUE;
if (!PyWinObject_AsIID(obrclsid, &rclsid))
bPythonIsHappy = FALSE;
if (!PyWinObject_AsIID(obriid, &riid))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
if (!PyCom_InterfaceFromPyInstanceOrObject(obpUnkOuter, IID_IUnknown, (void **)&pUnkOuter, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->CreateInstanceAtApplication(rclsid, pUnkOuter, dwClsContext, riid, &ppvObject);
pUnkOuter->Release();
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(ppvObject, IID_IUnknown, FALSE);
}
// @pymethod |PyIRemoteDebugApplication|QueryAlive|Returns True if alive, else False.
PyObject *PyIRemoteDebugApplication::QueryAlive(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":QueryAlive"))
return NULL;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->QueryAlive();
PY_INTERFACE_POSTCALL;
return PyInt_FromLong(hr == S_OK);
}
// @pymethod <o PyIEnumRemoteDebugApplicationThreads>|PyIRemoteDebugApplication|EnumThreads|Enumerates all threads known
// to be associated with the application.
PyObject *PyIRemoteDebugApplication::EnumThreads(PyObject *self, PyObject *args)
{
// @comm New threads may be added at any time.
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":EnumThreads"))
return NULL;
IEnumRemoteDebugApplicationThreads *perdat;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->EnumThreads(&perdat);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(perdat, IID_IEnumRemoteDebugApplicationThreads, FALSE);
}
// @pymethod |PyIRemoteDebugApplication|GetName|Description of GetName.
PyObject *PyIRemoteDebugApplication::GetName(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":GetName"))
return NULL;
BSTR pbstrName;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->GetName(&pbstrName);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
PyObject *obpbstrName = MakeBstrToObj(pbstrName);
PyObject *pyretval = Py_BuildValue("O", obpbstrName);
Py_XDECREF(obpbstrName);
SysFreeString(pbstrName);
return pyretval;
}
// @pymethod <o PyIDebugApplicationNode>|PyIRemoteDebugApplication|GetRootNode|Returns the application node under which
// all nodes associated with the application are added.
PyObject *PyIRemoteDebugApplication::GetRootNode(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":GetRootNode"))
return NULL;
IDebugApplicationNode *pNode;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->GetRootNode(&pNode);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(pNode, IID_IDebugApplicationNode, FALSE);
}
// @pymethod <o IEnumDebugExpressionContexts>|PyIRemoteDebugApplication|EnumGlobalExpressionContexts|Enumerates all
// global expression contexts
PyObject *PyIRemoteDebugApplication::EnumGlobalExpressionContexts(PyObject *self, PyObject *args)
{
IRemoteDebugApplication *pIRDA = GetI(self);
if (pIRDA == NULL)
return NULL;
if (!PyArg_ParseTuple(args, ":EnumGlobalExpressionContexts"))
return NULL;
IEnumDebugExpressionContexts *perdat;
PY_INTERFACE_PRECALL;
HRESULT hr = pIRDA->EnumGlobalExpressionContexts(&perdat);
PY_INTERFACE_POSTCALL;
if (FAILED(hr))
return SetPythonCOMError(self, hr);
return PyCom_PyObjectFromIUnknown(perdat, IID_IEnumDebugExpressionContexts, FALSE);
}
// @object PyIRemoteDebugApplication|Description of the interface
static struct PyMethodDef PyIRemoteDebugApplication_methods[] = {
{"ResumeFromBreakPoint", PyIRemoteDebugApplication::ResumeFromBreakPoint,
1}, // @pymeth ResumeFromBreakPoint|Continue an application which is currently in a breakpoint.
{"CauseBreak", PyIRemoteDebugApplication::CauseBreak,
1}, // @pymeth CauseBreak|Causes the application to break into the debugger at the earliest opportunity.
{"ConnectDebugger", PyIRemoteDebugApplication::ConnectDebugger,
1}, // @pymeth ConnectDebugger|Connects a debugger to the application.
{"DisconnectDebugger", PyIRemoteDebugApplication::DisconnectDebugger,
1}, // @pymeth DisconnectDebugger|Disconnects the current debugger from the application.
{"GetDebugger", PyIRemoteDebugApplication::GetDebugger,
1}, // @pymeth GetDebugger|Returns the current debugger connected to the application.
{"CreateInstanceAtApplication", PyIRemoteDebugApplication::CreateInstanceAtApplication,
1}, // @pymeth CreateInstanceAtApplication|Create objects in the application process address space.
{"QueryAlive", PyIRemoteDebugApplication::QueryAlive,
1}, // @pymeth QueryAlive|Indicates if the application is alive.
{"EnumThreads", PyIRemoteDebugApplication::EnumThreads,
1}, // @pymeth EnumThreads|Enumerates all threads known to be associated with the application.
{"GetName", PyIRemoteDebugApplication::GetName, 1}, // @pymeth GetName|Description of GetName
{"GetRootNode", PyIRemoteDebugApplication::GetRootNode,
1}, // @pymeth GetRootNode|Returns the application node under which all nodes associated with the application are
// added.
{"EnumGlobalExpressionContexts", PyIRemoteDebugApplication::EnumGlobalExpressionContexts,
1}, // @pymeth EnumGlobalExpressionContexts|Enumerates all global expression contexts.
{NULL}};
PyComTypeObject PyIRemoteDebugApplication::type("PyIRemoteDebugApplication", &PyIUnknown::type,
sizeof(PyIRemoteDebugApplication), PyIRemoteDebugApplication_methods,
GET_PYCOM_CTOR(PyIRemoteDebugApplication));
// ---------------------------------------------------
//
// Gateway Implementation
STDMETHODIMP PyGRemoteDebugApplication::ResumeFromBreakPoint(
/* [in] */ IRemoteDebugApplicationThread __RPC_FAR *prptFocus,
/* [in] */ BREAKRESUMEACTION bra,
/* [in] */ ERRORRESUMEACTION era)
{
PY_GATEWAY_METHOD;
PyObject *obprptFocus = PyCom_PyObjectFromIUnknown(prptFocus, IID_IRemoteDebugApplicationThread, TRUE);
HRESULT hr = InvokeViaPolicy("ResumeFromBreakPoint", NULL, "Oii", obprptFocus, bra, era);
Py_XDECREF(obprptFocus);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::CauseBreak(void)
{
PY_GATEWAY_METHOD;
HRESULT hr = InvokeViaPolicy("CauseBreak", NULL);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::ConnectDebugger(
/* [in] */ IApplicationDebugger __RPC_FAR *pad)
{
PY_GATEWAY_METHOD;
PyObject *obpad = PyCom_PyObjectFromIUnknown(pad, IID_IApplicationDebugger, TRUE);
HRESULT hr = InvokeViaPolicy("ConnectDebugger", NULL, "O", obpad);
Py_XDECREF(obpad);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::DisconnectDebugger(void)
{
PY_GATEWAY_METHOD;
HRESULT hr = InvokeViaPolicy("DisconnectDebugger", NULL);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::GetDebugger(
/* [out] */ IApplicationDebugger __RPC_FAR *__RPC_FAR *pad)
{
PY_GATEWAY_METHOD;
if (pad == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetDebugger", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obpad;
if (!PyArg_Parse(result, "O", &obpad))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obpad, IID_IApplicationDebugger, (void **)pad, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::CreateInstanceAtApplication(
/* [in] */ REFCLSID rclsid,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DWORD dwClsContext,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppvObject)
{
PY_GATEWAY_METHOD;
if (ppvObject == NULL)
return E_POINTER;
PyObject *obrclsid = PyWinObject_FromIID(rclsid);
PyObject *obpUnkOuter = PyCom_PyObjectFromIUnknown(pUnkOuter, IID_IUnknown, TRUE);
PyObject *obriid = PyWinObject_FromIID(riid);
PyObject *result;
HRESULT hr =
InvokeViaPolicy("CreateInstanceAtApplication", &result, "OOiO", obrclsid, obpUnkOuter, dwClsContext, obriid);
Py_XDECREF(obrclsid);
Py_XDECREF(obpUnkOuter);
Py_XDECREF(obriid);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obppvObject;
if (!PyArg_Parse(result, "O", &obppvObject))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obppvObject, IID_IUnknown, (void **)ppvObject, FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::EnumThreads(IEnumRemoteDebugApplicationThreads __RPC_FAR *__RPC_FAR *pperdat)
{
PY_GATEWAY_METHOD;
if (pperdat == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("EnumThreads", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *oberdat;
if (!PyArg_Parse(result, "O", &oberdat))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(oberdat, IID_IEnumRemoteDebugApplicationThreads, (void **)pperdat,
FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::QueryAlive(void)
{
PY_GATEWAY_METHOD;
HRESULT hr = InvokeViaPolicy("QueryAlive", NULL);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::GetName(
/* [out] */ BSTR __RPC_FAR *pbstrName)
{
PY_GATEWAY_METHOD;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetName", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obpbstrName;
if (!PyArg_Parse(result, "O", &obpbstrName))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_BstrFromPyObject(obpbstrName, pbstrName))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::GetRootNode(IDebugApplicationNode __RPC_FAR *__RPC_FAR *ppdanRoot)
{
PY_GATEWAY_METHOD;
if (ppdanRoot == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("GetRootNode", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *obnode;
if (!PyArg_Parse(result, "O", &obnode))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(obnode, IID_IDebugApplicationNode, (void **)ppdanRoot,
FALSE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
STDMETHODIMP PyGRemoteDebugApplication::EnumGlobalExpressionContexts(
IEnumDebugExpressionContexts __RPC_FAR *__RPC_FAR *ppedec)
{
PY_GATEWAY_METHOD;
if (ppedec == NULL)
return E_POINTER;
PyObject *result;
HRESULT hr = InvokeViaPolicy("EnumGlobalExpressionContexts", &result);
if (FAILED(hr))
return hr;
// Process the Python results, and convert back to the real params
PyObject *oberdat;
if (!PyArg_Parse(result, "O", &oberdat))
return PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
BOOL bPythonIsHappy = TRUE;
if (!PyCom_InterfaceFromPyInstanceOrObject(oberdat, IID_IEnumDebugExpressionContexts, (void **)ppedec,
TRUE /* bNoneOK */))
bPythonIsHappy = FALSE;
if (!bPythonIsHappy)
hr = PyCom_HandlePythonFailureToCOM(/*pexcepinfo*/);
Py_DECREF(result);
return hr;
}
| 39.026316 | 120 | 0.708906 | [
"object"
] |
f35093bed2c8c7306f83bce4481b9962deb5acc4 | 16,620 | cpp | C++ | ROVER/src/manager/accel_manager.cpp | majitaki/arliss2019_tadpole | 22c2f976dfb91d345a6be878a45bcd361247943b | [
"MIT"
] | null | null | null | ROVER/src/manager/accel_manager.cpp | majitaki/arliss2019_tadpole | 22c2f976dfb91d345a6be878a45bcd361247943b | [
"MIT"
] | null | null | null | ROVER/src/manager/accel_manager.cpp | majitaki/arliss2019_tadpole | 22c2f976dfb91d345a6be878a45bcd361247943b | [
"MIT"
] | null | null | null | #include <wiringPiI2C.h>
#include <wiringPi.h>
#include <time.h>
#include <string.h>
#include <fstream>
#include <sstream>
#include <unistd.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdarg.h>
#include <wiringSerial.h>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <vector>
#include "../rover_util/utils.h"
#include "../sensor/nineaxis.h"
#include "accel_manager.h"
#include "accel_mangaer_constanth.h"
AccelManager gAccelManager;
bool AccelManager::onInit(const struct timespec& time)
{
gNineAxisSensor.setRunMode(true);
mLastUpdateTime = time;
isTryNineaxis = false;
mAccelSamples.clear();
return true;
}
void AccelManager::onClean()
{
}
void AccelManager::onUpdate(const timespec & time)
{
double dt = Time::dt(time, mLastUpdateTime);
if (dt < ACCELMANAGER_UPDATE_INTERVAL_TIME)return;
mLastUpdateTime = time;
if (!gNineAxisSensor.isActive())
{
if (isTryNineaxis)
{
setRunMode(false);
return;
}
gNineAxisSensor.setRunMode(true);
isTryNineaxis = true;
}
UpdateMadgwickQuaternion(dt, getAx(), getAy(), getAz(), getGx()*M_PI / 180.0f, getGy()*M_PI / 180.0f, getGz()*M_PI / 180.0f, getMx(), getMy(), getMz());
//UpdateMahonyQuaternion(dt, getAx(), getAy(), getAz(), getGx()*M_PI / 180.0f, getGy()*M_PI / 180.0f, getGz()*M_PI / 180.0f, getMx(), getMy(), getMz());
if (!isSensorView) return;
printInfo();
}
bool AccelManager::onCommand(const std::vector<std::string>& args)
{
if (args[0].compare(getName()) != 0) return true;
switch (args.size())
{
case 1:
Debug::print(LOG_PRINT,
"\r\n\
accel calibmagnet : calibrate magnet. Do 8 circle!\r\n\
accel view : sensor view \r\n\n\
");
printInfo();
printCalibInfo();
return true;
case 2:
if (args[1].compare("calibmagnet") == 0)
{
calibrationMagnet(MAGNET_CALIBRATION_SAMPLES);
Debug::print(LOG_PRINT, "Magnet OFFSET POS X:%f, Y:%f, Z:%f\r\n", mOffsetMagnetX, mOffsetMagnetY, mOffsetMagnetZ);
Debug::print(LOG_PRINT, "Magnet OFFSET SCALE X:%f, Y:%f, Z:%f\r\n", mScaleMagnetX, mScaleMagnetY, mScaleMagnetZ);
}
else if (args[1].compare("view") == 0)
{
isSensorView = !isSensorView;
}
return true;
default:
return true;
}
}
void AccelManager::printInfo()
{
Debug::print(LOG_PRINT, "Accel %3.3f %3.3f %3.3f\r\n", getAx(), getAy(), getAz());
Debug::print(LOG_PRINT, "Gyro %3.3f %3.3f %3.3f\r\n", getGx(), getGy(), getGz());
Debug::print(LOG_PRINT, "Magnet %3.3f %3.3f %3.3f\r\n", getMx(), getMy(), getMz());
Debug::print(LOG_PRINT, "Magnet Angle %3.3f %3.3f %3.3f\r\n", getMx(), getMy(), getMz());
Debug::print(LOG_PRINT, "Roll, Pitch, Yaw %3.3f %3.3f %3.3f\r\n", getRoll(), getPitch(), getYaw());
Debug::print(LOG_PRINT, "Azimuth(deg) %3.3f\r\n", getRawMagnetDirection());
//Debug::print(LOG_PRINT, "Sx, Sy, Sz %3.3f %3.3f %3.3f\r\n", getSx(), getSy(), getSz());
Debug::print(LOG_PRINT, "Turn Side, Turn Back %s %s \r\n", isTurnSide() ? "true" : "false", isTurnBack() ? "true" : "false");
}
void AccelManager::printCalibInfo()
{
Debug::print(LOG_PRINT, "Calibration Magnet POS X:%3.3f, Y:%3.3f, Z:%3.3f\r\n", mOffsetMagnetX, mOffsetMagnetY, mOffsetMagnetZ);
Debug::print(LOG_PRINT, "Calibration Magnet SCALE X:%3.3f, Y:%3.3f, Z:%3.3f\r\n", mScaleMagnetX, mScaleMagnetY, mScaleMagnetZ);
}
bool AccelManager::isTurnSide()
{
float roll = abs(getRoll());
return (roll > 90 - TURN_SIDE_THRESHOLD && roll < 90 + TURN_SIDE_THRESHOLD);
}
bool AccelManager::isTurnBack()
{
float roll = abs(getRoll());
return (roll > 180 - TURN_BACK_THRESHOLD && roll < 180 + TURN_BACK_THRESHOLD);
}
VECTOR3 AccelManager::getVectorAccel() const
{
return VECTOR3();
}
double AccelManager::getAx() const
{
return gNineAxisSensor.getAccel().x;
}
double AccelManager::getAy() const
{
return gNineAxisSensor.getAccel().y;
}
double AccelManager::getAz() const
{
return gNineAxisSensor.getAccel().z;
}
VECTOR3 AccelManager::getVectorGyro() const
{
return VECTOR3();
}
double AccelManager::getGx() const
{
return gNineAxisSensor.getGyro().x;
}
double AccelManager::getGy() const
{
return gNineAxisSensor.getGyro().y;
}
double AccelManager::getGz() const
{
return gNineAxisSensor.getGyro().z;
}
void AccelManager::calibrationMagnet(int calib_magnet_samples)
{
std::vector<VECTOR3> magnet_samples;
for (; magnet_samples.size() < calib_magnet_samples;)
{
magnet_samples.push_back(gNineAxisSensor.getMagnet());
Debug::print(LOG_SUMMARY, "Calib Progres %d / %d\r\n", magnet_samples.size(), calib_magnet_samples);
delay(10);
}
std::vector<double> magnet_vector_x;
std::vector<double> magnet_vector_y;
std::vector<double> magnet_vector_z;
for (VECTOR3 sample : magnet_samples)
{
magnet_vector_x.push_back(sample.x);
magnet_vector_y.push_back(sample.y);
magnet_vector_z.push_back(sample.z);
}
auto max_x = max_element(magnet_vector_x.begin(), magnet_vector_x.end());
auto max_y = max_element(magnet_vector_y.begin(), magnet_vector_y.end());
auto max_z = max_element(magnet_vector_z.begin(), magnet_vector_z.end());
auto min_x = min_element(magnet_vector_x.begin(), magnet_vector_x.end());
auto min_y = min_element(magnet_vector_y.begin(), magnet_vector_y.end());
auto min_z = min_element(magnet_vector_z.begin(), magnet_vector_z.end());
mOffsetMagnetX = (*max_x + *min_x) / 2;
mOffsetMagnetY = (*max_y + *min_y) / 2;
mOffsetMagnetZ = (*max_z + *min_z) / 2;
double avg_delta = (mOffsetMagnetX + mOffsetMagnetY + mOffsetMagnetZ) / 3;
mScaleMagnetX = avg_delta / mOffsetMagnetX;
mScaleMagnetY = avg_delta / mOffsetMagnetY;
mScaleMagnetZ = avg_delta / mOffsetMagnetZ;
}
VECTOR3 AccelManager::getVectorMagnet() const
{
return gNineAxisSensor.getMagnet();
}
double AccelManager::getMx() const
{
return (gNineAxisSensor.getMagnet().x - mOffsetMagnetX) * mScaleMagnetX;
}
double AccelManager::getMy() const
{
return (gNineAxisSensor.getMagnet().y - mOffsetMagnetY) * mScaleMagnetY;
}
double AccelManager::getMz() const
{
return (gNineAxisSensor.getMagnet().z - mOffsetMagnetZ) * mScaleMagnetZ;
}
double AccelManager::getRawMagnetDirection() const
{
double azimuth;
double mag_x = getMx();
double mag_y = getMy();
double mag_z = getMz();
azimuth = -(fmod(atan2(mag_y, mag_x) * (180.0 / M_PI) + 270.0 - 7, 360.0) - 360.0);
return azimuth;
}
VECTOR3 AccelManager::getVectorSpeed() const
{
return VECTOR3();
}
double AccelManager::getSx() const
{
/*std::deque<VECTOR3> accel_samples = gNineAxisSensor.getAccelSamples();
std::deque<VECTOR3>::iterator it = accel_samples.begin();
double speed;
double curr_accel = 0.0;
double pre_accel = 0.0;
while (it != accel_samples.end())
{
curr_accel = (*it).x;
speed += (curr_accel + pre_accel) / 2 * NINEAXIS_UPDATE_INTERVAL_TIME;
pre_accel = curr_accel;
++it;
}
return speed;*/
return 0.0;
}
double AccelManager::getSy() const
{
/*std::deque<VECTOR3> accel_samples = gNineAxisSensor.getAccelSamples();
std::deque<VECTOR3>::iterator it = accel_samples.begin();
double speed;
double curr_accel = 0.0;
double pre_accel = 0.0;
while (it != accel_samples.end())
{
curr_accel = (*it).y;
speed += (curr_accel + pre_accel) / 2 * NINEAXIS_UPDATE_INTERVAL_TIME;
pre_accel = curr_accel;
++it;
}
return speed;*/
return 0.0;
}
double AccelManager::getSz() const
{
/*std::deque<VECTOR3> accel_samples = gNineAxisSensor.getAccelSamples();
std::deque<VECTOR3>::iterator it = accel_samples.begin();
double speed;
double curr_accel = 0.0;
double pre_accel = 0.0;
while (it != accel_samples.end())
{
curr_accel = (*it).z;
speed += (curr_accel + pre_accel) / 2 * NINEAXIS_UPDATE_INTERVAL_TIME;
pre_accel = curr_accel;
++it;
}
return speed;*/
return 0.0;
}
VECTOR3 AccelManager::getVectorRolling() const
{
return VECTOR3();
}
float AccelManager::getRoll() const
{
double roll = atan2(2.0f * (mQuaternion[0] * mQuaternion[1] + mQuaternion[2] * mQuaternion[3]), mQuaternion[0] * mQuaternion[0] - mQuaternion[1] * mQuaternion[1] - mQuaternion[2] * mQuaternion[2] + mQuaternion[3] * mQuaternion[3]);
roll *= 180.0f / M_PI;
return roll;
}
float AccelManager::getPitch() const
{
double pitch = -asin(2.0f * (mQuaternion[1] * mQuaternion[3] - mQuaternion[0] * mQuaternion[2]));
pitch *= 180.0f / M_PI;
return pitch;
}
float AccelManager::getYaw() const
{
double yaw = atan2(2.0f * (mQuaternion[1] * mQuaternion[2] + mQuaternion[0] * mQuaternion[3]), mQuaternion[0] * mQuaternion[0] + mQuaternion[1] * mQuaternion[1] - mQuaternion[2] * mQuaternion[2] - mQuaternion[3] * mQuaternion[3]);
yaw *= 180.0f / M_PI;
yaw -= -DECLINATION_FOR_YAW;
return yaw;
}
double AccelManager::normalize(double pos)
{
while (pos >= 180 || pos < -180)pos += (pos > 0) ? -360 : 360;
return pos;
}
void AccelManager::UpdateMadgwickQuaternion(double dt, float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = mQuaternion[0], q2 = mQuaternion[1], q3 = mQuaternion[2], q4 = mQuaternion[3]; // short name local variable for readability
float norm;
float hx, hy, _2bx, _2bz;
float s1, s2, s3, s4;
float qDot1, qDot2, qDot3, qDot4;
// Auxiliary variables to avoid repeated arithmetic
float _2q1mx;
float _2q1my;
float _2q1mz;
float _2q2mx;
float _4bx;
float _4bz;
float _2q1 = 2.0f * q1;
float _2q2 = 2.0f * q2;
float _2q3 = 2.0f * q3;
float _2q4 = 2.0f * q4;
float _2q1q3 = 2.0f * q1 * q3;
float _2q3q4 = 2.0f * q3 * q4;
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Normalise accelerometer measurement
norm = sqrtf(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrtf(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm;
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
_2q1mx = 2.0f * q1 * mx;
_2q1my = 2.0f * q1 * my;
_2q1mz = 2.0f * q1 * mz;
_2q2mx = 2.0f * q2 * mx;
hx = mx * q1q1 - _2q1my * q4 + _2q1mz * q3 + mx * q2q2 + _2q2 * my * q3 + _2q2 * mz * q4 - mx * q3q3 - mx * q4q4;
hy = _2q1mx * q4 + my * q1q1 - _2q1mz * q2 + _2q2mx * q3 - my * q2q2 + my * q3q3 + _2q3 * mz * q4 - my * q4q4;
_2bx = sqrtf(hx * hx + hy * hy);
_2bz = -_2q1mx * q3 + _2q1my * q2 + mz * q1q1 + _2q2mx * q4 - mz * q2q2 + _2q3 * my * q4 - mz * q3q3 + mz * q4q4;
_4bx = 2.0f * _2bx;
_4bz = 2.0f * _2bz;
// Gradient decent algorithm corrective step
s1 = -_2q3 * (2.0f * q2q4 - _2q1q3 - ax) + _2q2 * (2.0f * q1q2 + _2q3q4 - ay) - _2bz * q3 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q4 + _2bz * q2) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q3 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s2 = _2q4 * (2.0f * q2q4 - _2q1q3 - ax) + _2q1 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q2 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + _2bz * q4 * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q3 + _2bz * q1) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q4 - _4bz * q2) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s3 = -_2q1 * (2.0f * q2q4 - _2q1q3 - ax) + _2q4 * (2.0f * q1q2 + _2q3q4 - ay) - 4.0f * q3 * (1.0f - 2.0f * q2q2 - 2.0f * q3q3 - az) + (-_4bx * q3 - _2bz * q1) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (_2bx * q2 + _2bz * q4) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + (_2bx * q1 - _4bz * q3) * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
s4 = _2q2 * (2.0f * q2q4 - _2q1q3 - ax) + _2q3 * (2.0f * q1q2 + _2q3q4 - ay) + (-_4bx * q4 + _2bz * q2) * (_2bx * (0.5f - q3q3 - q4q4) + _2bz * (q2q4 - q1q3) - mx) + (-_2bx * q1 + _2bz * q3) * (_2bx * (q2q3 - q1q4) + _2bz * (q1q2 + q3q4) - my) + _2bx * q2 * (_2bx * (q1q3 + q2q4) + _2bz * (0.5f - q2q2 - q3q3) - mz);
norm = sqrtf(s1 * s1 + s2 * s2 + s3 * s3 + s4 * s4); // normalise step magnitude
norm = 1.0f / norm;
s1 *= norm;
s2 *= norm;
s3 *= norm;
s4 *= norm;
// Compute rate of change of quaternion
qDot1 = 0.5f * (-q2 * gx - q3 * gy - q4 * gz) - beta * s1;
qDot2 = 0.5f * (q1 * gx + q3 * gz - q4 * gy) - beta * s2;
qDot3 = 0.5f * (q1 * gy - q2 * gz + q4 * gx) - beta * s3;
qDot4 = 0.5f * (q1 * gz + q2 * gy - q3 * gx) - beta * s4;
// Integrate to yield quaternion
q1 += qDot1 * dt;
q2 += qDot2 * dt;
q3 += qDot3 * dt;
q4 += qDot4 * dt;
norm = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion
norm = 1.0f / norm;
mQuaternion[0] = q1 * norm;
mQuaternion[1] = q2 * norm;
mQuaternion[2] = q3 * norm;
mQuaternion[3] = q4 * norm;
}
void AccelManager::UpdateMahonyQuaternion(double dt, float ax, float ay, float az, float gx, float gy, float gz, float mx, float my, float mz)
{
float q1 = mQuaternion[0], q2 = mQuaternion[1], q3 = mQuaternion[2], q4 = mQuaternion[3]; // short name local variable for readability
float norm;
float hx, hy, bx, bz;
float vx, vy, vz, wx, wy, wz;
float ex, ey, ez;
float pa, pb, pc;
// Auxiliary variables to avoid repeated arithmetic
float q1q1 = q1 * q1;
float q1q2 = q1 * q2;
float q1q3 = q1 * q3;
float q1q4 = q1 * q4;
float q2q2 = q2 * q2;
float q2q3 = q2 * q3;
float q2q4 = q2 * q4;
float q3q3 = q3 * q3;
float q3q4 = q3 * q4;
float q4q4 = q4 * q4;
// Normalise accelerometer measurement
norm = sqrtf(ax * ax + ay * ay + az * az);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
ax *= norm;
ay *= norm;
az *= norm;
// Normalise magnetometer measurement
norm = sqrtf(mx * mx + my * my + mz * mz);
if (norm == 0.0f) return; // handle NaN
norm = 1.0f / norm; // use reciprocal for division
mx *= norm;
my *= norm;
mz *= norm;
// Reference direction of Earth's magnetic field
hx = 2.0f * mx * (0.5f - q3q3 - q4q4) + 2.0f * my * (q2q3 - q1q4) + 2.0f * mz * (q2q4 + q1q3);
hy = 2.0f * mx * (q2q3 + q1q4) + 2.0f * my * (0.5f - q2q2 - q4q4) + 2.0f * mz * (q3q4 - q1q2);
bx = sqrtf((hx * hx) + (hy * hy));
bz = 2.0f * mx * (q2q4 - q1q3) + 2.0f * my * (q3q4 + q1q2) + 2.0f * mz * (0.5f - q2q2 - q3q3);
// Estimated direction of gravity and magnetic field
vx = 2.0f * (q2q4 - q1q3);
vy = 2.0f * (q1q2 + q3q4);
vz = q1q1 - q2q2 - q3q3 + q4q4;
wx = 2.0f * bx * (0.5f - q3q3 - q4q4) + 2.0f * bz * (q2q4 - q1q3);
wy = 2.0f * bx * (q2q3 - q1q4) + 2.0f * bz * (q1q2 + q3q4);
wz = 2.0f * bx * (q1q3 + q2q4) + 2.0f * bz * (0.5f - q2q2 - q3q3);
// Error is cross product between estimated direction and measured direction of gravity
ex = (ay * vz - az * vy) + (my * wz - mz * wy);
ey = (az * vx - ax * vz) + (mz * wx - mx * wz);
ez = (ax * vy - ay * vx) + (mx * wy - my * wx);
if (Ki > 0.0f)
{
mErrorOfIntegral[0] += ex; // accumulate integral error
mErrorOfIntegral[1] += ey;
mErrorOfIntegral[2] += ez;
}
else
{
mErrorOfIntegral[0] = 0.0f; // prevent integral wind up
mErrorOfIntegral[1] = 0.0f;
mErrorOfIntegral[2] = 0.0f;
}
// Apply feedback terms
gx = gx + Kp * ex + Ki * mErrorOfIntegral[0];
gy = gy + Kp * ey + Ki * mErrorOfIntegral[1];
gz = gz + Kp * ez + Ki * mErrorOfIntegral[2];
// Integrate rate of change of quaternion
pa = q2;
pb = q3;
pc = q4;
q1 = q1 + (-q2 * gx - q3 * gy - q4 * gz) * (0.5f * dt);
q2 = pa + (q1 * gx + pb * gz - pc * gy) * (0.5f * dt);
q3 = pb + (q1 * gy - pa * gz + pc * gx) * (0.5f * dt);
q4 = pc + (q1 * gz + pa * gy - pb * gx) * (0.5f * dt);
// Normalise quaternion
norm = sqrtf(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4);
norm = 1.0f / norm;
mQuaternion[0] = q1 * norm;
mQuaternion[1] = q2 * norm;
mQuaternion[2] = q3 * norm;
mQuaternion[3] = q4 * norm;
}
void AccelManager::normalize(VECTOR3& pos)
{
pos.x = normalize(pos.x);
pos.y = normalize(pos.y);
pos.z = normalize(pos.z);
}
AccelManager::AccelManager() :mOffsetMagnetX(MAGNET_POS_OFFSET_X), mOffsetMagnetY(MAGNET_POS_OFFSET_Y), mOffsetMagnetZ(MAGNET_POS_OFFSET_Z), mScaleMagnetX(MAGNET_SCALE_OFFSET_X), mScaleMagnetY(MAGNET_SCALE_OFFSET_Y), mScaleMagnetZ(MAGNET_SCALE_OFFSET_Z)
{
setName("accel");
setPriority(TASK_PRIORITY_SENSOR, TASK_INTERVAL_SENSOR);
mQuaternion[0] = 1;
mQuaternion[1] = 0;
mQuaternion[2] = 0;
mQuaternion[3] = 0;
mErrorOfIntegral[0] = 0;
mErrorOfIntegral[1] = 0;
mErrorOfIntegral[2] = 0;
isSensorView = false;
}
AccelManager::~AccelManager()
{
} | 30.664207 | 385 | 0.640674 | [
"vector"
] |
f352febb969117befe3bbe84bf5fc7cde47a135c | 785 | cpp | C++ | test/Homogeneous_test.cpp | hhoppe/Mesh-processing-library | aa8c952fbbb00774008060767650b821bf72fa10 | [
"MIT"
] | 422 | 2017-01-12T04:44:39.000Z | 2022-03-21T14:38:49.000Z | test/Homogeneous_test.cpp | wangxihao/Mesh-processing-library | 194ce16b8b28bbab1263ca6bc26dedfa7a0eeea2 | [
"MIT"
] | 1 | 2017-06-07T16:36:09.000Z | 2017-06-07T16:36:09.000Z | test/Homogeneous_test.cpp | wangxihao/Mesh-processing-library | 194ce16b8b28bbab1263ca6bc26dedfa7a0eeea2 | [
"MIT"
] | 75 | 2017-01-12T04:44:41.000Z | 2021-11-09T02:57:34.000Z | // -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#include "libHh/Homogeneous.h"
using namespace hh;
int main() {
{
Point p(1.f, 2.f, 3.f), q(8.f, 7.f, 6.f);
Vector v(1.f, 2.f, 3.f), w(1.f, 0.f, 1.f), x(0.f, 1.f, 0.f), y = x;
SHOW(p, q, v, w, y);
SHOW(Homogeneous(p) + Homogeneous(q));
SHOW(to_Point((p + p * 2.f + p) / 4.f));
SHOW(to_Point((p + p) / 2.f));
SHOW(to_Point((p * 2.f) / 2.f));
SHOW(to_Point((p + q) / 2.f));
}
{
const Homogeneous h1(1.f, 2.f, 3.f, 4.f);
dummy_use(h1);
const Homogeneous h2(h1);
dummy_use(h2);
const Vec4<float> v(0.f, 0.f, 0.f, 0.f);
dummy_use(v);
const Homogeneous h3 = v;
dummy_use(h3);
const Homogeneous h4 = V(0.f, 0.f, 0.f, 0.f);
dummy_use(h4);
}
}
| 27.068966 | 71 | 0.526115 | [
"vector"
] |
f35a55385af34ab2793459295c4ddecdc4270ab9 | 11,527 | cpp | C++ | src/IECore/Group.cpp | goddardl/cortex | 323a160fd831569591cde1504f415a638f8b85bc | [
"BSD-3-Clause"
] | null | null | null | src/IECore/Group.cpp | goddardl/cortex | 323a160fd831569591cde1504f415a638f8b85bc | [
"BSD-3-Clause"
] | null | null | null | src/IECore/Group.cpp | goddardl/cortex | 323a160fd831569591cde1504f415a638f8b85bc | [
"BSD-3-Clause"
] | 1 | 2020-09-26T01:15:37.000Z | 2020-09-26T01:15:37.000Z | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2013, Image Engine Design 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 Image Engine Design nor the names of any
// other contributors to this software 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 <algorithm>
#include "IECore/Group.h"
#include "IECore/Renderer.h"
#include "IECore/AttributeBlock.h"
#include "IECore/AttributeState.h"
#include "IECore/MurmurHash.h"
#include "OpenEXR/ImathBoxAlgo.h"
#include "boost/format.hpp"
#include "boost/lexical_cast.hpp"
using namespace IECore;
using namespace std;
using namespace Imath;
static IndexedIO::EntryID g_transformEntry("transform");
static IndexedIO::EntryID g_stateEntry("state");
static IndexedIO::EntryID g_childrenEntry("children");
const unsigned int Group::m_ioVersion = 0;
IE_CORE_DEFINEOBJECTTYPEDESCRIPTION( Group );
Group::Group()
: m_transform( 0 ), m_parent( 0 )
{
}
Group::~Group()
{
clearChildren();
}
Transform *Group::getTransform()
{
return m_transform.get();
}
const Transform *Group::getTransform() const
{
return m_transform.get();
}
void Group::setTransform( TransformPtr transform )
{
m_transform = transform;
}
Imath::M44f Group::transformMatrix( float time ) const
{
ConstTransformPtr t = getTransform();
if( t )
{
return t->transform( time );
}
return Imath::M44f(); // identity
}
Imath::M44f Group::globalTransformMatrix( float time ) const
{
if( m_parent )
{
return transformMatrix( time ) * m_parent->globalTransformMatrix( time );
}
return transformMatrix( time );
}
void Group::addState( StateRenderablePtr state )
{
if( !state )
{
throw InvalidArgumentException( "Cannot add null state object." );
}
if( state->isInstanceOf( Transform::staticTypeId() ) )
{
throw Exception( "Transforms cannot be added as state." );
}
m_state.push_back( state );
}
void Group::removeState( StateRenderablePtr state )
{
StateContainer::iterator it = find( m_state.begin(), m_state.end(), state );
if( it==m_state.end() )
{
throw Exception( "State not present in Group" );
}
m_state.erase( it );
}
void Group::clearState()
{
m_state.clear();
}
const Group::StateContainer &Group::state() const
{
return m_state;
}
const Data *Group::getAttribute( const std::string &name ) const
{
StateContainer::const_reverse_iterator it = m_state.rbegin();
for( ; it != m_state.rend(); ++it )
{
if( ConstAttributeStatePtr attr = runTimeCast< const AttributeState >( *it ) )
{
CompoundDataMap::const_iterator attrIt = attr->attributes().find( name );
if( attrIt != attr->attributes().end() )
{
return attrIt->second.get();
}
}
}
if( m_parent )
{
return m_parent->getAttribute( name );
}
return 0;
}
void Group::setAttribute( const std::string &name, ConstDataPtr value )
{
// find existing attribute/override it ?
StateContainer::iterator it = m_state.begin();
AttributeStatePtr attrFound;
for( ; it != m_state.end(); ++it )
{
if( AttributeStatePtr attr = runTimeCast< AttributeState >( *it ) )
{
attrFound = attr;
CompoundDataMap::iterator attrIt = attr->attributes().find( name );
if( attrIt != attr->attributes().end() )
{
attr->attributes()[ name ] = value->copy();
return;
}
}
}
if( !attrFound )
{
attrFound = new AttributeState;
addState( attrFound );
}
attrFound->attributes()[ name ] = value->copy();
}
void Group::addChild( VisibleRenderablePtr child )
{
if( !child )
{
throw InvalidArgumentException( "Cannot add null child object." );
}
GroupPtr gChild = runTimeCast<Group>( child );
if( gChild )
{
GroupPtr gChildParent = gChild->parent();
if( gChildParent )
{
gChildParent->removeChild( gChild );
}
gChild->m_parent = this;
}
m_children.push_back( child );
}
void Group::removeChild( VisibleRenderablePtr child )
{
ChildContainer::iterator it = find( m_children.begin(), m_children.end(), child );
if( it==m_children.end() )
{
throw Exception( "Child is not a member of Group" );
}
GroupPtr gChild = runTimeCast<Group>( child );
if( gChild )
{
gChild->m_parent = 0;
}
m_children.erase( it );
}
void Group::clearChildren()
{
while( m_children.size() )
{
removeChild( m_children[0] );
}
}
const Group::ChildContainer &Group::children() const
{
return m_children;
}
Group *Group::parent()
{
return m_parent;
}
const Group *Group::parent() const
{
return m_parent;
}
void Group::copyFrom( const Object *other, CopyContext *context )
{
VisibleRenderable::copyFrom( other, context );
const Group *tOther = static_cast<const Group *>( other );
if( tOther->m_transform )
{
m_transform = context->copy<Transform>( tOther->m_transform.get() );
}
else
{
m_transform = 0;
}
clearState();
for( StateContainer::const_iterator it=tOther->state().begin(); it!=tOther->state().end(); it++ )
{
addState( context->copy<StateRenderable>( it->get() ) );
}
clearChildren();
for( ChildContainer::const_iterator it=tOther->children().begin(); it!=tOther->children().end(); it++ )
{
addChild( context->copy<VisibleRenderable>( it->get() ) );
}
}
void Group::save( SaveContext *context ) const
{
VisibleRenderable::save( context );
IndexedIOPtr container = context->container( staticTypeName(), m_ioVersion );
if( m_transform )
{
context->save( m_transform.get(), container.get(), g_transformEntry );
}
IndexedIOPtr stateContainer = container->subdirectory( g_stateEntry, IndexedIO::CreateIfMissing );
int i = 0;
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
string name = str( boost::format( "%d" ) % i );
context->save( it->get(), stateContainer.get(), name );
i++;
}
IndexedIOPtr childrenContainer = container->subdirectory( g_childrenEntry, IndexedIO::CreateIfMissing );
i = 0;
for( ChildContainer::const_iterator it = children().begin(); it!=children().end(); it++ )
{
string name = str( boost::format( "%d" ) % i );
context->save( it->get(), childrenContainer.get(), name );
i++;
}
}
bool Group::entryListCompare( const IndexedIO::EntryID& a, const IndexedIO::EntryID& b )
{
int a_idx( 0 );
int b_idx( 0 );
try
{
a_idx = boost::lexical_cast<int>( a.value() );
}
catch (...)
{
}
try
{
b_idx = boost::lexical_cast<int>( b.value() );
}
catch (...)
{
}
return a_idx < b_idx;
}
void Group::load( LoadContextPtr context )
{
VisibleRenderable::load( context );
unsigned int v = m_ioVersion;
ConstIndexedIOPtr container = context->container( staticTypeName(), v );
m_transform = 0;
try
{
m_transform = context->load<Transform>( container.get(), g_transformEntry );
}
catch( ... )
{
}
clearState();
ConstIndexedIOPtr stateContainer = container->subdirectory( g_stateEntry );
IndexedIO::EntryIDList l;
stateContainer->entryIds( l );
sort( l.begin(), l.end(), entryListCompare );
for( IndexedIO::EntryIDList::const_iterator it=l.begin(); it!=l.end(); it++ )
{
addState( context->load<StateRenderable>( stateContainer.get(), *it ) );
}
clearChildren();
ConstIndexedIOPtr childrenContainer = container->subdirectory( g_childrenEntry );
childrenContainer->entryIds( l );
sort( l.begin(), l.end(), entryListCompare );
for( IndexedIO::EntryIDList::const_iterator it=l.begin(); it!=l.end(); it++ )
{
addChild( context->load<VisibleRenderable>( childrenContainer.get(), *it ) );
}
}
bool Group::isEqualTo( const Object *other ) const
{
if( !VisibleRenderable::isEqualTo( other ) )
{
return false;
}
const Group *tOther = static_cast<const Group *>( other );
// check transform
if( (bool)m_transform != (bool)tOther->m_transform )
{
return false;
}
if( m_transform && !tOther->m_transform->isEqualTo( m_transform.get() ) )
{
return false;
}
// check state
if( m_state.size()!=tOther->m_state.size() )
{
return false;
}
for( size_t i=0; i<m_state.size(); i++ )
{
if( !m_state[i]->isEqualTo( tOther->m_state[i].get() ) )
{
return false;
}
}
// check children
if( m_children.size()!=tOther->m_children.size() )
{
return false;
}
for( size_t i=0; i<m_children.size(); i++ )
{
if( !m_children[i]->isEqualTo( tOther->m_children[i].get() ) )
{
return false;
}
}
return true;
}
void Group::memoryUsage( Object::MemoryAccumulator &a ) const
{
VisibleRenderable::memoryUsage( a );
if( m_transform )
{
a.accumulate( m_transform.get() );
}
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
a.accumulate( it->get() );
}
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
a.accumulate( it->get() );
}
}
void Group::hash( MurmurHash &h ) const
{
VisibleRenderable::hash( h );
if( m_transform )
{
m_transform->hash( h );
}
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
(*it)->hash( h );
}
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
(*it)->hash( h );
}
}
void Group::render( Renderer *renderer ) const
{
render( renderer, true );
}
void Group::render( Renderer *renderer, bool inAttributeBlock ) const
{
/// \todo I wonder if this should just use a transform block if
/// the Group doesn't have any state?
AttributeBlock attributeBlock( renderer, inAttributeBlock );
if( m_transform )
{
m_transform->render( renderer );
}
renderState( renderer );
renderChildren( renderer );
}
void Group::renderState( Renderer *renderer ) const
{
for( StateContainer::const_iterator it=state().begin(); it!=state().end(); it++ )
{
(*it)->render( renderer );
}
}
void Group::renderChildren( Renderer *renderer ) const
{
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
(*it)->render( renderer );
}
}
Imath::Box3f Group::bound() const
{
Box3f result;
for( ChildContainer::const_iterator it=children().begin(); it!=children().end(); it++ )
{
result.extendBy( (*it)->bound() );
}
return transform( result, transformMatrix() );
}
| 23.865424 | 105 | 0.673462 | [
"render",
"object",
"transform"
] |
f35a9a90955f2a234e7bbd9d364eeef1daa60971 | 306 | hpp | C++ | include/logging.hpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | include/logging.hpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | include/logging.hpp | teamprova/ProvaEngine-CPP | 0ba9b4b0d73a5a261194d5333e5a572c40c0c21f | [
"Unlicense"
] | null | null | null | #pragma once
#include <string>
#include "vector4.hpp"
#include "vector3.hpp"
#include "vector2.hpp"
#include "rect.hpp"
namespace Prova
{
void Log(float number);
void Log(Vector2 vector);
void Log(Vector3 vector);
void Log(Vector4 vector);
void Log(Rect rect);
void Log(std::string message);
} | 19.125 | 32 | 0.712418 | [
"vector"
] |
f368439d7bf4eeaaebfeb5975fcba25a818491f1 | 2,040 | cpp | C++ | src/tools.cpp | jroivas/nolang | 761655bf851a978fb8426cc8f465e53cc86dec28 | [
"MIT"
] | 2 | 2021-04-13T20:16:04.000Z | 2022-02-17T02:46:40.000Z | src/tools.cpp | jroivas/nolang | 761655bf851a978fb8426cc8f465e53cc86dec28 | [
"MIT"
] | null | null | null | src/tools.cpp | jroivas/nolang | 761655bf851a978fb8426cc8f465e53cc86dec28 | [
"MIT"
] | null | null | null | #include "tools.hh"
#include <iostream>
std::vector<std::string> nolang::applyToVector(std::vector<std::string> &dst, const std::vector<std::string> &src) {
dst.insert(dst.end(), src.begin(), src.end());
return dst;
}
void nolang::iterateTree(mpc_ast_t *tree, std::function<void(mpc_ast_t *)> closure) {
for (int c = 0; c < tree->children_num; ++c)
closure(tree->children[c]);
}
bool nolang::expect(mpc_ast_t *tree, std::string key, std::string val)
{
std::string tag = tree->tag;
if (tag.find(key) == std::string::npos) return false;
if (!val.empty() && tree->contents != val) return false;
return true;
}
void nolang::printError(std::string message, mpc_ast_t *item)
{
std::cerr << "** ERROR: " << message << ": " << item->tag << ": '" << item->contents << "'\n";
}
void nolang::printError(std::string message, const Statement *s)
{
std::cerr << "** ERROR: " << message << ": " << s->type() << ": '" << s->code() << "'\n";
}
void nolang::throwError(std::string message, mpc_ast_t *item)
{
throw message + ": " + item->tag + ": '" + item->contents;
}
void nolang::throwError(std::string message)
{
throw message;
}
void nolang::throwError(std::string message, std::string a)
{
throw message + " " + a;
}
void nolang::throwError(std::string message, std::string a, std::string b)
{
throw message + " " + a + " '" + b +"'";
}
mpc_ast_t *nolang::findFirstItemFromTree(mpc_ast_t *tree, std::string name)
{
for (int c = 0; c < tree->children_num; ++c) {
mpc_ast_t *item = tree->children[c];
if (std::string(item->tag).find(name) != std::string::npos) return item;
item = findFirstItemFromTree(item, name);
if (item != nullptr) return item;
};
return nullptr;
}
std::string nolang::combineStringList(const std::vector<std::string> &l, const std::string sep)
{
std::string res;
bool first = true;
for (auto v : l) {
if (first) first = false;
else res += sep;
res += v;
}
return res;
}
| 26.842105 | 116 | 0.598529 | [
"vector"
] |
f369ed07077b004dbef0a00e79622a989d6fea15 | 819 | cpp | C++ | stl/vector.cpp | anubhavnandan/leetCode | 2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f | [
"Apache-2.0"
] | 1 | 2021-09-30T10:02:35.000Z | 2021-09-30T10:02:35.000Z | stl/vector.cpp | anubhavnandan/leetCode | 2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f | [
"Apache-2.0"
] | null | null | null | stl/vector.cpp | anubhavnandan/leetCode | 2cb9511b2c37b80f3ee57b3932d1dc9e7be9994f | [
"Apache-2.0"
] | null | null | null | //C++ 11
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
void Method(vector <int> &v){
for(auto x : v)
cout<<x;
//Member Function
cout<<'\n'<<v.front();
cout<<'\n'<<v.back();
}
};
int main(){
int a[]={1,2,3,4,5};
vector <int> V(begin(a),end(a));
//Member Function
V.push_back(6);
V.insert(V.begin(),7);
V.pop_back();
Solution Obj;
Obj.Method(V);
//Sort
sort(V.begin(),V.end());
cout<<'\n';
Obj.Method(V);
//Binary Search
cout<<"\nSearch 5:"<<binary_search(V.begin(),V.end(),5);
//Merge
vector <int> M;
merge(V.begin(),V.end(),V.begin(),V.end(),back_inserter(M));
cout<<'\n';
Obj.Method(M);
//Swap
swap(V[0],V[1]);
cout<<'\n';
Obj.Method(V);
//Reverse
reverse(V.begin(),V.end());
cout<<'\n';
Obj.Method(V);
return 0;
}
| 13.42623 | 60 | 0.586081 | [
"vector"
] |
f370a24fa1a401119617f0a0327f5acf0619796d | 12,458 | cpp | C++ | src/main-ecm.cpp | rheiland/pc_ECM_model_for_nanoHUB | 161b586757756ce753eddc10e8bf14c3d5b5d170 | [
"BSD-3-Clause"
] | null | null | null | src/main-ecm.cpp | rheiland/pc_ECM_model_for_nanoHUB | 161b586757756ce753eddc10e8bf14c3d5b5d170 | [
"BSD-3-Clause"
] | null | null | null | src/main-ecm.cpp | rheiland/pc_ECM_model_for_nanoHUB | 161b586757756ce753eddc10e8bf14c3d5b5d170 | [
"BSD-3-Clause"
] | 1 | 2019-12-11T10:34:31.000Z | 2019-12-11T10:34:31.000Z | /*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version 1.2.2) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 2017 (in review). #
# preprint DOI: 10.1101/088773 #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version 1.2.2) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 2017 (in review). #
# preprint DOI: 10.1101/088773 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2017, Paul Macklin and the PhysiCell 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: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. 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. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <omp.h>
#include <fstream>
#include "./core/PhysiCell.h"
#include "./modules/PhysiCell_standard_modules.h"
// custom user modules
#include "./custom_modules/AMIGOS-invasion.h"
// #include "./custom_modules/ECM.h"
using namespace BioFVM;
using namespace PhysiCell;
// set number of threads for OpenMP (parallel computing)
void ecm_update(void);
int main( int argc, char* argv[] )
{
// load and parse settings file(s)
bool XML_status = false;
if( argc > 1 )
{ XML_status = load_PhysiCell_config_file( argv[1] ); }
else
{ XML_status = load_PhysiCell_config_file( "./config/PhysiCell_settings.xml" ); }
if( !XML_status )
{ exit(-1); }
// OpenMP setup
omp_set_num_threads(PhysiCell_settings.omp_num_threads);
// PNRG setup
// SeedRandom(0);
if( parameters.ints("unit_test_setup") == 1)
{SeedRandom(0);}
// time setup
std::string time_units = "min";
double t_max = PhysiCell_settings.max_time; // 1 days
/* Microenvironment setup */
setup_microenvironment();
/* PhysiCell setup */
// set mechanics voxel size, and match the data structure to BioFVM
double mechanics_voxel_size = 30;
Cell_Container* cell_container = create_cell_container_for_microenvironment( microenvironment, mechanics_voxel_size );
create_cell_types();
setup_tissue();
// ECM_setup(microenvironment.number_of_voxels());
/* Users typically start modifying here. START USERMODS */
/* Users typically stop modifying here. END USERMODS */
// set MultiCellDS save options
set_save_biofvm_mesh_as_matlab( true );
set_save_biofvm_data_as_matlab( true );
set_save_biofvm_cell_data( true );
set_save_biofvm_cell_data_as_custom_matlab( true );
// save a simulation snapshot
char filename[1024];
sprintf( filename , "%s/initial" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
// save a quick SVG cross section through z = 0, after setting its
// length bar to 200 microns
PhysiCell_SVG_options.length_bar = 200;
// for simplicity, set a pathology coloring function
std::vector<std::string> (*cell_coloring_function)(Cell*) = AMIGOS_invasion_coloring_function;
sprintf( filename , "%s/initial.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
display_citations();
run_biotransport( parameters.doubles("duration_of_uE_conditioning") );
if(parameters.bools("freeze_uE_profile")==true)
{
alter_cell_uptake_secretion_saturation();
}
if(parameters.ints("unit_test_setup")==1)
{
set_cell_motility_vectors();
}
// set the performance timers
BioFVM::RUNTIME_TIC();
BioFVM::TIC();
std::ofstream report_file;
//variables for March Project
double reset_Cells_interval = 980.0; // for a 1000 by 1000 um computational domain
bool enable_cell_resets = true;
// main loop
if( PhysiCell_settings.enable_legacy_saves == true )
{
sprintf( filename , "%s/simulation_report.txt" , PhysiCell_settings.folder.c_str() );
report_file.open(filename); // create the data log file
report_file<<"simulated time\tnum cells\tnum division\tnum death\twall time"<<std::endl;
}
try
{
while( PhysiCell_globals.current_time < t_max + 0.1*diffusion_dt )
{
// save data if it's time.
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_full_save_time ) < 0.01 * diffusion_dt )
{
display_simulation_status( std::cout );
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output( PhysiCell_globals.current_time , PhysiCell_globals.full_output_index, microenvironment, report_file);
}
if( PhysiCell_settings.enable_full_saves == true )
{
sprintf( filename , "%s/output%08u" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
}
if( parameters.bools("enable_ecm_outputs") == true)
{
sprintf( filename , "%s/output%08u_ECM.mat" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index);
write_ECM_Data_matlab( filename );
}
PhysiCell_globals.full_output_index++;
PhysiCell_globals.next_full_save_time += PhysiCell_settings.full_save_interval;
}
// save SVG plot if it's time
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_SVG_save_time ) < 0.01 * diffusion_dt )
{
if( PhysiCell_settings.enable_SVG_saves == true )
{
sprintf( filename , "%s/snapshot%08u.svg" , PhysiCell_settings.folder.c_str() , PhysiCell_globals.SVG_output_index );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
PhysiCell_globals.SVG_output_index++;
PhysiCell_globals.next_SVG_save_time += PhysiCell_settings.SVG_save_interval;
}
}
// Uncomment to run march test
if( fabs( PhysiCell_globals.current_time - reset_Cells_interval ) < 0.1 * diffusion_dt && parameters.ints("unit_test_setup") == 1 && parameters.ints("march_unit_test_setup") == 1)
{
if (enable_cell_resets == true )
{
reset_cell_position();
reset_Cells_interval += 980.0; // for a 1000 by 1000 um computational domain
}
}
// update the microenvironment
// if(parameters.bools("freeze_uE_profile")==true)
if( parameters.ints("unit_test_setup") == 0 && parameters.bools("freeze_uE_profile")==0 ) // Is there a way to set this only once??
{
microenvironment.simulate_diffusion_decay( diffusion_dt );
}
// run PhysiCell
((Cell_Container *)microenvironment.agent_container)->update_all_cells( PhysiCell_globals.current_time );
//add ECM update here!
// This changes the cell speed and bias as based on the ECM. It is the funciton that makes teh cells "see" the ECM and react to it with changes in their dynamics.
// In this current LS18 implementation, that means that only follower cells will see the ECM.
// May need something that specifics that only followers do this (fixed with test on cell type). Could perhaps put that into the custom stuff. Would need something similar for the ECM realignment. Would like to move this out of diffusion loop so we can specify how frequently it updates.
// cell_update_from_ecm();
PhysiCell_globals.current_time += diffusion_dt;
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output(PhysiCell_globals.current_time, PhysiCell_globals.full_output_index, microenvironment, report_file);
report_file.close();
}
}
}
catch( const std::exception& e )
{ // reference to the base of a polymorphic object
std::cout << e.what(); // information from length_error printed
}
// save a final simulation snapshot
sprintf( filename , "%s/final" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
sprintf( filename , "%s/final.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
// timer
std::cout << std::endl << "Total simulation runtime: " << std::endl;
BioFVM::display_stopwatch_value( std::cout , BioFVM::runtime_stopwatch_value() );
return 0;
} | 42.958621 | 299 | 0.61005 | [
"object",
"vector",
"model"
] |
f37318fcf097c9ffc0390661e928997ad4c6dcac | 3,067 | cpp | C++ | CMGui/cmrenderqueue.cpp | sultanqasim/cinemavi | 47ce572f818b2d5289f59a3b302b996fbf42ffd7 | [
"BSD-2-Clause"
] | null | null | null | CMGui/cmrenderqueue.cpp | sultanqasim/cinemavi | 47ce572f818b2d5289f59a3b302b996fbf42ffd7 | [
"BSD-2-Clause"
] | null | null | null | CMGui/cmrenderqueue.cpp | sultanqasim/cinemavi | 47ce572f818b2d5289f59a3b302b996fbf42ffd7 | [
"BSD-2-Clause"
] | null | null | null | #include "cmrenderqueue.h"
#include "cmrenderworker.h"
#include <cstring>
#include <QThread>
CMRenderQueue::CMRenderQueue(QObject *parent)
: QObject{parent}
{
// set up worker in its thread
worker.moveToThread(&renderThread);
connect(&renderThread, &QThread::started, &worker, &CMRenderWorker::render);
connect(&worker, &CMRenderWorker::imageRendered, this, &CMRenderQueue::renderDone);
saveWorker.moveToThread(&saveThread);
connect(&saveThread, &QThread::started, &saveWorker, &CMSaveWorker::save);
connect(&saveWorker, &CMSaveWorker::imageSaved, this, &CMRenderQueue::saveDone);
qRegisterMetaType<CMRawImage>("CMRawImage");
}
CMRenderQueue::~CMRenderQueue() {
renderThread.quit();
renderThread.wait();
saveThread.quit();
saveThread.wait();
}
void CMRenderQueue::setImage(const CMRawImage &img)
{
if (rendering) {
this->nextRaw = img;
imageQueued = true;
renderQueued = true;
} else {
this->currentRaw = img;
this->startRender();
}
}
void CMRenderQueue::setParams(const ImagePipelineParams ¶ms)
{
this->plParams = params;
this->paramsSet = true;
if (rendering)
renderQueued = true;
else
this->startRender();
}
void CMRenderQueue::startRender()
{
if (!paramsSet)
return;
rendering = true;
// prepare and launch worker
worker.setImage(&this->currentRaw);
worker.setParams(this->plParams);
renderThread.start();
}
void CMRenderQueue::renderDone(const QImage &img)
{
emit imageRendered(img);
renderThread.quit();
renderThread.wait();
if (imageQueued) {
currentRaw = nextRaw;
imageQueued = false;
}
if (renderQueued) {
startRender();
renderQueued = false;
} else {
rendering = false;
}
}
bool CMRenderQueue::autoWhiteBalance(const CMAutoWhiteParams ¶ms, double *temp_K, double *tint)
{
if (this->currentRaw.isEmpty())
return false;
pipeline_auto_white_balance(this->currentRaw.getRaw(), &this->currentRaw.getCaptureInfo(),
¶ms, temp_K, tint);
return true;
}
bool CMRenderQueue::saveImage(const QString &fileName)
{
if (this->currentRaw.isEmpty() || !paramsSet || saving)
return false;
saving = true;
if (imageQueued)
saveWorker.setParams(fileName.toStdString(), this->nextRaw, this->plParams);
else
saveWorker.setParams(fileName.toStdString(), this->currentRaw, this->plParams);
saveThread.start();
return true;
}
void CMRenderQueue::saveDone(bool success)
{
saveThread.quit();
saveThread.wait();
saving = false;
emit imageSaved(success);
}
// Enqueues set image operation at end of signal queue
void CMRenderQueue::setImageLater(const CMRawImage &img)
{
QMetaObject::invokeMethod(this, "setImage", Qt::QueuedConnection, Q_ARG(CMRawImage, img));
}
bool CMRenderQueue::hasImage()
{
if (imageQueued)
return !this->nextRaw.isEmpty();
else
return !this->currentRaw.isEmpty();
}
| 23.960938 | 99 | 0.665471 | [
"render"
] |
f374cf4a2187e0cd03825900a3c587b5b866a70f | 3,274 | hpp | C++ | stochepi/src/parameter.hpp | eeg-lanl/sarscov2-selection | c2087cbaf55de9930736aa6677a57008a2397583 | [
"BSD-3-Clause"
] | null | null | null | stochepi/src/parameter.hpp | eeg-lanl/sarscov2-selection | c2087cbaf55de9930736aa6677a57008a2397583 | [
"BSD-3-Clause"
] | null | null | null | stochepi/src/parameter.hpp | eeg-lanl/sarscov2-selection | c2087cbaf55de9930736aa6677a57008a2397583 | [
"BSD-3-Clause"
] | null | null | null | #ifndef _PARAMETER_HPP
#define _PARAMETER_HPP
#include <vector>
#include <map>
#include <list>
#include "aux.hpp" // Printable
#include "parprior.hpp"
#include "parse_params.hpp" // ParSpecs
// HACK 1: the first parameter is always the overdispersion of the noise
constexpr size_t IDX_SIGMA_OD = 0;
class Parameters : public Printable {
public:
Parameters() { /* empty */ }
Parameters(int n);
Parameters(const std::vector<size_t> & shape);
// TODO initilizer list
const ParPrior & operator[](int i) const; // retrieve a parameter by it's index (can use enum)
ParPrior & operator[](int i); // retrieve a parameter by it's index (can use enum)
const ParPrior & operator[](std::string name) const; // retrieve a parameter by it's name
ParPrior & operator[](std::string name); // retrieve a parameter by it's name
const ParPrior & operator()(size_t i) const; // retrieve i-th parameter, must be scalar
ParPrior & operator()(size_t i); // retrieve i-th parameter, must be scalar
const ParPrior & operator()(size_t i, size_t j) const; // retrieve (i,j)-th parameter according to shape
ParPrior & operator()(size_t i, size_t j); // retrieve (i,j)-th parameter according to shape
bool isScalar(size_t i) const; // is the i-th parameter a scalar according to shape?
size_t flat_size() const; // returns paramvec.size()
size_t size() const; // returns shape.size()
void mutate(Rng & rng, double rel_temp, double t);
void select(int r); // make sure that operator() returns the r-th element of vector-valued parameters
void deselect(); // remove selection
void lockAllBut(int r); // locks all parameter elements except the r-th if at least one element is NOT locked
void removeSingleLocks(); // removes all locks for random effects parameters if at least one element is NOT locked
void print(std::ostream & os) const override;
double loglike() const; // prior likelihood
// HACK 2: we have to disable some of the overdispersed noise terms
std::vector<double> select_od;
protected:
// aux methods for shape
std::pair<size_t, size_t> unflatten_index(size_t i) const;
size_t flatten_index(size_t i, size_t j) const;
// protected members
std::vector<ParPrior> paramvec;
std::vector<size_t> shape;
};
template <class T>
void load_param_specs(Parameters & par, const std::map<T, std::string> & parNameMap,
const std::list<ParSpecs> & parSpecsList) {
for ( auto & [symb, name] : parNameMap ) {
// find parameter in parSpecs
auto it = std::find_if(parSpecsList.begin(), parSpecsList.end(),
[name](const ParSpecs & psc) -> bool {return psc.name == name;});
if ( it == parSpecsList.end() ) {
throw std::runtime_error("parameter '" + name +
"' is not defined in the parameter specs list" + RIGHT_HERE);
} // else... parameter is defined
ParSpecs psc = *it;
// set value
par[symb] = psc.value;
// set name
par[symb].setName(name);
// if not locked, set bounds and sigma for the random walk
if ( !psc.is_locked ) {
par[symb].unlock();
par[symb].setPstd(psc.sigma_rw);
if ( psc.is_lbound ) {
par[symb].setLBound(psc.lbound);
}
if ( psc.is_ubound ) {
par[symb].setUBound(psc.ubound);
}
}
}
}
#endif
| 38.97619 | 116 | 0.682346 | [
"shape",
"vector"
] |
f379e2eb4869a7a3539cbcdcca9ceb2f92ed4b9b | 15,983 | cpp | C++ | source/gameengine/Rasterizer/RAS_2DFilterManager.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | 2 | 2018-06-18T01:50:25.000Z | 2018-06-18T01:50:32.000Z | source/gameengine/Rasterizer/RAS_2DFilterManager.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | source/gameengine/Rasterizer/RAS_2DFilterManager.cpp | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* 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.
*
* Contributor(s): none yet.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file gameengine/Rasterizer/RAS_2DFilterManager.cpp
* \ingroup bgerast
*/
#include "BLI_utildefines.h"
#include "RAS_OpenGLFilters/RAS_Blur2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Sharpen2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Dilation2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Erosion2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Laplacian2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Sobel2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Prewitt2DFilter.h"
#include "RAS_OpenGLFilters/RAS_GrayScale2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Sepia2DFilter.h"
#include "RAS_OpenGLFilters/RAS_Invert2DFilter.h"
#include "STR_String.h"
#include "RAS_ICanvas.h"
#include "RAS_Rect.h"
#include "RAS_2DFilterManager.h"
#include <iostream>
#include "GPU_glew.h"
#include <stdio.h>
#include "EXP_Value.h"
RAS_2DFilterManager::RAS_2DFilterManager():
texturewidth(-1), textureheight(-1),
/* numberoffilters(0), */ /* UNUSED */ need_tex_update(true)
{
isshadersupported = GLEW_ARB_shader_objects &&
GLEW_ARB_fragment_shader && GLEW_ARB_multitexture;
/* used to return before 2.49 but need to initialize values so don't */
if (!isshadersupported)
std::cout<<"shaders not supported!" << std::endl;
int passindex;
for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
{
m_filters[passindex] = 0;
m_enabled[passindex] = 0;
texflag[passindex] = 0;
m_gameObjects[passindex] = NULL;
}
texname[0] = texname[1] = texname[2] = -1;
errorprinted= false;
}
RAS_2DFilterManager::~RAS_2DFilterManager()
{
FreeTextures();
for (int passindex = 0; passindex < MAX_RENDER_PASS; passindex++) {
if (m_filters[passindex]) {
glDeleteObjectARB(m_filters[passindex]);
}
}
}
void RAS_2DFilterManager::PrintShaderErrors(unsigned int shader, const char *task, const char *code)
{
GLcharARB log[5000];
GLsizei length = 0;
const char *c, *pos, *end;
int line = 1;
if (errorprinted)
return;
errorprinted= true;
glGetInfoLogARB(shader, sizeof(log), &length, log);
end = code + strlen(code);
printf("2D Filter GLSL Shader: %s error:\n", task);
c = code;
while ((c < end) && (pos = strchr(c, '\n'))) {
printf("%2d ", line);
fwrite(c, (pos+1)-c, 1, stdout);
c = pos+1;
line++;
}
puts(c);
puts(log);
puts("\n");
}
unsigned int RAS_2DFilterManager::CreateShaderProgram(const char* shadersource)
{
GLuint program = 0;
GLuint fShader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER);
GLint success;
glShaderSourceARB(fShader, 1, (const char**)&shadersource, NULL);
glCompileShaderARB(fShader);
glGetObjectParameterivARB(fShader, GL_COMPILE_STATUS, &success);
if (!success) {
/*Shader Comile Error*/
PrintShaderErrors(fShader, "compile", shadersource);
goto fail;
}
program = glCreateProgramObjectARB();
glAttachObjectARB(program, fShader);
glLinkProgramARB(program);
glGetObjectParameterivARB(program, GL_LINK_STATUS, &success);
if (!success) {
/*Program Link Error*/
PrintShaderErrors(fShader, "link", shadersource);
goto fail;
}
glValidateProgramARB(program);
glGetObjectParameterivARB(program, GL_VALIDATE_STATUS, &success);
if (!success) {
/*Program Validation Error*/
PrintShaderErrors(fShader, "validate", shadersource);
goto fail;
}
/* owned by 'program' */
if (fShader) {
glDeleteObjectARB(fShader);
}
return program;
fail:
if (fShader) {
glDeleteObjectARB(fShader);
}
if (program) {
glDeleteObjectARB(program);
}
return 0;
}
unsigned int RAS_2DFilterManager::CreateShaderProgram(int filtermode)
{
switch (filtermode) {
case RAS_2DFILTER_BLUR:
return CreateShaderProgram(BlurFragmentShader);
case RAS_2DFILTER_SHARPEN:
return CreateShaderProgram(SharpenFragmentShader);
case RAS_2DFILTER_DILATION:
return CreateShaderProgram(DilationFragmentShader);
case RAS_2DFILTER_EROSION:
return CreateShaderProgram(ErosionFragmentShader);
case RAS_2DFILTER_LAPLACIAN:
return CreateShaderProgram(LaplacionFragmentShader);
case RAS_2DFILTER_SOBEL:
return CreateShaderProgram(SobelFragmentShader);
case RAS_2DFILTER_PREWITT:
return CreateShaderProgram(PrewittFragmentShader);
case RAS_2DFILTER_GRAYSCALE:
return CreateShaderProgram(GrayScaleFragmentShader);
case RAS_2DFILTER_SEPIA:
return CreateShaderProgram(SepiaFragmentShader);
case RAS_2DFILTER_INVERT:
return CreateShaderProgram(InvertFragmentShader);
}
return 0;
}
void RAS_2DFilterManager::AnalyseShader(int passindex, vector<STR_String>& propNames)
{
texflag[passindex] = 0;
if (glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture") != -1)
{
if (GLEW_ARB_depth_texture)
texflag[passindex] |= 0x1;
}
if (glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture") != -1)
{
texflag[passindex] |= 0x2;
}
if (m_gameObjects[passindex])
{
int objProperties = propNames.size();
int i;
for (i=0; i<objProperties; i++)
if (glGetUniformLocationARB(m_filters[passindex], propNames[i]) != -1)
m_properties[passindex].push_back(propNames[i]);
}
}
void RAS_2DFilterManager::StartShaderProgram(int passindex)
{
GLint uniformLoc;
glUseProgramObjectARB(m_filters[passindex]);
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTexture");
glActiveTextureARB(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texname[0]);
if (uniformLoc != -1)
{
glUniform1iARB(uniformLoc, 0);
}
/* send depth texture to glsl program if it needs */
if (texflag[passindex] & 0x1) {
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_DepthTexture");
glActiveTextureARB(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texname[1]);
if (uniformLoc != -1)
{
glUniform1iARB(uniformLoc, 1);
}
}
/* send luminance texture to glsl program if it needs */
if (texflag[passindex] & 0x2) {
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_LuminanceTexture");
glActiveTextureARB(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texname[2]);
if (uniformLoc != -1)
{
glUniform1iARB(uniformLoc, 2);
}
}
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_TextureCoordinateOffset");
if (uniformLoc != -1)
{
glUniform2fvARB(uniformLoc, 9, textureoffsets);
}
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureWidth");
if (uniformLoc != -1)
{
glUniform1fARB(uniformLoc,texturewidth);
}
uniformLoc = glGetUniformLocationARB(m_filters[passindex], "bgl_RenderedTextureHeight");
if (uniformLoc != -1)
{
glUniform1fARB(uniformLoc,textureheight);
}
int i, objProperties = m_properties[passindex].size();
for (i=0; i<objProperties; i++)
{
uniformLoc = glGetUniformLocationARB(m_filters[passindex], m_properties[passindex][i]);
if (uniformLoc == -1)
continue;
CValue *property = ((CValue *)m_gameObjects[passindex])->GetProperty(m_properties[passindex][i]);
if (!property)
continue;
switch (property->GetValueType()) {
case VALUE_INT_TYPE:
glUniform1iARB(uniformLoc, property->GetNumber());
break;
case VALUE_FLOAT_TYPE:
glUniform1fARB(uniformLoc, property->GetNumber());
break;
default:
break;
}
}
}
void RAS_2DFilterManager::EndShaderProgram()
{
glUseProgramObjectARB(0);
}
void RAS_2DFilterManager::FreeTextures()
{
if (texname[0]!=(unsigned int)-1)
glDeleteTextures(1, (GLuint*)&texname[0]);
if (texname[1]!=(unsigned int)-1)
glDeleteTextures(1, (GLuint*)&texname[1]);
if (texname[2]!=(unsigned int)-1)
glDeleteTextures(1, (GLuint*)&texname[2]);
}
void RAS_2DFilterManager::SetupTextures(bool depth, bool luminance)
{
FreeTextures();
glGenTextures(1, (GLuint*)&texname[0]);
glBindTexture(GL_TEXTURE_2D, texname[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texturewidth, textureheight, 0, GL_RGBA,
GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
if (depth) {
glGenTextures(1, (GLuint*)&texname[1]);
glBindTexture(GL_TEXTURE_2D, texname[1]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, texturewidth,textureheight,
0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE,NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE,
GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
}
if (luminance) {
glGenTextures(1, (GLuint*)&texname[2]);
glBindTexture(GL_TEXTURE_2D, texname[2]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE16, texturewidth, textureheight,
0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
}
}
void RAS_2DFilterManager::UpdateOffsetMatrix(RAS_ICanvas* canvas)
{
/* RAS_Rect canvas_rect = canvas->GetWindowArea(); */ /* UNUSED */
texturewidth = canvas->GetWidth()+1;
textureheight = canvas->GetHeight()+1;
GLint i,j;
if (!GL_ARB_texture_non_power_of_two)
{
i = 0;
while ((1 << i) <= texturewidth)
i++;
texturewidth = (1 << (i));
// Now for height
i = 0;
while ((1 << i) <= textureheight)
i++;
textureheight = (1 << (i));
}
GLfloat xInc = 1.0f / (GLfloat)texturewidth;
GLfloat yInc = 1.0f / (GLfloat)textureheight;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
textureoffsets[(((i*3)+j)*2)+0] = (-1.0f * xInc) + ((GLfloat)i * xInc);
textureoffsets[(((i*3)+j)*2)+1] = (-1.0f * yInc) + ((GLfloat)j * yInc);
}
}
}
void RAS_2DFilterManager::UpdateCanvasTextureCoord(const int viewport[4])
{
/*
* This function update canvascoord[].
* These parameters are used to create texcoord[1]
* That way we can access the texcoord relative to the canvas:
* (0.0,0.0) bottom left, (1.0,1.0) top right, (0.5,0.5) center
*/
canvascoord[0] = (GLfloat) viewport[0] / -viewport[2];
canvascoord[1] = (GLfloat) (texturewidth - viewport[0]) / viewport[2];
canvascoord[2] = (GLfloat) viewport[1] / -viewport[3];
canvascoord[3] = (GLfloat)(textureheight - viewport[1]) / viewport[3];
}
void RAS_2DFilterManager::RenderFilters(RAS_ICanvas* canvas)
{
bool need_depth=false;
bool need_luminance=false;
int num_filters = 0;
int passindex;
if (!isshadersupported)
return;
for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
{
if (m_filters[passindex] && m_enabled[passindex]) {
num_filters ++;
if (texflag[passindex] & 0x1)
need_depth = true;
if (texflag[passindex] & 0x2)
need_luminance = true;
if (need_depth && need_luminance)
break;
}
}
if (num_filters <= 0)
return;
const int *viewport = canvas->GetViewPort();
if (texturewidth != viewport[2] || textureheight != viewport[3])
{
UpdateOffsetMatrix(canvas);
UpdateCanvasTextureCoord(viewport);
need_tex_update = true;
}
if (need_tex_update)
{
SetupTextures(need_depth, need_luminance);
need_tex_update = false;
}
if (need_depth) {
glActiveTextureARB(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texname[1]);
glCopyTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT, viewport[0], viewport[1], viewport[2], viewport[3], 0);
}
if (need_luminance) {
glActiveTextureARB(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, texname[2]);
glCopyTexImage2D(GL_TEXTURE_2D,0,GL_LUMINANCE16, viewport[0], viewport[1], viewport[2], viewport[3], 0);
}
// reverting to texunit 0, without this we get bug [#28462]
glActiveTextureARB(GL_TEXTURE0);
// We do this to make side-by-side stereo rendering work correctly with 2D filters. It would probably be nicer to just set the viewport,
// but it can be easier for writing shaders to have the coordinates for the whole screen instead of just part of the screen.
RAS_Rect scissor_rect = canvas->GetDisplayArea();
glScissor(scissor_rect.GetLeft() + viewport[0],
scissor_rect.GetBottom() + viewport[1],
scissor_rect.GetWidth() + 1,
scissor_rect.GetHeight() + 1);
glDisable(GL_DEPTH_TEST);
// in case the previous material was wire
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// if the last rendered face had alpha add it would messes with the color of the plane we apply 2DFilter to
glDisable(GL_BLEND);
// fix for [#34523] alpha buffer is now available for all OSs
glDisable(GL_ALPHA_TEST);
glPushMatrix(); //GL_MODELVIEW
glLoadIdentity(); // GL_MODELVIEW
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
for (passindex =0; passindex<MAX_RENDER_PASS; passindex++)
{
if (m_filters[passindex] && m_enabled[passindex])
{
StartShaderProgram(passindex);
glActiveTextureARB(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texname[0]);
glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, viewport[0], viewport[1], viewport[2], viewport[3], 0); // Don't use texturewidth and textureheight in case we don't have NPOT support
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
glColor4f(1.f, 1.f, 1.f, 1.f);
glTexCoord2f(1.0f, 1.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[3]); glVertex2f(1.0f,1.0f);
glTexCoord2f(0.0f, 1.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[3]); glVertex2f(-1.0f,1.0f);
glTexCoord2f(0.0f, 0.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[0], canvascoord[2]); glVertex2f(-1.0f,-1.0f);
glTexCoord2f(1.0f, 0.0f); glMultiTexCoord2fARB(GL_TEXTURE3_ARB, canvascoord[1], canvascoord[2]); glVertex2f(1.0f,-1.0f);
glEnd();
}
}
glEnable(GL_DEPTH_TEST);
EndShaderProgram();
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
void RAS_2DFilterManager::EnableFilter(vector<STR_String>& propNames, void* gameObj, RAS_2DFILTER_MODE mode, int pass, STR_String& text)
{
if (!isshadersupported)
return;
if (pass<0 || pass>=MAX_RENDER_PASS)
return;
need_tex_update = true;
if (mode == RAS_2DFILTER_DISABLED)
{
m_enabled[pass] = 0;
return;
}
if (mode == RAS_2DFILTER_ENABLED)
{
m_enabled[pass] = 1;
return;
}
if (mode == RAS_2DFILTER_NOFILTER)
{
if (m_filters[pass])
glDeleteObjectARB(m_filters[pass]);
m_enabled[pass] = 0;
m_filters[pass] = 0;
m_gameObjects[pass] = NULL;
m_properties[pass].clear();
texflag[pass] = 0;
return;
}
if (mode == RAS_2DFILTER_CUSTOMFILTER)
{
if (m_filters[pass])
glDeleteObjectARB(m_filters[pass]);
m_filters[pass] = CreateShaderProgram(text.Ptr());
m_gameObjects[pass] = gameObj;
AnalyseShader(pass, propNames);
m_enabled[pass] = 1;
return;
}
// We've checked all other cases, which means we must be dealing with a builtin filter
if (m_filters[pass])
glDeleteObjectARB(m_filters[pass]);
m_filters[pass] = CreateShaderProgram(mode);
m_gameObjects[pass] = NULL;
AnalyseShader(pass, propNames);
m_enabled[pass] = 1;
}
| 28.388988 | 182 | 0.728837 | [
"vector"
] |
f37b05329773b73f8a1136de151878d5eb4485da | 6,657 | cpp | C++ | test/treeifier.cpp | remyers/btcdeb | abe0f457f84167120b318174df0ad38cd91a0fb2 | [
"MIT"
] | 2 | 2019-02-09T21:50:28.000Z | 2021-11-03T16:46:49.000Z | test/treeifier.cpp | remyers/btcdeb | abe0f457f84167120b318174df0ad38cd91a0fb2 | [
"MIT"
] | null | null | null | test/treeifier.cpp | remyers/btcdeb | abe0f457f84167120b318174df0ad38cd91a0fb2 | [
"MIT"
] | 2 | 2018-12-01T13:31:27.000Z | 2021-12-11T14:53:02.000Z | #include "catch.hpp"
#include "../compiler/tinyparser.h"
// inline std::vector<tiny::st_c> _list(tiny::st_t* list[]) {
// std::vector<tiny::st_c> r;
// for (size_t i = 0; list[i]; ++i) {
// r.emplace_back(list[i]);
// }
// return r;
// }
// #define LIST(vals...) _list((tiny::st_t*[]){vals, nullptr})
#define RVAL(str, r) new tiny::value_t(tiny::tok_number, str, r)
#define VAL(str) RVAL(str, tiny::tok_undef)
#define VAR(name) new tiny::var_t(name)
#define BIN(op,a,b) new tiny::bin_t(op, a, b)
// #define CALL(fname, args) new tiny::call_t(fname, new tiny::list_t(LIST(args)))
// #define PCALL(r, args) new tiny::pcall_t(r, new tiny::list_t(LIST(args)))
#define PREG(args, seq) new tiny::func_t(args, seq)
#define SET(varname, val) new tiny::set_t(varname, val)
// #define SEQ(vals...) new tiny::sequence_t(LIST(vals))
TEST_CASE("Simple Treeify", "[treeify-simple]") {
SECTION("1 entry") {
const char* inputs[] = {
"0",
"1",
"arr",
"\"hello world\"",
"my_var",
"0x",
"0x1234",
"0b1011",
"aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899",
"aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889",
nullptr,
};
tiny::st_t* expected[] = {
VAL("0"),
VAL("1"),
VAR("arr"),
VAL("hello world"),
VAR("my_var"),
RVAL("", tiny::tok_hex),
RVAL("1234", tiny::tok_hex),
RVAL("1011", tiny::tok_bin),
VAR("aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"),
VAR("aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889"),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("2 tokens") {
const char* inputs[] = {
"(0)",
"(1)",
"(arr)",
"(\"hello world\")",
"(my_var)",
"(0x)",
"(0x1234)",
"(0b1011)",
"(aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899)",
"(aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889)",
"!1",
"!0",
nullptr,
};
tiny::st_t* expected[] = {
VAL("0"),
VAL("1"),
VAR("arr"),
VAL("hello world"),
VAR("my_var"),
RVAL("", tiny::tok_hex),
RVAL("1234", tiny::tok_hex),
RVAL("1011", tiny::tok_bin),
VAR("aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"),
VAR("aabbccddeeff00112233445566778899gaabbccddeeff0011223344556677889"),
new tiny::unary_t(tiny::tok_not, VAL("1")),
new tiny::unary_t(tiny::tok_not, VAL("0")),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("3 tokens") {
const char* inputs[] = {
"1 + 1",
"1 - 1",
"a * a",
"10 / 5",
"\"hello\" ++ \"world\"",
"0xab ++ 0xcd",
"function()",
nullptr,
};
tiny::st_t* expected[] = {
BIN(tiny::tok_plus, VAL("1"), VAL("1")),
BIN(tiny::tok_minus, VAL("1"), VAL("1")),
BIN(tiny::tok_mul, VAR("a"), VAR("a")),
BIN(tiny::tok_div, VAL("10"), VAL("5")),
BIN(tiny::tok_concat, VAL("hello"), VAL("world")),
BIN(tiny::tok_concat, RVAL("ab", tiny::tok_hex), RVAL("cd", tiny::tok_hex)),
new tiny::call_t("function", nullptr),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("4 tokens") {
const char* inputs[] = {
"a *= 5",
// "() {}",
"a ++= 11",
nullptr,
};
tiny::st_t* expected[] = {
SET("a", BIN(tiny::tok_mul, VAR("a"), VAL("5"))),
// PREG(std::vector<std::string>(), SEQ(nullptr)),
SET("a", BIN(tiny::tok_concat, VAR("a"), VAL("11"))),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
SECTION("5 tokens") {
const char* inputs[] = {
"2 + 3 * 5",
"2 * 3 + 5",
"2 ++ 3 * 5",
"2 * 3 ++ 5",
// "() { 10 }",
"a = a * 5",
nullptr,
};
tiny::st_t* expected[] = {
BIN(tiny::tok_plus, VAL("2"), BIN(tiny::tok_mul, VAL("3"), VAL("5"))),
BIN(tiny::tok_plus, BIN(tiny::tok_mul, VAL("2"), VAL("3")), VAL("5")),
BIN(tiny::tok_concat, VAL("2"), BIN(tiny::tok_mul, VAL("3"), VAL("5"))),
BIN(tiny::tok_concat, BIN(tiny::tok_mul, VAL("2"), VAL("3")), VAL("5")),
// PREG(std::vector<std::string>(), SEQ(VAL("10"))),
SET("a", BIN(tiny::tok_mul, VAR("a"), VAL("5"))),
};
for (size_t i = 0; inputs[i]; ++i) {
GIVEN(inputs[i]) {
tiny::token_t* t = tiny::tokenize(inputs[i]);
tiny::st_t* tree = tiny::treeify(t);
REQUIRE(tree->to_string() == expected[i]->to_string());
delete t;
delete tree;
delete expected[i];
}
}
}
}
| 34.853403 | 88 | 0.453658 | [
"vector"
] |
f37bcc500bf4601362a54a132406e50803e430a1 | 29,233 | cpp | C++ | src/openms/source/FORMAT/MzTab.cpp | andreott/OpenMS | 718fa2e8a91280ff65e4cf834a3d825811dce1dc | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 1 | 2021-07-06T09:15:10.000Z | 2021-07-06T09:15:10.000Z | src/openms/source/FORMAT/MzTab.cpp | andreott/OpenMS | 718fa2e8a91280ff65e4cf834a3d825811dce1dc | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | src/openms/source/FORMAT/MzTab.cpp | andreott/OpenMS | 718fa2e8a91280ff65e4cf834a3d825811dce1dc | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2018.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
namespace OpenMS
{
MzTabParameterList::~MzTabParameterList()
{
}
bool MzTabParameterList::isNull() const
{
return parameters_.empty();
}
void MzTabParameterList::setNull(bool b)
{
if (b)
{
parameters_.clear();
}
}
String MzTabParameterList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabParameter>::const_iterator it = parameters_.begin(); it != parameters_.end(); ++it)
{
if (it != parameters_.begin())
{
ret += "|";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabParameterList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split("|", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabParameter p;
lower = fields[i];
lower.toLower().trim();
if (lower == "null")
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("MzTabParameter in MzTabParameterList must not be null '") + s);
}
p.fromCellString(fields[i]);
parameters_.push_back(p);
}
}
}
std::vector<MzTabParameter> MzTabParameterList::get() const
{
return parameters_;
}
void MzTabParameterList::set(const std::vector<MzTabParameter>& parameters)
{
parameters_ = parameters;
}
MzTabStringList::MzTabStringList() :
sep_('|')
{
}
MzTabStringList::~MzTabStringList()
{
}
void MzTabStringList::setSeparator(char sep)
{
sep_ = sep;
}
bool MzTabStringList::isNull() const
{
return entries_.empty();
}
void MzTabStringList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabStringList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabString>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += sep_;
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabStringList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split(sep_, fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabString ts;
ts.fromCellString(fields[i]);
entries_.push_back(ts);
}
}
}
std::vector<MzTabString> MzTabStringList::get() const
{
return entries_;
}
void MzTabStringList::set(const std::vector<MzTabString>& entries)
{
entries_ = entries;
}
MzTabModification::MzTabModification()
{
}
MzTabModification::~MzTabModification()
{
}
bool MzTabModification::isNull() const
{
return pos_param_pairs_.empty() && mod_identifier_.isNull();
}
void MzTabModification::setNull(bool b)
{
if (b)
{
pos_param_pairs_.clear();
mod_identifier_.setNull(true);
}
}
void MzTabModification::setPositionsAndParameters(const std::vector<std::pair<Size, MzTabParameter> >& ppp)
{
pos_param_pairs_ = ppp;
}
std::vector<std::pair<Size, MzTabParameter> > MzTabModification::getPositionsAndParameters() const
{
return pos_param_pairs_;
}
void MzTabModification::setModificationIdentifier(const MzTabString& mod_id)
{
mod_identifier_ = mod_id;
}
MzTabString MzTabModification::getModOrSubstIdentifier() const
{
assert(!isNull());
return mod_identifier_;
}
String MzTabModification::toCellString() const
{
if (isNull())
{
return String("null");
}
else
{
String pos_param_string;
for (Size i = 0; i != pos_param_pairs_.size(); ++i)
{
pos_param_string += pos_param_pairs_[i].first;
// attach MzTabParameter if available
if (!pos_param_pairs_[i].second.isNull())
{
pos_param_string += pos_param_pairs_[i].second.toCellString();
}
// add | as separator (except for last one)
if (i < pos_param_pairs_.size() - 1)
{
pos_param_string += String("|");
}
}
// quick sanity check
if (mod_identifier_.isNull())
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Modification or Substitution identifier MUST NOT be null or empty in MzTabModification"));
}
String res;
// only add '-' if we have position information
if (!pos_param_string.empty())
{
res = pos_param_string + "-" + mod_identifier_.toCellString();
}
else
{
res = mod_identifier_.toCellString();
}
return res;
}
}
void MzTabModification::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
if (!lower.hasSubstring("-")) // no positions? simply use s as mod identifier
{
mod_identifier_.set(String(s).trim());
}
else
{
String ss = s;
ss.trim();
std::vector<String> fields;
ss.split("-", fields);
if (fields.size() != 2)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Can't convert to MzTabModification from '") + s);
}
mod_identifier_.fromCellString(fields[1].trim());
std::vector<String> position_fields;
fields[0].split("|", position_fields);
for (Size i = 0; i != position_fields.size(); ++i)
{
Size spos = position_fields[i].find_first_of("[");
if (spos == std::string::npos) // only position information and no parameter
{
pos_param_pairs_.push_back(std::make_pair(position_fields[i].toInt(), MzTabParameter()));
}
else
{
// extract position part
Int pos = String(position_fields[i].begin(), position_fields[i].begin() + spos).toInt();
// extract [,,,] part
MzTabParameter param;
param.fromCellString(position_fields[i].substr(spos));
pos_param_pairs_.push_back(std::make_pair(pos, param));
}
}
}
}
}
MzTabModificationList::~MzTabModificationList()
{
}
bool MzTabModificationList::isNull() const
{
return entries_.empty();
}
void MzTabModificationList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabModificationList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabModification>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += ",";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabModificationList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
if (!ss.hasSubstring("[")) // no parameters
{
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabModification ms;
ms.fromCellString(fields[i]);
entries_.push_back(ms);
}
}
else
{
// example string: 3|4[a,b,,v]|8[,,"blabla, [bla]",v],1|2|3[a,b,,v]-mod:123
// we don't want to split at the , inside of [ ] MzTabParameter brackets.
// Additionally, and we don't want to recognise quoted brackets inside the MzTabParameter where they can occur in quoted text (see example string)
bool in_param_bracket = false;
bool in_quotes = false;
for (Size pos = 0; pos != ss.size(); ++pos)
{
// param_bracket state
if (ss[pos] == '[' && !in_quotes)
{
in_param_bracket = true;
continue;
}
if (ss[pos] == ']' && !in_quotes)
{
in_param_bracket = false;
continue;
}
// quote state
if (ss[pos] == '\"')
{
in_quotes = !in_quotes;
continue;
}
// comma in param bracket
if (ss[pos] == ',' && !in_quotes && in_param_bracket)
{
ss[pos] = ((char)007); // use ASCII bell as temporary separator
continue;
}
}
// now the split at comma is save
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
fields[i].substitute(((char)007), ','); // resubstitute comma after split
MzTabModification ms;
ms.fromCellString(fields[i]);
entries_.push_back(ms);
}
}
}
}
std::vector<MzTabModification> MzTabModificationList::get() const
{
return entries_;
}
void MzTabModificationList::set(const std::vector<MzTabModification>& entries)
{
entries_ = entries;
}
MzTabSpectraRef::MzTabSpectraRef() :
ms_run_(0)
{
}
MzTabSpectraRef::~MzTabSpectraRef()
{
}
bool MzTabSpectraRef::isNull() const
{
return (ms_run_ < 1) || (spec_ref_.empty());
}
void MzTabSpectraRef::setNull(bool b)
{
if (b)
{
ms_run_ = 0;
spec_ref_.clear();
}
}
void MzTabSpectraRef::setMSFile(Size index)
{
assert(index >= 1);
if (index >= 1)
{
ms_run_ = index;
}
}
void MzTabSpectraRef::setSpecRef(String spec_ref)
{
assert(!spec_ref.empty());
if (!spec_ref.empty())
{
spec_ref_ = spec_ref;
}
}
String MzTabSpectraRef::getSpecRef() const
{
assert(!isNull());
return spec_ref_;
}
Size MzTabSpectraRef::getMSFile() const
{
assert(!isNull());
return ms_run_;
}
void MzTabSpectraRef::setSpecRefFile(const String& spec_ref)
{
assert(!spec_ref.empty());
if (!spec_ref.empty())
{
spec_ref_ = spec_ref;
}
}
String MzTabSpectraRef::toCellString() const
{
if (isNull())
{
return String("null");
}
else
{
return String("ms_run[") + String(ms_run_) + "]:" + spec_ref_;
}
}
void MzTabSpectraRef::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split(":", fields);
if (fields.size() != 2)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Can not convert to MzTabSpectraRef from '") + s);
}
spec_ref_ = fields[1];
ms_run_ = (Size)(fields[0].substitute("ms_run[", "").remove(']').toInt());
}
}
MzTabProteinSectionRow::MzTabProteinSectionRow()
{
// use "," as list separator because "|" can be used for go terms and protein accessions
go_terms.setSeparator(',');
ambiguity_members.setSeparator(',');
}
MzTabMetaData::MzTabMetaData()
{
mz_tab_version.fromCellString(String("1.0.0"));
}
MzTab::MzTab()
{
}
MzTab::~MzTab()
{
}
const MzTabMetaData& MzTab::getMetaData() const
{
return meta_data_;
}
void MzTab::setMetaData(const MzTabMetaData& md)
{
meta_data_ = md;
}
const MzTabProteinSectionRows& MzTab::getProteinSectionRows() const
{
return protein_data_;
}
void MzTab::setProteinSectionRows(const MzTabProteinSectionRows& psd)
{
protein_data_ = psd;
}
const MzTabPeptideSectionRows& MzTab::getPeptideSectionRows() const
{
return peptide_data_;
}
void MzTab::setPeptideSectionRows(const MzTabPeptideSectionRows& psd)
{
peptide_data_ = psd;
}
const MzTabPSMSectionRows& MzTab::getPSMSectionRows() const
{
return psm_data_;
}
void MzTab::setPSMSectionRows(const MzTabPSMSectionRows& psd)
{
psm_data_ = psd;
}
void MzTab::setCommentRows(const std::map<Size, String>& com)
{
comment_rows_ = com;
}
void MzTab::setEmptyRows(const std::vector<Size>& empty)
{
empty_rows_ = empty;
}
const std::vector<Size>& MzTab::getEmptyRows() const
{
return empty_rows_;
}
const std::map<Size, String>& MzTab::getCommentRows() const
{
return comment_rows_;
}
const MzTabSmallMoleculeSectionRows& MzTab::getSmallMoleculeSectionRows() const
{
return small_molecule_data_;
}
void MzTab::setSmallMoleculeSectionRows(const MzTabSmallMoleculeSectionRows& smsd)
{
small_molecule_data_ = smsd;
}
std::vector<String> MzTab::getProteinOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!protein_data_.empty())
{
for (MzTabProteinSectionRows::const_iterator it = protein_data_.begin(); it != protein_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
std::vector<String> MzTab::getPeptideOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!peptide_data_.empty())
{
for (MzTabPeptideSectionRows::const_iterator it = peptide_data_.begin(); it != peptide_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
std::vector<String> MzTab::getPSMOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!psm_data_.empty())
{
for (MzTabPSMSectionRows::const_iterator it = psm_data_.begin(); it != psm_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
std::vector<String> MzTab::getSmallMoleculeOptionalColumnNames() const
{
// vector is used to preserve the column order
std::vector<String> names;
if (!small_molecule_data_.empty())
{
for (MzTabSmallMoleculeSectionRows::const_iterator it = small_molecule_data_.begin(); it != small_molecule_data_.end(); ++it)
{
for (std::vector<MzTabOptionalColumnEntry>::const_iterator it_opt = it->opt_.begin(); it_opt != it->opt_.end(); ++it_opt)
{
if (std::find(names.begin(), names.end(), it_opt->first) == names.end())
{
names.push_back(it_opt->first);
}
}
}
}
return names;
}
MzTabParameter::MzTabParameter()
: CV_label_(""),
accession_(""),
name_(""),
value_("")
{
}
MzTabParameter::~MzTabParameter()
{
}
bool MzTabParameter::isNull() const
{
return CV_label_.empty() && accession_.empty() && name_.empty() && value_.empty();
}
void MzTabParameter::setNull(bool b)
{
if (b)
{
CV_label_.clear();
accession_.clear();
name_.clear();
value_.clear();
}
}
void MzTabParameter::setCVLabel(const String& CV_label)
{
CV_label_ = CV_label;
}
void MzTabParameter::setAccession(const String& accession)
{
accession_ = accession;
}
void MzTabParameter::setName(const String& name)
{
name_ = name;
}
void MzTabParameter::setValue(const String& value)
{
value_ = value;
}
String MzTabParameter::getCVLabel() const
{
assert(!isNull());
return CV_label_;
}
String MzTabParameter::getAccession() const
{
assert(!isNull());
return accession_;
}
String MzTabParameter::getName() const
{
assert(!isNull());
return name_;
}
String MzTabParameter::getValue() const
{
assert(!isNull());
return value_;
}
String MzTabParameter::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret = "[";
ret += CV_label_ + ", ";
ret += accession_ + ", ";
if (name_.hasSubstring(", "))
{
ret += String("\"") + name_ + String("\""); // quote name if it contains a ","
}
else
{
ret += name_;
}
ret += String(", ");
if (value_.hasSubstring(", "))
{
ret += String("\"") + value_ + String("\""); // quote value if it contains a ","
}
else
{
ret += value_;
}
ret += "]";
return ret;
}
}
void MzTabParameter::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
StringList fields;
String field;
bool in_quotes = false;
for (String::const_iterator sit = s.begin(); sit != s.end(); ++sit)
{
if (*sit == '\"') // start or end of quotes
{
in_quotes = !in_quotes;
}
else if (*sit == ',') // , encountered
{
if (in_quotes) // case 1: , in quote
{
field += ','; // add , (no split)
}
else // split at , if not in quotes
{
fields.push_back(field.trim());
field.clear();
}
}
else if (*sit != '[' && *sit != ']')
{
// skip leading ws
if (*sit == ' ' && field.empty())
{
continue;
}
field += *sit;
}
}
fields.push_back(field.trim());
if (fields.size() != 4)
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert String '") + s + "' to MzTabParameter");
}
CV_label_ = fields[0];
accession_ = fields[1];
name_ = fields[2];
value_ = fields[3];
}
}
MzTabString::MzTabString(const String& s)
{
set(s);
}
MzTabString::~MzTabString()
{
}
void MzTabString::set(const String& value)
{
String lower = value;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
value_ = value;
value_.trim();
}
}
String MzTabString::get() const
{
return value_;
}
bool MzTabString::isNull() const
{
return value_.empty();
}
void MzTabString::setNull(bool b)
{
if (b)
{
value_.clear();
}
}
MzTabString::MzTabString()
: value_()
{
}
String MzTabString::toCellString() const
{
if (isNull())
{
return String("null");
}
else
{
return value_;
}
}
void MzTabString::fromCellString(const String& s)
{
set(s);
}
MzTabBoolean::MzTabBoolean(bool v)
{
set(v);
}
MzTabBoolean::~MzTabBoolean()
{
}
MzTabBoolean::MzTabBoolean()
: value_(false)
{
}
void MzTabBoolean::set(const bool& value)
{
setNull(false);
value_ = value;
}
Int MzTabBoolean::get() const
{
return value_;
}
String MzTabBoolean::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
if (value_)
{
return "1";
}
else
{
return "0";
}
}
}
void MzTabBoolean::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
if (s == "0")
{
set(false);
}
else if (s == "1")
{
set(true);
}
else
{
throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert String '") + s + "' to MzTabBoolean");
}
}
}
MzTabIntegerList::MzTabIntegerList()
{
}
bool MzTabIntegerList::isNull() const
{
return entries_.empty();
}
void MzTabIntegerList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabIntegerList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabInteger>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += ",";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabIntegerList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split(",", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabInteger ds;
ds.fromCellString(fields[i]);
entries_.push_back(ds);
}
}
}
std::vector<MzTabInteger> MzTabIntegerList::get() const
{
return entries_;
}
void MzTabIntegerList::set(const std::vector<MzTabInteger>& entries)
{
entries_ = entries;
}
MzTabInteger::MzTabInteger(const int v)
{
set(v);
}
MzTabInteger::~MzTabInteger()
{
}
MzTabInteger::MzTabInteger()
: value_(0)
{
}
void MzTabInteger::set(const Int& value)
{
state_ = MZTAB_CELLSTATE_DEFAULT;
value_ = value;
}
Int MzTabInteger::get() const
{
if (state_ == MZTAB_CELLSTATE_DEFAULT)
{
return value_;
}
else
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Trying to extract MzTab Integer value from non-integer valued cell. Did you check the cell state before querying the value?"));
}
}
String MzTabInteger::toCellString() const
{
switch (state_)
{
case MZTAB_CELLSTATE_NULL:
return String("null");
case MZTAB_CELLSTATE_NAN:
return String("NaN");
case MZTAB_CELLSTATE_INF:
return String("Inf");
case MZTAB_CELLSTATE_DEFAULT:
default:
return String(value_);
}
}
void MzTabInteger::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else if (lower == "nan")
{
setNaN();
}
else if (lower == "inf")
{
setInf();
}
else // default case
{
set(lower.toInt());
}
}
MzTabNullAbleBase::MzTabNullAbleBase() :
null_(true)
{
}
MzTabNullAbleBase::~MzTabNullAbleBase()
{
}
bool MzTabNullAbleBase::isNull() const
{
return null_;
}
void MzTabNullAbleBase::setNull(bool b)
{
null_ = b;
}
MzTabNullNaNAndInfAbleBase::MzTabNullNaNAndInfAbleBase() :
state_(MZTAB_CELLSTATE_NULL)
{
}
MzTabNullNaNAndInfAbleBase::~MzTabNullNaNAndInfAbleBase()
{
}
bool MzTabNullNaNAndInfAbleBase::isNull() const
{
return state_ == MZTAB_CELLSTATE_NULL;
}
void MzTabNullNaNAndInfAbleBase::setNull(bool b)
{
state_ = b ? MZTAB_CELLSTATE_NULL : MZTAB_CELLSTATE_DEFAULT;
}
bool MzTabNullNaNAndInfAbleBase::isNaN() const
{
return state_ == MZTAB_CELLSTATE_NAN;
}
void MzTabNullNaNAndInfAbleBase::setNaN()
{
state_ = MZTAB_CELLSTATE_NAN;
}
bool MzTabNullNaNAndInfAbleBase::isInf() const
{
return state_ == MZTAB_CELLSTATE_INF;
}
void MzTabNullNaNAndInfAbleBase::setInf()
{
state_ = MZTAB_CELLSTATE_INF;
}
MzTabDouble::MzTabDouble()
: value_(0.0)
{
}
MzTabDouble::MzTabDouble(const double v)
{
set(v);
}
MzTabDouble::~MzTabDouble()
{
}
void MzTabDouble::set(const double& value)
{
state_ = MZTAB_CELLSTATE_DEFAULT;
value_ = value;
}
double MzTabDouble::get() const
{
if (state_ != MZTAB_CELLSTATE_DEFAULT)
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Trying to extract MzTab Double value from non-double valued cell. Did you check the cell state before querying the value?"));
}
return value_;
}
String MzTabDouble::toCellString() const
{
switch (state_)
{
case MZTAB_CELLSTATE_NULL:
return String("null");
case MZTAB_CELLSTATE_NAN:
return String("NaN");
case MZTAB_CELLSTATE_INF:
return String("Inf");
case MZTAB_CELLSTATE_DEFAULT:
default:
return String(value_);
}
}
void MzTabDouble::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else if (lower == "nan")
{
setNaN();
}
else if (lower == "inf")
{
setInf();
}
else // default case
{
set(lower.toDouble());
}
}
MzTabDoubleList::MzTabDoubleList()
{
}
MzTabDoubleList::~MzTabDoubleList()
{
}
bool MzTabDoubleList::isNull() const
{
return entries_.empty();
}
void MzTabDoubleList::setNull(bool b)
{
if (b)
{
entries_.clear();
}
}
String MzTabDoubleList::toCellString() const
{
if (isNull())
{
return "null";
}
else
{
String ret;
for (std::vector<MzTabDouble>::const_iterator it = entries_.begin(); it != entries_.end(); ++it)
{
if (it != entries_.begin())
{
ret += "|";
}
ret += it->toCellString();
}
return ret;
}
}
void MzTabDoubleList::fromCellString(const String& s)
{
String lower = s;
lower.toLower().trim();
if (lower == "null")
{
setNull(true);
}
else
{
String ss = s;
std::vector<String> fields;
ss.split("|", fields);
for (Size i = 0; i != fields.size(); ++i)
{
MzTabDouble ds;
ds.fromCellString(fields[i]);
entries_.push_back(ds);
}
}
}
std::vector<MzTabDouble> MzTabDoubleList::get() const
{
return entries_;
}
void MzTabDoubleList::set(const std::vector<MzTabDouble>& entries)
{
entries_ = entries;
}
MzTabNullAbleInterface::~MzTabNullAbleInterface()
{
}
MzTabNullNaNAndInfAbleInterface::~MzTabNullNaNAndInfAbleInterface()
{
}
}
| 20.880714 | 218 | 0.570006 | [
"vector"
] |
3ce1cb8c1372cb4e2511a02982842fcf62ebd33f | 9,347 | cpp | C++ | unittests/cancellation.cpp | alexbriskin/taskflow | da69f8989f26f8ff7bc731dbafb2f6ce171934fc | [
"MIT"
] | 3,457 | 2018-06-09T15:36:42.000Z | 2020-06-01T22:09:25.000Z | unittests/cancellation.cpp | alexbriskin/taskflow | da69f8989f26f8ff7bc731dbafb2f6ce171934fc | [
"MIT"
] | 146 | 2018-06-11T04:11:22.000Z | 2020-06-01T20:59:21.000Z | unittests/cancellation.cpp | alexbriskin/taskflow | da69f8989f26f8ff7bc731dbafb2f6ce171934fc | [
"MIT"
] | 426 | 2018-06-06T18:01:16.000Z | 2020-06-01T05:26:17.000Z | #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest.h>
#include <taskflow/taskflow.hpp>
// EmptyFuture
TEST_CASE("EmptyFuture" * doctest::timeout(300)) {
tf::Future<void> fu;
REQUIRE(fu.valid() == false);
REQUIRE(fu.cancel() == false);
}
// Future
TEST_CASE("Future" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
for(int i=0; i<100; i++) {
taskflow.emplace([&](){
counter.fetch_add(1, std::memory_order_relaxed);
});
}
auto fu = executor.run(taskflow);
fu.get();
REQUIRE(counter == 100);
}
// Cancel
TEST_CASE("Cancel" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<10000; i++) {
taskflow.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
// a new round
counter = 0;
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
// a new round
counter = 0;
fu = executor.run_n(taskflow, 100);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
}
// multiple cnacels
TEST_CASE("MultipleCancels" * doctest::timeout(300)) {
tf::Taskflow taskflow1, taskflow2, taskflow3, taskflow4;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<10000; i++) {
taskflow1.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
taskflow2.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
taskflow3.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
taskflow4.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
// a new round
counter = 0;
auto fu1 = executor.run(taskflow1);
auto fu2 = executor.run(taskflow2);
auto fu3 = executor.run(taskflow3);
auto fu4 = executor.run(taskflow4);
REQUIRE(fu1.cancel() == true);
REQUIRE(fu2.cancel() == true);
REQUIRE(fu3.cancel() == true);
REQUIRE(fu4.cancel() == true);
executor.wait_for_all();
REQUIRE(counter < 10000);
REQUIRE(fu1.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
REQUIRE(fu2.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
REQUIRE(fu3.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
REQUIRE(fu4.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready);
}
// cancel subflow
TEST_CASE("CancelSubflow" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<100; i++) {
taskflow.emplace([&, i](tf::Subflow& sf){
for(int j=0; j<100; j++) {
sf.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
if(i % 2) {
sf.join();
}
else {
sf.detach();
}
});
}
// a new round
counter = 0;
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
// a new round
counter = 0;
auto fu1 = executor.run(taskflow);
auto fu2 = executor.run(taskflow);
auto fu3 = executor.run(taskflow);
REQUIRE(fu1.cancel() == true);
REQUIRE(fu2.cancel() == true);
REQUIRE(fu3.cancel() == true);
fu1.get();
fu2.get();
fu3.get();
REQUIRE(counter < 10000);
}
// cancel asynchronous tasks in subflow
TEST_CASE("CancelSubflowAsyncTasks" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
std::atomic<int> counter{0};
// artificially long (possible larger than 300 seconds)
for(int i=0; i<100; i++) {
taskflow.emplace([&](tf::Subflow& sf){
for(int j=0; j<100; j++) {
auto a = sf.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
auto b = sf.emplace([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
a.precede(b);
sf.async([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
sf.silent_async([&](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.fetch_add(1, std::memory_order_relaxed);
});
}
});
}
// a new round
counter = 0;
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
REQUIRE(counter < 10000);
}
// cancel infinite loop
TEST_CASE("CancelInfiniteLoop" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
for(int i=0; i<100; i++) {
auto a = taskflow.emplace([](){});
auto b = taskflow.emplace([](){ return 0; });
a.precede(b);
b.precede(b);
}
auto fu = executor.run(taskflow);
REQUIRE(fu.cancel() == true);
fu.get();
}
// cancel from another
TEST_CASE("CancelFromAnother" * doctest::timeout(300)) {
tf::Taskflow taskflow, another;
tf::Executor executor(4);
// create a single inifnite loop
auto a = taskflow.emplace([](){});
auto b = taskflow.emplace([](){ return 0; });
a.precede(b);
b.precede(b);
auto fu = executor.run(taskflow);
REQUIRE(fu.wait_for(
std::chrono::milliseconds(100)) == std::future_status::timeout
);
// create a task to cancel another flow
another.emplace([&]() { REQUIRE(fu.cancel() == true); });
executor.run(another).wait();
}
// cancel from async task
TEST_CASE("CancelFromAsync" * doctest::timeout(300)) {
tf::Taskflow taskflow;
tf::Executor executor(4);
// create a single inifnite loop
auto a = taskflow.emplace([](){});
auto b = taskflow.emplace([&](){ return 0; });
a.precede(b);
b.precede(b);
executor.async([&](){
auto fu = executor.run_n(taskflow, 100);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
REQUIRE(fu.cancel() == true);
});
executor.wait_for_all();
}
// cancel async tasks
TEST_CASE("CancelAsync") {
tf::Executor executor(2);
std::vector<tf::Future<void>> futures;
for(int i=0; i<10000; i++) {
futures.push_back(executor.async([](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}));
}
size_t n_success = 0, n_failure = 0;
for(auto& fu : futures) {
if(fu.cancel() == true) n_success++;
else n_failure++;
}
executor.wait_for_all();
REQUIRE(n_success > n_failure);
for(auto& fu : futures) {
REQUIRE(fu.valid());
CHECK_NOTHROW(fu.get());
}
}
// cancel subflow async tasks
TEST_CASE("CancelSubflowAsync") {
tf::Taskflow taskflow;
tf::Executor executor(2);
std::atomic<bool> futures_ready {false};
std::vector<tf::Future<void>> futures;
taskflow.emplace([&](tf::Subflow& sf){
for(int i=0; i<10000; i++) {
futures.push_back(sf.async([](){
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}));
}
futures_ready = true;
});
executor.run(taskflow);
while(!futures_ready);
size_t n_success = 0, n_failure = 0;
for(auto& fu : futures) {
if(fu.cancel() == true) n_success++;
else n_failure++;
}
executor.wait_for_all();
REQUIRE(n_success > n_failure);
for(auto& fu : futures) {
REQUIRE(fu.valid());
CHECK_NOTHROW(fu.get());
}
}
// cancel composition tasks
TEST_CASE("CancelComposition") {
tf::Executor executor(4);
// f1 has two independent tasks
tf::Taskflow f1("F1");
auto f1A = f1.emplace([&](){ });
auto f1B = f1.emplace([&](){ });
f1A.name("f1A");
f1B.name("f1B");
// f2A ---
// |----> f2C
// f2B ---
//
// f1_module_task
tf::Taskflow f2("F2");
auto f2A = f2.emplace([&](){ });
auto f2B = f2.emplace([&](){ });
auto f2C = f2.emplace([&](){ });
f2A.name("f2A");
f2B.name("f2B");
f2C.name("f2C");
f2A.precede(f2C);
f2B.precede(f2C);
f2.composed_of(f1).name("module_of_f1");
// f3 has a module task (f2) and a regular task
tf::Taskflow f3("F3");
f3.composed_of(f2).name("module_of_f2");
f3.emplace([](){ }).name("f3A");
// f4: f3_module_task -> f2_module_task
tf::Taskflow f4;
f4.name("F4");
auto f3_module_task = f4.composed_of(f3).name("module_of_f3");
auto f2_module_task = f4.composed_of(f2).name("module_of_f2");
f3_module_task.precede(f2_module_task);
for(int r=0; r<100; r++) {
size_t N = 100;
size_t success = 0;
std::vector<tf::Future<void>> futures;
for(int i=0; i<100; i++) {
futures.emplace_back(executor.run(f4));
}
for(auto& fu: futures) {
success += (fu.cancel() ? 1 : 0);
}
executor.wait_for_all();
REQUIRE(success <= N);
}
}
| 23.72335 | 83 | 0.616882 | [
"vector"
] |
3cedd21274cecc4294b4cd65c7bee6eb7847133f | 2,021 | cpp | C++ | kuka_interface_pkg/src/single_lwr_homing.cpp | IIRAI/kuka_interface | 5886f68c00650342ab083984debb7b29e443bf7c | [
"BSD-3-Clause"
] | 5 | 2018-09-12T05:45:58.000Z | 2020-02-27T03:12:45.000Z | kuka_interface_pkg/src/single_lwr_homing.cpp | IIRAI/kuka_interface | 5886f68c00650342ab083984debb7b29e443bf7c | [
"BSD-3-Clause"
] | null | null | null | kuka_interface_pkg/src/single_lwr_homing.cpp | IIRAI/kuka_interface | 5886f68c00650342ab083984debb7b29e443bf7c | [
"BSD-3-Clause"
] | 2 | 2019-05-16T10:42:36.000Z | 2021-04-01T13:12:44.000Z | #include <ros/ros.h>
#include <ros/rate.h>
#include <math.h>
#include <geometry_msgs/Pose.h>
#include <sensor_msgs/JointState.h>
#include <std_msgs/Float64.h>
bool received_state = false;
std::vector<double> q0;
void state_callback(const sensor_msgs::JointState& msg)
{
if(received_state) return;
q0.push_back(msg.position.at(0));
q0.push_back(msg.position.at(1));
q0.push_back(msg.position.at(6)); //NOTE: this is because e1 is at the end of the state vector
q0.push_back(msg.position.at(2));
q0.push_back(msg.position.at(3));
q0.push_back(msg.position.at(4));
q0.push_back(msg.position.at(5));
received_state=true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "single_lwr_homing");
ros::NodeHandle n_;
double rateHZ = 100;
std::vector<double> homing, homing_right;
homing.push_back(1.0); //a1
homing.push_back(1.0); //a2
homing.push_back(1.0); //e1
homing.push_back(1.0); //a3
homing.push_back(1.0); //a4
homing.push_back(1.0); //a5
homing.push_back(1.0); //a6
geometry_msgs::Pose command_msg;
ros::Subscriber sub = n_.subscribe("/joint_states",1,&state_callback);
ros::Publisher pub_command_l = n_.advertise<geometry_msgs::Pose>("/kuka_command", 10);
ros::Rate r(rateHZ);
bool active=false;
while(!received_state && ros::ok())
{
r.sleep();
ros::spinOnce();
}
double alpha=0.0;
while(ros::ok())
{
command_msg.position.x = alpha*homing.at(0) + (1-alpha)*q0.at(0);
command_msg.position.y = alpha*homing.at(1) + (1-alpha)*q0.at(1);
command_msg.position.z = alpha*homing.at(2) + (1-alpha)*q0.at(2);
command_msg.orientation.x = alpha*homing.at(3) + (1-alpha)*q0.at(3);
command_msg.orientation.y = alpha*homing.at(4) + (1-alpha)*q0.at(4);
command_msg.orientation.z = alpha*homing.at(5) + (1-alpha)*q0.at(5);
command_msg.orientation.w = alpha*homing.at(6) + (1-alpha)*q0.at(6);
pub_command_l.publish(command_msg);
r.sleep();
ros::spinOnce();
alpha+=0.0025;
if(alpha>1) break;
}
std::cout<<"Homing: DONE"<<std::endl;
return 0;
} | 24.950617 | 95 | 0.685799 | [
"vector"
] |
3cf307f4ebb7a7979d77881b2a868c52ae5c4ea9 | 12,775 | cpp | C++ | methods/islet/islet_isl.cpp | ambrad/COMPOSE | 0bda7aeaf2b8494c7de8cd179c22e340b08eda6e | [
"BSD-3-Clause"
] | 3 | 2018-12-30T20:01:25.000Z | 2020-07-22T23:44:14.000Z | methods/islet/islet_isl.cpp | E3SM-Project/COMPOSE | 0bda7aeaf2b8494c7de8cd179c22e340b08eda6e | [
"BSD-3-Clause"
] | 8 | 2019-02-06T19:08:31.000Z | 2020-04-24T03:40:49.000Z | methods/islet/islet_isl.cpp | ambrad/COMPOSE | 0bda7aeaf2b8494c7de8cd179c22e340b08eda6e | [
"BSD-3-Clause"
] | 2 | 2019-01-16T03:58:31.000Z | 2019-02-06T22:45:43.000Z | #include <cassert>
#include <array>
#include <vector>
#include <limits>
#include "islet_tables.hpp"
#include "islet_util.hpp"
#include "islet_isl.hpp"
#include "islet_xnodes_metrics.hpp"
#include "islet_npx.hpp"
extern "C" {
void dgemm_(const char* transa, const char* transb, const int* m,
const int* n, const int* k, const double* alpha, const double* a,
const int* lda, const double* b, const int* ldb,
const double* beta, double* c, const int* ldc);
void dpotrf_(const char* uplo, const int* n, double* a, const int* lda,
int* info);
void dpotrs_(const char* uplo, const int* n, const int* nrhs, const double* a,
const int* lda, double* b, const int* ldb, int* info);
void dtrsm_(const char* side, const char* uplo, const char* transa, const char* diag,
const int* n, const int* nrhs, const double* alpha, const double* a,
const int* lda, double* b, const int* ldb);
void dtrtrs_(const char* uplo, const char* trans, const char* diag,
const int* n, const int* nrhs, double* a, const int* lda,
double* b, const int* ldb, int* info);
void dgeqrf_(const int* m, const int* n, double* a, const int* lda,
double* tau, double* wrk, int* iwrk, int* info);
void dormqr_(const char* side, const char* trans,
const int* m, const int* n, const int* k,
double* a, const int* lda,
double* tau, double* c, const int* ldc,
double* wrk, const int* iwrk, int* info);
}
namespace islet {
// C = alpha op(A) op(B) + beta C
void dgemm (char transa, char transb, int m, int nrhs, int n, double alpha,
const double* a, int lda, const double* b, int ldb, double beta,
const double* c, int ldc) {
dgemm_(&transa, &transb, &m, &nrhs, &n, &alpha, const_cast<double*>(a), &lda,
const_cast<double*>(b), &ldb, &beta, const_cast<double*>(c), &ldc);
}
int dpotrf (char uplo, int n, double* a, int lda) {
int info;
dpotrf_(&uplo, &n, a, &lda, &info);
return info;
}
int dpotrs (char uplo, int n, int nrhs, const double* a, int lda, double* bx,
int ldb) {
int info;
dpotrs_(&uplo, &n, &nrhs, const_cast<double*>(a), &lda, bx, &ldb, &info);
return info;
}
void dtrsm (char side, char uplo, char transa, char diag, int n, int nrhs,
double alpha, const double* a, int lda, double* bx, int ldb) {
dtrsm_(&side, &uplo, &transa, &diag, &n, &nrhs, &alpha,
const_cast<double*>(a), &lda, bx, &ldb);
}
int dtrtrs (char uplo, char trans, char diag, int n, int nrhs,
double* a, int lda, double* b, int ldb) {
int info;
dtrtrs_(&uplo, &trans, &diag, &n, &nrhs, a, &lda, b, &ldb, &info);
return info;
}
// tau[min(m,n)], wrk[>= n]
int dgeqrf (int m, int n, double* a, int lda,
double* tau, double* wrk, int iwrk) {
int info;
dgeqrf_(&m, &n, a, &lda, tau, wrk, &iwrk, &info);
return info;
}
// tau[min(m,n)], wrk[>= max(m,n)]
int dormqr (char side, char trans, int m, int n, int k, double* a, int lda,
double* tau, double* c, int ldc, double* wrk, int iwrk) {
int info;
dormqr_(&side, &trans, &m, &n, &k, a, &lda, tau, c, &ldc, wrk, &iwrk, &info);
return info;
}
struct GllNatural : public Operator {
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
eval_lagrange_poly(get_xnodes(np), np, x, v);
}
};
struct GllOffsetNodalSubset : public Operator, public npxstab<Real> {
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
npxstab<Real>::eval(np, x, v);
}
};
void eval_offset_nodal_subset (
const Int np, const Int nreg, const Int* subnp, const Int* os, const Real* xnodes,
const Real& x, Real* const v)
{
if (x > 0) {
eval_offset_nodal_subset(np, nreg, subnp, os, xnodes, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
bool done = false;
for (Int i = 0; i < nreg; ++i)
if (x < xnodes[i+1]) {
std::fill(v, v + np, 0);
eval_lagrange_poly(xnodes + os[i], subnp[i], x, v + os[i]);
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(xnodes, np, x, v);
}
static void eval_offset (const Int& np, const Real* const xnodes,
const Int* const subnp, const Int* const offst,
const Real& x, Real* const v) {
if (x > 0) {
eval_offset(np, xnodes, subnp, offst, -x, v);
for (int i = 0; i < np/2; ++i)
std::swap(v[i], v[np-i-1]);
return;
}
bool done = false;
for (Int i = 0; i < np/2; ++i)
if (x < xnodes[i+1]) {
std::fill(v, v + np, 0);
eval_lagrange_poly(xnodes + offst[i], subnp[i], x, v + offst[i]);
done = true;
break;
}
if ( ! done)
eval_lagrange_poly(xnodes, np, x, v);
}
struct GllBest : public Operator {
static void eval_np4 (const Real* const xnodes, const Real& x, Real* const y) {
static const Real c1 = 0.306;
if (x < xnodes[1] || x > xnodes[2]) {
y[0] = y[3] = 0;
const Int os = x < xnodes[1] ? 0 : 1;
eval_lagrange_poly(xnodes + os, 3, x, y + os);
Real y4[4];
eval_lagrange_poly(xnodes, 4, x, y4);
const Real x0 = 2*(1 - std::abs(x))/(1 - xnodes[2]) - 1;
const Real a = (c1 + (0.5 - c1)*x0)*(x0 + 1);
for (int i = 0; i < 4; ++i)
y[i] = a*y[i] + (1 - a)*y4[i];
} else
eval_lagrange_poly(xnodes, 4, x, y);
}
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
const Real* xnodes = get_xnodes(np);
switch (np) {
case 4: eval_np4(xnodes, x, v); break; // 2
case 5: { // 2
const Int subnp[] = {3,4};
const Int offst[] = {0,0};
eval_offset(5, xnodes, subnp, offst, x, v);
} break;
case 6: { // 4
const Int subnp[] = {5,5,6};
const Int n0[] = { 0, 1, 2, 3, 4, };
const Int n1[] = { 0, 1, 2, 3, 5};
const Int n2[] = { 0, 1, 2, 3, 4, 5};
const Int* nodes[] = {n0,n1,n2};
::eval(6, true, xnodes, subnp, nodes, x, v);
} break;
case 7: { // 4
const Int subnp[] = {5,5,6};
const Int offst[] = {0,0,0};
eval_offset(7, xnodes, subnp, offst, x, v);
} break;
case 8: { // 5
const Int subnp[] = {6,6,7,6};
const Int offst[] = {0,0,0,1};
eval_offset(8, xnodes, subnp, offst, x, v);
} break;
case 9: { // 6
const Int subnp[] = {7,8,8,7};
const Int n0[] = { 0, 1, 2, 3, 4, 5, 8};
const Int n1[] = { 0, 1, 2, 3, 4, 5, 7, 8};
const Int n2[] = { 0, 1, 2, 3, 4, 5, 6, 8};
const Int n3[] = { 1, 2, 3, 4, 5, 6, 7 };
const Int* nodes[] = {n0,n1,n2,n3};
::eval(9, true, xnodes, subnp, nodes, x, v);
} break;
case 10: { // 6
const Int subnp[] = {7,7,7,8,8};
const Int offst[] = {0,0,0,0,1};
eval_offset(10, xnodes, subnp, offst, x, v);
} break;
case 11: { // 7
const Int subnp[] = {8,9,8,9,8};
const Int offst[] = {0,0,0,0,1};
eval_offset(11, xnodes, subnp, offst, x, v);
} break;
case 12: { // 8
const Int subnp[] = {9,9,10,10,9,10};
const Int offst[] = {0,0,0,0,1,1};
eval_offset(12, xnodes, subnp, offst, x, v);
} break;
case 13: { // 9
const Int subnp[] = {10,10,10,10,11,10};
const Int offst[] = {0,0,0,0,0,1};
eval_offset(13, xnodes, subnp, offst, x, v);
} break;
default: throw_if(true, "not impl'ed");
}
}
std::string get_basis_string (const Int& np) const override {
switch (np) {
case 5: return "5 1 | 0 3: 0 1 2 | 1 4: 0 1 2 3";
case 6: return "6 1 | 0 5: 0 1 2 3 4 | 1 5: 0 1 2 3 5 | 2 6: 0 1 2 3 4 5";
case 7: return "7 1 | 0 5: 0 1 2 3 4 | 1 5: 0 1 2 3 4 | 2 6: 0 1 2 3 4 5";
case 8: return "8 1 | 0 6: 0 1 2 3 4 5 | 1 6: 0 1 2 3 4 5 | 2 7: 0 1 2 3 4 5 6 | 3 6: 1 2 3 4 5 6";
case 9: return "9 1 | 0 7: 0 1 2 3 4 5 8 | 1 8: 0 1 2 3 4 5 7 8 | 2 8: 0 1 2 3 4 5 6 8 | 3 7: 1 2 3 4 5 6 7";
case 10: return "10 1 | 0 7: 0 1 2 3 4 5 6 | 1 7: 0 1 2 3 4 5 6 | 2 7: 0 1 2 3 4 5 6 | 3 8: 0 1 2 3 4 5 6 7 | 4 8: 1 2 3 4 5 6 7 8";
case 11: return "11 1 | 0 8: 0 1 2 3 4 5 6 7 | 1 9: 0 1 2 3 4 5 6 7 8 | 2 8: 0 1 2 3 4 5 6 7 | 3 9: 0 1 2 3 4 5 6 7 8 | 4 8: 1 2 3 4 5 6 7 8";
case 12: return "12 1 | 0 9: 0 1 2 3 4 5 6 7 8 | 1 9: 0 1 2 3 4 5 6 7 8 | 2 10: 0 1 2 3 4 5 6 7 8 9 | 3 10: 0 1 2 3 4 5 6 7 8 9 | 4 9: 1 2 3 4 5 6 7 8 9 | 5 10: 1 2 3 4 5 6 7 8 9 10";
case 13: return "13 1 | 0 10: 0 1 2 3 4 5 6 7 8 9 | 1 10: 0 1 2 3 4 5 6 7 8 9 | 2 10: 0 1 2 3 4 5 6 7 8 9 | 3 10: 0 1 2 3 4 5 6 7 8 9 | 4 11: 0 1 2 3 4 5 6 7 8 9 10 | 5 10: 1 2 3 4 5 6 7 8 9 10";
default: return "";
}
}
};
struct UniformOffsetNodalSubset : public Operator {
virtual const Real* get_xnodes (const Int& np) const override {
if (np < 2 || np > np_max+1) return nullptr;
static Real xnode[np_max+1][np_max+1] = {0};
if (xnode[np][0] == 0) {
for (Int i = 0; i < np; ++i)
xnode[np][i] = 2*(Real(i)/(np-1)) - 1;
}
return xnode[np];
}
virtual void eval (const Int& np, const Real& x, Real* const v) const override {
const Real* xnodes = get_xnodes(np);
switch (np) {
case 2: {
const Int subnp[] = {2};
const Int offst[] = {0};
eval_offset(2, xnodes, subnp, offst, x, v);
} break;
case 3: {
const Int subnp[] = {3};
const Int offst[] = {0};
eval_offset(3, xnodes, subnp, offst, x, v);
} break;
case 4: {
const Int subnp[] = {3,4};
const Int offst[] = {0,0};
eval_offset(4, xnodes, subnp, offst, x, v);
} break;
case 5: {
const Int subnp[] = {3,4};
const Int offst[] = {0,0};
eval_offset(5, xnodes, subnp, offst, x, v);
} break;
case 6: {
const Int subnp[] = {3,4,6};
const Int offst[] = {0,0,0};
eval_offset(6, xnodes, subnp, offst, x, v);
} break;
case 7: {
const Int subnp[] = {3,4,4};
const Int offst[] = {0,0,1};
eval_offset(7, xnodes, subnp, offst, x, v);
} break;
case 8: {
const Int subnp[] = {4,4,4,4};
const Int offst[] = {0,0,1,2};
eval_offset(8, xnodes, subnp, offst, x, v);
} break;
case 9: {
const Int subnp[] = {4,4,4,4};
const Int offst[] = {0,0,1,2};
eval_offset(9, xnodes, subnp, offst, x, v);
} break;
case 10: {
const Int subnp[] = {4,4,4,4,4};
const Int offst[] = {0,0,1,2,3};
eval_offset(10, xnodes, subnp, offst, x, v);
} break;
case 11: {
const Int subnp[] = {4,4,4,4,4};
const Int offst[] = {0,0,1,2,3};
eval_offset(11, xnodes, subnp, offst, x, v);
} break;
case 12: {
const Int subnp[] = {4,4,4,4,4,4};
const Int offst[] = {0,0,1,2,3,4};
eval_offset(12, xnodes, subnp, offst, x, v);
} break;
case 13: {
const Int subnp[] = {4,4,4,4,4,4};
const Int offst[] = {0,0,1,2,3,4};
eval_offset(13, xnodes, subnp, offst, x, v);
} break;
default: throw_if(true, "not impl'ed");
}
}
};
Operator::ConstPtr Operator::create (Operator::Method m) {
switch (m) {
case gll_natural: return std::make_shared<GllNatural>();
case gll_offset_nodal_subset: return std::make_shared<GllOffsetNodalSubset>();
case gll_best: return std::make_shared<GllBest>();
case uniform_offset_nodal_subset: return std::make_shared<UniformOffsetNodalSubset>();
default: throw_if(true, "Operator::create: not a method: " << m);
}
return nullptr;
}
Int unittest_eval () {
Int nerr = 0;
{
GllOffsetNodalSubset o1;
GllBest o2;
for (const Int np : {5,7,8,10,11,12,13}) {
const Int n = 100;
Int ne = 0;
for (Int i = 0; i <= n; ++i) {
const Real x = 2*(Real(i)/n) - 1;
Real v1[np_max], v2[np_max];
o1.eval(np, x, v1);
o2.eval(np, x, v2);
for (Int j = 0; j < np; ++j) if (v1[j] != v2[j]) ++ne;
}
if (ne) printf("GllOffsetNodalSubset vs GllBest np %d failed\n", np);
nerr += ne;
}
}
return nerr;
}
} // namespace islet
using namespace islet;
extern "C" { // For python ctypes.
void get_xnodes (const Int method, const Int np, Real* xnodes) {
const auto op = Operator::create(static_cast<Operator::Method>(method));
const auto x = op->get_xnodes(np);
for (Int i = 0; i < np; ++i) xnodes[i] = x[i];
}
void eval_interpolant (const Int method, const Int np, const Int nx,
// y is np x nx, np the fast index.
const Real* const x, Real* const y) {
const auto op = Operator::create(static_cast<Operator::Method>(method));
for (Int ix = 0; ix < nx; ++ix)
op->eval(np, x[ix], y + np*ix);
}
} // extern "C"
| 35 | 199 | 0.539648 | [
"vector"
] |
3cf35ab94d4a56b771c5691dbc4374c4c8f70632 | 10,441 | cc | C++ | engine/source/game/module.cc | marauder2k7/Torque2DCMake | 7c50b2accc7beb1bfaba930a956ab8fa0bb5eb68 | [
"MIT"
] | null | null | null | engine/source/game/module.cc | marauder2k7/Torque2DCMake | 7c50b2accc7beb1bfaba930a956ab8fa0bb5eb68 | [
"MIT"
] | null | null | null | engine/source/game/module.cc | marauder2k7/Torque2DCMake | 7c50b2accc7beb1bfaba930a956ab8fa0bb5eb68 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "game/module.h"
#include "collection/vector.h"
#include "string/stringTable.h"
Module* Module::smFirst;
//-----------------------------------------------------------------------------
bool Module::_constrainedToComeBefore(Module* module, Mode mode)
{
if (module == this)
return false;
for (Dependency* dependency = _getDependencies(mode);
dependency != NULL; dependency = dependency->mNext)
{
Module* depModule = dependency->mModule;
if (!depModule)
{
depModule = EngineModuleManager::findModule(dependency->mModuleName);
if (!depModule)
{
// Module does not exist. Only emit a warning here so that modules
// can be omitted from a link without requiring the module definitions
// to be adapted.
//Platform::outputDebugString("[EngineModuleManager] Module of depends on module '%s' which does not exist");
continue;
}
dependency->mModule = depModule;
}
if (dependency->mType == DependencyBefore)
{
if (depModule == module
|| depModule->_constrainedToComeBefore(module, mode))
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
bool Module::_constrainedToComeAfter(Module* module, Mode mode)
{
if (module == this)
return false;
for (Dependency* dependency = _getDependencies(mode);
dependency != NULL; dependency = dependency->mNext)
{
Module* depModule = dependency->mModule;
if (!depModule)
{
depModule = EngineModuleManager::findModule(dependency->mModuleName);
if (!depModule)
{
// Module does not exist. Only emit a warning here so that modules
// can be omitted from a link without requiring the module definitions
// to be adapted.
//Platform::outputDebugString("[EngineModuleManager] Module of depends on module '%s' which does not exist");
continue;
}
dependency->mModule = depModule;
}
if (dependency->mType == DependencyAfter)
{
if (depModule == module
|| depModule->_constrainedToComeAfter(module, mode))
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void EngineModuleManager::_printModuleList(Vector< Module* >& moduleList)
{
//Platform::outputDebugString(_moduleListToString(moduleList));
}
//-----------------------------------------------------------------------------
void EngineModuleManager::_insertIntoModuleList(Module::Mode mode, Vector< Module* >& moduleList, Module* module)
{
// If this module is being overridden, switch over to
// the module overriding it.
Module* override;
do
{
override = _findOverrideFor(module);
if (override)
module = override;
} while (override != NULL);
// If we are already on the list, return.
if (_getIndexOfModuleInList(moduleList, module) != -1)
return;
// If we don't have dependencies, just push the module
// to the back of the list.
if (!module->_getDependencies(mode))
{
moduleList.push_back(module);
return;
}
// First make sure that all 'after' dependencies are in the list.
for (Module::Dependency* dependency = module->_getDependencies(mode);
dependency != NULL; dependency = dependency->mNext)
{
if (dependency->mType != Module::DependencyAfter)
continue;
dependency->mModule = findModule(dependency->mModuleName);
if (!dependency->mModule)
continue; // Allow modules to not exist.
if (_getIndexOfModuleInList(moduleList, dependency->mModule) == -1)
_insertIntoModuleList(mode, moduleList, dependency->mModule);
}
AssertFatal(_getIndexOfModuleInList(moduleList, module) == -1,
avar("EngineModuleManager::_insertModuleIntoList - Cycle in 'after' %s dependency chain of '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName()));
// Now add the module itself.
const U32 numModules = moduleList.size();
for (U32 i = 0; i < numModules; ++i)
{
const bool thisBeforeCurrent = module->_constrainedToComeBefore(moduleList[i], mode);
const bool currentAfterThis = moduleList[i]->_constrainedToComeAfter(module, mode);
AssertFatal(!(thisBeforeCurrent && currentAfterThis),
avar("EngineModuleManager::_insertModuleIntoList - Ambiguous %s placement of module '%s' relative to '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(), moduleList[i]->getName()));
// If no contraints relate us to this module,
// push us one more position back in the line.
if (!thisBeforeCurrent && !currentAfterThis)
continue;
// If this module is contrained to come before the
// module at our current position but that module does
// not actually have dependencies of its own, make sure
// that module is at the back of the module list so that
// if we have more dependencies, it will not prevent us
// from correctly positioning us in relation to them.
if (thisBeforeCurrent && !moduleList[i]->_getDependencies(mode) && i != numModules - 1)
{
Module* depModule = moduleList[i];
moduleList.erase(i);
--i;
moduleList.push_back(depModule);
continue;
}
// Try the reverse constraint with all remaining modules in the list.
// If there is one for which we have one, then the placement of this
// module is ambiguous.
for (U32 n = i + 1; n < numModules; ++n)
AssertFatal(!(moduleList[n]->_constrainedToComeBefore(module, mode)
|| module->_constrainedToComeAfter(moduleList[n], mode)),
avar("EngineModuleManager::_insertModuleIntoList - Ambiguous %s constraint on module '%s' to come before '%s' yet after '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(),
moduleList[i]->getName(),
moduleList[n]->getName()));
// Add the module at this position.
moduleList.push_back(module);
return;
}
moduleList.push_back(module);
}
//-----------------------------------------------------------------------------
Module* EngineModuleManager::_findOverrideFor(Module* module)
{
const char* name = module->getName();
for (Module* ptr = Module::smFirst; ptr != NULL; ptr = ptr->mNext)
for (Module::Override* override = ptr->mOverrides; override != NULL; override = override->mNext)
if (dStricmp(override->mModuleName, name) == 0)
return ptr;
return NULL;
}
//-----------------------------------------------------------------------------
S32 EngineModuleManager::_getIndexOfModuleInList(Vector< Module* >& moduleList, Module* module)
{
const U32 numModules = moduleList.size();
for (U32 i = 0; i < numModules; ++i)
if (moduleList[i] == module)
return i;
return -1;
}
//-----------------------------------------------------------------------------
S32 EngineModuleManager::_getIndexOfModuleInList(Vector< Module* >& moduleList, const char* moduleName)
{
const U32 numModules = moduleList.size();
for (U32 i = 0; i < numModules; ++i)
if (dStricmp(moduleList[i]->getName(), moduleName) == 0)
return i;
return -1;
}
//-----------------------------------------------------------------------------
void EngineModuleManager::_createModuleList(Module::Mode mode, Vector< Module* >& moduleList)
{
for (Module* module = Module::smFirst; module != NULL; module = module->mNext)
_insertIntoModuleList(mode, moduleList, module);
}
//-----------------------------------------------------------------------------
void EngineModuleManager::initializeSystem()
{
Vector< Module* > modules;
_createModuleList(Module::ModeInitialize, modules);
const U32 numModules = modules.size();
for (U32 i = 0; i < numModules; ++i)
{
Module* module = modules[i];
if (!module->mIsInitialized)
{
module->initialize();
module->mIsInitialized = true;
}
}
}
//-----------------------------------------------------------------------------
void EngineModuleManager::shutdownSystem()
{
Vector< Module* > modules;
_createModuleList(Module::ModeShutdown, modules);
const U32 numModules = modules.size();
for (U32 i = 0; i < numModules; ++i)
{
if (modules[i]->mIsInitialized)
{
modules[i]->shutdown();
modules[i]->mIsInitialized = false;
}
}
}
//-----------------------------------------------------------------------------
Module* EngineModuleManager::findModule(const char* name)
{
for (Module* module = Module::smFirst; module != NULL; module = module->mNext)
if (dStricmp(module->getName(), name) == 0)
return module;
return NULL;
}
| 33.041139 | 138 | 0.585672 | [
"vector"
] |
3cf6d29286fc54cf7aaeb1b81d47b78b1623ddc8 | 4,439 | cpp | C++ | src/inputHandler.cpp | kaprikawn/shoot | f07121a275e8c3aec1f66cbb6825951123371ccb | [
"MIT"
] | 1 | 2018-07-09T21:12:55.000Z | 2018-07-09T21:12:55.000Z | src/inputHandler.cpp | kaprikawn/shoot | f07121a275e8c3aec1f66cbb6825951123371ccb | [
"MIT"
] | 1 | 2019-06-09T14:16:31.000Z | 2019-06-18T20:10:33.000Z | src/inputHandler.cpp | kaprikawn/shoot | f07121a275e8c3aec1f66cbb6825951123371ccb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "inputHandler.hpp"
#include "game.hpp"
InputHandler* InputHandler::instance_ = 0;
void InputHandler::initialiseJoysticks() {
if( SDL_WasInit( SDL_INIT_JOYSTICK ) == 0 ) {
SDL_InitSubSystem( SDL_INIT_JOYSTICK );
}
if( SDL_NumJoysticks() > 0 ) {
for( int i = 0; i < SDL_NumJoysticks(); i++ ) {
SDL_Joystick* joy = SDL_JoystickOpen( i );
if( joy == NULL ) {
std::cout << SDL_GetError() << std::endl;
} else {
joysticks_.push_back( joy );
//m_joystickValues.push_back( std::make_pair( new Vector2D( 0, 0 ), new Vector2D( 0, 0 ) ) );
for( int b = 0; b < SDL_JoystickNumButtons( joy ); b++ ) {
buttonStates_.push_back( false );
}
}
}
SDL_JoystickEventState( SDL_ENABLE );
joysticksInitialised_ = true;
} else {
joysticksInitialised_ = false;
}
std::cout << "Initialised " << joysticks_.size() << " joystick(s)" << std::endl;
}
void InputHandler::onKeyDown() {
keystates_ = SDL_GetKeyboardState( NULL );
if( keystates_[ SDL_SCANCODE_ESCAPE ] == 1 ) {
TheGame::Instance() -> quit();
}
}
void InputHandler::onKeyUp() {
keystates_ = SDL_GetKeyboardState( NULL );
}
bool InputHandler::isKeyDown( SDL_Scancode key ) {
if( keystates_ != 0 ) {
if( keystates_[key] == 1 ) {
return true;
} else {
return false;
}
}
return false;
}
bool InputHandler::isPressed( int button ) {
if( button == 0 ) {
if( keystates_[ SDL_SCANCODE_RIGHT ] == 1 || keystates_[ SDL_SCANCODE_L ] == 1 || currentHat_ == SDL_HAT_RIGHT || currentHat_ == SDL_HAT_RIGHTUP || currentHat_ == SDL_HAT_RIGHTDOWN ) {
return true;
}
} else if( button == 1 ) {
if( keystates_[ SDL_SCANCODE_LEFT ] == 1 || keystates_[ SDL_SCANCODE_H ] == 1 || currentHat_ == SDL_HAT_LEFT || currentHat_ == SDL_HAT_LEFTUP || currentHat_ == SDL_HAT_LEFTDOWN ) {
return true;
}
} else if( button == 2 ) {
if( keystates_[ SDL_SCANCODE_UP ] == 1 || keystates_[ SDL_SCANCODE_K ] == 1 || currentHat_ == SDL_HAT_UP || currentHat_ == SDL_HAT_LEFTUP || currentHat_ == SDL_HAT_RIGHTUP ) {
return true;
}
} else if( button == 3 ) {
if( keystates_[ SDL_SCANCODE_DOWN ] == 1 || keystates_[ SDL_SCANCODE_J ] == 1 || currentHat_ == SDL_HAT_DOWN || currentHat_ == SDL_HAT_LEFTDOWN || currentHat_ == SDL_HAT_RIGHTDOWN ) {
return true;
}
} else if( button == 4 ) { // fire
if( keystates_[ SDL_SCANCODE_F ] == 1 ) {
return true;
}
if( gamepadsInitialised_ ) {
if( buttonStates_[ 2 ] ) {
return true;
}
}
} else if( button == 5 ) { // roll
if( keystates_[ SDL_SCANCODE_D ] == 1 ) {
return true;
}
} else if( button == 6 ) { // bomb
if( keystates_[ SDL_SCANCODE_S ] ) {
return true;
}
}
/*else if( button == 7 ) { // start
if( keystates_[ SDL_SCANCODE_S ] == 1 ) {
return true;
}
} else if( button == 8 ) { // quit
if( keystates_[ SDL_SCANCODE_Q ] == 1 ) {
return true;
}
} else if( button == 9 ) { // ok
if( keystates_[ SDL_SCANCODE_O ] == 1 ) {
return true;
}
} else if( button == 10 ) { // back
if( keystates_[ SDL_SCANCODE_BACKSPACE ] == 1 ) {
return true;
}
}*/
return false;
}
void InputHandler::onHatMotion( SDL_Event &event ) {
if( !joysticksInitialised_ ) {
return;
}
for( unsigned int i = 0; i < joysticks_.size(); i++ ) {
currentHat_ = SDL_JoystickGetHat( joysticks_[i], 0 );
}
}
void InputHandler::update() {
SDL_Event event;
while( SDL_PollEvent( &event ) ) {
switch( event.type ) {
case SDL_QUIT:
TheGame::Instance() -> quit(); break;
case SDL_KEYDOWN:
onKeyDown(); break;
case SDL_KEYUP:
onKeyUp(); break;
case SDL_JOYHATMOTION:
onHatMotion( event ); break;
case SDL_JOYBUTTONDOWN:
whichOne_ = event.jaxis.which;
buttonStates_[ event.jbutton.button ] = true;
//printf( "%d pressed\n", event.jbutton.button );
break;
case SDL_JOYBUTTONUP:
whichOne_ = event.jaxis.which;
buttonStates_[ event.jbutton.button ] = false;
break;
default:
break;
}
}
}
void InputHandler::clean() {
if( gamepadsInitialised_ ) {
for( int i = 0; i < SDL_NumJoysticks(); i++ ) {
SDL_JoystickClose( joysticks_[i] );
}
}
}
| 27.918239 | 188 | 0.589097 | [
"vector"
] |
3cfe09386b33d282437cc1d4f906e66f54ed5164 | 7,532 | cpp | C++ | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/requests/validation/common.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/requests/validation/common.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/requests/validation/common.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2015-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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 "agent-framework/module/constants/compute.hpp"
#include "agent-framework/module/constants/chassis.hpp"
#include "agent-framework/module/constants/pnc.hpp"
#include "agent-framework/module/constants/regular_expressions.hpp"
#include "agent-framework/module/model/attributes/attributes.hpp"
#include "agent-framework/module/requests/validation/common.hpp"
#include "agent-framework/module/requests/validation/json_check_type.hpp"
#include "agent-framework/module/common_components.hpp"
#include "agent-framework/validators/procedure_validator.hpp"
using namespace agent_framework::exceptions;
using namespace agent_framework::model::attribute;
namespace agent_framework {
namespace model {
namespace requests {
namespace validation {
void CommonValidator::validate_set_drive_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Drive::ASSET_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::Drive::ERASED == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::Drive::SECURELY_ERASE == name) {
// value does not matter
}
else if (literals::Drive::OEM == name) {
Oem::from_json(value);
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_processor_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Fpga::ERASED == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::Fpga::SECURELY_ERASE == name) {
// value does not matter
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_chassis_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Chassis::ASSET_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::Chassis::RESET == name) {
check_enum<enums::ResetType>(value, name, "agent-framework");
}
else if (literals::Chassis::GEO_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::Chassis::LOCATION_ID == name) {
check_string(value, name, "agent-framework");
}
else if (literals::Chassis::OEM == name) {
Oem::from_json(value);
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_system_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::System::BOOT_OVERRIDE == name) {
check_enum<enums::BootOverride>(value, name, "agent-framework");
}
else if (literals::System::BOOT_OVERRIDE_MODE == name) {
check_enum<enums::BootOverrideMode>(value, name, "agent-framework");
}
else if (literals::System::BOOT_OVERRIDE_TARGET == name) {
check_enum<enums::BootOverrideTarget>(value, name, "agent-framework");
}
else if (literals::System::RESET == name) {
check_enum<enums::ResetType>(value, name, "agent-framework");
}
else if (literals::System::ASSET_TAG == name) {
check_nullable_string(value, name, "agent-framework");
}
else if (literals::System::USER_MODE_ENABLED == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::System::RESET_CONFIGURATION == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::System::ERASE_CONFIGURATION_KEYS == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::System::OEM == name) {
Oem::from_json(value);
}
else if (literals::System::CURRENT_PERFORMANCE_CONFIGURATION == name) {
check_number(value, name, "agent-framework");
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_manager_attributes(const Attributes& attributes) {
for (const auto& name : attributes.get_names()) {
const auto& value = attributes.get_value(name);
if (literals::Manager::RESET == name) {
check_enum<enums::ResetType>(value, name, "agent-framework");
}
else if (literals::Manager::FACTORY_DEFAULTS == name) {
check_boolean(value, name, "agent-framework");
}
else if (literals::Manager::PACKAGE_URL == name) {
check_string(value, name, "agent-framework");
}
else if (literals::Manager::OEM == name) {
Oem::from_json(value);
}
else {
THROW(InvalidField, "agent-framework", "Unrecognized attribute.", name, value);
}
}
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_pcie_device_attributes(const Attributes& attributes) {
jsonrpc::ProcedureValidator validator(
jsonrpc::PARAMS_BY_NAME,
literals::PcieDevice::ASSET_TAG, VALID_OPTIONAL(VALID_NULLABLE(VALID_JSON_STRING)),
literals::PcieDevice::OEM, VALID_OPTIONAL(VALID_JSON_OBJECT),
nullptr
);
validator.validate(attributes.to_json());
log_debug("agent-framework", "Request validation passed.");
}
void CommonValidator::validate_set_endpoint_attributes(const Attributes& attributes) {
static jsonrpc::ProcedureValidator validator(
jsonrpc::PARAMS_BY_NAME,
literals::Endpoint::USERNAME, VALID_NULLABLE(VALID_REGEX(literals::regex::Common::NO_WHITESPACE_STRING)),
literals::Endpoint::PASSWORD, VALID_OPTIONAL(VALID_NULLABLE(VALID_REGEX(literals::regex::Common::NO_WHITESPACE_STRING))),
nullptr
);
validator.validate(attributes.to_json());
log_debug("agent-framework", "Request validation passed.");
}
}
}
}
}
| 37.472637 | 129 | 0.653213 | [
"model"
] |
3cfea127fa7d5e2343ff1ed90a23418252f68f25 | 6,172 | cpp | C++ | 3rdparty/meshlab-master/src/meshlabplugins/render_radiance_scaling/gpuProgram.cpp | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/meshlab/src/meshlabplugins/render_radiance_scaling/gpuProgram.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/meshlab/src/meshlabplugins/render_radiance_scaling/gpuProgram.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
* Render Radiance Scaling *
* Meshlab's plugin *
* *
* Copyright(C) 2010 *
* Vergne Romain, Dumas Olivier *
* INRIA - Institut Nationnal de Recherche en Informatique et Automatique *
* *
* All rights reserved. *
* *
* 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 (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#include "gpuProgram.h"
#include <iostream>
using namespace std;
GPUProgram::GPUProgram(GPUShader* vs,GPUShader* fs,GPUShader *gs,
int inputGeometry,int outputGeometry,int outVertices)
: _vs(vs),
_fs(fs),
_gs(gs),
_inputGeometry(inputGeometry),
_outputGeometry(outputGeometry),
_outVertices(outVertices) {
_programId = glCreateProgram();
setGeometryParameters(_inputGeometry,_outputGeometry,_outVertices);
attachAndLink();
}
GPUProgram::GPUProgram(const string &vsFile,
const string &fsFile,
const string &gsFile,
int inputGeometry,
int outputGeometry,
int outVertices)
:_inputGeometry(inputGeometry),
_outputGeometry(outputGeometry),
_outVertices(outVertices) {
_vs = _fs = _gs = NULL;
if(vsFile!="")
_vs = new GPUShader(VERT,vsFile);
if(fsFile!="")
_fs = new GPUShader(FRAG,fsFile);
if(gsFile!="")
_gs = new GPUShader(GEOM,gsFile);
_programId = glCreateProgram();
setGeometryParameters(_inputGeometry,_outputGeometry,_outVertices);
attachAndLink();
}
GPUProgram::~GPUProgram() {
detach();
if(_vs!=NULL) {
delete _vs;
}
if(_fs!=NULL) {
delete _fs;
}
if(_gs!=NULL) {
delete _gs;
}
glDeleteProgram(_programId);
}
void GPUProgram::setGeometryParameters(int inputGeometry,int outputGeometry,int outVertices) {
#ifdef GL_EXT_geometry_shader4
if(GL_EXT_geometry_shader4 && _gs!=NULL && _gs->id()!=0) {
glProgramParameteriEXT(_programId,GL_GEOMETRY_INPUT_TYPE_EXT,inputGeometry);
glProgramParameteriEXT(_programId,GL_GEOMETRY_OUTPUT_TYPE_EXT,outputGeometry);
glProgramParameteriEXT(_programId,GL_GEOMETRY_VERTICES_OUT_EXT,outVertices);
}
#endif
}
void GPUProgram::attach() {
if(_vs!=NULL) {
glAttachShader(_programId,_vs->id());
}
if(_fs!=NULL) {
glAttachShader(_programId,_fs->id());
}
if(_gs!=NULL) {
glAttachShader(_programId,_gs->id());
}
}
void GPUProgram::detach() {
if(_vs!=NULL) {
glDetachShader(_programId,_vs->id());
}
if(_fs!=NULL) {
glDetachShader(_programId,_fs->id());
}
if(_gs!=NULL) {
glDetachShader(_programId,_gs->id());
}
}
bool GPUProgram::link() {
int linked = 1;
glLinkProgram(_programId);
glGetObjectParameterivARB(_programId,GL_OBJECT_LINK_STATUS_ARB,&linked);
if(linked)
return true;
return false;
}
bool GPUProgram::attachAndLink() {
attach();
return link();
}
void GPUProgram::reload() {
detach();
bool allOk = true;
if(_vs!=NULL) {
allOk = allOk && _vs->loadAndCompile();
}
if(_fs!=NULL) {
allOk = allOk && _fs->loadAndCompile();
}
if(_gs!=NULL) {
allOk = allOk && _gs->loadAndCompile();
}
if(!allOk){
std::cout << "reload fail, maybe missing file" << std::endl;
}
setGeometryParameters(_inputGeometry,_outputGeometry,_outVertices);
attachAndLink();
// reload uniforms
for(map<string,GLint>::iterator i=_uniformLocations.begin();i!=_uniformLocations.end();i++) {
_uniformLocations[(*i).first] = glGetUniformLocation(_programId,(*i).first.c_str());
}
// reload attributes
for(map<string,GLint>::iterator i=_attributeLocations.begin();i!=_attributeLocations.end();i++) {
_uniformLocations[(*i).first] = glGetAttribLocation(_programId,(*i).first.c_str());
}
// free textures
_textures.clear();
}
void GPUProgram::addUniform(const string &uniformName) {
GLint location = glGetUniformLocation(_programId,uniformName.c_str());
_uniformLocations[uniformName] = location;
}
void GPUProgram::addAttribute(const string &attributeName) {
GLint location = glGetAttribLocation(_programId,attributeName.c_str());
_attributeLocations[attributeName] = location;
}
bool GPUProgram::haveShaderOfType(SHADER_TYPE type) {
if(type==VERT)
return _vs!=NULL;
if(type==FRAG)
return _fs!=NULL;
if(type==GEOM)
return _gs!=NULL;
cout << "Warning : unknown type !" << endl;
return false;
}
string GPUProgram::filename(SHADER_TYPE type) {
if(type==VERT && _vs!=NULL)
return _vs->filename();
if(type==FRAG && _fs!=NULL)
return _fs->filename();
if(type==GEOM && _gs!=NULL)
return _gs->filename();
cout << "Warning : unknown type !" << endl;
return "";
}
| 27.431111 | 99 | 0.559624 | [
"render"
] |
3cff022b50e3d9a95cc95b3c0a9731ad4dd2b9e1 | 5,953 | hpp | C++ | cpp/src/datacentric/dc/types/variant/variant.hpp | datacentricorg/datacentric-cpp | 252f642b1a81c2475050d48e9564eec0a561907e | [
"Apache-2.0"
] | 2 | 2019-08-08T01:29:02.000Z | 2019-08-18T19:19:00.000Z | cpp/src/datacentric/dc/types/variant/variant.hpp | datacentricorg/datacentric-cpp | 252f642b1a81c2475050d48e9564eec0a561907e | [
"Apache-2.0"
] | null | null | null | cpp/src/datacentric/dc/types/variant/variant.hpp | datacentricorg/datacentric-cpp | 252f642b1a81c2475050d48e9564eec0a561907e | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2013-present The DataCentric 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.
*/
#pragma once
#include <dc/declare.hpp>
#include <dc/types/record/value_type.hpp>
#include <dot/noda_time/local_date_util.hpp>
#include <dot/noda_time/local_time_util.hpp>
#include <dot/noda_time/local_minute_util.hpp>
#include <dot/noda_time/local_date_time_util.hpp>
#include <dot/system/enum.hpp>
#include <dot/system/object.hpp>
#include <dot/system/string.hpp>
#include <dot/system/type.hpp>
#include <dot/noda_time/local_date_time.hpp>
#include <dot/noda_time/local_minute.hpp>
namespace dc
{
/// Variant type can hold any atomic value or be empty.
class DC_CLASS Variant
{
typedef Variant self;
private: // FIELDS
dot::Object value_;
public: // CONSTRUCTORS
/// Default constructor.
Variant();
/// Create from Object of supported types, error message if argument type is unsupported.
Variant(dot::Object value);
public: // PROPERTIES
/// Type of the value held by the Variant.
ValueType get_value_type()
{
if (value_ == nullptr)
return ValueType::empty_type;
dot::Type value_type = value_->get_type();
// The purpose of this check is to ensure that Variant holds only one of the supported types
if (value_type->equals(dot::typeof<dot::String>())) return ValueType::string_type;
if (value_type->equals(dot::typeof<double>())) return ValueType::double_type;
if (value_type->equals(dot::typeof<bool>())) return ValueType::bool_type;
if (value_type->equals(dot::typeof<int>())) return ValueType::int_type;
if (value_type->equals(dot::typeof<int64_t>())) return ValueType::long_type;
if (value_type->equals(dot::typeof<dot::LocalDate>())) return ValueType::local_date_type;
if (value_type->equals(dot::typeof<dot::LocalTime>())) return ValueType::local_time_type;
if (value_type->equals(dot::typeof<dot::LocalMinute>())) return ValueType::local_minute_type;
if (value_type->equals(dot::typeof<dot::LocalDateTime>())) return ValueType::local_date_time_type;
if (value_type->is_enum()) return ValueType::enum_type;
// Error message if any other type, should normally not get to here
throw dot::Exception(get_wrong_type_error_message(value_));
}
/// Value held by the Variant, which may be null.
dot::Object get_value()
{
return value_;
}
public: // METHODS
/// Check if the Variant is equal to default constructed Object.
bool is_empty();
/// Provides alternate serialization of certain value types.
dot::String to_string();
/// Hash code is zero for null objects.
size_t hash_code();
/// Variants are equal when both types and values are equal.
/// Comparison of doubles is performed with roundoff tolerance.
bool equals(const Variant& other);
public: // OPERATORS
/// Variants are equal when both types and values are equal.
/// Comparison of doubles is performed with roundoff tolerance.
bool operator==(const Variant& other);
/// Variants are equal when both types and values are equal.
/// Comparison of doubles is performed with roundoff tolerance.
bool operator!=(const Variant& other);
public: // STATIC
static Variant parse(ValueType value_type, dot::String value);
template <class T>
static Variant parse(dot::String value)
{
if (dot::String::is_null_or_empty(value))
{
// Empty value
return Variant();
}
dot::Type value_type = dot::typeof<T>();
// The purpose of this check is to ensure that Variant holds only one of the supported types
if (value_type->equals(dot::typeof<dot::String>())) return Variant(value);
if (value_type->equals(dot::typeof<double>())) return Variant(dot::DoubleImpl::parse(value));
if (value_type->equals(dot::typeof<bool>())) return Variant(dot::BoolImpl::parse(value));
if (value_type->equals(dot::typeof<int>())) return Variant(dot::IntImpl::parse(value));
if (value_type->equals(dot::typeof<int64_t>())) return Variant(dot::LongImpl::parse(value));
if (value_type->equals(dot::typeof<dot::LocalDate>())) return Variant(dot::LocalDateUtil::parse(value));
if (value_type->equals(dot::typeof<dot::LocalTime>())) return Variant(dot::LocalTimeUtil::parse(value));
if (value_type->equals(dot::typeof<dot::LocalMinute>())) return Variant(dot::LocalMinuteUtil::parse(value));
if (value_type->equals(dot::typeof<dot::LocalDateTime>())) return Variant(dot::LocalDateTimeUtil::parse(value));
if (value_type->is_enum()) return Variant(dot::EnumBase::parse(value_type, value));
// Error message if any other type
throw dot::Exception(get_wrong_type_error_message(T()));
}
private: // PRIVATE
static dot::String get_wrong_type_error_message(dot::Object value);
};
}
| 41.340278 | 125 | 0.635646 | [
"object"
] |
a702083929c19296fe39c2d31959624962b5dc26 | 13,485 | cpp | C++ | src/mlssample.cpp | csiro-workspace/pointcloudplugin | 815dd598ccf3780739b1ecae086ee78daa94ed5d | [
"BSD-3-Clause"
] | 5 | 2015-09-22T02:33:34.000Z | 2018-08-29T07:37:54.000Z | src/mlssample.cpp | csiro-workspace/pointcloudplugin | 815dd598ccf3780739b1ecae086ee78daa94ed5d | [
"BSD-3-Clause"
] | 1 | 2018-12-12T12:08:28.000Z | 2018-12-13T06:14:54.000Z | src/mlssample.cpp | csiro-workspace/pointcloudplugin | 815dd598ccf3780739b1ecae086ee78daa94ed5d | [
"BSD-3-Clause"
] | 4 | 2015-03-04T00:09:18.000Z | 2020-09-08T02:58:06.000Z | /*============================================================================
Copyright 2015 by:
Commonwealth Scientific and Industrial Research Organisation (CSIRO)
This file is licensed by CSIRO under the copy of the CSIRO Open Source
Software License Agreement (variation of the BSD / MIT License) included
with the file.
As a condition of this license, you agree that where you make any
adaptations, modifications, further developments, or additional features
available to CSIRO or the public in connection with your access to the
Software, you do so on the terms of the BSD 3-Clause License template,
a copy available at: http://opensource.org/licenses/BSD-3-Clause
For further information, contact the CSIRO Workspace Team:
workspace@csiro.au
This copyright notice must be included with all copies of the source code.
============================================================================*/
/*
Copyright (c) 2015, Stuart Mead - Risk Frontiers, Macquarie University
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 holder 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.
For further information, contact:
Stuart Mead
Risk Frontiers
Dept. of Environmental Sciences
Macquarie University
North Ryde NSW 2109
*/
#include <cassert>
#include <iostream>
#include <QString>
#include "Workspace/Application/LanguageUtils/streamqstring.h"
#include "Workspace/DataExecution/DataObjects/typedobject.h"
#include "Workspace/DataExecution/InputOutput/inputscalar.h"
#include "Workspace/DataExecution/InputOutput/inputarray.h"
#include "Workspace/DataExecution/InputOutput/output.h"
#include "Workspace/DataExecution/Operations/typedoperationfactory.h"
#include "Mesh/DataStructures/MeshModelInterface/meshmodelinterface.h"
#include "Mesh/DataStructures/MeshModelInterface/meshelementsinterface.h"
#include "Mesh/DataStructures/MeshModelInterface/meshnodesinterface.h"
#include "pointcloudplugin.h"
#include "mlssample.h"
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>
namespace CSIRO
{
using namespace Mesh;
using namespace DataExecution;
namespace PointCloud
{
/**
* \internal
*/
class MlsSampleImpl
{
// Allow string translation to work properly
Q_DECLARE_TR_FUNCTIONS(MlsSampleImpl)
public:
MlsSample& op_;
// Data objects
DataExecution::TypedObject< MeshModelInterface > dataMesh_;
DataExecution::TypedObject< bool > dataOMP_;
DataExecution::TypedObject< MeshModelInterface > dataOutputMesh_;
DataExecution::TypedObject< double > searchRadius_;
DataExecution::TypedObject< int > polyOrder_;
DataExecution::TypedObject< bool > polyFit_;
DataExecution::TypedObject< bool > upsample_;
DataExecution::TypedObject< double > upsampRadius_;
DataExecution::TypedObject< double > stepSize_;
// Inputs and outputs
DataExecution::InputScalar inputMesh_;
DataExecution::InputScalar inputOMP_;
DataExecution::InputScalar inputSearchRadius_;
DataExecution::InputScalar inputpolyOrder_;
DataExecution::InputScalar inputpolyFit_;
DataExecution::InputScalar inputupsample_;
DataExecution::InputScalar inputupsampRadius_;
DataExecution::InputScalar inputstepSize_;
DataExecution::Output outputMesh_;
MlsSampleImpl(MlsSample& op);
bool execute();
void logText(const QString& msg) { op_.logText(msg); }
};
/**
*
*/
MlsSampleImpl::MlsSampleImpl(MlsSample& op) :
op_(op),
dataMesh_(),
dataOMP_(false),
dataOutputMesh_(),
searchRadius_(2.0),
polyOrder_(2),
polyFit_(true),
upsample_(true),
upsampRadius_(3.0),
stepSize_(0.5),
inputMesh_("Points", dataMesh_, op_),
inputOMP_("Use OpenMP", dataOMP_, op_),
inputSearchRadius_("Search Radius", searchRadius_, op_),
inputpolyOrder_("Polynomial Order", polyOrder_, op_),
inputpolyFit_("Polynomial Fitting", polyFit_, op_),
inputupsample_("Upsampling enabled", upsample_, op_),
inputupsampRadius_("Upsampling radius", upsampRadius_, op_),
inputstepSize_("Upsampling step sizes", stepSize_, op_),
outputMesh_("Mesh Model", dataOutputMesh_, op_)
{
inputSearchRadius_.setDescription("Set the sphere radius that is to be used for determining the k-nearest neighbors used for fitting");
inputOMP_.setDescription("Enables OpenMP based computation, threads will be determined on the OMP_NUM_THREADS environment variable");
inputpolyOrder_.setDescription("Order of the polynomial to be fit, if polynomial fitting is true");
inputpolyFit_.setDescription("Approximate the surface and normal using a polynomial, if not, tangent estimation is used");
inputupsampRadius_.setDescription("Radius of the circle in the local point plan that will be sampled");
inputstepSize_.setDescription("Step size for the local plane upsampling");
}
/**
*
*/
bool MlsSampleImpl::execute()
{
MeshModelInterface& mesh = *dataMesh_;
MeshModelInterface& outputMesh = *dataOutputMesh_;
MeshNodesInterface& nodes = mesh.getNodes();
/* No rgb states in mls at the moment after GSOC 2014 might be different
if (!nodes.hasState("RGBA"))
{
std::cout << QString("ERROR: Nodes do not have RGBA state") + "\n";
return false;
}
NodeStateHandle inputRgba = nodes.getStateHandle("RGBA");
*/
outputMesh.clear();//Always clear outputmesh
MeshNodesInterface& outputNodes = outputMesh.getNodes();
//Kinect stuff
const NodeStateHandle* pixIdStateIn = 0;
const NodeStateHandle* textureSStateOut = 0;
const NodeStateHandle* textureTStateOut = 0;
if (nodes.hasState("pixId"))
{
pixIdStateIn = &nodes.getStateHandle("pixId");
textureSStateOut = &outputNodes.addState<double>("textureS", 0.0);
textureTStateOut = &outputNodes.addState<double>("textureT", 0.0);
}
//Add states for normal and curvature
const NodeStateHandle& normalStateOut = outputNodes.addState("normal", Vector3d(0,0,-1));
const NodeStateHandle& curvatureStateOut = outputNodes.addState<double>("curvature",0.0);
//Finish if input mesh is empty
if(nodes.size() == 0)
{
std::cout << QString("WARNING: Mesh has no nodes, returning successfully") + "\n";
return true;
}
//For each node add point to point cloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
//pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud_rgba (new pcl::PointCloud<pcl::PointXYZRGBA>);//RGBA states
MeshNodesInterface::const_iterator nIter = nodes.begin();
MeshNodesInterface::const_iterator end = nodes.end();
for(; nIter != end; ++nIter)
{
int rgba = 0;
Vector3d v = nodes.getPosition(*nIter);
//nodes.getState(*nIter,inputRgba,rgba);
pcl::PointXYZ p;
p.x = v.x;
p.y = v.y;
p.z = v.z;
//p.rgb = rgba;
cloud->push_back(pcl::PointXYZ(p));
}
std::cout << QString("Point cloud generated, has %1 points").arg(cloud->size()) + "\n";
// Create a KD-Tree
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
// Output has the PointNormal type in order to store the normals from mls
pcl::PointCloud<pcl::PointNormal> mls_cloud;
#ifdef _OPENMP
if (*dataOMP_)
{
// Init object (second point type is for the normals, even if unused)
pcl::MovingLeastSquaresOMP<pcl::PointXYZ, pcl::PointNormal> mls;
char * ompThreads;
ompThreads = getenv("OMP_NUM_THREADS");
if (ompThreads != NULL)
{
mls.setNumberOfThreads(atoi(ompThreads));
}
else {
std::cout << QString("WARNING: OMP selected, but OMP_NUM_THREADS not set - using automatic detection") + "\n";
}
//For time being, we will make sure we only calc normals, maybe not later.
mls.setComputeNormals(true);
//Set input parameters
mls.setInputCloud(cloud);
if (*polyFit_)
{
mls.setPolynomialFit(true);
mls.setPolynomialOrder(*polyOrder_);
}
mls.setSearchMethod(tree);
mls.setSearchRadius(*searchRadius_);
//Paramaters for upsampling
if (*upsample_)
{
mls.setUpsamplingMethod (pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal>::SAMPLE_LOCAL_PLANE);
mls.setUpsamplingRadius (*upsampRadius_);
mls.setUpsamplingStepSize (*stepSize_);
}
//Reconstruct
mls.process(mls_cloud);
}
else
#endif
{
// Init object (second point type is for the normals, even if unused)
pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls;
//For time being, we will make sure we only calc normals, maybe not later.
mls.setComputeNormals(true);
//Set input parameters
mls.setInputCloud(cloud);
if (*polyFit_)
{
mls.setPolynomialFit(true);
mls.setPolynomialOrder(*polyOrder_);
}
mls.setSearchMethod(tree);
mls.setSearchRadius(*searchRadius_);
//Paramaters for upsampling
if (*upsample_)
{
mls.setUpsamplingMethod (pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal>::SAMPLE_LOCAL_PLANE);
mls.setUpsamplingRadius (*upsampRadius_);
mls.setUpsamplingStepSize (*stepSize_);
}
//Reconstruct
mls.process(mls_cloud);
}
//Now add the filtered nodes to the output mesh model
int a = 0;
NodeStateHandle rgbahandle = outputNodes.addState("RGBA", a);
for (size_t i = 0; i < mls_cloud.points.size (); ++i)
{
Vector3d vo,no;
vo.x = mls_cloud.points[i].x;
vo.y = mls_cloud.points[i].y;
vo.z = mls_cloud.points[i].z;
no.x = mls_cloud.points[i].normal_x;
no.y = mls_cloud.points[i].normal_y;
no.z = mls_cloud.points[i].normal_z;
NodeHandle node = outputNodes.add(vo);
outputNodes.setState(node,normalStateOut,no);
outputNodes.setState(node,curvatureStateOut,mls_cloud.points[i].curvature);
//int alph = static_cast<int> (mls_cloud.points[i].rgb);
//outputNodes.setState(node,rgbahandle,alph);
}
return true;
}
/**
*
*/
MlsSample::MlsSample() :
DataExecution::Operation(
DataExecution::OperationFactoryTraits< MlsSample >::getInstance(),
tr("MLS sample local plane upsampling"))
{
pImpl_ = new MlsSampleImpl(*this);
}
/**
*
*/
MlsSample::~MlsSample()
{
delete pImpl_;
}
/**
*
*/
bool MlsSample::execute()
{
return pImpl_->execute();
}
}
}
using namespace CSIRO;
using namespace PointCloud;
DEFINE_WORKSPACE_OPERATION_FACTORY(MlsSample,
PointCloud::PointCloudPlugin::getInstance(),
DataExecution::Operation::tr("PointCloud/Upsampling"))
| 37.562674 | 143 | 0.630923 | [
"mesh",
"object",
"model"
] |
a7092c7191ff9924e755ed5c39550b117086ffa7 | 32,345 | cpp | C++ | gdal/frmts/sde/sderasterband.cpp | ajolma/gdal | 19d847c8519919fcd1e7e7247644d28771034317 | [
"MIT"
] | 9 | 2019-05-30T17:01:56.000Z | 2021-01-30T01:06:41.000Z | gdal/frmts/sde/sderasterband.cpp | ajolma/gdal | 19d847c8519919fcd1e7e7247644d28771034317 | [
"MIT"
] | 4 | 2018-10-23T18:43:35.000Z | 2019-07-01T19:29:49.000Z | gdal/frmts/sde/sderasterband.cpp | ajolma/gdal | 19d847c8519919fcd1e7e7247644d28771034317 | [
"MIT"
] | 6 | 2019-02-03T14:19:32.000Z | 2021-12-19T06:36:49.000Z | /******************************************************************************
*
* Project: ESRI ArcSDE Raster reader
* Purpose: Rasterband implementation for ESRI ArcSDE Rasters
* Author: Howard Butler, hobu@hobu.net
*
* This work was sponsored by the Geological Survey of Canada, Natural
* Resources Canada. http://gsc.nrcan.gc.ca/
*
******************************************************************************
* Copyright (c) 2007, Howard Butler <hobu@hobu.net>
*
* 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 "sderasterband.h"
CPL_CVSID("$Id$")
/************************************************************************/
/* SDERasterBand implements a GDAL RasterBand for ArcSDE. This class */
/* carries around a pointer to SDE's internal band representation */
/* is of type SE_RASBANDINFO*. SDERasterBand provides the following */
/* capabilities: */
/* */
/* -- Statistics support - uses SDE's internal band statistics */
/* -- Colortable - translates SDE's internal colortable to GDAL's */
/* -- Block reading through IReadBlock */
/* -- Overview support */
/* -- NODATA support */
/* */
/* Instantiating a SDERasterBand is rather expensive because of all */
/* of the round trips to the database the SDE C API must make to */
/* calculate band information. This overhead hit is also taken in */
/* the case of grabbing an overview, because information between */
/* bands is not shared. It might be possible in the future to do */
/* do so, but it would likely make things rather complicated. */
/* In particular, the stream, constraint, and queryinfo SDE objects */
/* could be passed around from band to overview band without having */
/* to be instantiated every time. Stream creation has an especially */
/* large overhead. */
/* */
/* Once the band or overview band is established, querying raster */
/* blocks does not carry much more network overhead than that required */
/* to actually download the bytes. */
/* */
/* Overview of internal methods: */
/* -- InitializeBand - does most of the work of construction */
/* of the band and communication with SDE. */
/* Calls InitializeConstraint and */
/* InitializeQuery. */
/* -- InitializeQuery - Initializes a SDE queryinfo object */
/* that contains information about which */
/* tables we are querying from. */
/* -- InitializeConstraint - Specifies block constraints (which */
/* are initially set to none in */
/* InitializeBand) as well as which */
/* band for SDE to query from. */
/* -- MorphESRIRasterType - translates SDE's raster type to GDAL*/
/* -- MorphESRIRasterDepth - calculates the bit depth from SDE */
/* -- ComputeColorTable - does the work of getting and */
/* translating the SDE colortable to GDAL. */
/* -- ComputeSDEBandNumber - returns the band # for SDE's */
/* internal representation of the band.*/
/* -- QueryRaster - Does the work of setting the constraint */
/* and preparing for querying tiles from SDE. */
/* */
/************************************************************************/
/************************************************************************/
/* SDERasterBand() */
/************************************************************************/
SDERasterBand::SDERasterBand( SDEDataset *poDS,
int nBand,
int nOverview,
const SE_RASBANDINFO* band )
{
// Carry some of the data we were given at construction.
// If we were passed -1 for an overview at construction, reset it
// to 0 to ensure we get the zero'th level from SDE.
// The SE_RASBANDINFO* we were given is actually owned by the
// dataset. We want it around for convenience.
this->poDS = poDS;
this->nBand = nBand;
this->nOverview = nOverview;
this->poBand = band;
// Initialize our SDE opaque object pointers to NULL.
// The nOverviews private data member will be updated when
// GetOverviewCount is called and subsequently returned immediately in
// later calls if it has been set to anything other than 0.
this->hConstraint = NULL;
this->hQuery = NULL;
this->poColorTable = NULL;
if (this->nOverview == -1 || this->nOverview == 0)
this->nOverviews = SDERasterBand::GetOverviewCount();
else
this->nOverviews = 0;
if (nOverview == -1) {
this->papoOverviews = (GDALRasterBand**) CPLMalloc( nOverviews * sizeof(GDALRasterBand*) );
}
else {
this->papoOverviews = NULL;
}
this->eDataType = SDERasterBand::GetRasterDataType();
// nSDERasterType is set by GetRasterDataType
this->dfDepth = MorphESRIRasterDepth(nSDERasterType);
InitializeBand(this->nOverview);
}
/************************************************************************/
/* ~SDERasterBand() */
/************************************************************************/
SDERasterBand::~SDERasterBand( void )
{
if (hQuery)
SE_queryinfo_free(hQuery);
if (hConstraint)
SE_rasconstraint_free(hConstraint);
if (papoOverviews)
for (int i=0; i < nOverviews; i++)
delete papoOverviews[i];
CPLFree(papoOverviews);
if (poColorTable != NULL)
delete poColorTable;
}
/************************************************************************/
/* GetColorTable() */
/************************************************************************/
GDALColorTable* SDERasterBand::GetColorTable(void)
{
if (SE_rasbandinfo_has_colormap(*poBand)) {
if (poColorTable == NULL)
ComputeColorTable();
return poColorTable;
} else {
return NULL;
}
}
/************************************************************************/
/* GetColorInterpretation() */
/************************************************************************/
GDALColorInterp SDERasterBand::GetColorInterpretation()
{
// Only return Paletted images when SDE has a colormap. Otherwise,
// just return gray, even in the instance where we have 3 or 4 band,
// imagery. Let the client be smart instead of trying to do too much.
if (SE_rasbandinfo_has_colormap(*poBand))
return GCI_PaletteIndex;
else
return GCI_GrayIndex;
}
/************************************************************************/
/* GetOverview() */
/************************************************************************/
GDALRasterBand* SDERasterBand::GetOverview( int nOverviewValue )
{
if (papoOverviews) {
return papoOverviews[nOverviewValue];
}
else
return NULL;
}
/************************************************************************/
/* GetOverviewCount() */
/************************************************************************/
int SDERasterBand::GetOverviewCount( void )
{
// grab our existing overview count if we have already gotten it,
// otherwise request it from SDE and set our member data with it.
long nSDEErr;
BOOL bSkipLevel;
LONG nOvRet;
// return nothing if we were an overview band
if (nOverview != -1)
return 0;
nSDEErr = SE_rasbandinfo_get_max_level(*poBand, &nOvRet, &bSkipLevel);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_band_size" );
}
nOverviews = nOvRet;
return nOverviews;
}
/************************************************************************/
/* GetRasterDataType() */
/************************************************************************/
GDALDataType SDERasterBand::GetRasterDataType(void)
{
// Always ask SDE what it thinks our type is.
LONG nSDEErr;
nSDEErr = SE_rasbandinfo_get_pixel_type(*poBand, &nSDERasterType);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_pixel_type" );
return GDT_Byte;
}
return MorphESRIRasterType(nSDERasterType);
}
/************************************************************************/
/* GetStatistics() */
/************************************************************************/
CPLErr SDERasterBand::GetStatistics( int bApproxOK, int bForce,
double *pdfMin, double *pdfMax,
double *pdfMean, double *pdfStdDev )
{
// if SDE hasn't already cached our statistics, we'll depend on the
// GDALRasterBands's method for getting them.
bool bHasStats;
bHasStats = SE_rasbandinfo_has_stats (*poBand);
if (!bHasStats)
return GDALRasterBand::GetStatistics( bApproxOK,
bForce,
pdfMin,
pdfMax,
pdfMean,
pdfStdDev);
// bForce has no effect currently. We always go to SDE to get our
// stats if SDE has them.
// bApproxOK has no effect currently. If we're getting stats from
// SDE, we're hoping SDE calculates them in the way we want.
long nSDEErr;
nSDEErr = SE_rasbandinfo_get_stats_min(*poBand, pdfMin);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_min" );
return CE_Fatal;
}
nSDEErr = SE_rasbandinfo_get_stats_max(*poBand, pdfMax);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_max" );
return CE_Fatal;
}
nSDEErr = SE_rasbandinfo_get_stats_mean(*poBand, pdfMean);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_mean" );
return CE_Fatal;
}
nSDEErr = SE_rasbandinfo_get_stats_stddev(*poBand, pdfStdDev);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_stats_stddev" );
return CE_Fatal;
}
return CE_None;
}
/************************************************************************/
/* GetMinimum() */
/************************************************************************/
double SDERasterBand::GetMinimum(int *pbSuccess)
{
double dfMin, dfMax, dfMean, dfStdDev;
CPLErr error = GetStatistics( TRUE, TRUE,
&dfMin,
&dfMax,
&dfMean,
&dfStdDev );
if (error == CE_None) {
*pbSuccess = TRUE;
return dfMin;
}
*pbSuccess = FALSE;
return 0.0;
}
/************************************************************************/
/* GetMaximum() */
/************************************************************************/
double SDERasterBand::GetMaximum(int *pbSuccess)
{
double dfMin, dfMax, dfMean, dfStdDev;
CPLErr error = GetStatistics( TRUE, TRUE,
&dfMin,
&dfMax,
&dfMean,
&dfStdDev );
if (error == CE_None) {
*pbSuccess = TRUE;
return dfMax;
}
*pbSuccess = FALSE;
return 0.0;
}
/************************************************************************/
/* IReadBlock() */
/************************************************************************/
CPLErr SDERasterBand::IReadBlock( int nBlockXOff,
int nBlockYOff,
void * pImage )
{
// grab our Dataset to limit the casting we have to do.
SDEDataset *poGDS = (SDEDataset *) poDS;
// SDE manages the acquisition of raster data in "TileInfo" objects.
// The hTile is the only heap-allocated object in this method, and
// we should make sure to delete it at the end. Once we get the
// pixel data, we'll memcopy it back on to the pImage pointer.
SE_RASTILEINFO hTile;
long nSDEErr;
nSDEErr = SE_rastileinfo_create(&hTile);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_create" );
return CE_Fatal;
}
hConstraint = InitializeConstraint( (long*) &nBlockXOff, (long*) &nBlockYOff );
if (!hConstraint)
CPLError( CE_Failure, CPLE_AppDefined,
"ConstraintInfo initialization failed");
CPLErr error = QueryRaster(hConstraint);
if (error != CE_None)
return error;
LONG level;
nSDEErr = SE_rastileinfo_get_level(hTile, &level);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_get_level" );
return CE_Fatal;
}
nSDEErr = SE_stream_get_raster_tile(poGDS->hStream, hTile);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_get_raster_tile" );
return CE_Fatal;
}
LONG row, column;
nSDEErr = SE_rastileinfo_get_rowcol(hTile, &row, &column);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_get_level" );
return CE_Fatal;
}
LONG length;
unsigned char* pixels;
nSDEErr = SE_rastileinfo_get_pixel_data(hTile, (void**) &pixels, &length);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rastileinfo_get_pixel_data" );
return CE_Fatal;
}
int bits_per_pixel = static_cast<int>(dfDepth * 8 + 0.0001);
int block_size = (nBlockXSize * bits_per_pixel + 7) / 8 * nBlockYSize;
int bitmap_size = (nBlockXSize * nBlockYSize + 7) / 8;
if (length == 0) {
// ArcSDE says the block has no data in it.
// Write 0's and be done with it
memset( pImage, 0,
nBlockXSize*nBlockYSize*GDALGetDataTypeSize(eDataType)/8);
return CE_None;
}
if ((length == block_size) || (length == (block_size + bitmap_size))) {
if (bits_per_pixel >= 8) {
memcpy(pImage, pixels, block_size);
} else {
GByte *p = reinterpret_cast<GByte*>(pImage);
int bit_mask = (2 << bits_per_pixel) - 1;
int i = 0;
for (int y = 0; y < nBlockYSize; ++y) {
for (int x = 0; x < nBlockXSize; ++x) {
*p++ = (pixels[i >> 3] >> (i & 7)) & bit_mask;
i += bits_per_pixel;
}
i = (i + 7) / 8 * 8;
}
}
} else {
CPLError( CE_Failure, CPLE_AppDefined,
"Bit size calculation failed... "\
"SDE's length:%d With bitmap length: %d Without bitmap length: %d",
length, block_size + bitmap_size, block_size );
return CE_Fatal;
}
SE_rastileinfo_free (hTile);
return CE_None ;
}
/* ---------------------------------------------------------------------*/
/* Private Methods */
/************************************************************************/
/* ComputeColorTable() */
/************************************************************************/
void SDERasterBand::ComputeColorTable(void)
{
SE_COLORMAP_TYPE eCMap_Type;
SE_COLORMAP_DATA_TYPE eCMap_DataType;
LONG nCMapEntries;
void *phSDEColormapData = NULL;
long nSDEErr =
SE_rasbandinfo_get_colormap( *poBand,
&eCMap_Type,
&eCMap_DataType,
&nCMapEntries,
&phSDEColormapData );
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasbandinfo_get_colormap" );
}
// Assign both the short and char pointers
// to the void*, and we'll switch and read based
// on the eCMap_DataType
unsigned char* puszSDECMapData = (unsigned char*) phSDEColormapData;
unsigned short* pushSDECMapData = (unsigned short*) phSDEColormapData;
poColorTable = new GDALColorTable(GPI_RGB);
int red, green, blue, alpha;
CPLDebug("SDERASTER", "%d colormap entries specified", nCMapEntries);
switch (eCMap_DataType) {
case SE_COLORMAP_DATA_BYTE:
switch (eCMap_Type){
case SE_COLORMAP_RGB:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*3;
red = puszSDECMapData[j];
green = puszSDECMapData[j+1];
blue = puszSDECMapData[j+2];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = 255;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_BYTE "\
"SE_COLORMAP_RGB Colormap Entry: %d %d %d",
red, blue, green);
}
break;
case SE_COLORMAP_RGBA:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*4;
red = puszSDECMapData[j];
green = puszSDECMapData[j+1];
blue = puszSDECMapData[j+2];
alpha = puszSDECMapData[j+3];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = alpha;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_BYTE "\
"SE_COLORMAP_RGBA Colormap Entry: %d %d %d %d",
red, blue, green, alpha);
}
break;
case SE_COLORMAP_NONE:
break;
}
break;
case SE_COLORMAP_DATA_SHORT:
switch (eCMap_Type) {
case SE_COLORMAP_RGB:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*3;
red = pushSDECMapData[j];
green = pushSDECMapData[j+1];
blue = pushSDECMapData[j+2];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = 255;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_SHORT "\
"SE_COLORMAP_RGB Colormap Entry: %d %d %d",
red, blue, green);
}
break;
case SE_COLORMAP_RGBA:
for (int i = 0; i < (nCMapEntries); i++) {
int j = i*4;
red = pushSDECMapData[j];
green = pushSDECMapData[j+1];
blue = pushSDECMapData[j+2];
alpha = pushSDECMapData[j+3];
GDALColorEntry sColor;
sColor.c1 = red;
sColor.c2 = green;
sColor.c3 = blue;
sColor.c4 = alpha;
// sColor is copied
poColorTable->SetColorEntry(i,&sColor);
CPLDebug ("SDERASTER", "SE_COLORMAP_DATA_SHORT "\
"SE_COLORMAP_RGBA Colormap Entry: %d %d %d %d",
red, blue, green, alpha);
}
break;
case SE_COLORMAP_NONE:
break;
}
break;
}
SE_rasbandinfo_free_colormap(phSDEColormapData);
}
/************************************************************************/
/* InitializeBand() */
/************************************************************************/
CPLErr SDERasterBand::InitializeBand( int nOverview )
{
SDEDataset *poGDS = (SDEDataset *) poDS;
long nSDEErr;
hConstraint = InitializeConstraint( NULL, NULL );
if (!hConstraint)
CPLError( CE_Failure, CPLE_AppDefined,
"ConstraintInfo initialization failed");
if (!hQuery) {
hQuery = InitializeQuery();
if (!hQuery)
CPLError( CE_Failure, CPLE_AppDefined,
"QueryInfo initialization failed");
}
nSDEErr = SE_stream_close(poGDS->hStream, 1);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_close" );
return CE_Fatal;
}
nSDEErr = SE_stream_query_with_info(poGDS->hStream, hQuery);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_query_with_info" );
return CE_Fatal;
}
nSDEErr = SE_stream_execute (poGDS->hStream);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_execute" );
return CE_Fatal;
}
nSDEErr = SE_stream_fetch (poGDS->hStream);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_fetch" );
return CE_Fatal;
}
CPLErr error = QueryRaster(hConstraint);
if (error != CE_None)
return error;
LONG nBXRet, nBYRet;
nSDEErr = SE_rasterattr_get_tile_size (poGDS->hAttributes,
&nBXRet, &nBYRet);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasterattr_get_tile_size" );
return CE_Fatal;
}
nBlockXSize = nBXRet;
nBlockYSize = nBYRet;
LONG offset_x, offset_y, num_bands, nXSRet, nYSRet;
nSDEErr = SE_rasterattr_get_image_size_by_level (poGDS->hAttributes,
&nXSRet, &nYSRet,
&offset_x,
&offset_y,
&num_bands,
(nOverview == -1) ? (0): (nOverview));
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasterattr_get_image_size_by_level" );
return CE_Fatal;
}
nRasterXSize = nXSRet;
nRasterYSize = nYSRet;
nBlockSize = nBlockXSize * nBlockYSize;
// We're the base level
if( nOverview == -1 )
{
for( int i = 0; i<this->nOverviews; i++ )
{
papoOverviews[i]= new SDERasterBand(poGDS, nBand, i, poBand);
}
}
return CE_None;
}
/************************************************************************/
/* InitializeConstraint() */
/************************************************************************/
SE_RASCONSTRAINT& SDERasterBand::InitializeConstraint( long* nBlockXOff,
long* nBlockYOff)
{
long nSDEErr;
if (!hConstraint) {
nSDEErr = SE_rasconstraint_create(&hConstraint);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_create" );
}
nSDEErr = SE_rasconstraint_set_level(hConstraint, (nOverview == -1) ? (0): (nOverview));
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_create" );
}
LONG nBandIn = nBand;
nSDEErr = SE_rasconstraint_set_bands(hConstraint, 1, &nBandIn);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_set_bands" );
}
nSDEErr = SE_rasconstraint_set_interleave(hConstraint, SE_RASTER_INTERLEAVE_BSQ);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_set_interleave" );
}
}
if (nBlockXSize != -1 && nBlockYSize != -1) { // we aren't initialized yet
if (nBlockXSize >= 0 && nBlockYSize >= 0) {
if (nBlockXOff != NULL && nBlockYOff != NULL &&
*nBlockXOff >= 0 && *nBlockYOff >= 0) {
long nMinX, nMinY, nMaxX, nMaxY;
nMinX = *nBlockXOff;
nMinY = *nBlockYOff;
nMaxX = *nBlockXOff;
nMaxY = *nBlockYOff;
nSDEErr = SE_rasconstraint_set_envelope (hConstraint,
nMinX,
nMinY,
nMaxX,
nMaxY);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_rasconstraint_set_envelope" );
}
}
}
}
return hConstraint;
}
/************************************************************************/
/* InitializeQuery() */
/************************************************************************/
SE_QUERYINFO& SDERasterBand::InitializeQuery( void )
{
SDEDataset *poGDS = (SDEDataset *) poDS;
long nSDEErr;
nSDEErr = SE_queryinfo_create(&hQuery);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_create" );
}
nSDEErr = SE_queryinfo_set_tables(hQuery,
1,
(const char**) &(poGDS->pszLayerName),
NULL);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_set_tables" );
}
nSDEErr = SE_queryinfo_set_where_clause(hQuery, (const char*) "");
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_set_where" );
}
nSDEErr = SE_queryinfo_set_columns(hQuery,
1,
(const char**) &(poGDS->pszColumnName));
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_queryinfo_set_where" );
}
return hQuery;
}
/************************************************************************/
/* MorphESRIRasterDepth() */
/************************************************************************/
double SDERasterBand::MorphESRIRasterDepth(int gtype) {
switch (gtype) {
case SE_PIXEL_TYPE_1BIT:
return 0.125;
case SE_PIXEL_TYPE_4BIT:
return 0.5;
case SE_PIXEL_TYPE_8BIT_U:
return 1.0;
case SE_PIXEL_TYPE_8BIT_S:
return 1.0;
case SE_PIXEL_TYPE_16BIT_U:
return 2.0;
case SE_PIXEL_TYPE_16BIT_S:
return 2.0;
case SE_PIXEL_TYPE_32BIT_U:
return 4.0;
case SE_PIXEL_TYPE_32BIT_S:
return 4.0;
case SE_PIXEL_TYPE_32BIT_REAL:
return 4.0;
case SE_PIXEL_TYPE_64BIT_REAL:
return 8.0;
default:
return 2.0;
}
}
/************************************************************************/
/* MorphESRIRasterType() */
/************************************************************************/
GDALDataType SDERasterBand::MorphESRIRasterType(int gtype) {
switch (gtype) {
case SE_PIXEL_TYPE_1BIT:
return GDT_Byte;
case SE_PIXEL_TYPE_4BIT:
return GDT_Byte;
case SE_PIXEL_TYPE_8BIT_U:
return GDT_Byte;
case SE_PIXEL_TYPE_8BIT_S:
return GDT_Byte;
case SE_PIXEL_TYPE_16BIT_U:
return GDT_UInt16;
case SE_PIXEL_TYPE_16BIT_S:
return GDT_Int16;
case SE_PIXEL_TYPE_32BIT_U:
return GDT_UInt32;
case SE_PIXEL_TYPE_32BIT_S:
return GDT_Int32;
case SE_PIXEL_TYPE_32BIT_REAL:
return GDT_Float32;
case SE_PIXEL_TYPE_64BIT_REAL:
return GDT_Float64;
default:
return GDT_UInt16;
}
}
/************************************************************************/
/* QueryRaster() */
/************************************************************************/
CPLErr SDERasterBand::QueryRaster( SE_RASCONSTRAINT& constraint ) const
{
SDEDataset *poGDS = (SDEDataset *) poDS;
long nSDEErr;
nSDEErr = SE_stream_query_raster_tile(poGDS->hStream, constraint);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_query_raster_tile" );
return CE_Fatal;
}
nSDEErr = SE_stream_get_raster (poGDS->hStream, 1, poGDS->hAttributes);
if( nSDEErr != SE_SUCCESS )
{
IssueSDEError( nSDEErr, "SE_stream_fetch" );
return CE_Fatal;
}
return CE_None;
}
//T:\>gdal_translate -of GTiff SDE:nakina.gis.iastate.edu,5151,,geoservwrite,EsrI4ever,sde_master.geoservwrite.century foo.tif
//T:\>gdalinfo SDE:nakina.gis.iastate.edu,5151,,geoservwrite,EsrI4ever,sde_master.geoservwrite.century
| 37.566783 | 126 | 0.470614 | [
"object"
] |
a70b348e2fd88b4de5bd93f6697e51e89a86fc77 | 8,911 | cpp | C++ | com/netfx/src/clr/vm/comobject.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/netfx/src/clr/vm/comobject.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/netfx/src/clr/vm/comobject.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Header: COMObject.cpp
**
** Author: Derek Yenzer (dereky)
**
** Purpose: Native methods on System.Object
**
** Date: March 27, 1998
**
===========================================================*/
#include "common.h"
#include <object.h>
#include "excep.h"
#include "vars.hpp"
#include "field.h"
#include "COMObject.h"
#include "COMClass.h"
#include "COMSynchronizable.h"
#include "gcscan.h"
#include "remoting.h"
/********************************************************************/
/* gets an object's 'value'. For normal classes, with reference
based semantics, this means the object's pointer. For boxed
primitive types, it also means just returning the pointer (because
they are immutable), for other value class, it means returning
a boxed copy. */
FCIMPL1(Object*, ObjectNative::GetObjectValue, Object* obj)
if (obj == 0)
return(obj);
MethodTable* pMT = obj->GetMethodTable();
if (pMT->GetNormCorElementType() != ELEMENT_TYPE_VALUETYPE)
return(obj);
Object* retVal;
OBJECTREF or(obj);
HELPER_METHOD_FRAME_BEGIN_RET_1(or); // Set up a frame
retVal = OBJECTREFToObject(FastAllocateObject(pMT));
CopyValueClass(retVal->GetData(), or->GetData(), pMT, retVal->GetAppDomain());
HELPER_METHOD_FRAME_END();
return(retVal);
FCIMPLEND
// Note that we obtain a sync block index without actually building a sync block.
// That's because a lot of objects are hashed, without requiring support for
FCIMPL1(INT32, ObjectNative::GetHashCode, Object* or) {
if (or == 0)
return 0;
VALIDATEOBJECTREF(or);
DWORD idx = or->GetSyncBlockIndex();
_ASSERTE(idx != 0);
// If the syncblock already exists, it has now become precious. Otherwise the
// hash code would not be stable across GCs.
SyncBlock *psb = or->PassiveGetSyncBlock();
if (psb)
psb->SetPrecious();
return idx;
}
FCIMPLEND
//
// Compare by ref for normal classes, by value for value types.
//
// @todo: it would be nice to customize this method based on the
// defining class rather than doing a runtime check whether it is
// a value type.
//
FCIMPL2(BOOL, ObjectNative::Equals, Object *pThisRef, Object *pCompareRef)
{
if (pThisRef == pCompareRef)
return TRUE;
// Since we are in FCALL, we must handle NULL specially.
if (pThisRef == NULL || pCompareRef == NULL)
return FALSE;
MethodTable *pThisMT = pThisRef->GetMethodTable();
// If it's not a value class, don't compare by value
if (!pThisMT->IsValueClass())
return FALSE;
// Make sure they are the same type.
if (pThisMT != pCompareRef->GetMethodTable())
return FALSE;
// Compare the contents (size - vtable - sink block index).
BOOL ret = !memcmp((void *) (pThisRef+1), (void *) (pCompareRef+1), pThisRef->GetMethodTable()->GetBaseSize() - sizeof(Object) - sizeof(int));
FC_GC_POLL_RET();
return ret;
}
FCIMPLEND
LPVOID __stdcall ObjectNative::GetClass(GetClassArgs *args)
{
OBJECTREF or = args->m_pThis;
REFLECTCLASSBASEREF refClass = NULL;
EEClass* pClass = or->GetTrueMethodTable()->m_pEEClass;
// Arrays of Pointers are implemented by reflection,
// defer to COMClass for them.
if (pClass->IsArrayClass()) {
// This code is essentially duplicated in GetExistingClass.
ArrayBase* array = (ArrayBase*) OBJECTREFToObject(or);
TypeHandle arrayType = array->GetTypeHandle();
refClass = (REFLECTCLASSBASEREF) arrayType.AsArray()->CreateClassObj();
}
else if (or->GetClass()->IsThunking()) {
refClass = CRemotingServices::GetClass(or);
}
else
refClass = (REFLECTCLASSBASEREF) pClass->GetExposedClassObject();
LPVOID rv;
_ASSERTE(refClass != NULL);
*((REFLECTCLASSBASEREF *)&rv) = refClass;
return rv;
}
// *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING
//
// IF YOU CHANGE THIS METHOD, PLEASE ALSO MAKE CORRESPONDING CHANGES TO
// CtxProxy::Clone() AS DESCRIBED BELOW.
//
// *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING
LPVOID __stdcall ObjectNative::Clone(NoArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
_ASSERTE(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
// ObjectNative::Clone() ensures that the source and destination are always in
// the same context. CtxProxy::Clone() must clone an object into a different
// context. Leaving aside that difference, the rest of the two methods should
// be the same and should be maintained together.
// @TODO: write barrier!
MethodTable* pMT;
OBJECTREF clone;
LPVOID pvSrc;
LPVOID pvClone;
DWORD cb;
pMT = pargs->m_pThis->GetMethodTable();
// assert that String has overloaded the Clone() method
_ASSERTE(pMT != g_pStringClass);
cb = pMT->GetBaseSize() - sizeof(ObjHeader);
if (pMT->IsArray()) {
// @TODO: step through array cloning
// _ASSERTE(!"array cloning hasn't been tested yet");
BASEARRAYREF base = (BASEARRAYREF)pargs->m_pThis;
cb += base->GetNumComponents() * pMT->GetComponentSize();
// @TODO: it would be nice to get a non-zeroed array,
// since we're gonna blast over it anyway
clone = DupArrayForCloning(base);
} else {
// @TODO: it would be nice to get a non-zeroed object,
// since we're gonna blast over it anyway
// We don't need to call the <cinit> because we know
// that it has been called....(It was called before this was created)
clone = AllocateObject(pMT);
}
// copy contents of "this" to the clone
*((OBJECTREF *)&pvSrc) = pargs->m_pThis;
*((OBJECTREF *)&pvClone) = clone;
memcpyGCRefs(pvClone, pvSrc, cb);
return pvClone;
}
INT32 __stdcall ObjectNative::WaitTimeout(WaitTimeoutArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
ASSERT(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
if ((pargs->m_Timeout < 0) && (pargs->m_Timeout != INFINITE_TIMEOUT))
COMPlusThrowArgumentOutOfRange(L"millisecondsTimeout", L"ArgumentOutOfRange_NeedNonNegNum");
OBJECTREF or = pargs->m_pThis;
return or->Wait(pargs->m_Timeout,pargs->m_exitContext);
}
void __stdcall ObjectNative::Pulse(NoArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
ASSERT(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
OBJECTREF or = pargs->m_pThis;
or->Pulse();
}
void __stdcall ObjectNative::PulseAll(NoArgs *pargs)
{
THROWSCOMPLUSEXCEPTION();
ASSERT(pargs != NULL);
if (pargs->m_pThis == NULL)
COMPlusThrow(kNullReferenceException, L"NullReference_This");
OBJECTREF or = pargs->m_pThis;
or->PulseAll();
}
// This method will return a Class object for the object
// iff the Class object has already been created.
// If the Class object doesn't exist then you must call the GetClass() method.
FCIMPL1(Object*, ObjectNative::GetExistingClass, Object* thisRef) {
if (thisRef == NULL)
FCThrow(kNullReferenceException);
EEClass* pClass = thisRef->GetTrueMethodTable()->m_pEEClass;
// For marshalbyref classes, let's just punt for the moment
if (pClass->IsMarshaledByRef())
return 0;
OBJECTREF refClass;
if (pClass->IsArrayClass()) {
// This code is essentially a duplicate of the code in GetClass, done for perf reasons.
ArrayBase* array = (ArrayBase*) OBJECTREFToObject(thisRef);
TypeHandle arrayType;
// Erect a GC Frame around the call to GetTypeHandle, since on the first call,
// it can call AppDomain::RaiseTypeResolveEvent, which allocates Strings and calls
// a user-provided managed callback. Yes, we have to do an allocation to do a
// lookup, since TypeHandles are used as keys. Yes this sucks. -- BrianGru, 9/12/2000
HELPER_METHOD_FRAME_BEGIN_RET_1(array);
arrayType = array->GetTypeHandle();
refClass = COMClass::QuickLookupExistingArrayClassObj(arrayType.AsArray());
HELPER_METHOD_FRAME_END();
}
else
refClass = pClass->GetExistingExposedClassObject();
return OBJECTREFToObject(refClass);
}
FCIMPLEND
| 32.053957 | 147 | 0.629335 | [
"object"
] |
a70ce1e72446859185930c244cf72a0293152849 | 2,931 | hpp | C++ | source/Homology/Homology.hpp | NickG-Math/Mackey | 0bd1e5b8aca16f3422c4ab9c5656990e1b501e54 | [
"MIT"
] | null | null | null | source/Homology/Homology.hpp | NickG-Math/Mackey | 0bd1e5b8aca16f3422c4ab9c5656990e1b501e54 | [
"MIT"
] | null | null | null | source/Homology/Homology.hpp | NickG-Math/Mackey | 0bd1e5b8aca16f3422c4ab9c5656990e1b501e54 | [
"MIT"
] | null | null | null | #pragma once
#include "Chain_Complexes/Chains.hpp"
#include "Utility/General.hpp"
#include "Smith.hpp"
#include "Abelian.hpp"
///@file
///@brief Contains the class \ref mackey::Homology.
namespace mackey {
///The Homology of a Junction
//
///@tparam rank_t The rank type is a dense Eigen row vector of signed integer scalar eg Eigen::Matrix<int,1,-1>.
///It stores the ranks of the modules of the differentials
///Eg in the G equivariant case \f$[1,2,4]\f$ means \f$Z[G/G}\oplus Z[G/G']\oplus Z[G/G'']\f$ where \f$|G:G'|=2, |G/G''|=4\f$ (current implementation only for prime power cyclic groups)
///@tparam diff_t The different
template<typename rank_t, typename diff_t>
class Homology {
typedef std::conditional_t<SFINAE::is_finite_cyclic<scalar_t<diff_t>>::value, scalar_t<diff_t>, int64_t> HScalar; //scalar with extended accuracy for Z coefficients (no change for Z/N coefficients)
typedef std::conditional_t<SFINAE::is_Dense<diff_t>::value, Eigen::Matrix<HScalar, -1, -1>, Eigen::SparseMatrix<HScalar, 0, storage_t<diff_t>>> diff_t_C; //diff_t column major with the scalar above
typedef std::conditional_t<SFINAE::is_Dense<diff_t>::value, Eigen::Matrix<HScalar, -1, -1, 1>, Eigen::SparseMatrix<HScalar, 1, storage_t<diff_t>>> diff_t_R; //diff_t row major with the scalar above
public:
///The type of our matrix of generators
typedef diff_t_C Gens_t;
///The dense type of our generators (a column in the generator matrix, always dense for convenience)
typedef col_vector_t<diff_t_C> gen_t;
AbelianGroup<rank_t> group;///<Encodes the homology groups as follows: group=[1,2,3] means homology Z+Z/2+Z/3. This works even for Z/n coefficients: the free module (Z/n)^, is encoded as [n,n,...,n]
Gens_t generators;///<Encodes the generators homology groups as follows: The i-th column corresponds to the generator for group[i]
bool isZero;///<1 if the homology is trivial
///Default constructor
Homology()=default;
///Compute the homology of Junction from the given Junction
///@param J The given Junction
///@param getQ Whether we want to store the Q matrix; this is used by the boundary function
Homology(const Junction<rank_t, diff_t>& J, bool getQ=0);
//////////////////////////////////////
///Given an element in homology, write it as a linear combination of the generators of the homology
///The answer is encoded as follows: basis=[-1,0,3] means element=-gen[0]+3*gen[2]
///////////////////////////////////////
rank_t basis(const gen_t&) const;
///Given an x that is a boundary returns a y s.t. dy=x
gen_t boundary(const gen_t&) const;
private:
diff_t_R Out_Qi, In_P_full, In_P_reduced;
std::vector<typename diff_t::StorageIndex> dontModOut;
diff_t_C In_Q;
row_vector_t<diff_t_C> diagonal;
typename diff_t::StorageIndex M;
diff_t_C getKernel(diff_t_C&);
void KernelModImage(diff_t_C&, diff_t_C&, bool);
};
}
#include "impl/Homology.ipp"
| 45.092308 | 200 | 0.710679 | [
"vector"
] |
a7173fcfd0ef6392f9b8a3ae194c34d837e33626 | 14,135 | cpp | C++ | lib/Dialect/TPU/Backend/Kernel/TgBf16MatchTemplateKernel.cpp | sophgo/tpu_compiler | 6299ea0a3adae1e5c206bcb9bedf225d16e636db | [
"Apache-2.0"
] | 3 | 2022-03-14T11:47:20.000Z | 2022-03-16T01:45:37.000Z | lib/Dialect/TPU/Backend/Kernel/TgBf16MatchTemplateKernel.cpp | sophgo/tpu_compiler | 6299ea0a3adae1e5c206bcb9bedf225d16e636db | [
"Apache-2.0"
] | null | null | null | lib/Dialect/TPU/Backend/Kernel/TgBf16MatchTemplateKernel.cpp | sophgo/tpu_compiler | 6299ea0a3adae1e5c206bcb9bedf225d16e636db | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) Cvitek Co., Ltd. 2019-2020. All rights reserved.
*
* File Name: TgBf16MatchTemplateKenrel.cpp
* Description:
*/
#include "CviBackendContext.h"
#include "backend/backend_tl_api.h"
#include <cmath>
#include <iostream>
#include <llvm/Support/Debug.h>
#include <llvm/Support/Format.h>
#include <llvm/Support/raw_ostream.h>
#define DEBUG_TYPE "cvi_backend_match_template_kernel"
#define ASSERT(x) assert(x)
static cvk_tl_t *load(const CviBackendContext &ctx, cvk_tl_shape_t &tl_shape,
cvk_tg_stride_t &gstride, uint64_t ga_src, cvk_fmt_t ifmt,
cvk_fmt_t fmt, uint32_t layer_id, float_t mean) {
cvk_tl_t *tl_ifmap = ctx.lmem_alloc_tensor(tl_shape, fmt, 1);
ASSERT(tl_ifmap);
cvk_tdma_g2l_tensor_copy_param_t p = {0};
cvk_tg_t tg_src;
tg_src.start_address = ga_src;
tg_src.base_reg_index = ctx.getTdmaBaseSelectIndexFromGaddr(tg_src.start_address);
tg_src.int8_rnd_mode = 0;
tg_src.fmt = ifmt;
tg_src.shape = ctx.tg_shape_t4(tl_shape.n, tl_shape.c, tl_shape.h, tl_shape.w);
tg_src.stride = gstride;
p.src = &tg_src;
p.dst = tl_ifmap;
ctx.tdma_g2l_tensor_copy(&p);
// temporary fix overflow issue, for some extream case it still don't work
if (mean != 0){
cvk_tiu_add_param_t p1 = {0};
p1.res_high = nullptr;
p1.res_low = tl_ifmap;
p1.a_high = nullptr;
p1.a_low = tl_ifmap;
p1.b_is_const = true;
p1.b_const.val = ctx.convert_fp32_to_bf16(-mean);
p1.b_const.is_signed = 1;
p1.rshift_bits = 0;
p1.layer_id = layer_id;
p1.relu_enable = false;
ctx.tiu_add(&p1);
}
return tl_ifmap;
}
static cvk_tl_t *load_template(const CviBackendContext &ctx, int64_t ga_src,
int32_t c_step, int32_t h, int32_t w,
cvk_fmt_t ifmt, cvk_fmt_t fmt,
bool boradcast, uint32_t layer_id, float_t &mean) {
cvk_tl_shape_t tl_tshape;
if (boradcast)
// load and broadcast template to lanes
tl_tshape = ctx.tl_shape_t4(1, NPU_NUM, h, w);
else
tl_tshape = ctx.tl_shape_t4(1, c_step, h, w);
cvk_tg_stride_t tg_tstride = ctx.tg_default_stride({1, 1, tl_tshape.h, tl_tshape.w}, ifmt);
tg_tstride.n = 0;
tg_tstride.c = 0;
cvk_tl_t *tl_template = load(ctx, tl_tshape, tg_tstride, ga_src, ifmt, fmt, layer_id, mean);
return tl_template;
}
// _____________ _____________
// ||slide | | | | output
// ||window|th | | _______| _____
// ||__tw__| ih ...... | | | --> | | n
// | | | | | |____|
// |______iw____| |_____|______| c
void cvi_backend_tg_bf16_match_template_kernel(
const CviBackendContext &ctx, uint32_t layer_id,
gaddr_t ga_input, gaddr_t ga_template,
gaddr_t ga_table, gaddr_t ga_mantissa_table,
gaddr_t ga_output, int ih, int iw,
int th, int tw, const char* mode) {
int32_t n, c, h, w, stride, outer_size, reduce_size;
uint32_t lmem_used = 0;
cvk_fmt_t fmt = CVK_FMT_BF16;
// according to which set in Quantization.cpp:145
cvk_fmt_t ifmt = CVK_FMT_U8;
float_t mean = 0.;
int32_t g_elt_size = ctx.bytesize_of_fmt(ifmt);
bool boradcast = false;
// reshape input
n = ih - th + 1;
c = iw - tw + 1;
h = th;
w = tw;
stride = iw;
outer_size = n * c;
reduce_size = h * w;
if (h >= MAX_WIDTH || w >= MAX_WIDTH) {
llvm::errs() << llvm::format("Template size[%d] is too large\n", reduce_size);
assert(0);
}
// load table
cvk_tl_shape_t table_shape = ctx.lut_table_shape(fmt);
cvk_tl_t *tl_lut = ctx.lmem_alloc_tensor(table_shape, fmt, 1);
cvk_tl_t *tl_lut_mantissa = ctx.lmem_alloc_tensor(table_shape, fmt, 1);
ctx.tdma_load(tl_lut, ga_table);
ctx.tdma_load(tl_lut_mantissa, ga_mantissa_table);
lmem_used += 2 * ctx.lmem_tensor_to_size(table_shape, fmt, 1);
// tile policy
int c_step = std::min(outer_size, MAX_CHANNEL);
while (c_step > 0) {
// for table
uint32_t mem_need = lmem_used;
// for input
mem_need += ctx.lmem_tensor_to_size(1, c_step, h, w, fmt, 1);
// for intermidate value and output
uint32_t out_mem_need = ctx.lmem_tensor_to_size(1, c_step, 1, 1, fmt, 1);
if (!strcmp(mode, "TM_CCOEFF_NORMED")) {
// for template. boradcast defult is false
mean = 128.;
if (boradcast)
mem_need += ctx.lmem_tensor_to_size(1, NPU_NUM, h, w, fmt, 1); // for test
else
mem_need += ctx.lmem_tensor_to_size(1, c_step, h, w, fmt, 1);
// 4 means tl_out, tl_inter_res, tl_buf, tl_lut_out
mem_need += 4 * out_mem_need;
}
else if(!strcmp(mode, "TM_SQDIFF")){
// broadcast template,
mem_need += ctx.lmem_tensor_to_size(1, NPU_NUM, h, w, fmt, 1);
// for output, tl_buf, tl_lut_out
mem_need += 3 * out_mem_need;
boradcast = true;
}
else {
llvm::errs() << llvm::format("Match template not support [%s] method.\n", mode);
assert(0);
}
if (mem_need <= (uint32_t) LOCAL_MEM_SIZE){
break;
}
if(c_step % NPU_NUM != 0){
c_step -= c_step % NPU_NUM;
} else {
c_step -= NPU_NUM;
}
}
if (c_step <= 0){
llvm::errs() << llvm::format("Tilling Match Template failed, src shape:[1,%d,%d,%d]\n",
outer_size, h, w);
assert(0);
}
cvk_tl_t *tl_template = load_template(ctx, ga_template, c_step, h, w,
ifmt, fmt, boradcast, layer_id, mean);
cvk_tg_stride_t tg_istride = {
(uint32_t)(stride * g_elt_size), (uint32_t)g_elt_size,
(uint32_t)(stride * g_elt_size), (uint32_t)g_elt_size
};
if (!strcmp(mode, "TM_CCOEFF_NORMED")) {
ctx.parallel_disable();
for (int c_pos = 0; c_pos < outer_size;){
int _c = std::min(c_step, outer_size - c_pos);
uint64_t in_offset = (c_pos / c * stride + c_pos % c) * g_elt_size;
uint64_t out_offset = c_pos * ctx.bytesize_of_fmt(fmt);
if (c_pos / c != (c_pos + _c - 1) / c){
// if end idx in next row , cut off rest and next loop will cal from next row.
_c -= (c_pos + _c) % c; // num of windows keep
c_pos += _c;
}
else{
c_pos += c_step;
}
// load input. For now input assume always be uint8
cvk_tl_shape_t tl_ishape = ctx.tl_shape_t4(1, _c, h, w);
cvk_tl_shape_t tl_oshape = ctx.tl_shape_t4(1, _c, 1, 1);
cvk_tl_t *tl_input = load(ctx, tl_ishape, tg_istride, ga_input + in_offset,
ifmt, fmt, layer_id, mean);
cvk_tl_t *tl_output = ctx.lmem_alloc_tensor(tl_oshape, fmt, 1);
cvk_tl_t *tl_inter_res = ctx.lmem_alloc_tensor(tl_oshape, fmt, 1);
// cal reduce_sum(pow(input, 2))
cvk_tiu_depthwise_pt_convolution_param_t p2 = {0};
p2.ofmap = tl_inter_res;
p2.ifmap = tl_input;
p2.weight = tl_input;
p2.bias = nullptr;
p2.ins_h = 0;
p2.ins_w = 0;
p2.ins_last_h = 0;
p2.ins_last_w = 0;
p2.pad_bottom = 0;
p2.pad_top= 0;
p2.pad_left = 0;
p2.pad_right = 0;
p2.stride_h = 1;
p2.stride_w = 1;
p2.dilation_h = 1;
p2.dilation_w = 1;
p2.rshift_bits = 0;
p2.relu_enable = 0;
p2.layer_id = layer_id;
ctx.tiu_pt_depthwise_convolution(&p2);
// cal reduce_sum(mul(input, tmplate))
cvk_tl_t _tl_template;
_tl_template.start_address = tl_template->start_address;
_tl_template.shape = tl_input->shape;
_tl_template.stride = tl_input->stride;
_tl_template.fmt = tl_template->fmt;
if (boradcast){
_tl_template.stride.n = 0;
_tl_template.stride.c = 0;
cvk_tiu_mul_param_t p0 = {0};
p0.res_high = nullptr;
p0.res_low = tl_input;
p0.a = tl_input;
p0.b = &_tl_template;
p0.b_is_const = 0;
p0.rshift_bits = 0;
p0.layer_id = layer_id;
p0.relu_enable = 0;
ctx.tiu_mul(&p0);
cvk_tiu_average_pooling_param_t param = {0};
param.ofmap = tl_output;
param.ifmap = tl_input;
param.kh = h;
param.kw = w;
param.pad_top = 0;
param.pad_bottom = 0;
param.pad_left = 0;
param.pad_right = 0;
param.stride_h = 1;
param.stride_w = 1;
param.avg_pooling_const = ctx.convert_fp32_to_bf16(h * w);
param.layer_id = layer_id;
param.ins_val = 0;
param.ins_fp = param.avg_pooling_const;
ctx.tiu_average_pooling(¶m);
} else{
// it seems more efficient in cuerrent case.
cvk_tiu_depthwise_pt_convolution_param_t p1 = {0};
p1.ofmap = tl_output;
p1.ifmap = tl_input;
p1.weight = tl_template;
p1.bias = nullptr;
p1.ins_h = 0;
p1.ins_w = 0;
p1.ins_last_h = 0;
p1.ins_last_w = 0;
p1.pad_bottom = 0;
p1.pad_top= 0;
p1.pad_left = 0;
p1.pad_right = 0;
p1.stride_h = 1;
p1.stride_w = 1;
p1.dilation_h = 1;
p1.dilation_w = 1;
p1.rshift_bits = 0;
p1.relu_enable = 0;
p1.layer_id = layer_id;
ctx.tiu_pt_depthwise_convolution(&p1);
}
// lut reduce)sum(sqrt(power(input, 2)))
cvk_tl_t *tl_buf = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tl_t *tl_lut_out = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tiu_bf16_lookup_interp_table_param_t p3 = {0};
p3.ifmap = tl_inter_res;
p3.buf = tl_buf;
p3.tbl_answer = tl_lut;
p3.tbl_answer_mantissa = tl_lut_mantissa;
p3.ofmap = tl_lut_out;
p3.is_scientific = 1;
ctx.tiu_bf16_lookup_interp_table(&p3);
// mul numerator and denominator
cvk_tiu_mul_param_t p4 = {0};
p4.res_high = nullptr;
p4.res_low = tl_output;
p4.a = tl_output;
p4.b = tl_lut_out;
p4.b_is_const = 0;
p4.rshift_bits = 0;
p4.layer_id = layer_id;
p4.relu_enable = 0;
ctx.tiu_mul(&p4);
ctx.tdma_store(tl_output, ga_output + out_offset);
ctx.lmem_free_tensor(tl_lut_out);
ctx.lmem_free_tensor(tl_buf);
ctx.lmem_free_tensor(tl_inter_res);
ctx.lmem_free_tensor(tl_output);
ctx.lmem_free_tensor(tl_input);
} // end for
} // end if
else {
// param: prevent overflow
float_t scale = 1. / (h * w * 100);
float_t esp = 1e-5;
ctx.parallel_disable();
for (int c_pos = 0; c_pos < outer_size;){
int _c = std::min(c_step, outer_size - c_pos);
uint64_t in_offset = (c_pos / c * stride + c_pos % c) * g_elt_size;
uint64_t out_offset = c_pos * ctx.bytesize_of_fmt(fmt);
if (c_pos / c != (c_pos + _c - 1) / c){
_c -= (c_pos + _c) % c;
c_pos += _c;
}
else{
c_pos += c_step;
}
cvk_tl_shape_t tl_ishape = ctx.tl_shape_t4(1, _c, h, w);
cvk_tl_shape_t tl_oshape = ctx.tl_shape_t4(1, _c, 1, 1);
cvk_tl_t *tl_input = load(ctx, tl_ishape, tg_istride, ga_input + in_offset,
ifmt, fmt, layer_id, mean);
cvk_tl_t *tl_output = ctx.lmem_alloc_tensor(tl_oshape, fmt, 1);
cvk_tl_t _tl_template;
_tl_template.start_address = tl_template->start_address;
_tl_template.shape = tl_input->shape;
_tl_template.stride = tl_input->stride;
_tl_template.stride.n = 0;
_tl_template.stride.c = 0;
_tl_template.fmt = tl_template->fmt;
// cal input - tmplate
cvk_tiu_sub_param_t p1 = {0};
p1.res_high = 0;
p1.res_low = tl_input;
p1.a_high = 0;
p1.a_low = tl_input;
p1.b_high = 0;
p1.b_low = &_tl_template;
p1.rshift_bits = 0;
p1.layer_id = layer_id;
ctx.tiu_sub(&p1);
// cal reduce_sum(pow((input - tmplate), 2))
cvk_tiu_depthwise_pt_convolution_param_t p2 = {0};
p2.ofmap = tl_output;
p2.ifmap = tl_input;
p2.weight = tl_input;
p2.bias = nullptr;
p2.ins_h = 0;
p2.ins_w = 0;
p2.ins_last_h = 0;
p2.ins_last_w = 0;
p2.pad_bottom = 0;
p2.pad_top= 0;
p2.pad_left = 0;
p2.pad_right = 0;
p2.stride_h = 1;
p2.stride_w = 1;
p2.dilation_h = 1;
p2.dilation_w = 1;
p2.rshift_bits = 0;
p2.relu_enable = 0;
p2.layer_id = layer_id;
ctx.tiu_pt_depthwise_convolution(&p2);
// diff from ccoeff sqdiff need min value
cvk_tiu_mul_param_t p3 = {0}; // prevent precision truncation
p3.res_high = nullptr;
p3.res_low = tl_output;
p3.a = tl_output;
p3.b_const.val = ctx.convert_fp32_to_bf16(scale);
p3.b_const.is_signed = 1;
p3.b_is_const = true;
p3.rshift_bits = 0;
p3.layer_id = layer_id;
p3.relu_enable = false;
ctx.tiu_mul(&p3);
cvk_tiu_add_param_t p4 = {0}; // prevent overflow
p4.res_high = nullptr;
p4.res_low = tl_output;
p4.a_high = nullptr;
p4.a_low = tl_output;
p4.b_is_const = true;
p4.b_const.val = ctx.convert_fp32_to_bf16(esp);
p4.b_const.is_signed = 1;
p4.rshift_bits = 0;
p4.layer_id = layer_id;
p4.relu_enable = false;
ctx.tiu_add(&p4);
// convert max to min
cvk_tl_t *tl_buf = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tl_t *tl_lut_out = ctx.lmem_alloc_tensor(tl_output->shape, tl_output->fmt, 1);
cvk_tiu_bf16_lookup_interp_table_param_t p5 = {0};
p5.ifmap = tl_output;
p5.buf = tl_buf;
p5.tbl_answer = tl_lut;
p5.tbl_answer_mantissa = tl_lut_mantissa;
p5.ofmap = tl_lut_out;
p5.is_scientific = 1;
ctx.tiu_bf16_lookup_interp_table(&p5);
ctx.tdma_store(tl_lut_out, ga_output + out_offset);
ctx.lmem_free_tensor(tl_lut_out);
ctx.lmem_free_tensor(tl_buf);
ctx.lmem_free_tensor(tl_output);
ctx.lmem_free_tensor(tl_input);
} // end for
} // end else
// free table and template
ctx.lmem_free_tensor(tl_template);
ctx.lmem_free_tensor(tl_lut_mantissa);
ctx.lmem_free_tensor(tl_lut);
} // end fun | 34.644608 | 94 | 0.61139 | [
"shape"
] |
a72033b7901f0c6ee46e5ea25ff8aa60b3fda998 | 13,396 | hpp | C++ | Engine/AssetIO/include/bf/asset_io/bf_model_loader.hpp | BluFedora/BluFedoraEngine | 41d0948f6a3a41c38fcc9217fe68105e6f1f9c5f | [
"MIT"
] | null | null | null | Engine/AssetIO/include/bf/asset_io/bf_model_loader.hpp | BluFedora/BluFedoraEngine | 41d0948f6a3a41c38fcc9217fe68105e6f1f9c5f | [
"MIT"
] | null | null | null | Engine/AssetIO/include/bf/asset_io/bf_model_loader.hpp | BluFedora/BluFedoraEngine | 41d0948f6a3a41c38fcc9217fe68105e6f1f9c5f | [
"MIT"
] | null | null | null | #ifndef BF_ASSETIO_MODEL_LOADER_HPP
#define BF_ASSETIO_MODEL_LOADER_HPP
#include "bf/memory/bf_imemory_manager.hpp" // IMemoryManager
#include "bf/bf_api_types.h" // bfStringRange
#include "bf/bifrost_math.hpp" // Math Structs
#include <array> // array
#include <cstdint> // uint32_t
#include <memory> // uninitialized_fill_n
namespace bf
{
using AssetIndexType = std::uint32_t;
////////////////////
struct AABB final
{
float min[3];
float max[3];
AABB() = default;
AABB(const bfTransform& transform);
AABB(const Vector3f& vmin, const Vector3f& vmax)
{
min[0] = vmin.x;
min[1] = vmin.y;
min[2] = vmin.z;
max[0] = vmax.x;
max[1] = vmax.y;
max[2] = vmax.z;
}
Vector3f center() const
{
return {
(max[0] + min[0]) * 0.5f,
(max[1] + min[1]) * 0.5f,
(max[2] + min[2]) * 0.5f,
1.0f,
};
}
Vector3f dimensions() const
{
return {
(max[0] - min[0]),
(max[1] - min[1]),
(max[2] - min[2]),
0.0f,
};
}
Vector3f extents() const
{
return dimensions() * 0.5f;
}
bool canContain(const AABB& rhs) const
{
for (int i = 0; i < 3; ++i)
{
if (rhs.min[i] < min[i] && !math::isAlmostEqual(min[i], rhs.min[i]) ||
rhs.max[i] > max[i] && !math::isAlmostEqual(max[i], rhs.max[i]))
{
return false;
}
}
return true;
}
bool operator==(const AABB& rhs) const
{
for (int i = 0; i < 3; ++i)
{
if (!math::isAlmostEqual(min[i], rhs.min[i]) || !math::isAlmostEqual(max[i], rhs.max[i]))
{
return false;
}
}
return true;
}
bool operator!=(const AABB& rhs) const
{
return !(*this == rhs);
}
};
namespace aabb
{
/*!
* @brief
* Creates a new bounding box that contains both \p a and \p b.
*
* @param out
* The result of this function.
*
* @param a
* The first AABB to merge.
*
* @param b
* The second AABB to merge.
*/
inline void mergeBounds(AABB& out, const AABB& a, const AABB& b)
{
for (int i = 0; i < 3; ++i)
{
out.min[i] = a.min[i] < b.min[i] ? a.min[i] : b.min[i];
out.max[i] = a.max[i] > b.max[i] ? a.max[i] : b.max[i];
}
}
inline AABB mergeBounds(const AABB& a, const AABB& b)
{
AABB out; // NOLINT
mergeBounds(out, a, b);
return out;
}
inline void expandBy(AABB& self, float amount)
{
for (int i = 0; i < 3; ++i)
{
self.min[i] = self.min[i] - amount;
self.max[i] = self.max[i] + amount;
}
}
inline AABB expandedBy(const AABB& self, float amount)
{
AABB clone = self;
expandBy(clone, amount);
return clone;
}
inline float surfaceArea(const AABB& self)
{
const float d[3] =
{
self.max[0] - self.min[0],
self.max[1] - self.min[1],
self.max[2] - self.min[2],
};
return 2.0f * (d[0] * d[1] + d[1] * d[2] + d[2] * d[0]);
}
inline AABB fromPoints(const Vector3f* points, std::size_t num_points)
{
AABB result;
result.min[0] = result.max[0] = points[0].x;
result.min[1] = result.max[1] = points[0].y;
result.min[2] = result.max[2] = points[0].z;
for (std::size_t i = 1; i < num_points; ++i)
{
const Vector3f& point = points[i];
result.min[0] = std::min(result.min[0], point.x);
result.min[1] = std::min(result.min[1], point.y);
result.min[2] = std::min(result.min[2], point.z);
result.max[0] = std::max(result.max[0], point.x);
result.max[1] = std::max(result.max[1], point.y);
result.max[2] = std::max(result.max[2], point.z);
}
return result;
}
AABB transform(const AABB& aabb, const Mat4x4& matrix);
} // namespace aabb
////////////////////
struct Mesh
{
AssetIndexType index_offset;
AssetIndexType num_indices;
std::uint32_t material_idx;
};
static constexpr std::size_t k_MaxVertexBones = 4;
static constexpr std::size_t k_MaxBones = 128;
struct AssetModelLoadResult;
struct AssetModelLoadSettings;
AssetModelLoadResult loadModel(const AssetModelLoadSettings& load_settings) noexcept;
// Lovely Simple DataStructures that lend themselves to a linear allocator.
//
// Due to this using a 'Variable Length Member' anytime you store an object of
// this type it should be a pointer as it always needs to be dynamically allocated.
// T must be default constructable.
//
template<typename T>
struct AssetTempArray
{
std::size_t length; //!< The number of elements in 'AssetTempArray::data'.
T data[1]; //!< Fake Variable Length Member, really 'AssetTempArray::length' in size.
T* begin() noexcept { return data; }
T* end() noexcept { return data + length; }
};
// using AssetTempString = AssetTempArray<char>;
template<std::size_t kSize>
struct AssetTempString
{
std::size_t length;
char data[kSize];
operator bfStringRange() const noexcept
{
return {data, data + length};
}
operator bool() const noexcept
{
return length != 0;
}
void copyOverString(const char* src, std::size_t src_length) noexcept
{
src_length = std::min(kSize - 1, src_length);
std::memcpy(data, src, src_length);
length = src_length;
data[src_length] = '\0';
}
};
using AssetTempLargeString = AssetTempString<1024>;
using AssetTempSmallString = AssetTempString<256>;
template<typename T>
AssetTempArray<T>* allocateTempArray(IMemoryManager& mem, std::size_t num_elements, T default_value = T()) noexcept
{
static_assert(std::is_trivially_destructible_v<T>, "Destructors of T will not be called.");
AssetTempArray<T>* result = new (mem.allocate(offsetof(AssetTempArray<T>, data) + sizeof(T) * num_elements)) AssetTempArray<T>;
result->length = num_elements;
std::uninitialized_fill_n(result->data, num_elements, default_value);
return result;
}
template<typename T>
void deallocateTempArray(IMemoryManager& mem, AssetTempArray<T>* temp_array)
{
temp_array->~AssetTempArray<T>();
mem.deallocate(temp_array, offsetof(AssetTempArray<T>, data) + sizeof(T) * temp_array->length);
}
// The Meats and Bones
struct AssetModelLoadSettings
{
private:
bfStringRange file_path;
IMemoryManager* memory;
bool import_animations;
bool import_lights;
bool import_cameras;
bool smooth_normals;
bool row_major;
float scale_factor;
public:
///
/// 'filename' is not required to be nul terminated :)
///
AssetModelLoadSettings(bfStringRange filename, IMemoryManager& mem) noexcept :
file_path{filename},
memory{&mem},
import_animations{true},
import_lights{false},
import_cameras{false},
smooth_normals{true},
row_major{false},
scale_factor{1.0f}
{
}
AssetModelLoadSettings& importAnimations(bool value)
{
import_animations = value;
return *this;
}
friend AssetModelLoadResult bf::loadModel(const AssetModelLoadSettings&) noexcept;
};
namespace PBRTextureType
{
enum
{
DIFFUSE,
NORMAL,
METALLIC,
ROUGHNESS,
AO,
MAX,
};
}
struct AssetModelVertex
{
Vector3f position;
Vector3f normal;
Vector3f tangent;
Vector3f bitangent;
color4f color;
Vector2f uv;
float bone_weights[k_MaxVertexBones];
std::uint8_t bone_indices[k_MaxVertexBones];
};
namespace detail
{
template<typename T>
struct PtrDeleter
{
IMemoryManager* memory;
void operator()(T* ptr) const noexcept
{
deallocateTempArray(*memory, ptr);
}
};
template<typename T>
using Ptr = std::unique_ptr<T, PtrDeleter<T>>;
template<typename T>
Ptr<T> makeUnique(T* ptr, IMemoryManager* owning_allocator) noexcept
{
return Ptr<T>(ptr, PtrDeleter<T>{owning_allocator});
}
template<typename T>
Ptr<AssetTempArray<T>> makeUniqueTempArray(IMemoryManager& mem, std::size_t num_elements, T default_value = T())
{
return makeUnique(allocateTempArray(mem, num_elements, std::move(default_value)), &mem);
}
//
// This pointer nulls itself out when moved.
//
template<typename T>
struct MovablePtr
{
T* ptr = nullptr;
MovablePtr() = default;
MovablePtr(MovablePtr&& rhs) noexcept :
ptr{std::exchange(rhs.ptr, nullptr)}
{
}
MovablePtr& operator=(MovablePtr&& rhs) noexcept = delete;
MovablePtr& operator=(T* rhs) noexcept
{
// assert(!ptr);
ptr = rhs;
return *this;
}
T& operator[](int i)
{
return ptr[i];
}
const T& operator[](int i) const
{
return ptr[i];
}
operator T*() const
{
return ptr;
}
};
} // namespace detail
struct AssetPBRMaterial
{
AssetTempLargeString textures[PBRTextureType::MAX];
float diffuse_color[4];
bool isOpaque() const { return diffuse_color[3] == 0.0f; }
};
struct AnimationKey
{
double time;
float data[4];
};
// all_keys = [pos, rot, scale]
struct ModelAnimationChannel
{
AssetTempSmallString name = {};
AssetTempArray<AnimationKey>* all_keys = {};
std::uint32_t rotation_key_offset = 0u;
std::uint32_t scale_key_offset = 0u;
std::uint32_t num_position_keys = 0u;
std::uint32_t num_rotation_keys = 0u;
std::uint32_t num_scale_keys = 0u;
};
struct ModelAnimation
{
AssetTempSmallString name = {};
double duration = 0.0; // Duration in ticks.
double ticks_per_second = 0.0; // Ticks per second. 0 if not specified in the imported file
AssetTempArray<ModelAnimationChannel>* channels = {};
};
using Matrix4x4f = ::Mat4x4;
struct AssetNode
{
AssetTempSmallString name = {};
Matrix4x4f transform = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f};
std::uint8_t model_to_bone_idx = static_cast<std::uint8_t>(-1);
unsigned int first_child = static_cast<unsigned int>(-1);
unsigned int num_children = 0;
};
struct ModelSkeleton
{
Matrix4x4f global_inv_transform;
unsigned int num_nodes;
detail::MovablePtr<AssetNode> nodes;
std::uint8_t num_bones;
std::pair<unsigned int, Matrix4x4f> bones[k_MaxBones]; // <node index, transform>
};
using AssetMeshArray = AssetTempArray<Mesh>;
using AssetVertexArray = AssetTempArray<AssetModelVertex>;
using AssetIndexArray = AssetTempArray<AssetIndexType>;
using AssetMaterialArray = AssetTempArray<AssetPBRMaterial>;
using AssetAnimationArray = AssetTempArray<ModelAnimation>;
struct AssetModelLoadResult
{
IMemoryManager* memory = nullptr;
detail::Ptr<AssetMeshArray> mesh_list = nullptr;
detail::Ptr<AssetVertexArray> vertices = nullptr;
detail::Ptr<AssetIndexArray> indices = nullptr;
detail::Ptr<AssetMaterialArray> materials = nullptr;
detail::Ptr<AssetAnimationArray> animations = nullptr;
ModelSkeleton skeleton = {};
AABB object_space_bounds = {};
bfStringRange error = {nullptr, nullptr};
std::array<char, 128> error_buffer = {'\0'}; //!< Private Do not use. Read from 'AssetModelLoadResult::error' instead.
AssetModelLoadResult() = default;
AssetModelLoadResult(const AssetModelLoadResult& rhs) noexcept = delete;
AssetModelLoadResult(AssetModelLoadResult&& rhs) noexcept = default;
AssetModelLoadResult& operator=(const AssetModelLoadResult& rhs) noexcept = delete;
AssetModelLoadResult& operator=(AssetModelLoadResult&& rhs) noexcept = delete;
operator bool() const noexcept
{
return error.str_bgn == nullptr;
}
// Private API
void setError(const char* err_message) noexcept;
~AssetModelLoadResult()
{
if (skeleton.nodes)
{
for (ModelAnimation& animation : *animations)
{
for (ModelAnimationChannel& channel : *animation.channels)
{
deallocateTempArray(*memory, channel.all_keys);
}
deallocateTempArray(*memory, animation.channels);
}
memory->deallocateArray<AssetNode>(skeleton.nodes);
}
}
};
} // namespace bf
#endif /* BF_ASSETIO_MODEL_LOADER_HPP */ | 26.318271 | 142 | 0.575993 | [
"mesh",
"object",
"transform"
] |
a7214a24d51a6d4e12e34bfe50e81c50f0cbd687 | 6,004 | cpp | C++ | example/GsQueryTest/queryresult.cpp | yulei880831/gskernel | 955385165a79f3be2d0ec06bf2d9099071fa8c74 | [
"Apache-2.0"
] | null | null | null | example/GsQueryTest/queryresult.cpp | yulei880831/gskernel | 955385165a79f3be2d0ec06bf2d9099071fa8c74 | [
"Apache-2.0"
] | null | null | null | example/GsQueryTest/queryresult.cpp | yulei880831/gskernel | 955385165a79f3be2d0ec06bf2d9099071fa8c74 | [
"Apache-2.0"
] | null | null | null | #include "queryresult.h"
#include "ui_queryresult.h"
#include <QMainWindow>
#include <QStyle>
#include <QStyleFactory>
using namespace GeoStar::Utility::Data;
QueryResult::QueryResult(QWidget *parent) :
QDialog(parent),
ui(new Ui::QueryResult)
{
ui->setupUi(this);
ui->treeWidget->setHeaderHidden(true);
//设置树图的式样为windows式样
QStyle* style = QStyleFactory::create(tr("Windows"));
QStringList keys = QStyleFactory::keys() ;
ui->treeWidget->setStyle(style);
m_nCount = 0;
m_bInner = false;
}
QueryResult::~QueryResult()
{
UnAdvise();
delete ui;
}
void QueryResult::BindMap(GsMap* pMap)
{
UnAdvise();
m_ptrMap = pMap;
Advise();
}
void QueryResult::UnAdvise()
{
if(!m_ptrMap)
return;
m_ptrMap->ScreenDisplay()->OnBeforeEndDrawing.Remove(this,&QueryResult::OnTrackerDraw);
}
void QueryResult::OnTrackerDraw(GsDisplay* pDisp)
{
if(m_nCount <=0)
return;
if((m_nCount % 2) == 0)
return;
if(!m_ptrSymbol || !m_ptrGeometry)
return;
m_ptrSymbol->StartDrawing(pDisp->Canvas(),pDisp->DisplayTransformation());
m_ptrSymbol->Draw(m_ptrGeometry);
m_ptrSymbol->EndDrawing();
}
void QueryResult::Advise()
{
if(!m_ptrMap)
return;
m_ptrMap->ScreenDisplay()->OnBeforeEndDrawing.Add(this,&QueryResult::OnTrackerDraw);
}
QTreeWidgetItem* QueryResult::CreateTreeItem(GsSelectionSet* pSet,GsFeatureLayer* pFeaLyr)
{
QStringList list;
list<<QString::fromStdString(pFeaLyr->Name());
QTreeWidgetItem* pItem = new QTreeWidgetItem(list);
GsEnumIDsPtr ptrEnum = pSet->EnumIDs();
long long nID = ptrEnum->Next();
while(nID >=0)
{
list.clear();
list<<QString::number(nID);
QTreeWidgetItem* c = new QTreeWidgetItem(pItem,list);
nID = ptrEnum->Next();
}
return pItem;
}
void QueryResult::Add(GsSelectionSet* pSet,GsFeatureLayer* pFeaLyr)
{
ui->treeWidget->addTopLevelItem(CreateTreeItem(pSet,pFeaLyr));
}
void QueryResult::ShowResult(std::vector<GsFeatureLayerPtr>& vec,GsSpatialQueryFilter* pQF)
{
m_bInner = true;
ui->treeWidget->clear();
ui->listWidget->clear();
std::vector<GsFeatureLayerPtr>::iterator it = vec.begin();
for(;it != vec.end();it++)
{
GsSelectionSetPtr ptrSel =(*it)->FeatureClass()->Select(pQF);
Add(ptrSel,*it);
}
m_vec = vec;
m_bInner = false;
if(!this->isVisible())
{
this->setWindowFlags(Qt::WindowStaysOnTopHint);
this->show();
}
}
void QueryResult::ShowProperty(GsFeature* pFea)
{
ui->listWidget->clear();
if(NULL == pFea)
return;
GsFields fs = pFea->FeatureClass()->Fields();
new QListWidgetItem(QString("OID\t") + QString::number(pFea->OID()),ui->listWidget);
for(int i =2;i<fs.Fields.size();i++)
{
GsField f = fs.Fields[i];
QString strField = QString::fromStdString( f.Name);
strField+="\t";
switch(f.Type)
{
case eErrorType:
strField+="Empty";
break;
/// \brief BOOL类型
case eBoolType:
strField+="Empty";
break;
/// \brief 32位的整型
case eIntType:
strField+=QString::number(pFea->ValueInt(i));
break;
/// \brief 32位的无符号整型
case eUIntType:
strField+=QString::number(pFea->ValueUInt(i));
break;
/// \brief 64位的整型
case eInt64Type:
strField+=QString::number(pFea->ValueInt64(i));
break;
/// \brief 64位的无符号整型
case eUInt64Type:
strField+=QString::number(pFea->ValueUInt64(i));
break;
/// \brief 字符串类型
case eStringType:
{
GeoStar::Utility::GsString str = pFea->ValueString(i);
strField+=QString::fromUtf8(str.c_str());
break;
}
/// \brief 二进制类型
case eBlobType:
strField+="Blob";
break;
/// \brief 浮点型
case eFloatType:
strField+=QString::number(pFea->ValueFloat(i));
break;
/// \brief 双精度浮点型
case eDoubleType:
strField+=QString::number(pFea->ValueDouble(i));
break;
/// \brief 几何类型
case eGeometryType:
strField+="Geometry";
break;
}
new QListWidgetItem(strField,ui->listWidget);
}
}
void QueryResult::HighLight(GsFeature* pFea)
{
ShowProperty(pFea);
if(!pFea)
return;
m_ptrGeometry = pFea->Geometry();
if(!m_ptrGeometry)
return;
if(!m_ptrPointSymbol)
m_ptrPointSymbol = new GsSimplePointSymbol(GsColor(GsColor::Red),4);
if(!m_ptrLineSymbol)
m_ptrLineSymbol = new GsSimpleLineSymbol(GsColor(GsColor::Red),1);
if(!m_ptrFillSymbol)
m_ptrFillSymbol = new GsSimpleFillSymbol(GsColor(GsColor::Red));
int nDim = GsGeometry::GeometryTypeDimension(m_ptrGeometry->GeometryType());
if(nDim ==0)
m_ptrSymbol = m_ptrPointSymbol.p;
else if(nDim ==1)
m_ptrSymbol = m_ptrLineSymbol.p;
else if(nDim ==2)
m_ptrSymbol = m_ptrFillSymbol.p;
m_nCount = 4;
m_Timer.start(100);
}
GsFeatureLayerPtr QueryResult::FindLayer(const QString& str)
{
std::vector<GsFeatureLayerPtr>::iterator it = m_vec.begin();
for(;it != m_vec.end();it++)
{
QString strName = QString::fromStdString((*it)->Name());
if(strName.compare(str,Qt::CaseInsensitive) ==0)
return *it;
}
return 0;
}
void QueryResult::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
if(m_bInner)
return ;
ui->listWidget->clear();
if(item == NULL)
return;
if(item->parent() == NULL)
return;
QTreeWidgetItem* pParent = item->parent();
GsFeatureLayerPtr ptrFeaLyr = FindLayer(pParent->text(0));
if(!ptrFeaLyr)
return ;
long long oid = item->text(0).toLongLong();
GsFeaturePtr pFea = ptrFeaLyr->FeatureClass()->Feature(oid);
HighLight(pFea);
}
| 26.218341 | 91 | 0.612425 | [
"geometry",
"vector"
] |
a7257ddec08031446fcc3270b6a9069a17f958a8 | 5,394 | cpp | C++ | src/mame/video/aeroboto.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/mame/video/aeroboto.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/mame/video/aeroboto.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Carlos A. Lozano, Uki
/***************************************************************************
video/aeroboto.c
***************************************************************************/
#include "emu.h"
#include "includes/aeroboto.h"
// how the starfield ROM is interpreted: 0=256x256x1 linear bitmap, 1=8x8x1x1024 tilemap
#define STARS_LAYOUT 1
// scroll speed of the stars: 1=normal, 2=half, 3=one-third...etc.(possitive integers only)
#define SCROLL_SPEED 1
/***************************************************************************
Callbacks for the TileMap code
***************************************************************************/
TILE_GET_INFO_MEMBER(aeroboto_state::get_tile_info)
{
uint8_t code = m_videoram[tile_index];
tileinfo.set(0,
code + (m_charbank << 8),
m_tilecolor[code],
(m_tilecolor[code] >= 0x33) ? 0 : TILE_FORCE_LAYER0);
}
// transparency should only affect tiles with color 0x33 or higher
/***************************************************************************
Start the video hardware emulation.
***************************************************************************/
void aeroboto_state::video_start()
{
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(aeroboto_state::get_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 32, 64);
m_bg_tilemap->set_transparent_pen(0);
m_bg_tilemap->set_scroll_rows(64);
save_item(NAME(m_charbank));
save_item(NAME(m_starsoff));
save_item(NAME(m_sx));
save_item(NAME(m_sy));
save_item(NAME(m_ox));
save_item(NAME(m_oy));
#if STARS_LAYOUT
{
int i;
std::vector<uint8_t> temp(m_stars_length);
memcpy(&temp[0], m_stars_rom, m_stars_length);
for (i = 0; i < m_stars_length; i++)
m_stars_rom[(i & ~0xff) + (i << 5 & 0xe0) + (i >> 3 & 0x1f)] = temp[i];
}
#endif
}
/***************************************************************************
Memory handlers
***************************************************************************/
uint8_t aeroboto_state::aeroboto_in0_r()
{
return ioport(flip_screen() ? "P2" : "P1")->read();
}
void aeroboto_state::aeroboto_3000_w(uint8_t data)
{
/* bit 0 selects both flip screen and player1/player2 controls */
flip_screen_set(data & 0x01);
/* bit 1 = char bank select */
if (m_charbank != ((data & 0x02) >> 1))
{
m_bg_tilemap->mark_all_dirty();
m_charbank = (data & 0x02) >> 1;
}
/* bit 2 = disable star field? */
m_starsoff = data & 0x4;
}
void aeroboto_state::aeroboto_videoram_w(offs_t offset, uint8_t data)
{
m_videoram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset);
}
void aeroboto_state::aeroboto_tilecolor_w(offs_t offset, uint8_t data)
{
if (m_tilecolor[offset] != data)
{
m_tilecolor[offset] = data;
m_bg_tilemap->mark_all_dirty();
}
}
/***************************************************************************
Display refresh
***************************************************************************/
void aeroboto_state::draw_sprites( bitmap_ind16 &bitmap, const rectangle &cliprect )
{
for (int offs = 0; offs < m_spriteram.bytes(); offs += 4)
{
int x = m_spriteram[offs + 3];
int y = 240 - m_spriteram[offs];
if (flip_screen())
{
x = 248 - x;
y = 240 - y;
}
m_gfxdecode->gfx(1)->transpen(bitmap,cliprect,
m_spriteram[offs + 1],
m_spriteram[offs + 2] & 0x07,
flip_screen(), flip_screen(),
((x + 8) & 0xff) - 8, y, 0);
}
}
uint32_t aeroboto_state::screen_update_aeroboto(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
rectangle const splitrect1(0, 255, 0, 39);
rectangle const splitrect2(0, 255, 40, 255);
int sky_color, star_color;
sky_color = star_color = *m_bgcolor << 2;
// the star field is supposed to be seen through tile pen 0 when active
if (!m_starsoff)
{
if (star_color < 0xd0)
{
star_color = 0xd0;
sky_color = 0;
}
star_color += 2;
bitmap.fill(sky_color, cliprect);
// actual scroll speed is unknown but it can be adjusted by changing the SCROLL_SPEED constant
m_sx += char(*m_starx - m_ox);
m_ox = *m_starx;
int const x = m_sx / SCROLL_SPEED;
if (*m_vscroll != 0xff)
m_sy += char(*m_stary - m_oy);
m_oy = *m_stary;
int const y = m_sy / SCROLL_SPEED;
uint8_t const *const src_base = m_stars_rom;
for (int i = 0; i < 256; i++)
{
int src_offsx = (x + i) & 0xff;
int const src_colmask = 1 << (src_offsx & 7);
src_offsx >>= 3;
uint8_t const *const src_colptr = src_base + src_offsx;
int const pen = star_color + ((i + 8) >> 4 & 1);
for (int j = 0; j < 256; j++)
{
uint8_t const *const src_rowptr = src_colptr + (((y + j) & 0xff) << 5 );
if (!((unsigned)*src_rowptr & src_colmask))
bitmap.pix(j, i) = pen;
}
}
}
else
{
m_sx = m_ox = *m_starx;
m_sy = m_oy = *m_stary;
bitmap.fill(sky_color, cliprect);
}
for (int y = 0; y < 64; y++)
m_bg_tilemap->set_scrollx(y, m_hscroll[y]);
// the playfield is part of a splitscreen and should not overlap with status display
m_bg_tilemap->set_scrolly(0, *m_vscroll);
m_bg_tilemap->draw(screen, bitmap, splitrect2, 0, 0);
draw_sprites(bitmap, cliprect);
// the status display behaves more closely to a 40-line splitscreen than an overlay
m_bg_tilemap->set_scrolly(0, 0);
m_bg_tilemap->draw(screen, bitmap, splitrect1, 0, 0);
return 0;
}
| 25.323944 | 162 | 0.579162 | [
"vector"
] |
a725bc25f95475f8d7bba0fb6276be5031bc3d74 | 13,921 | cpp | C++ | tree_morse.cpp | andythebreaker/Graphical_user_interface_for_Morse_code_transmitter_and_dot_matrix_text_generation | aa0248bdd6252ed6a26d621d2f2c123dcb60034b | [
"MIT"
] | null | null | null | tree_morse.cpp | andythebreaker/Graphical_user_interface_for_Morse_code_transmitter_and_dot_matrix_text_generation | aa0248bdd6252ed6a26d621d2f2c123dcb60034b | [
"MIT"
] | 1 | 2021-07-03T18:13:56.000Z | 2021-07-03T18:13:56.000Z | tree_morse.cpp | andythebreaker/Graphical_user_interface_for_Morse_code_transmitter_and_dot_matrix_text_generation | aa0248bdd6252ed6a26d621d2f2c123dcb60034b | [
"MIT"
] | null | null | null | //using g++ 6.3.0 ; aka MinGW.org GCC-6.3.0-1
/**
* logic tree of Morse code
*
* @author andythebreaker
* @version 0.0.1, 07/04/2021
*/
#include <algorithm>
#include <iostream>
#include <string>
#include <list>
#include <map>
#include <vector>
#include <math.h>
#include <stdlib.h>
#include <fstream>
#include <regex>
#include <sstream>
#include <queue>
#include <utility>
#define ALL_MOS_PAT_NUM 56
#define MORSE_ARRAY_TO_VECTOR(MORSE_ARRAY_INPUT, MORSE_ARRAY_NNAME) vector<int> MORSE_ARRAY_NNAME(MORSE_ARRAY_INPUT, MORSE_ARRAY_INPUT + sizeof(MORSE_ARRAY_INPUT) / sizeof(MORSE_ARRAY_INPUT[0]))
using namespace std;
class cell
{
public:
// Default constructor
cell() {}
// Initialize a Box with custom dimensions
cell(string name, vector<int> morse)
: m_name(name), m_morse(morse)
{
}
string name(void) { return m_name; };
vector<int> morse(void) { return m_morse; }
private:
// Will have value of 0 when default constructor is called.
// If we didn't zero-init here, default constructor would
// leave them uninitialized with garbage values.
string m_name{NULL};
vector<int> m_morse{NULL};
};
// 宣告類別
class tree_node
{
// 宣告 public 成員
public:
tree_node()
{
numb = count;
count++;
}
static int count;
int numb;
tree_node *dot;
tree_node *dash;
vector<cell> endof;
};
int tree_node::count = 0;
string print_int_ary(int *int_ary)
{
string output_str = "";
int arrSize = sizeof(int_ary) / sizeof(int_ary[0]);
for (size_t i = 0; i < arrSize; i++)
{
output_str += to_string(int_ary[i]) + " ,";
}
return output_str;
}
string int_vec_2_str(vector<int> int_vec)
{
string str_out = "";
vector<int>::iterator it;
for (it = int_vec.begin(); it != int_vec.end(); it++)
{
str_out += to_string(*it) + ", ";
}
return str_out;
}
int main()
{
cout << "Running..." << endl;
//56
int morse_ary_A[] = {1, 2, 0};
int morse_ary_B[] = {2, 1, 1, 1, 0};
int morse_ary_C[] = {2, 1, 2, 1, 0};
int morse_ary_D[] = {2, 1, 1, 0};
int morse_ary_E[] = {1, 0};
int morse_ary_F[] = {1, 1, 2, 1, 0};
int morse_ary_G[] = {2, 2, 1, 0};
int morse_ary_H[] = {1, 1, 1, 1, 0};
int morse_ary_I[] = {1, 1, 0};
int morse_ary_J[] = {1, 2, 2, 2, 0};
int morse_ary_K[] = {2, 1, 2, 0};
int morse_ary_L[] = {1, 2, 1, 1, 0};
int morse_ary_M[] = {2, 2, 0};
int morse_ary_N[] = {2, 1, 0};
int morse_ary_O[] = {2, 2, 2, 0};
int morse_ary_P[] = {1, 2, 2, 1, 0};
int morse_ary_Q[] = {2, 2, 1, 2, 0};
int morse_ary_R[] = {1, 2, 1, 0};
int morse_ary_S[] = {1, 1, 1, 0};
int morse_ary_T[] = {2, 0};
int morse_ary_U[] = {1, 1, 2, 0};
int morse_ary_V[] = {1, 1, 1, 2, 0};
int morse_ary_W[] = {1, 2, 2, 0};
int morse_ary_X[] = {2, 1, 1, 2, 0};
int morse_ary_Y[] = {2, 1, 2, 2, 0};
int morse_ary_Z[] = {2, 2, 1, 1, 0};
int morse_ary_0[] = {2, 2, 2, 2, 2, 0};
int morse_ary_1[] = {1, 2, 2, 2, 2, 0};
int morse_ary_2[] = {1, 1, 2, 2, 2, 0};
int morse_ary_3[] = {1, 1, 1, 2, 2, 0};
int morse_ary_4[] = {1, 1, 1, 1, 2, 0};
int morse_ary_5[] = {1, 1, 1, 1, 1, 0};
int morse_ary_6[] = {2, 1, 1, 1, 1, 0};
int morse_ary_7[] = {2, 2, 1, 1, 1, 0};
int morse_ary_8[] = {2, 2, 2, 1, 1, 0};
int morse_ary_9[] = {2, 2, 2, 2, 1, 0};
int morse_ary_DOT[] = {1, 2, 1, 2, 1, 2, 0};
int morse_ary_LB[] = {2, 1, 2, 2, 1, 0};
int morse_ary_RB[] = {2, 1, 2, 2, 1, 2, 0};
int morse_ary_PLUS[] = {1, 2, 1, 2, 1, 0};
int morse_ary_SP[] = {2, 1, 2, 1, 2, 1, 0};
int morse_ary_UQ[] = {1, 1, 2, 1, 2, 0};
int morse_ary_COMA[] = {2, 2, 1, 1, 2, 2, 0};
int morse_ary_DASH[] = {2, 1, 1, 1, 1, 2, 0};
int morse_ary_EQ[] = {2, 1, 1, 1, 2, 0};
int morse_ary_UEXC[] = {2, 2, 1, 1, 1, 2, 0};
int morse_ary_QM[] = {1, 1, 2, 2, 1, 1, 0};
int morse_ary_AND[] = {1, 2, 1, 1, 1, 0};
int morse_ary_DD[] = {1, 1, 2, 2, 1, 2, 0};
int morse_ary_MONY[] = {1, 1, 1, 2, 1, 1, 2, 0};
int morse_ary_EXC[] = {2, 1, 2, 1, 2, 2, 0};
int morse_ary_SQUT[] = {1, 2, 2, 2, 2, 1, 0};
int morse_ary_COLN[] = {2, 2, 2, 1, 1, 1, 0};
int morse_ary_DQUT[] = {1, 2, 1, 1, 2, 1, 0};
int morse_ary_AT[] = {1, 2, 2, 1, 2, 1, 0};
int morse_ary_SLAH[] = {2, 1, 1, 2, 1, 0};
MORSE_ARRAY_TO_VECTOR(morse_ary_A, NNAME_morse_ary_A);
MORSE_ARRAY_TO_VECTOR(morse_ary_B, NNAME_morse_ary_B);
MORSE_ARRAY_TO_VECTOR(morse_ary_C, NNAME_morse_ary_C);
MORSE_ARRAY_TO_VECTOR(morse_ary_D, NNAME_morse_ary_D);
MORSE_ARRAY_TO_VECTOR(morse_ary_E, NNAME_morse_ary_E);
MORSE_ARRAY_TO_VECTOR(morse_ary_F, NNAME_morse_ary_F);
MORSE_ARRAY_TO_VECTOR(morse_ary_G, NNAME_morse_ary_G);
MORSE_ARRAY_TO_VECTOR(morse_ary_H, NNAME_morse_ary_H);
MORSE_ARRAY_TO_VECTOR(morse_ary_I, NNAME_morse_ary_I);
MORSE_ARRAY_TO_VECTOR(morse_ary_J, NNAME_morse_ary_J);
MORSE_ARRAY_TO_VECTOR(morse_ary_K, NNAME_morse_ary_K);
MORSE_ARRAY_TO_VECTOR(morse_ary_L, NNAME_morse_ary_L);
MORSE_ARRAY_TO_VECTOR(morse_ary_M, NNAME_morse_ary_M);
MORSE_ARRAY_TO_VECTOR(morse_ary_N, NNAME_morse_ary_N);
MORSE_ARRAY_TO_VECTOR(morse_ary_O, NNAME_morse_ary_O);
MORSE_ARRAY_TO_VECTOR(morse_ary_P, NNAME_morse_ary_P);
MORSE_ARRAY_TO_VECTOR(morse_ary_Q, NNAME_morse_ary_Q);
MORSE_ARRAY_TO_VECTOR(morse_ary_R, NNAME_morse_ary_R);
MORSE_ARRAY_TO_VECTOR(morse_ary_S, NNAME_morse_ary_S);
MORSE_ARRAY_TO_VECTOR(morse_ary_T, NNAME_morse_ary_T);
MORSE_ARRAY_TO_VECTOR(morse_ary_U, NNAME_morse_ary_U);
MORSE_ARRAY_TO_VECTOR(morse_ary_V, NNAME_morse_ary_V);
MORSE_ARRAY_TO_VECTOR(morse_ary_W, NNAME_morse_ary_W);
MORSE_ARRAY_TO_VECTOR(morse_ary_X, NNAME_morse_ary_X);
MORSE_ARRAY_TO_VECTOR(morse_ary_Y, NNAME_morse_ary_Y);
MORSE_ARRAY_TO_VECTOR(morse_ary_Z, NNAME_morse_ary_Z);
MORSE_ARRAY_TO_VECTOR(morse_ary_0, NNAME_morse_ary_0);
MORSE_ARRAY_TO_VECTOR(morse_ary_1, NNAME_morse_ary_1);
MORSE_ARRAY_TO_VECTOR(morse_ary_2, NNAME_morse_ary_2);
MORSE_ARRAY_TO_VECTOR(morse_ary_3, NNAME_morse_ary_3);
MORSE_ARRAY_TO_VECTOR(morse_ary_4, NNAME_morse_ary_4);
MORSE_ARRAY_TO_VECTOR(morse_ary_5, NNAME_morse_ary_5);
MORSE_ARRAY_TO_VECTOR(morse_ary_6, NNAME_morse_ary_6);
MORSE_ARRAY_TO_VECTOR(morse_ary_7, NNAME_morse_ary_7);
MORSE_ARRAY_TO_VECTOR(morse_ary_8, NNAME_morse_ary_8);
MORSE_ARRAY_TO_VECTOR(morse_ary_9, NNAME_morse_ary_9);
MORSE_ARRAY_TO_VECTOR(morse_ary_DOT, NNAME_morse_ary_DOT);
MORSE_ARRAY_TO_VECTOR(morse_ary_LB, NNAME_morse_ary_LB);
MORSE_ARRAY_TO_VECTOR(morse_ary_RB, NNAME_morse_ary_RB);
MORSE_ARRAY_TO_VECTOR(morse_ary_PLUS, NNAME_morse_ary_PLUS);
MORSE_ARRAY_TO_VECTOR(morse_ary_SP, NNAME_morse_ary_SP);
MORSE_ARRAY_TO_VECTOR(morse_ary_UQ, NNAME_morse_ary_UQ);
MORSE_ARRAY_TO_VECTOR(morse_ary_COMA, NNAME_morse_ary_COMA);
MORSE_ARRAY_TO_VECTOR(morse_ary_DASH, NNAME_morse_ary_DASH);
MORSE_ARRAY_TO_VECTOR(morse_ary_EQ, NNAME_morse_ary_EQ);
MORSE_ARRAY_TO_VECTOR(morse_ary_UEXC, NNAME_morse_ary_UEXC);
MORSE_ARRAY_TO_VECTOR(morse_ary_QM, NNAME_morse_ary_QM);
MORSE_ARRAY_TO_VECTOR(morse_ary_AND, NNAME_morse_ary_AND);
MORSE_ARRAY_TO_VECTOR(morse_ary_DD, NNAME_morse_ary_DD);
MORSE_ARRAY_TO_VECTOR(morse_ary_MONY, NNAME_morse_ary_MONY);
MORSE_ARRAY_TO_VECTOR(morse_ary_EXC, NNAME_morse_ary_EXC);
MORSE_ARRAY_TO_VECTOR(morse_ary_SQUT, NNAME_morse_ary_SQUT);
MORSE_ARRAY_TO_VECTOR(morse_ary_COLN, NNAME_morse_ary_COLN);
MORSE_ARRAY_TO_VECTOR(morse_ary_DQUT, NNAME_morse_ary_DQUT);
MORSE_ARRAY_TO_VECTOR(morse_ary_AT, NNAME_morse_ary_AT);
MORSE_ARRAY_TO_VECTOR(morse_ary_SLAH, NNAME_morse_ary_SLAH);
cell morse_ary[ALL_MOS_PAT_NUM] = {
{"ASCII88PATTERN_A", NNAME_morse_ary_A},
{"ASCII88PATTERN_B", NNAME_morse_ary_B},
{"ASCII88PATTERN_C", NNAME_morse_ary_C},
{"ASCII88PATTERN_D", NNAME_morse_ary_D},
{"ASCII88PATTERN_E", NNAME_morse_ary_E},
{"ASCII88PATTERN_F", NNAME_morse_ary_F},
{"ASCII88PATTERN_G", NNAME_morse_ary_G},
{"ASCII88PATTERN_H", NNAME_morse_ary_H},
{"ASCII88PATTERN_I", NNAME_morse_ary_I},
{"ASCII88PATTERN_J", NNAME_morse_ary_J},
{"ASCII88PATTERN_K", NNAME_morse_ary_K},
{"ASCII88PATTERN_L", NNAME_morse_ary_L},
{"ASCII88PATTERN_M", NNAME_morse_ary_M},
{"ASCII88PATTERN_N", NNAME_morse_ary_N},
{"ASCII88PATTERN_O", NNAME_morse_ary_O},
{"ASCII88PATTERN_P", NNAME_morse_ary_P},
{"ASCII88PATTERN_Q", NNAME_morse_ary_Q},
{"ASCII88PATTERN_R", NNAME_morse_ary_R},
{"ASCII88PATTERN_S", NNAME_morse_ary_S},
{"ASCII88PATTERN_T", NNAME_morse_ary_T},
{"ASCII88PATTERN_U", NNAME_morse_ary_U},
{"ASCII88PATTERN_V", NNAME_morse_ary_V},
{"ASCII88PATTERN_W", NNAME_morse_ary_W},
{"ASCII88PATTERN_X", NNAME_morse_ary_X},
{"ASCII88PATTERN_Y", NNAME_morse_ary_Y},
{"ASCII88PATTERN_Z", NNAME_morse_ary_Z},
{"ASCII88PATTERN_0", NNAME_morse_ary_0},
{"ASCII88PATTERN_1", NNAME_morse_ary_1},
{"ASCII88PATTERN_2", NNAME_morse_ary_2},
{"ASCII88PATTERN_3", NNAME_morse_ary_3},
{"ASCII88PATTERN_4", NNAME_morse_ary_4},
{"ASCII88PATTERN_5", NNAME_morse_ary_5},
{"ASCII88PATTERN_6", NNAME_morse_ary_6},
{"ASCII88PATTERN_7", NNAME_morse_ary_7},
{"ASCII88PATTERN_8", NNAME_morse_ary_8},
{"ASCII88PATTERN_9", NNAME_morse_ary_9},
{"ASCII88PATTERN_DOT", NNAME_morse_ary_DOT},
{"ASCII88PATTERN_LB", NNAME_morse_ary_LB},
{"ASCII88PATTERN_RB", NNAME_morse_ary_RB},
{"ASCII88PATTERN_PLUS", NNAME_morse_ary_PLUS},
{"ASCII88PATTERN_SP", NNAME_morse_ary_SP},
{"ASCII88PATTERN_UQ", NNAME_morse_ary_UQ},
{"ASCII88PATTERN_COMA", NNAME_morse_ary_COMA},
{"ASCII88PATTERN_DASH", NNAME_morse_ary_DASH},
{"ASCII88PATTERN_EQ", NNAME_morse_ary_EQ},
{"ASCII88PATTERN_UEXC", NNAME_morse_ary_UEXC},
{"ASCII88PATTERN_QM", NNAME_morse_ary_QM},
{"ASCII88PATTERN_AND", NNAME_morse_ary_AND},
{"ASCII88PATTERN_DD", NNAME_morse_ary_DD},
{"ASCII88PATTERN_MONY", NNAME_morse_ary_MONY},
{"ASCII88PATTERN_EXC", NNAME_morse_ary_EXC},
{"ASCII88PATTERN_SQUT", NNAME_morse_ary_SQUT},
{"ASCII88PATTERN_COLN", NNAME_morse_ary_COLN},
{"ASCII88PATTERN_DQUT", NNAME_morse_ary_DQUT},
{"ASCII88PATTERN_AT", NNAME_morse_ary_AT},
{"ASCII88PATTERN_SLAH", NNAME_morse_ary_SLAH},
};
int max_step_numb = 0;
for (size_t i = 0; i < ALL_MOS_PAT_NUM; i++)
{
cout << morse_ary[i].name() << endl;
cout << int_vec_2_str(morse_ary[i].morse()) << endl;
max_step_numb = (morse_ary[i].morse().size() > max_step_numb) ? morse_ary[i].morse().size() : max_step_numb;
}
cout << "\t\tmax_step_numb:" << to_string(max_step_numb) << endl;
double length_of_all_tree_node = 0;
double pause_point = 0;
for (size_t i = 0; i < max_step_numb; i++)
{
length_of_all_tree_node += pow((double)2, (double)i);
if (i + 2 == max_step_numb)
{
pause_point = length_of_all_tree_node;
}
}
cout << "\t\tlength_of_all_tree_node:" << to_string(length_of_all_tree_node) << endl;
cout << "\t\tpause_point:" << to_string(pause_point) << endl;
vector<tree_node> tree_all;
for (double i = 0; i < length_of_all_tree_node; i++)
{
tree_all.push_back(tree_node());
}
for (double i = 0; i < pause_point; i++)
{
tree_all[int(i)].dot = &tree_all[(int(i) + 1) * 2 - 1];
tree_all[int(i)].dash = &tree_all[(int(i) + 1) * 2];
}
for (double i = pause_point; i < length_of_all_tree_node; i++)
{
tree_all[int(i)].dot = NULL;
tree_all[int(i)].dash = NULL;
}
for (size_t i = 0; i < ALL_MOS_PAT_NUM; i++)
{
tree_node *tmp_tn = &tree_all[0];
cout << "pattern:" + to_string(i);
for (size_t ii = 0; ii < max_step_numb; ii++)
{
cout << ", " + to_string(morse_ary[i].morse()[ii]);
if (morse_ary[i].morse()[ii] == 1)
{
cout << "[dot](" << to_string((*tmp_tn).numb);
tmp_tn = tmp_tn->dot;
cout << "->" << to_string((*tmp_tn).numb) << ")";
}
else if (morse_ary[i].morse()[ii] == 2)
{
cout << "[dash](" << to_string((*tmp_tn).numb);
tmp_tn = tmp_tn->dash;
cout << "->" << to_string((*tmp_tn).numb) << ")";
}
else
{
cout << "[endof](" << to_string((*tmp_tn).numb);
(*tmp_tn).endof.push_back(morse_ary[i]);
cout << "->" << to_string((*tmp_tn).numb) << ")";
break;
}
}
cout << endl;
}
string main_output = "";
for (double i = 0; i < length_of_all_tree_node; i++)
{
main_output += "case " + to_string(tree_all[int(i)].numb) + ":\nif(input_bool==1){\n" + ((tree_all[int(i)].dot) ? ("morse_pattern_status=" + to_string((*(tree_all[int(i)].dot)).numb) + ";") : "target_morse_pattern_error_event();") +
"\n}else if(input_bool==2){\n" + ((tree_all[int(i)].dash) ? ("morse_pattern_status=" + to_string((*(tree_all[int(i)].dash)).numb) + ";") : "target_morse_pattern_error_event();") +
"\n}else{\n" +
((tree_all[int(i)].endof.size() > 0) ? ("morse_pattern_status=0;\nSCREEN_SHOW_FRAM(" + (*(tree_all[int(i)].endof.begin())).name() + ")") : "target_morse_pattern_error_event();") + "\n}break;";
}
cout << "================================================================" << endl;
cout << main_output << endl;
} | 39.660969 | 240 | 0.631348 | [
"vector"
] |
a7260a454ed1ed7e0699965b99a2f8495165f2af | 21,108 | cc | C++ | third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 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 "third_party/blink/renderer/core/layout/ng/inline/ng_line_truncator.h"
#include "base/containers/adapters.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_box_state.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_inline_item_result.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_line_info.h"
#include "third_party/blink/renderer/core/layout/ng/inline/ng_logical_line_item.h"
#include "third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
#include "third_party/blink/renderer/platform/fonts/shaping/harfbuzz_shaper.h"
#include "third_party/blink/renderer/platform/fonts/shaping/shape_result_view.h"
namespace blink {
namespace {
bool IsLeftMostOffset(const ShapeResult& shape_result, unsigned offset) {
if (shape_result.IsRtl())
return offset == shape_result.NumCharacters();
return offset == 0;
}
bool IsRightMostOffset(const ShapeResult& shape_result, unsigned offset) {
if (shape_result.IsRtl())
return offset == 0;
return offset == shape_result.NumCharacters();
}
} // namespace
NGLineTruncator::NGLineTruncator(const NGLineInfo& line_info)
: line_style_(&line_info.LineStyle()),
available_width_(line_info.AvailableWidth() - line_info.TextIndent()),
line_direction_(line_info.BaseDirection()) {}
const ComputedStyle& NGLineTruncator::EllipsisStyle() const {
// The ellipsis is styled according to the line style.
// https://drafts.csswg.org/css-ui/#ellipsing-details
DCHECK(line_style_);
return *line_style_;
}
void NGLineTruncator::SetupEllipsis() {
const Font& font = EllipsisStyle().GetFont();
ellipsis_font_data_ = font.PrimaryFont();
DCHECK(ellipsis_font_data_);
ellipsis_text_ =
ellipsis_font_data_ && ellipsis_font_data_->GlyphForCharacter(
kHorizontalEllipsisCharacter)
? String(&kHorizontalEllipsisCharacter, 1)
: String(u"...");
HarfBuzzShaper shaper(ellipsis_text_);
ellipsis_shape_result_ =
ShapeResultView::Create(shaper.Shape(&font, line_direction_).get());
ellipsis_width_ = ellipsis_shape_result_->SnappedWidth();
}
LayoutUnit NGLineTruncator::PlaceEllipsisNextTo(
NGLogicalLineItems* line_box,
NGLogicalLineItem* ellipsized_child) {
// Create the ellipsis, associating it with the ellipsized child.
DCHECK(ellipsized_child->HasInFlowFragment());
const LayoutObject* ellipsized_layout_object =
ellipsized_child->GetMutableLayoutObject();
DCHECK(ellipsized_layout_object);
DCHECK(ellipsized_layout_object->IsInline());
DCHECK(ellipsized_layout_object->IsText() ||
ellipsized_layout_object->IsAtomicInlineLevel());
// Now the offset of the ellpisis is determined. Place the ellpisis into the
// line box.
LayoutUnit ellipsis_inline_offset =
IsLtr(line_direction_)
? ellipsized_child->InlineOffset() + ellipsized_child->inline_size
: ellipsized_child->InlineOffset() - ellipsis_width_;
FontHeight ellipsis_metrics;
DCHECK(ellipsis_font_data_);
if (ellipsis_font_data_) {
ellipsis_metrics = ellipsis_font_data_->GetFontMetrics().GetFontHeight(
line_style_->GetFontBaseline());
}
DCHECK(ellipsis_text_);
DCHECK(ellipsis_shape_result_.get());
line_box->AddChild(
*ellipsized_layout_object, NGStyleVariant::kEllipsis,
std::move(ellipsis_shape_result_), ellipsis_text_,
LogicalRect(ellipsis_inline_offset, -ellipsis_metrics.ascent,
ellipsis_width_, ellipsis_metrics.LineHeight()),
/* bidi_level */ 0);
return ellipsis_inline_offset;
}
wtf_size_t NGLineTruncator::AddTruncatedChild(
wtf_size_t source_index,
bool leave_one_character,
LayoutUnit position,
TextDirection edge,
NGLogicalLineItems* line_box,
NGInlineLayoutStateStack* box_states) {
NGLogicalLineItems& line = *line_box;
const NGLogicalLineItem& source_item = line[source_index];
DCHECK(source_item.shape_result);
scoped_refptr<ShapeResult> shape_result =
source_item.shape_result->CreateShapeResult();
unsigned text_offset = shape_result->OffsetToFit(position, edge);
if (IsLtr(edge) ? IsLeftMostOffset(*shape_result, text_offset)
: IsRightMostOffset(*shape_result, text_offset)) {
if (!leave_one_character)
return kDidNotAddChild;
text_offset =
shape_result->OffsetToFit(shape_result->PositionForOffset(
IsRtl(edge) == shape_result->IsRtl()
? 1
: shape_result->NumCharacters() - 1),
edge);
}
const wtf_size_t new_index = line.size();
line.AddChild(TruncateText(source_item, *shape_result, text_offset, edge));
box_states->ChildInserted(new_index);
return new_index;
}
LayoutUnit NGLineTruncator::TruncateLine(LayoutUnit line_width,
NGLogicalLineItems* line_box,
NGInlineLayoutStateStack* box_states) {
// Shape the ellipsis and compute its inline size.
SetupEllipsis();
// Loop children from the logical last to the logical first to determine where
// to place the ellipsis. Children maybe truncated or moved as part of the
// process.
NGLogicalLineItem* ellipsized_child = nullptr;
absl::optional<NGLogicalLineItem> truncated_child;
if (IsLtr(line_direction_)) {
NGLogicalLineItem* first_child = line_box->FirstInFlowChild();
for (auto& child : base::Reversed(*line_box)) {
if (EllipsizeChild(line_width, ellipsis_width_, &child == first_child,
&child, &truncated_child)) {
ellipsized_child = &child;
break;
}
}
} else {
NGLogicalLineItem* first_child = line_box->LastInFlowChild();
for (auto& child : *line_box) {
if (EllipsizeChild(line_width, ellipsis_width_, &child == first_child,
&child, &truncated_child)) {
ellipsized_child = &child;
break;
}
}
}
// Abort if ellipsis could not be placed.
if (!ellipsized_child)
return line_width;
// Truncate the text fragment if needed.
if (truncated_child) {
// In order to preserve layout information before truncated, hide the
// original fragment and insert a truncated one.
size_t child_index_to_truncate = ellipsized_child - line_box->begin();
line_box->InsertChild(child_index_to_truncate + 1,
std::move(*truncated_child));
box_states->ChildInserted(child_index_to_truncate + 1);
NGLogicalLineItem* child_to_truncate =
&(*line_box)[child_index_to_truncate];
ellipsized_child = std::next(child_to_truncate);
HideChild(child_to_truncate);
DCHECK_LE(ellipsized_child->inline_size, child_to_truncate->inline_size);
if (UNLIKELY(IsRtl(line_direction_))) {
ellipsized_child->rect.offset.inline_offset +=
child_to_truncate->inline_size - ellipsized_child->inline_size;
}
}
// Create the ellipsis, associating it with the ellipsized child.
LayoutUnit ellipsis_inline_offset =
PlaceEllipsisNextTo(line_box, ellipsized_child);
return std::max(ellipsis_inline_offset + ellipsis_width_, line_width);
}
// This function was designed to work only with <input type=file>.
// We assume the line box contains:
// (Optional) children without in-flow fragments
// Children with in-flow fragments, and
// (Optional) children without in-flow fragments
// in this order, and the children with in-flow fragments have no padding,
// no border, and no margin.
// Children with IsPlaceholder() can appear anywhere.
LayoutUnit NGLineTruncator::TruncateLineInTheMiddle(
LayoutUnit line_width,
NGLogicalLineItems* line_box,
NGInlineLayoutStateStack* box_states) {
// Shape the ellipsis and compute its inline size.
SetupEllipsis();
NGLogicalLineItems& line = *line_box;
wtf_size_t initial_index_left = kNotFound;
wtf_size_t initial_index_right = kNotFound;
for (wtf_size_t i = 0; i < line_box->size(); ++i) {
auto& child = line[i];
if (child.IsPlaceholder())
continue;
if (!child.shape_result) {
if (initial_index_right != kNotFound)
break;
continue;
}
// Skip pseudo elements like ::before.
if (!child.GetNode())
continue;
if (initial_index_left == kNotFound)
initial_index_left = i;
initial_index_right = i;
}
// There are no truncatable children.
if (initial_index_left == kNotFound)
return line_width;
DCHECK_NE(initial_index_right, kNotFound);
DCHECK(line[initial_index_left].HasInFlowFragment());
DCHECK(line[initial_index_right].HasInFlowFragment());
// line[]:
// s s s p f f p f f s s
// ^ ^
// initial_index_left |
// initial_index_right
// s: child without in-flow fragment
// p: placeholder child
// f: child with in-flow fragment
const LayoutUnit static_width_left = line[initial_index_left].InlineOffset();
LayoutUnit static_width_right = LayoutUnit(0);
if (initial_index_right + 1 < line.size()) {
const NGLogicalLineItem& item = line[initial_index_right + 1];
// |line_width| and/or InlineOffset() might be saturated.
if (line_width <= item.InlineOffset())
return line_width;
// We can do nothing if the right-side static item sticks out to the both
// sides.
if (item.InlineOffset() < 0)
return line_width;
static_width_right =
line_width - item.InlineOffset() + item.margin_line_left;
}
const LayoutUnit available_width =
available_width_ - static_width_left - static_width_right;
if (available_width <= ellipsis_width_)
return line_width;
LayoutUnit available_width_left = (available_width - ellipsis_width_) / 2;
LayoutUnit available_width_right = available_width_left;
// Children for ellipsis and truncated fragments will have index which
// is >= new_child_start.
const wtf_size_t new_child_start = line.size();
wtf_size_t index_left = initial_index_left;
wtf_size_t index_right = initial_index_right;
if (IsLtr(line_direction_)) {
// Find truncation point at the left, truncate, and add an ellipsis.
while (available_width_left >= line[index_left].inline_size) {
available_width_left -= line[index_left++].inline_size;
if (index_left >= line.size()) {
// We have a logic bug. Do nothing.
return line_width;
}
}
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_left].IsPlaceholder());
wtf_size_t new_index = AddTruncatedChild(
index_left, index_left == initial_index_left, available_width_left,
TextDirection::kLtr, line_box, box_states);
if (new_index == kDidNotAddChild) {
DCHECK_GT(index_left, initial_index_left);
DCHECK_GT(index_left, 0u);
wtf_size_t i = index_left;
while (!line[--i].HasInFlowFragment())
DCHECK(line[i].IsPlaceholder());
PlaceEllipsisNextTo(line_box, &line[i]);
available_width_right += available_width_left;
} else {
PlaceEllipsisNextTo(line_box, &line[new_index]);
available_width_right +=
available_width_left - line[new_index].inline_size;
}
// Find truncation point at the right.
while (available_width_right >= line[index_right].inline_size) {
available_width_right -= line[index_right].inline_size;
if (index_right == 0) {
// We have a logic bug. We proceed anyway because |line| was already
// modified.
break;
}
--index_right;
}
LayoutUnit new_modified_right_offset =
line[line.size() - 1].InlineOffset() + ellipsis_width_;
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_right].IsPlaceholder());
if (available_width_right > 0) {
new_index = AddTruncatedChild(
index_right, false,
line[index_right].inline_size - available_width_right,
TextDirection::kRtl, line_box, box_states);
if (new_index != kDidNotAddChild) {
line[new_index].rect.offset.inline_offset = new_modified_right_offset;
new_modified_right_offset += line[new_index].inline_size;
}
}
// Shift unchanged children at the right of the truncated child.
// It's ok to modify existing children's offsets because they are not
// web-exposed.
LayoutUnit offset_diff = line[index_right].InlineOffset() +
line[index_right].inline_size -
new_modified_right_offset;
for (wtf_size_t i = index_right + 1; i < new_child_start; ++i)
line[i].rect.offset.inline_offset -= offset_diff;
line_width -= offset_diff;
} else {
// Find truncation point at the right, truncate, and add an ellipsis.
while (available_width_right >= line[index_right].inline_size) {
available_width_right -= line[index_right].inline_size;
if (index_right == 0) {
// We have a logic bug. Do nothing.
return line_width;
}
--index_right;
}
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_right].IsPlaceholder());
wtf_size_t new_index =
AddTruncatedChild(index_right, index_right == initial_index_right,
line[index_right].inline_size - available_width_right,
TextDirection::kRtl, line_box, box_states);
if (new_index == kDidNotAddChild) {
DCHECK_LT(index_right, initial_index_right);
wtf_size_t i = index_right;
while (!line[++i].HasInFlowFragment())
DCHECK(line[i].IsPlaceholder());
PlaceEllipsisNextTo(line_box, &line[i]);
available_width_left += available_width_right;
} else {
line[new_index].rect.offset.inline_offset +=
line[index_right].inline_size - line[new_index].inline_size;
PlaceEllipsisNextTo(line_box, &line[new_index]);
available_width_left +=
available_width_right - line[new_index].inline_size;
}
LayoutUnit ellipsis_offset = line[line.size() - 1].InlineOffset();
// Find truncation point at the left.
while (available_width_left >= line[index_left].inline_size) {
available_width_left -= line[index_left++].inline_size;
if (index_left >= line.size()) {
// We have a logic bug. We proceed anyway because |line| was already
// modified.
break;
}
}
DCHECK_LE(index_left, index_right);
DCHECK(!line[index_left].IsPlaceholder());
if (available_width_left > 0) {
new_index = AddTruncatedChild(index_left, false, available_width_left,
TextDirection::kLtr, line_box, box_states);
if (new_index != kDidNotAddChild) {
line[new_index].rect.offset.inline_offset =
ellipsis_offset - line[new_index].inline_size;
}
}
// Shift unchanged children at the left of the truncated child.
// It's ok to modify existing children's offsets because they are not
// web-exposed.
LayoutUnit offset_diff =
line[line.size() - 1].InlineOffset() - line[index_left].InlineOffset();
for (wtf_size_t i = index_left; i > 0; --i)
line[i - 1].rect.offset.inline_offset += offset_diff;
line_width -= offset_diff;
}
// Hide left/right truncated children and children between them.
for (wtf_size_t i = index_left; i <= index_right; ++i) {
if (line[i].HasInFlowFragment())
HideChild(&line[i]);
}
return line_width;
}
// Hide this child from being painted. Leaves a hidden fragment so that layout
// queries such as |offsetWidth| work as if it is not truncated.
void NGLineTruncator::HideChild(NGLogicalLineItem* child) {
DCHECK(child->HasInFlowFragment());
if (const NGLayoutResult* layout_result = child->layout_result.get()) {
// Need to propagate OOF descendants in this inline-block child.
const auto& fragment =
To<NGPhysicalBoxFragment>(layout_result->PhysicalFragment());
if (fragment.HasOutOfFlowPositionedDescendants())
return;
// Truncate this object. Atomic inline is monolithic.
DCHECK(fragment.IsMonolithic());
LayoutObject* layout_object = fragment.GetMutableLayoutObject();
DCHECK(layout_object);
DCHECK(layout_object->IsAtomicInlineLevel());
layout_object->SetIsTruncated(true);
return;
}
if (child->inline_item) {
child->is_hidden_for_paint = true;
return;
}
NOTREACHED();
}
// Return the offset to place the ellipsis.
//
// This function may truncate or move the child so that the ellipsis can fit.
bool NGLineTruncator::EllipsizeChild(
LayoutUnit line_width,
LayoutUnit ellipsis_width,
bool is_first_child,
NGLogicalLineItem* child,
absl::optional<NGLogicalLineItem>* truncated_child) {
DCHECK(truncated_child && !*truncated_child);
// Leave out-of-flow children as is.
if (!child->HasInFlowFragment())
return false;
// Inline boxes should not be ellipsized. Usually they will be created in the
// later phase, but empty inline box are already created.
if (child->IsInlineBox())
return false;
// Can't place ellipsis if this child is completely outside of the box.
LayoutUnit child_inline_offset =
IsLtr(line_direction_)
? child->InlineOffset()
: line_width - (child->InlineOffset() + child->inline_size);
LayoutUnit space_for_child = available_width_ - child_inline_offset;
if (space_for_child <= 0) {
// This child is outside of the content box, but we still need to hide it.
// When the box has paddings, this child outside of the content box maybe
// still inside of the clipping box.
if (!is_first_child)
HideChild(child);
return false;
}
// At least part of this child is in the box.
// If |child| can fit in the space, truncate this line at the end of |child|.
space_for_child -= ellipsis_width;
if (space_for_child >= child->inline_size)
return true;
// If not all of this child can fit, try to truncate.
if (TruncateChild(space_for_child, is_first_child, *child, truncated_child))
return true;
// This child is partially in the box, but it can't be truncated to fit. It
// should not be visible because earlier sibling will be truncated.
if (!is_first_child)
HideChild(child);
return false;
}
// Truncate the specified child. Returns true if truncated successfully, false
// otherwise.
//
// Note that this function may return true even if it can't fit the child when
// |is_first_child|, because the spec defines that the first character or atomic
// inline-level element on a line must be clipped rather than ellipsed.
// https://drafts.csswg.org/css-ui/#text-overflow
bool NGLineTruncator::TruncateChild(
LayoutUnit space_for_child,
bool is_first_child,
const NGLogicalLineItem& child,
absl::optional<NGLogicalLineItem>* truncated_child) {
DCHECK(truncated_child && !*truncated_child);
// If the space is not enough, try the next child.
if (space_for_child <= 0 && !is_first_child)
return false;
// Only text fragments can be truncated.
if (!child.shape_result)
return is_first_child;
// TODO(layout-dev): Add support for OffsetToFit to ShapeResultView to avoid
// this copy.
scoped_refptr<ShapeResult> shape_result =
child.shape_result->CreateShapeResult();
DCHECK(shape_result);
const NGTextOffset original_offset = child.text_offset;
// Compute the offset to truncate.
unsigned offset_to_fit = shape_result->OffsetToFit(
IsLtr(line_direction_) ? space_for_child
: shape_result->Width() - space_for_child,
line_direction_);
DCHECK_LE(offset_to_fit, original_offset.Length());
if (!offset_to_fit || offset_to_fit == original_offset.Length()) {
if (!is_first_child)
return false;
offset_to_fit = !offset_to_fit ? 1 : offset_to_fit - 1;
}
*truncated_child =
TruncateText(child, *shape_result, offset_to_fit, line_direction_);
return true;
}
NGLogicalLineItem NGLineTruncator::TruncateText(const NGLogicalLineItem& item,
const ShapeResult& shape_result,
unsigned offset_to_fit,
TextDirection direction) {
const NGTextOffset new_text_offset =
direction == shape_result.Direction()
? NGTextOffset(item.StartOffset(), item.StartOffset() + offset_to_fit)
: NGTextOffset(item.StartOffset() + offset_to_fit, item.EndOffset());
scoped_refptr<ShapeResultView> new_shape_result = ShapeResultView::Create(
&shape_result, new_text_offset.start, new_text_offset.end);
DCHECK(item.inline_item);
return NGLogicalLineItem(item, std::move(new_shape_result), new_text_offset);
}
} // namespace blink
| 39.016636 | 83 | 0.695376 | [
"object",
"shape"
] |
a72d26b17f1473bfb0742bb1c69da5ef25d420e5 | 1,233 | cpp | C++ | Engine/Source/Runtime/EmptyRHI/Private/EmptyRenderTarget.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/EmptyRHI/Private/EmptyRenderTarget.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/EmptyRHI/Private/EmptyRenderTarget.cpp | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
EmptyRenderTarget.cpp: Empty render target implementation.
=============================================================================*/
#include "EmptyRHIPrivate.h"
#include "ScreenRendering.h"
void FEmptyDynamicRHI::RHICopyToResolveTarget(FTextureRHIParamRef SourceTextureRHI, FTextureRHIParamRef DestTextureRHI, bool bKeepOriginalSurface, const FResolveParams& ResolveParams)
{
}
void FEmptyDynamicRHI::RHIReadSurfaceData(FTextureRHIParamRef TextureRHI, FIntRect Rect, TArray<FColor>& OutData, FReadSurfaceDataFlags InFlags)
{
}
void FEmptyDynamicRHI::RHIMapStagingSurface(FTextureRHIParamRef TextureRHI,void*& OutData,int32& OutWidth,int32& OutHeight)
{
}
void FEmptyDynamicRHI::RHIUnmapStagingSurface(FTextureRHIParamRef TextureRHI)
{
}
void FEmptyDynamicRHI::RHIReadSurfaceFloatData(FTextureRHIParamRef TextureRHI, FIntRect Rect, TArray<FFloat16Color>& OutData, ECubeFace CubeFace,int32 ArrayIndex,int32 MipIndex)
{
}
void FEmptyDynamicRHI::RHIRead3DSurfaceFloatData(FTextureRHIParamRef TextureRHI,FIntRect InRect,FIntPoint ZMinMax,TArray<FFloat16Color>& OutData)
{
}
| 30.825 | 183 | 0.728305 | [
"render"
] |
a73516ad92d166426ce2697e4cd8866e580593f9 | 20,732 | hpp | C++ | include/optimization/rotation_folding.hpp | amccaskey/staq | 7f76503b7d3d2e3eb87dc0d26d0a58aa5ab30db0 | [
"MIT"
] | null | null | null | include/optimization/rotation_folding.hpp | amccaskey/staq | 7f76503b7d3d2e3eb87dc0d26d0a58aa5ab30db0 | [
"MIT"
] | null | null | null | include/optimization/rotation_folding.hpp | amccaskey/staq | 7f76503b7d3d2e3eb87dc0d26d0a58aa5ab30db0 | [
"MIT"
] | null | null | null | /*
* This file is part of staq.
*
* MIT License
*
* 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.
*/
/**
* \file optimization/rotation_folding.hpp
* \brief Rotation folding algorithm
*/
#pragma once
#include "ast/visitor.hpp"
#include "ast/replacer.hpp"
#include "gates/channel.hpp"
#include <list>
#include <unordered_map>
#include <sstream>
namespace staq {
namespace optimization {
/**
* \class staq::optimization::RotationOptimizer
* \brief Rotation gate merging algorithm based on arXiv:1903.12456
*
* Returns a replacement list giving the nodes to the be replaced (or erased)
*/
class RotationOptimizer final : public ast::Visitor {
using Gatelib = gates::ChannelRepr<ast::VarAccess>;
public:
struct config {
bool correct_global_phase = true;
};
RotationOptimizer() = default;
RotationOptimizer(const config& params) : Visitor(), config_(params) {}
~RotationOptimizer() = default;
std::unordered_map<int, std::list<ast::ptr<ast::Gate>>>
run(ast::ASTNode& node) {
reset();
node.accept(*this);
return std::move(replacement_list_);
}
/* Variables */
void visit(ast::VarAccess&) {}
/* Expressions */
void visit(ast::BExpr&) {}
void visit(ast::UExpr&) {}
void visit(ast::PiExpr&) {}
void visit(ast::IntExpr&) {}
void visit(ast::RealExpr&) {}
void visit(ast::VarExpr&) {}
/* Statements */
void visit(ast::MeasureStmt& stmt) {
push_uninterp(Gatelib::Uninterp({stmt.q_arg()}));
}
void visit(ast::ResetStmt& stmt) {
push_uninterp(Gatelib::Uninterp({stmt.arg()}));
}
void visit(ast::IfStmt& stmt) {
mergeable_ = false;
stmt.then().accept(*this);
mergeable_ = true;
}
/* Gates */
void visit(ast::UGate& gate) {
push_uninterp(Gatelib::Uninterp({gate.arg()}));
}
void visit(ast::CNOTGate& gate) {
auto ctrl = gate.ctrl();
auto tgt = gate.tgt();
if (mergeable_) {
current_clifford_ *= Gatelib::Clifford::cnot(ctrl, tgt);
} else {
push_uninterp(Gatelib::Uninterp({ctrl, tgt}));
}
}
void visit(ast::BarrierGate& gate) {
push_uninterp(Gatelib::Uninterp({gate.args()}));
}
void visit(ast::DeclaredGate& gate) {
auto name = gate.name();
if (mergeable_) {
if (name == "cx")
current_clifford_ *=
Gatelib::Clifford::cnot(gate.qarg(0), gate.qarg(1));
else if (name == "h")
current_clifford_ *= Gatelib::Clifford::h(gate.qarg(0));
else if (name == "x")
current_clifford_ *= Gatelib::Clifford::x(gate.qarg(0));
else if (name == "y")
current_clifford_ *= Gatelib::Clifford::y(gate.qarg(0));
else if (name == "z")
current_clifford_ *= Gatelib::Clifford::z(gate.qarg(0));
else if (name == "s")
current_clifford_ *= Gatelib::Clifford::sdg(gate.qarg(0));
else if (name == "sdg")
current_clifford_ *= Gatelib::Clifford::s(gate.qarg(0));
else if (name == "t") {
auto rot = Gatelib::Rotation::t(gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::z,
gate.qarg(0)};
accum_.push_back(
std::make_pair(info, rot.commute_left(current_clifford_)));
} else if (name == "tdg") {
auto rot = Gatelib::Rotation::tdg(gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::z,
gate.qarg(0)};
accum_.push_back(
std::make_pair(info, rot.commute_left(current_clifford_)));
} else if (name == "rz") {
auto angle = gate.carg(0).constant_eval();
if (angle) {
auto rot = Gatelib::Rotation::rz(utils::Angle(*angle),
gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::z,
gate.qarg(0)};
accum_.push_back(std::make_pair(
info, rot.commute_left(current_clifford_)));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
} else if (name == "rx") {
auto angle = gate.carg(0).constant_eval();
if (angle) {
auto rot = Gatelib::Rotation::rx(utils::Angle(*angle),
gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::x,
gate.qarg(0)};
accum_.push_back(std::make_pair(
info, rot.commute_left(current_clifford_)));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
} else if (name == "ry") {
auto angle = gate.carg(0).constant_eval();
if (angle) {
auto rot = Gatelib::Rotation::ry(utils::Angle(*angle),
gate.qarg(0));
rotation_info info{gate.uid(), rotation_info::axis::y,
gate.qarg(0)};
accum_.push_back(std::make_pair(
info, rot.commute_left(current_clifford_)));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
} else
push_uninterp(Gatelib::Uninterp(gate.qargs()));
} else {
push_uninterp(Gatelib::Uninterp(gate.qargs()));
}
}
/* Declarations */
void visit(ast::GateDecl& decl) {
// Initialize a new local state
circuit_callback local_state;
Gatelib::Clifford local_clifford;
std::swap(accum_, local_state);
std::swap(current_clifford_, local_clifford);
// Process gate body
decl.foreach_stmt([this](auto& stmt) { stmt.accept(*this); });
accum_.push_back(current_clifford_);
// Fold the gate body
fold(accum_, true);
// Reset the state
std::swap(accum_, local_state);
std::swap(current_clifford_, local_clifford);
}
void visit(ast::OracleDecl&) {}
void visit(ast::RegisterDecl&) {}
void visit(ast::AncillaDecl&) {}
/* Program */
void visit(ast::Program& prog) {
prog.foreach_stmt([this](auto& stmt) { stmt.accept(*this); });
accum_.push_back(current_clifford_);
fold(accum_, config_.correct_global_phase);
}
private:
// Store information necessary for generating a replacement of <node> with a
// different angle
struct rotation_info {
enum class axis { x, y, z };
int uid;
axis rotation_axis;
ast::VarAccess arg;
};
using circuit_callback =
std::list<std::variant<Gatelib::Uninterp, Gatelib::Clifford,
std::pair<rotation_info, Gatelib::Rotation>>>;
config config_;
std::unordered_map<int, std::list<ast::ptr<ast::Gate>>> replacement_list_;
/* Algorithm state */
circuit_callback
accum_; // The currently accumulating circuit (in channel repr.)
bool mergeable_ =
true; // Whether we're in a context where a gate can be merged
Gatelib::Clifford current_clifford_; // The current clifford operator
// Note: current clifford is stored as the dagger of the actual Clifford
// gate this is so that left commutation (i.e. conjugation) actually
// right-commutes the rotation gate, allowing us to walk the circuit
// forwards rather than backwards That is, we want to end up with the form
// C_0R_1R_2R_3...R_n
// rather than the form
// R_n...R_3R_2R_1C_0
// as in the paper
void reset() {
replacement_list_.clear();
accum_.clear();
mergeable_ = true;
current_clifford_ = Gatelib::Clifford();
}
/* Phase two of the algorithm */
void fold(circuit_callback& circuit, bool phase_correction) {
auto global_phase = utils::angles::zero;
ast::VarAccess* tgt = nullptr;
std::list<ast::ptr<ast::Gate>>* subst_ref = nullptr;
for (auto it = circuit.rbegin(); it != circuit.rend(); it++) {
auto& op = *it;
if (auto tmp =
std::get_if<std::pair<rotation_info, Gatelib::Rotation>>(
&op)) {
auto [new_phase, new_R] =
fold_forward(circuit, std::next(it), tmp->second);
global_phase += new_phase;
if (!(new_R == tmp->second)) {
std::list<ast::ptr<ast::Gate>> subst;
auto rot = alloc_rot(tmp->first, new_R.rotation_angle());
if (rot)
subst.emplace_back(rot);
replacement_list_[tmp->first.uid] = std::move(subst);
// WARNING: this is a massive hack so that the global phase
// correction can be performed by the replacement engine. We
// append the final phase correction to the last gate
// substitution in-place in the replacement list. Since we
// need a qubit to apply the phase correction on, we select
// the qubit on which the rotation itself was applied.
tgt = &(tmp->first.arg);
subst_ref = &(replacement_list_[tmp->first.uid]);
}
}
}
if (phase_correction && (global_phase != utils::angles::zero)) {
if (global_phase == utils::angles::pi) {
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "z", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "z", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
} else if (global_phase == utils::angles::pi_half) {
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
} else if (global_phase == -utils::angles::pi_half) {
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
} else if (global_phase == utils::angles::pi_quarter) {
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "s", {}, {*tgt}));
} else if (global_phase == -utils::angles::pi_quarter) {
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "sdg", {}, {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "h", {}, {*tgt}));
} else {
std::vector<ast::ptr<ast::Expr>> tmp1;
std::vector<ast::ptr<ast::Expr>> tmp2;
tmp1.emplace_back(ast::angle_to_expr(global_phase));
tmp2.emplace_back(ast::angle_to_expr(global_phase));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "rz", std::move(tmp1), {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
subst_ref->emplace_back(new ast::DeclaredGate(
parser::Position(), "rz", std::move(tmp2), {*tgt}));
subst_ref->emplace_back(
new ast::DeclaredGate(parser::Position(), "x", {}, {*tgt}));
}
}
}
std::pair<utils::Angle, Gatelib::Rotation>
fold_forward(circuit_callback& circuit,
circuit_callback::reverse_iterator it, Gatelib::Rotation R) {
// Tries to commute op backward as much as possible, merging with
// applicable gates and deleting them as it goes Note: We go backwards
// so that we only commute **left** past C^*/**right** past C
auto phase = utils::angles::zero;
bool cont = true;
for (; cont && it != circuit.rend(); it++) {
auto visitor = utils::overloaded{
[this, it, &R, &phase,
&circuit](std::pair<rotation_info, Gatelib::Rotation>& P) {
auto res = R.try_merge(P.second);
if (res) {
auto& [new_phase, new_R] = res.value();
phase += new_phase;
R = new_R;
// Delete R in circuit & the node
replacement_list_[P.first.uid] =
std::move(std::list<ast::ptr<ast::Gate>>());
circuit.erase(std::next(it).base());
return false;
} else if (R.commutes_with(P.second)) {
return true;
} else {
return false;
}
},
[&R](Gatelib::Clifford& C) {
R = R.commute_left(C);
return true;
},
[&R](Gatelib::Uninterp& U) {
if (!R.commutes_with(U))
return false;
else
return true;
}};
cont = std::visit(visitor, *it);
}
return std::make_pair(phase, R);
}
/* Utilities */
void push_uninterp(Gatelib::Uninterp op) {
accum_.push_back(current_clifford_);
accum_.push_back(op);
// Clear the current clifford
current_clifford_ = Gatelib::Clifford();
}
// Assumes basic gates (x, y, z, s, sdg, t, tdg, rx, ry, rz) are defined
ast::Gate* alloc_rot(const rotation_info& rinfo,
const utils::Angle& theta) {
if (theta.numeric_value() == 0)
return nullptr;
parser::Position pos;
std::string name;
std::vector<ast::ptr<ast::Expr>> cargs;
std::vector<ast::VarAccess> qargs{rinfo.arg};
// Determine the name & classical arguments
if (theta.is_numeric()) {
// Angle is real-valued
switch (rinfo.rotation_axis) {
case rotation_info::axis::x:
name = "rx";
break;
case rotation_info::axis::y:
name = "ry";
break;
case rotation_info::axis::z:
name = "rz";
break;
}
cargs.emplace_back(ast::angle_to_expr(theta));
} else {
// Angle is of the form pi*(a/b) for a & b integers
auto [a, b] = *(theta.symbolic_value());
switch (rinfo.rotation_axis) {
case rotation_info::axis::x:
if ((a == 1) && (b == 1)) {
// X gate
name = "x";
} else {
// Rx gate
name = "rx";
cargs.emplace_back(ast::angle_to_expr(theta));
}
break;
case rotation_info::axis::y:
if ((a == 1) && (b == 1)) {
// Y gate
name = "y";
} else {
// Ry gate
name = "ry";
cargs.emplace_back(ast::angle_to_expr(theta));
}
break;
case rotation_info::axis::z:
if ((a == 1) && (b == 1)) {
// Z gate
name = "z";
} else if (((a == 1) || (a == -3)) && (b == 2)) {
// S gate
name = "s";
} else if (((a == -1) || (a == 3)) && (b == 2)) {
// Sdg gate
name = "sdg";
} else if (((a == 1) || (a == -7)) && (b == 4)) {
// T gate
name = "t";
} else if (((a == -1) || (a == 7)) && (b == 4)) {
// Tdg gate
name = "tdg";
} else {
// Rz gate
name = "rz";
cargs.emplace_back(ast::angle_to_expr(theta));
}
break;
}
}
return new ast::DeclaredGate(pos, name, std::move(cargs),
std::move(qargs));
}
};
/** \brief Performs the rotation folding optimization */
inline void fold_rotations(ast::ASTNode& node) {
RotationOptimizer optimizer;
auto res = optimizer.run(node);
replace_gates(node, std::move(res));
}
/** \brief Performs the rotation folding optimization with configuration */
inline void fold_rotations(ast::ASTNode& node,
const RotationOptimizer::config& params) {
RotationOptimizer optimizer(params);
auto res = optimizer.run(node);
replace_gates(node, std::move(res));
}
} // namespace optimization
} // namespace staq
| 39.792706 | 80 | 0.500772 | [
"vector"
] |
a73a6eab6922b68faa12458c3d753108ac54df0d | 9,575 | hpp | C++ | src/xercesc/dom/DOMLSInput.hpp | gajgeospatial/xerces-c-3.2.2 | 8396d30350e6523313766f9c18e07c4f708be9cb | [
"Apache-2.0"
] | 218 | 2015-07-17T19:18:07.000Z | 2022-03-03T18:00:08.000Z | src/xercesc/dom/DOMLSInput.hpp | rsn8887/xerces-c | eafbd0b1755fe55550e10aaaf3b15c587d900f39 | [
"Apache-2.0"
] | 88 | 2015-07-08T15:35:46.000Z | 2020-08-13T13:03:09.000Z | src/xercesc/dom/DOMLSInput.hpp | rsn8887/xerces-c | eafbd0b1755fe55550e10aaaf3b15c587d900f39 | [
"Apache-2.0"
] | 56 | 2015-09-17T21:22:32.000Z | 2021-04-01T20:19:32.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DOMLSInput.hpp 527149 2007-04-10 14:56:39Z amassari $
*/
#if !defined(XERCESC_INCLUDE_GUARD_DOMLSINPUT_HPP)
#define XERCESC_INCLUDE_GUARD_DOMLSINPUT_HPP
#include <xercesc/util/XercesDefs.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class InputSource;
/**
* This interface represents a single input source for an XML entity.
*
* <p>This interface allows an application to encapsulate information about
* an input source in a single object, which may include a public identifier,
* a system identifier, a byte stream (possibly with a specified encoding),
* and/or a character stream.</p>
*
* <p>There are two places that the application will deliver this input source
* to the parser: as the argument to the parse method, or as the return value
* of the DOMLSResourceResolver.resolveResource method.</p>
*
* <p>The DOMLSParser will use the DOMLSInput object to determine how to
* read XML input. If there is a character stream available, the parser will
* read that stream directly; if not, the parser will use a byte stream, if
* available; if neither a character stream nor a byte stream is available,
* the parser will attempt to open a URI connection to the resource identified
* by the system identifier.</p>
*
* <p>A DOMLSInput object belongs to the application: the parser shall
* never modify it in any way (it may modify a copy if necessary).</p>
*
* @see DOMLSParser#parse
* @see DOMLSResourceResolver#resolveResource
* @since DOM Level 3
*/
class CDOM_EXPORT DOMLSInput
{
protected:
// -----------------------------------------------------------------------
// Hidden constructors
// -----------------------------------------------------------------------
/** @name Hidden constructors */
//@{
DOMLSInput() {};
//@}
private:
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
/** @name Unimplemented constructors and operators */
//@{
DOMLSInput(const DOMLSInput &);
DOMLSInput & operator = (const DOMLSInput &);
//@}
public:
// -----------------------------------------------------------------------
// All constructors are hidden, just the destructor is available
// -----------------------------------------------------------------------
/** @name Destructor */
//@{
/**
* Destructor
*
*/
virtual ~DOMLSInput() {};
//@}
// -----------------------------------------------------------------------
// Virtual DOMLSInput interface
// -----------------------------------------------------------------------
/** @name Functions introduced in DOM Level 3 */
//@{
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/**
* String data to parse. If provided, this will always be treated as a sequence of 16-bit units (UTF-16 encoded characters).
* It is not a requirement to have an XML declaration when using stringData. If an XML declaration is present, the value of
* the encoding attribute will be ignored.
*
*/
virtual const XMLCh* getStringData() const = 0;
/**
* Returns the byte stream for this input source.
*
* @see InputSource
*/
virtual InputSource* getByteStream() const = 0;
/**
* An input source can be set to force the parser to assume a particular
* encoding for the data that input source reprsents, via the setEncoding()
* method. This method returns name of the encoding that is to be forced.
* If the encoding has never been forced, it returns a null pointer.
*
* @return The forced encoding, or null if none was supplied.
* @see #setEncoding
* @since DOM Level 3
*/
virtual const XMLCh* getEncoding() const = 0;
/**
* Get the public identifier for this input source.
*
* @return The public identifier, or null if none was supplied.
* @see #setPublicId
* @since DOM Level 3
*/
virtual const XMLCh* getPublicId() const = 0;
/**
* Get the system identifier for this input source.
*
* <p>If the system ID is a URL, it will be fully resolved.</p>
*
* @return The system identifier.
* @see #setSystemId
* @since DOM Level 3
*/
virtual const XMLCh* getSystemId() const = 0;
/**
* Get the base URI to be used for resolving relative URIs to absolute
* URIs. If the baseURI is itself a relative URI, the behavior is
* implementation dependent.
*
* @return The base URI.
* @see #setBaseURI
* @since DOM Level 3
*/
virtual const XMLCh* getBaseURI() const = 0;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
/**
* Sets the UTF-16 string for this input source.
*
*/
virtual void setStringData(const XMLCh* data) = 0;
/**
* Sets the byte stream for this input source.
*
* @see BinInputStream
*/
virtual void setByteStream(InputSource* stream) = 0;
/**
* Set the encoding which will be required for use with the XML text read
* via a stream opened by this input source.
*
* <p>This is usually not set, allowing the encoding to be sensed in the
* usual XML way. However, in some cases, the encoding in the file is known
* to be incorrect because of intermediate transcoding, for instance
* encapsulation within a MIME document.
*
* @param encodingStr The name of the encoding to force.
* @since DOM Level 3
*/
virtual void setEncoding(const XMLCh* const encodingStr) = 0;
/**
* Set the public identifier for this input source.
*
* <p>The public identifier is always optional: if the application writer
* includes one, it will be provided as part of the location information.</p>
*
* @param publicId The public identifier as a string.
* @see #getPublicId
* @since DOM Level 3
*/
virtual void setPublicId(const XMLCh* const publicId) = 0;
/**
* Set the system identifier for this input source.
*
* <p>The system id is always required. The public id may be used to map
* to another system id, but the system id must always be present as a fall
* back.</p>
*
* <p>If the system ID is a URL, it must be fully resolved.</p>
*
* @param systemId The system identifier as a string.
* @see #getSystemId
* @since DOM Level 3
*/
virtual void setSystemId(const XMLCh* const systemId) = 0;
/**
* Set the base URI to be used for resolving relative URIs to absolute
* URIs. If the baseURI is itself a relative URI, the behavior is
* implementation dependent.
*
* @param baseURI The base URI.
* @see #getBaseURI
* @since DOM Level 3
*/
virtual void setBaseURI(const XMLCh* const baseURI) = 0;
//@}
// -----------------------------------------------------------------------
// Non-standard Extension
// -----------------------------------------------------------------------
/** @name Non-standard Extension */
//@{
/**
* Indicates if the parser should issue fatal error if this input source
* is not found. If set to false, the parser issue warning message instead.
*
* @param flag True if the parser should issue fatal error if this input source is not found.
* If set to false, the parser issue warning message instead. (Default: true)
*
* @see #getIssueFatalErrorIfNotFound
*/
virtual void setIssueFatalErrorIfNotFound(bool flag) = 0;
/**
* Get the flag that indicates if the parser should issue fatal error if this input source
* is not found.
*
* @return True if the parser should issue fatal error if this input source is not found.
* False if the parser issue warning message instead.
* @see #setIssueFatalErrorIfNotFound
*/
virtual bool getIssueFatalErrorIfNotFound() const = 0;
/**
* Called to indicate that this DOMLSInput is no longer in use
* and that the implementation may relinquish any resources associated with it.
*
* Access to a released object will lead to unexpected result.
*/
virtual void release() = 0;
//@}
};
XERCES_CPP_NAMESPACE_END
#endif
| 34.818182 | 129 | 0.58047 | [
"object"
] |
a73b76de47d75b15af0934527886353a526b134b | 752 | cpp | C++ | Sorting_Techniques/Heap_Sort/Heap_Sort.cpp | Amit366/DSA-guide | a0f30d281e311d9c1974b9c91fa8d16ec72f871d | [
"MIT"
] | 60 | 2020-10-04T13:19:26.000Z | 2022-01-23T09:09:27.000Z | Sorting_Techniques/Heap_Sort/Heap_Sort.cpp | Amit366/DSA-guide | a0f30d281e311d9c1974b9c91fa8d16ec72f871d | [
"MIT"
] | 202 | 2020-10-04T13:03:46.000Z | 2021-07-29T07:39:15.000Z | Sorting_Techniques/Heap_Sort/Heap_Sort.cpp | Amit366/DSA-guide | a0f30d281e311d9c1974b9c91fa8d16ec72f871d | [
"MIT"
] | 169 | 2020-10-04T13:21:09.000Z | 2022-03-20T16:59:35.000Z |
#include <bits/stdc++.h>
using namespace std;
int main() {
// Taking the length of the array
int n;
cin >> n;
vector<int> arr(n);
// Taking the array elements and storing it in arr.
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
// Printing the input array without sort
cout << "Your unsorted array: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
make_heap(arr.begin(), arr.end()); // Building the heap from the array.
sort_heap(arr.begin(), arr.end()); // Sorting the heap
// Printing the sorted array
cout << "Your sorted array: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
| 21.485714 | 75 | 0.50133 | [
"vector"
] |
a73cf58c37ddb4c390ce3e9512fb068ecb3595df | 1,334 | cpp | C++ | tests/UT_NOK_missing_mandatory-4.cpp | LucHermitte/NamedParameter | 394eca773c122c1c0504ade79e08b777250ebbfd | [
"BSL-1.0"
] | 5 | 2016-03-14T12:06:55.000Z | 2020-12-28T21:12:42.000Z | tests/UT_NOK_missing_mandatory-4.cpp | LucHermitte/NamedParameter | 394eca773c122c1c0504ade79e08b777250ebbfd | [
"BSL-1.0"
] | null | null | null | tests/UT_NOK_missing_mandatory-4.cpp | LucHermitte/NamedParameter | 394eca773c122c1c0504ade79e08b777250ebbfd | [
"BSL-1.0"
] | null | null | null | /**@file tests/UT_NOK_missing_mandatory-4.cpp
* @author Luc Hermitte <EMAIL:luc{dot}hermitte{at}gmail{dot}com>
*
* Distributed under the Boost Software License, Version 1.0.
* See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt
*/
#define BOOST_TEST_MODULE "Named parameters related tests"
#define BOOST_TEST_DYN_LINK
#include "named-parameters.hpp"
#include <boost/test/unit_test.hpp>
#include <vector>
using namespace na::literals;
// ===[ copy_no_default1 ]==================================== {{{1
template <typename ...Args>
void f_copy_with_default4(Args&& ...args)
{
auto a = na::get("a"_na = 1 , std::forward<Args>(args)...);
auto b = na::get("b"_na , std::forward<Args>(args)...);
auto c = na::get("c"_na = "bar", std::forward<Args>(args)...);
auto d = na::get("d"_na = 24.5 , std::forward<Args>(args)...);
}
BOOST_AUTO_TEST_CASE(copy_no_default5)
{
auto v = std::vector<int>{ 1, 2, 3, 4, 5};
auto const x = std::vector<int>{ 11, 12, 13, 14, 15};
f_copy_with_default4(
"a"_na=42,
// "b"_na=v,
"c"_na="foo",
"d"_na=12.5
);
BOOST_CHECK_EQUAL(v.size(), 5); // check v was copied
}
// =========================================================== }}}1
// vim:set fdm=marker:
| 31.023256 | 67 | 0.571214 | [
"vector"
] |
a73daabc71bc8b58c192236acde0f8d810c8ef93 | 2,070 | cpp | C++ | Sources/AGEngine/Engine/Entity/BinaryEntity.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 47 | 2015-03-29T09:44:25.000Z | 2020-11-30T10:05:56.000Z | Sources/AGEngine/Engine/Entity/BinaryEntity.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 313 | 2015-01-01T18:16:30.000Z | 2015-11-30T07:54:07.000Z | Sources/AGEngine/Engine/Entity/BinaryEntity.cpp | Another-Game-Engine/AGE | d5d9e98235198fe580a43007914f515437635830 | [
"MIT"
] | 9 | 2015-06-07T13:21:54.000Z | 2020-08-25T09:50:07.000Z | #include "BinaryEntity.hpp"
#include <Entity/EntityData.hh>
#include <Entity/ArchetypeManager.hpp>
#include <Core/AScene.hh>
#include <cereal/types/vector.hpp>
#include <cereal/types/map.hpp>
#include <cereal/types/string.hpp>
#include <Components\ComponentRegistrationManager.hpp>
#include "Components/ArchetypeComponent.hpp"
#include <Utils/Debug.hpp>
namespace AGE
{
BinaryEntity::BinaryEntity()
{}
BinaryEntity::~BinaryEntity()
{}
void BinaryEntity::save(cereal::PortableBinaryOutputArchive &ar, const std::uint32_t version) const
{
AGE::Link link = entity->getLink();
ENTITY_FLAGS flags = entity.getFlags();
ar(cereal::make_nvp("link", link)
, cereal::make_nvp("children", children)
, cereal::make_nvp("flags", flags)
, cereal::make_nvp("components_number", componentTypes)
, CEREAL_NVP(archetypesDependency)
);
for (auto &e : components)
{
ComponentRegistrationManager::getInstance().serializeBinary(e, ar);
}
}
void BinaryEntity::load(cereal::PortableBinaryInputArchive &ar, const std::uint32_t version)
{
ENTITY_FLAGS flags;
AGE_ASSERT(typesMap != nullptr);
ar(entity->getLink()
, children
, flags
, componentTypes
, archetypesDependency);
auto archetypeManager = entity->getScene()->getInstance<AGE::IArchetypeManager>();
// we load archetypes dependency
if (!archetypesDependency.empty())
{
for (auto &dep : archetypesDependency)
{
archetypeManager->loadOne(dep);
}
}
entity->getLink().setPosition(entity->getLink().getPosition());
entity->getLink().setOrientation(entity->getLink().getOrientation());
entity->getLink().setScale(entity->getLink().getScale());
//entity.setFlags(f);
for (auto &e : componentTypes)
{
auto hashType = (*typesMap)[e];
auto newComponent = ComponentRegistrationManager::getInstance().loadBinary(hashType, entity, ar);
}
if (entity->haveComponent<ArchetypeComponent>())
{
auto archetypeName = entity->getComponent<ArchetypeComponent>()->archetypeName;
archetypeManager->spawn(entity, archetypeName);
}
}
} | 25.875 | 101 | 0.72029 | [
"vector"
] |
a7443299a25053f087928accb385edf2c0a2083d | 1,352 | hpp | C++ | src/include/common/logger.hpp | arthurmco/familyline | 849eee40cff266af9a3f848395ed139b7ce66197 | [
"MIT"
] | 6 | 2018-05-11T23:16:02.000Z | 2019-06-13T01:35:07.000Z | src/include/common/logger.hpp | arthurmco/familyline | 849eee40cff266af9a3f848395ed139b7ce66197 | [
"MIT"
] | 33 | 2018-05-11T14:12:22.000Z | 2022-03-12T00:55:25.000Z | src/include/common/logger.hpp | arthurmco/familyline | 849eee40cff266af9a3f848395ed139b7ce66197 | [
"MIT"
] | 1 | 2018-12-06T23:39:55.000Z | 2018-12-06T23:39:55.000Z | #pragma once
/**
* Familyline logging functions
*
* Copyright (C) 2020 Arthur Mendes
*/
#include <chrono>
#include <cstdio>
#include <memory>
#include <vector>
#include <string>
namespace familyline
{
#define LOGDEBUG(log, tag, format, ...) log->write(tag, LogType::Debug, format, __VA_ARGS__)
enum LogType { Debug, Info, Warning, Error, Fatal };
class Logger
{
private:
FILE* _out = nullptr;
LogType _minlog;
std::vector<std::string> blockTags_;
std::chrono::steady_clock::time_point _start;
double getDelta();
public:
Logger(
FILE* out = stderr, LogType minlog = LogType::Info, std::vector<std::string> blockTags = {})
: _out(out),
_minlog(minlog),
_start(std::chrono::steady_clock::now()),
blockTags_(blockTags)
{
}
void write(std::string_view tag, LogType type, const char* format, ...);
};
class LoggerService
{
private:
static std::unique_ptr<Logger> _logger;
public:
static void createLogger(
FILE* out = stderr, LogType minlog = LogType::Debug,
std::vector<std::string> blockTags = {})
{
_logger = std::make_unique<Logger>(out, minlog, blockTags);
}
static std::unique_ptr<Logger>& getLogger() { return _logger; }
};
} // namespace familyline
| 22.533333 | 101 | 0.616124 | [
"vector"
] |
a7445802d818382e75ce6ad5bddf005a3a3837d6 | 17,362 | cpp | C++ | Code/Cpp/detect_marks.cpp | sgino209/Bracelet_decoder | d1b557254355601b277924313b760b6b30b48326 | [
"Apache-2.0"
] | null | null | null | Code/Cpp/detect_marks.cpp | sgino209/Bracelet_decoder | d1b557254355601b277924313b760b6b30b48326 | [
"Apache-2.0"
] | null | null | null | Code/Cpp/detect_marks.cpp | sgino209/Bracelet_decoder | d1b557254355601b277924313b760b6b30b48326 | [
"Apache-2.0"
] | null | null | null | // Bracelet-Decoder algo app
// (c) Shahar Gino, September-2017, sgino209@gmail.com
#include "detect_marks.hpp"
double find_possible_marks(mark_list_t &possible_marks_final, cv::Mat &frame_gray, cv::Mat &frame_thresh, unsigned int MinPixelWidth,
unsigned int MaxPixelWidth, unsigned int MinPixelHeight, unsigned int MaxPixelHeight, double MinAspectRatio,
double MaxAspectRatio, unsigned int MinPixelArea, unsigned int MaxPixelArea, double MinExtent, double MaxExtent,
double MinTexture, double MaxTexture, double MaxDrift, unsigned int PerspectiveMode, std::string FindContoursMode,
unsigned int HoughParams1, unsigned int HoughParams2, unsigned int HoughParams3,unsigned int HoughParams4,
unsigned int HoughParams5, unsigned int HoughParams6, bool debugMode, std::map<std::string,cv::Mat>* debug_imgs) {
char buffer[1000];
double rotation_angle_deg;
rotation_align_t rotation_align;
unsigned int possible_marks_cntr=0;
mark_list_t possible_marks_list, possible_marks_wo_outliers;
// Find all contours in the image:
std::vector<std::vector<cv::Point>> contours;
if (FindContoursMode == "Legacy") {
cv::findContours(frame_thresh.clone(), contours, cv::RETR_LIST, cv::CHAIN_APPROX_NONE);
}
else if (FindContoursMode == "Hough") {
std::vector<cv::Vec3f> circles;
cv::HoughCircles(
frame_thresh.clone(), // 8-bit, single channel image
circles, // detected circles (results)
cv::HOUGH_GRADIENT, // Defines the method to detect circles in images
(HoughParams1 > 0 ? HoughParams1 : 1), // Large dp values --> smaller accumulator array
(HoughParams2 > 0 ? HoughParams2 : 60), // Min distance between the detected circles centers
(HoughParams3 > 0 ? HoughParams3 : 50), // Gradient value used to handle edge detection
(HoughParams4 > 0 ? HoughParams4 : 18), // Accumulator thresh val (smaller = more circles)
(HoughParams5 > 0 ? HoughParams5 : 20), // Minimum size of the radius (in pixels)
(HoughParams6 > 0 ? HoughParams6 : 50) // Maximum size of the radius (in pixels)
);
if (!circles.empty()) {
for (auto it = circles.begin(); it != circles.end(); it++) {
contours.push_back(circle_to_contour(*it, 50, 0.7));
}
}
}
else {
error("Unsupported FindContoursMode mode: " + FindContoursMode);
}
// Foreach contour, check if it describes a possible character:
cv::Mat frame_contours = cv::Mat::zeros(frame_thresh.size(), CV_8UC3);
for (unsigned int i = 0; i < contours.size(); i++) {
// Register the contour as a possible character (+calculate intrinsic metrics):
PossibleMark possible_mark = PossibleMark(contours[i], frame_gray,
MinPixelWidth, MaxPixelWidth,
MinPixelHeight, MaxPixelHeight,
MinAspectRatio, MaxAspectRatio,
MinPixelArea, MaxPixelArea,
MinExtent, MaxExtent,
MinTexture, MaxTexture,
debugMode);
// If contour is a possible char, increment count of possible chars and add to list of possible chars:
if (possible_mark.checkIfPossibleMark()) {
possible_marks_cntr++;
possible_marks_list.push_back(possible_mark);
}
if (debugMode || debug_imgs) {
cv::drawContours(frame_contours, contours, i, SCALAR_WHITE);
}
}
if (possible_marks_list.size() == 0) {
possible_marks_final = possible_marks_list;
return 0;
}
// Remove outliers in a PCA scheme, i.e. possible marks which are too faraway from the group or interiors:
possible_marks_wo_outliers = remove_outliers(possible_marks_list, MaxDrift, debugMode);
// Rotation and Perspective alignments:
rotation_angle_deg = 0;
if (possible_marks_wo_outliers.size() > 0) {
// Rotation Alignment (SVD decomposition):
rotation_align = rotation_alignment(possible_marks_wo_outliers, debugMode);
rotation_angle_deg = rotation_align.rotation_angle_deg;
// Perspective Alignment (Homography+PerspectiveWarp):
possible_marks_final = possible_marks_wo_outliers;
perspective_alignment(possible_marks_final, PerspectiveMode, rotation_angle_deg, debugMode);
}
// -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- .. -- ..
if (debugMode || debug_imgs) {
int kx, ky;
unsigned int X_xc, X_yc;
mark_list_t::iterator it;
cv::Mat frame_possible_marks = cv::Mat::zeros(frame_thresh.size(), CV_8UC3);
for(it=possible_marks_wo_outliers.begin(); it<possible_marks_wo_outliers.end(); it++) {
std::vector<std::vector<cv::Point>> contours;
contours.push_back(it->contour);
cv::drawContours(frame_possible_marks, contours, 0, SCALAR_WHITE);
for (ky=-3; ky<=3; ky++) {
for (kx=-3; kx<=3; kx++) {
if ((it->intCenterY+ky >= 0) && (it->intCenterY+ky < frame_thresh.size().height) &&
(it->intCenterX+kx >= 0) && (it->intCenterX+kx < frame_thresh.size().width)) {
frame_possible_marks.at<cv::Vec3b>(it->intCenterY+ky,it->intCenterX+kx)[2] = 255;
}
if ((it->intCenterY_r+ky >= 0) && (it->intCenterY_r+ky < frame_thresh.size().height) &&
(it->intCenterX_r+kx >= 0) && (it->intCenterX_r+kx < frame_thresh.size().width)) {
frame_possible_marks.at<cv::Vec3b>(it->intCenterY_r+ky,it->intCenterX_r+kx)[0] = 255;
}
}
}
}
for(it=possible_marks_final.begin(); it<possible_marks_final.end(); it++) {
for (ky=-3; ky<=3; ky++) {
for (kx=-3; kx<=3; kx++) {
if ((it->intCenterY_r+ky >= 0) && (it->intCenterY_r+ky < frame_thresh.size().height) &&
(it->intCenterX_r+kx >= 0) && (it->intCenterX_r+kx < frame_thresh.size().width)) {
frame_possible_marks.at<cv::Vec3b>(it->intCenterY_r+ky,it->intCenterX_r+kx)[1] = 255;
frame_possible_marks.at<cv::Vec3b>(it->intCenterY_r+ky,it->intCenterX_r+kx)[2] = 255;
}
}
}
}
cv::putText(frame_possible_marks, "Original", cv::Point(10, 30), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_RED, 2);
cv::putText(frame_possible_marks, "Rotation fix (SVD)", cv::Point(10, 70), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_BLUE, 2);
cv::putText(frame_possible_marks, "Centroid", cv::Point(10, 110), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_GREEN, 2);
cv::putText(frame_possible_marks, "Perspective fix", cv::Point(10, 150), cv::FONT_HERSHEY_SIMPLEX, 1, SCALAR_YELLOW, 2);
if (PerspectiveMode == 1) {
// place-holder (TBD: translate from Python):
//frame_possible_marks = polylines(frame_possible_marks, array([rect_src]), True, (255, 0, 0), 1, LINE_AA)
//frame_possible_marks = polylines(frame_possible_marks, array([rect_dst]), True, (0, 255, 255), 1, LINE_AA)
}
X_xc = std::max(3,int(rotation_align.centroid_x));
X_yc = std::max(3,int(rotation_align.centroid_y));
for (ky=-3; ky<=3; ky++) {
for (kx=-3; kx<=3; kx++) {
frame_possible_marks.at<cv::Vec3b>(X_yc+ky,X_xc+kx)[1] = 255;
}
}
if (debugMode) {
sprintf(buffer, "Amount of detected contours: %d", contours.size());
debug(buffer);
sprintf(buffer, "Amount of possible marks: %d", possible_marks_cntr);
debug(buffer);
sprintf(buffer, "Amount of possible marks w/o outliers: %d", possible_marks_wo_outliers.size());
debug(buffer);
sprintf(buffer, "Rotation: %.2f", rotation_angle_deg);
debug(buffer);
cv::imwrite("img_contours_all.jpg", frame_contours);
cv::imwrite("img_possible_marks.jpg", frame_possible_marks);
}
if (debug_imgs) {
(*debug_imgs)["img_contours_all"] = frame_contours;
(*debug_imgs)["img_possible_marks"] = frame_possible_marks;
}
}
return rotation_angle_deg;
}
// ------------------------------------------------------------------------------------------------------------------------------
mark_list_t remove_outliers(mark_list_t possible_marks_list, double MaxDrift, bool debugMode) {
std::string dbg;
bool is_interior;
char buffer[1000];
cv::Point2f p1, p2;
std::vector<double> dist;
mark_list_t::iterator it;
mark_list_t possible_marks_list_final;
double median_x, median_y, median_dist, d, dr;
std::vector<unsigned int> median_x_vec, median_y_vec;
// Extract marks relevant data (Median calculation):
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
median_x_vec.push_back(it->intCenterX);
median_y_vec.push_back(it->intCenterY);
}
median_x = median_calc<unsigned int>(median_x_vec);
median_y = median_calc<unsigned int>(median_y_vec);
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
p1 = cv::Point2f(it->intCenterX, it->intCenterY);
p2 = cv::Point2f(median_x, median_y);
d = distance_mse(p1,p2);
dist.push_back(d);
}
median_dist = median_calc<double>(dist);
if (debugMode) {
sprintf(buffer, "median_x=%.2f, median_y=%.2f, median_dist=%.2f", median_x, median_y, median_dist);
debug(buffer);
}
// Exclude marks with a too-high drift or interiors:
for (unsigned k=0; k<possible_marks_list.size(); k++) {
dbg = "";
PossibleMark possible_mark = possible_marks_list.at(k);
dr = (median_dist == 0) ? 0 : dist.at(k)/median_dist;
is_interior = false;
for (unsigned l=0; l<possible_marks_list.size(); l++) {
if (l == k) {
continue;
}
p1 = cv::Point2f(possible_mark.intCenterX, possible_mark.intCenterY);
p2 = cv::Point2f(possible_marks_list.at(l).intCenterX, possible_marks_list.at(l).intCenterY);
d = distance_mse(p1,p2);
if ((d < 2*MaxDrift) && (possible_mark.intBoundingRectArea < possible_marks_list.at(l).intBoundingRectArea)) {
is_interior = true;
dbg = "(X)";
}
}
if ((dr < MaxDrift) && !is_interior) {
possible_marks_list_final.push_back(possible_mark);
dbg = "(*)";
}
if (debugMode) {
sprintf(buffer, "possible_mark=%s, dist[%d]=%.2f, disr_r=%.2f %s", possible_mark.to_string().c_str(), k, dist.at(k), dr, dbg.c_str());
debug(buffer);
}
}
return possible_marks_list_final;
}
// ------------------------------------------------------------------------------------------------------------------------------
rotation_align_t rotation_alignment(mark_list_t &possible_marks_list, bool debugMode) {
cv::SVD svdMat;
cv::Mat S, U, Vt;
char buffer[1000];
mark_list_t::iterator it;
std::vector<cv::Point> H;
rotation_align_t rotation_align;
unsigned int n=1, centroid_x=0, centroid_y=0;
double mean_x=0, mean_y=0, rotation_angle_deg=0, rotation_angle;
// Calculate Centroid:
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
mean_x += (it->intCenterX - mean_x)/n;
mean_y += (it->intCenterY - mean_y)/n;
n++;
}
// Calculate covariance matrix (H):
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
H.push_back(cv::Point(round(it->intCenterX - mean_x), round(it->intCenterY - mean_y)));
}
if (debugMode) {
debug("Covariance matrix (H):");
print_point_vec<cv::Point>(H);
}
// SVD decomposition:
if (0) {
cv::SVD::compute(H, S, U, Vt, cv::SVD::FULL_UV);
}
else {
int num = possible_marks_list.size();
float arr[num][2];
for(int i=0; i<num; i++) {
arr[i][1] = possible_marks_list[i].intCenterY;
arr[i][0] = possible_marks_list[i].intCenterX;
}
cv::Mat mat = cv::Mat(num, 2, CV_32FC1, &arr);
cv::Mat cov, mean;
cv::calcCovarMatrix(mat, cov, mean, cv::COVAR_NORMAL | cv::COVAR_ROWS);
cov = cov / (mat.rows - 1);
cv::eigen(cov, S, Vt);
Vt *= -1;
}
// Calculate rotation angle:
rotation_angle = std::atan2(Vt.at<double>(0,1), Vt.at<double>(0,0));
rotation_angle_deg = rotation_angle * (180 / CV_PI);
// Rotation alignment:
int k=0;
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++, k++) {
it->intCenterX_r = (int)(H[k].x * cos(rotation_angle) + H[k].y * sin(rotation_angle) + (int)(mean_x));
it->intCenterY_r = (int)(H[k].x * -sin(rotation_angle) + H[k].y * cos(rotation_angle) + (int)(mean_y));
if (debugMode) {
sprintf(buffer, "possible_mark=%s", it->to_string().c_str());
debug(buffer);
}
}
rotation_align.rotation_angle_deg = rotation_angle_deg;
rotation_align.centroid_x = centroid_x;
rotation_align.centroid_y = centroid_y;
return rotation_align;
}
// ------------------------------------------------------------------------------------------------------------------------------
void perspective_alignment(mark_list_t &possible_marks_list, unsigned int PerspectiveMode, double rotation_angle_deg, bool debugMode) {
if (PerspectiveMode == 0) {
return perspective_alignment_opt0(possible_marks_list, rotation_angle_deg, debugMode);
}
else if (PerspectiveMode == 1) {
return perspective_alignment_opt1(possible_marks_list, debugMode);
}
else {
error("Invalid PerspectiveMode (%d)" + std::to_string(PerspectiveMode));
}
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
void perspective_alignment_opt0(mark_list_t &possible_marks_list, double rotation_angle_deg, bool debugMode) {
double mean_x = 0;
unsigned int n = 1;
unsigned int dist_x;
mark_list_t::iterator it;
// Calculate meanX:
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
mean_x += (it->intCenterX_r - mean_x)/n;
n++;
}
// Update marks coordinates (adaptive with angle):
for(it=possible_marks_list.begin(); it<possible_marks_list.end(); it++) {
dist_x = std::abs(it->intCenterX_r - mean_x);
if (std::abs(rotation_angle_deg) > 90) {
if (std::abs(rotation_angle_deg) < 170) {
it->intCenterY_r -= (unsigned int)(2 * sqrt(dist_x));
}
else {
it->intCenterY_r -= (unsigned int)(1 * sqrt(dist_x));
}
}
else {
it->intCenterY_r += (unsigned int)(2 * sqrt(dist_x));
}
}
// Debug:
if (debugMode) {
debug("(xR,yR) after Perspective Fix:");
print_mark_vec<PossibleMark>(possible_marks_list);
}
}
// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
void perspective_alignment_opt1(mark_list_t &possible_marks_list, bool debugMode) {
error("PerspectiveMode=1 is Not supported at the moment in CPP edition");
}
// ------------------------------------------------------------------------------------------------------------------------------
std::vector<cv::Point> circle_to_contour(cv::Vec3f circle, unsigned int points_per_contour, float resize_factor) {
cv::Point center(round(circle[0]), round(circle[1]));
int xc = center.x;
int yc = center.y;
double r = cvRound(circle[2]);
r *= resize_factor;
std::vector<cv::Point> contour;
const double pi2 = 2*M_PI;
for (double i=0; i<pi2; i+=pi2/points_per_contour) {
int y = int(yc + r * sin(i));
int x = int(xc + r * cos(i));
contour.push_back(cv::Point(x,y));
}
return contour;
}
// ------------------------------------------------------------------------------------------------------------------------------
template <class T>
double median_calc(std::vector<T> data_vec) {
double median;
sort(data_vec.begin(), data_vec.end());
if(data_vec.size()%2==0) median = ( data_vec[ data_vec.size()/2 - 1 ] + data_vec[ data_vec.size()/2 ] )/2.0;
else median = data_vec[ data_vec.size()/2 ];
return median;
}
// ------------------------------------------------------------------------------------------------------------------------------
template <class T>
void print_point_vec(std::vector<T> data_vec) {
std::cout << "[[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->x << " " << std::flush;
}
std::cout << "]" << std::endl << "[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->y << " " << std::flush;
}
std::cout << "]]" << std::endl << std::flush;
}
// ---------------------------------------------------------------------------------------------------------------
template <class T>
void print_mark_vec(std::vector<T> data_vec) {
std::cout << "[[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->intCenterX_r << " " << std::flush;
}
std::cout << "]" << std::endl << "[ " << std::flush;
for(auto it=data_vec.begin(); it<data_vec.end(); it++) {
std::cout << it->intCenterY_r << " " << std::flush;
}
std::cout << "]]" << std::endl << std::flush;
}
| 38.928251 | 141 | 0.587087 | [
"vector"
] |
a74471a4400e43a00fb284691005f853cbdf79a9 | 12,442 | cpp | C++ | third_party/boost/libs/gil/test/pixel_iterator.cpp | Jackarain/tinyrpc | 07060e3466776aa992df8574ded6c1616a1a31af | [
"BSL-1.0"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | third_party/boost/libs/gil/test/pixel_iterator.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 1 | 2019-03-04T11:21:00.000Z | 2019-05-24T01:36:31.000Z | third_party/boost/libs/gil/test/pixel_iterator.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | //
// Copyright 2005-2007 Adobe Systems Incorporated
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/gil.hpp>
#include <boost/mpl/vector.hpp>
#include <cassert>
#include <exception>
#include <iostream>
#include <vector>
using namespace boost::gil;
using namespace std;
void test_pixel_iterator()
{
boost::function_requires<Point2DConcept<point<int>>>();
boost::function_requires<MutablePixelIteratorConcept<bgr8_ptr_t> >();
boost::function_requires<MutablePixelIteratorConcept<cmyk8_planar_ptr_t> >();
boost::function_requires<PixelIteratorConcept<rgb8c_planar_step_ptr_t> >();
boost::function_requires<MutableStepIteratorConcept<rgb8_step_ptr_t> >();
boost::function_requires<MutablePixelLocatorConcept<rgb8_step_loc_t> >();
boost::function_requires<PixelLocatorConcept<rgb8c_planar_step_loc_t> >();
boost::function_requires<MutableStepIteratorConcept<cmyk8_planar_step_ptr_t> >();
boost::function_requires<StepIteratorConcept<gray8c_step_ptr_t> >();
boost::function_requires<MutablePixelLocatorConcept<memory_based_2d_locator<rgb8_step_ptr_t> > >();
typedef const bit_aligned_pixel_reference<std::uint8_t, boost::mpl::vector3_c<int,1,2,1>, bgr_layout_t, true> bgr121_ref_t;
typedef bit_aligned_pixel_iterator<bgr121_ref_t> bgr121_ptr_t;
boost::function_requires<MutablePixelIteratorConcept<bgr121_ptr_t> >();
boost::function_requires<PixelBasedConcept<bgr121_ptr_t> >();
boost::function_requires<MemoryBasedIteratorConcept<bgr121_ptr_t> >();
boost::function_requires<HasDynamicXStepTypeConcept<bgr121_ptr_t> >();
// TEST dynamic_step_t
BOOST_STATIC_ASSERT(( boost::is_same<cmyk16_step_ptr_t,dynamic_x_step_type<cmyk16_step_ptr_t>::type>::value ));
BOOST_STATIC_ASSERT(( boost::is_same<cmyk16_planar_step_ptr_t,dynamic_x_step_type<cmyk16_planar_ptr_t>::type>::value ));
BOOST_STATIC_ASSERT(( boost::is_same<iterator_type<uint8_t,gray_layout_t,false,false,false>::type,gray8c_ptr_t>::value ));
// TEST iterator_is_step
BOOST_STATIC_ASSERT(iterator_is_step< cmyk16_step_ptr_t >::value);
BOOST_STATIC_ASSERT(iterator_is_step< cmyk16_planar_step_ptr_t >::value);
BOOST_STATIC_ASSERT(!iterator_is_step< cmyk16_planar_ptr_t >::value);
typedef color_convert_deref_fn<rgb8c_ref_t, gray8_pixel_t> ccv_rgb_g_fn;
typedef color_convert_deref_fn<gray8c_ref_t, rgb8_pixel_t> ccv_g_rgb_fn;
gil_function_requires<PixelDereferenceAdaptorConcept<ccv_rgb_g_fn> >();
gil_function_requires<PixelDereferenceAdaptorConcept<deref_compose<ccv_rgb_g_fn,ccv_g_rgb_fn> > >();
typedef dereference_iterator_adaptor<rgb8_ptr_t, ccv_rgb_g_fn> rgb2gray_ptr;
BOOST_STATIC_ASSERT(!iterator_is_step< rgb2gray_ptr >::value);
typedef dynamic_x_step_type<rgb2gray_ptr>::type rgb2gray_step_ptr;
BOOST_STATIC_ASSERT(( boost::is_same< rgb2gray_step_ptr, dereference_iterator_adaptor<rgb8_step_ptr_t, ccv_rgb_g_fn> >::value));
make_step_iterator(rgb2gray_ptr(),2);
typedef dereference_iterator_adaptor<rgb8_step_ptr_t, ccv_rgb_g_fn> rgb2gray_step_ptr1;
BOOST_STATIC_ASSERT(iterator_is_step< rgb2gray_step_ptr1 >::value);
BOOST_STATIC_ASSERT(( boost::is_same< rgb2gray_step_ptr1, dynamic_x_step_type<rgb2gray_step_ptr1>::type >::value));
typedef memory_based_step_iterator<dereference_iterator_adaptor<rgb8_ptr_t, ccv_rgb_g_fn> > rgb2gray_step_ptr2;
BOOST_STATIC_ASSERT(iterator_is_step< rgb2gray_step_ptr2 >::value);
BOOST_STATIC_ASSERT(( boost::is_same< rgb2gray_step_ptr2, dynamic_x_step_type<rgb2gray_step_ptr2>::type >::value));
make_step_iterator(rgb2gray_step_ptr2(),2);
// bit_aligned iterators test
// Mutable reference to a BGR232 pixel
typedef const bit_aligned_pixel_reference<std::uint8_t, boost::mpl::vector3_c<unsigned,2,3,2>, bgr_layout_t, true> bgr232_ref_t;
// A mutable iterator over BGR232 pixels
typedef bit_aligned_pixel_iterator<bgr232_ref_t> bgr232_ptr_t;
// BGR232 pixel value. It is a packed_pixel of size 1 byte. (The last bit is unused)
typedef std::iterator_traits<bgr232_ptr_t>::value_type bgr232_pixel_t;
BOOST_STATIC_ASSERT((sizeof(bgr232_pixel_t)==1));
bgr232_pixel_t red(0,0,3); // = 0RRGGGBB, = 01100000
// a buffer of 7 bytes fits exactly 8 BGR232 pixels.
unsigned char pix_buffer[7];
std::fill(pix_buffer,pix_buffer+7,0);
bgr232_ptr_t pix_it(&pix_buffer[0],0); // start at bit 0 of the first pixel
for (int i=0; i<8; ++i) {
*pix_it++ = red;
}
// test cross byte pixel values - meaning when a pixel value is stretched over two bytes
typedef bit_aligned_image1_type< 3, gray_layout_t >::type gray3_image_t;
typedef gray3_image_t image_t;
typedef image_t::view_t view_t;
typedef view_t::reference ref_t;
typedef bit_aligned_pixel_iterator< ref_t > iterator_t;
std::vector< unsigned char > buf( 4 );
// bit pattern is: 1011 0110 0110 1101 1101 1011
// each byte is read right to left
buf[0] = 182;
buf[1] = 109;
buf[2] = 219;
iterator_t it( &buf[0], 0 );
ref_t p1 = *it; it++;
ref_t p2 = *it; it++;
ref_t p3 = *it; it++;
ref_t p4 = *it; it++;
ref_t p5 = *it; it++;
ref_t p6 = *it; it++;
ref_t p7 = *it; it++;
ref_t p8 = *it; it++;
unsigned char v1 = get_color( p1, gray_color_t() );
unsigned char v2 = get_color( p2, gray_color_t() );
unsigned char v3 = get_color( p3, gray_color_t() );
unsigned char v4 = get_color( p4, gray_color_t() );
unsigned char v5 = get_color( p5, gray_color_t() );
unsigned char v6 = get_color( p6, gray_color_t() );
unsigned char v7 = get_color( p7, gray_color_t() );
unsigned char v8 = get_color( p8, gray_color_t() );
// all values should be 110b ( 6 );
assert( v1 == 6 );
assert( v2 == 6 );
assert( v3 == 6 );
assert( v4 == 6 );
assert( v5 == 6 );
assert( v6 == 6 );
assert( v7 == 6 );
assert( v8 == 6 );
}
// TODO: Make better tests. Use some code from below.
/*
template <typename Pixel>
void invert_pixel1(Pixel& pix) {
at_c<0>(pix)=0;
}
template <typename T> inline void ignore_unused_variable_warning(const T&){}
void test_pixel_iterator() {
rgb8_pixel_t rgb8(1,2,3);
rgba8_pixel_t rgba8;
rgb8_ptr_t ptr1=&rgb8;
memunit_advance(ptr1, 3);
const rgb8_ptr_t ptr2=memunit_advanced(ptr1,10);
memunit_distance(ptr1,ptr2);
const rgb8_pixel_t& ref=memunit_advanced_ref(ptr1,10); ignore_unused_variable_warning(ref);
rgb8_planar_ptr_t planarPtr1(&rgb8);
rgb8_planar_ptr_t planarPtr2(&rgb8);
memunit_advance(planarPtr1,10);
memunit_distance(planarPtr1,planarPtr2);
rgb8_planar_ptr_t planarPtr3=memunit_advanced(planarPtr1,10);
// planarPtr2=&rgba8;
planar_pixel_reference<uint8_t&,rgb_t> pxl=*(planarPtr1+5);
rgb8_pixel_t pv2=pxl;
rgb8_pixel_t pv3=*(planarPtr1+5);
rgb8_pixel_t pv=planarPtr1[5];
assert(*(planarPtr1+5)==planarPtr1[5]);
rgb8_planar_ref_t planarRef=memunit_advanced_ref(planarPtr1,10);
rgb8_step_ptr_t stepIt(&rgb8,5);
stepIt++;
rgb8_step_ptr_t stepIt2=stepIt+10;
stepIt2=stepIt;
rgb8_step_ptr_t stepIt3(&rgb8,5);
rgb8_pixel_t& ref1=stepIt3[5];
// bool v=boost::is_POD<iterator_traits<memory_based_step_iterator<rgb8_ptr_t> >::value_type>::value;
// v=boost::is_POD<rgb8_pixel_t>::value;
// v=boost::is_POD<int>::value;
rgb8_step_ptr_t rgb8StepIt(ptr1, 10);
rgb8_step_ptr_t rgb8StepIt2=rgb8StepIt;
rgb8StepIt=rgb8StepIt2;
++rgb8StepIt;
rgb8_ref_t reff=*rgb8StepIt; ignore_unused_variable_warning(reff);
rgb8StepIt+=10;
std::ptrdiff_t dst=rgb8StepIt2-rgb8StepIt; ignore_unused_variable_warning(dst);
rgb8_pixel_t val1=ref1;
rgb8_ptr_t ptr=&ref1;
invert_pixel1(*planarPtr1);
// invert_pixel1(*ptr);
rgb8c_planar_ptr_t r8cpp;
// invert_pixel1(*r8cpp);
rgb8_pixel_t& val21=stepIt3[5];
rgb8_pixel_t val22=val21;
rgb8_pixel_t val2=stepIt3[5];
rgb8_ptr_t ptr11=&(stepIt3[5]); ignore_unused_variable_warning(ptr11);
rgb8_ptr_t ptr3=&*(stepIt3+5); ignore_unused_variable_warning(ptr3);
rgb8_step_ptr_t stepIt4(ptr,5);
++stepIt4;
rgb8_step_ptr_t stepIt5;
if (stepIt4==stepIt5) {
int st=0;ignore_unused_variable_warning(st);
}
iterator_from_2d<rgb8_loc_t> pix_img_it(rgb8_loc_t(ptr, 20), 5);
++pix_img_it;
pix_img_it+=10;
rgb8_pixel_t& refr=*pix_img_it;
refr=rgb8_pixel_t(1,2,3);
*pix_img_it=rgb8_pixel_t(1,2,3);
pix_img_it[3]=rgb8_pixel_t(1,2,3);
*(pix_img_it+3)=rgb8_pixel_t(1,2,3);
iterator_from_2d<rgb8c_loc_t> pix_img_it_c(rgb8c_loc_t(rgb8c_ptr_t(ptr),20), 5);
++pix_img_it_c;
pix_img_it_c+=10;
// *pix_img_it_c=rgb8_pixel_t(1,2,3); // error: assigning though const iterator
typedef iterator_from_2d<rgb8_loc_t>::difference_type dif_t;
dif_t dt=0;
std::ptrdiff_t tdt=dt; ignore_unused_variable_warning(tdt);
// memory_based_step_iterator<rgb8_pixel_t> stepIt3Err=stepIt+10; // error: non-const from const iterator
memory_based_2d_locator<rgb8_step_ptr_t> xy_locator(ptr,27);
xy_locator.x()++;
// memory_based_step_iterator<rgb8_pixel_t>& yit=xy_locator.y();
xy_locator.y()++;
xy_locator+=point<std::ptrdiff_t>(3,4);
// *xy_locator=(xy_locator(-1,0)+xy_locator(0,1))/2;
rgb8_pixel_t& rf=*xy_locator; ignore_unused_variable_warning(rf);
make_step_iterator(rgb8_ptr_t(),3);
make_step_iterator(rgb8_planar_ptr_t(),3);
make_step_iterator(rgb8_planar_step_ptr_t(),3);
// Test operator-> on planar ptrs
{
rgb8c_planar_ptr_t cp(&rgb8);
rgb8_planar_ptr_t p(&rgb8);
// get_color(p,red_t()) = get_color(cp,green_t()); // does not compile - cannot assign a non-const pointer to a const pointer. Otherwise you will be able to modify the value through it.
}
// xy_locator.y()++;
// dimensions to explore
//
// values, references, pointers
// color spaces (rgb,cmyk,gray)
// channel ordering (bgr vs rgb)
// planar vs interleaved
// Pixel POINTERS
// typedef const iterator_traits<rgb8_ptr_t>::pointer RGB8ConstPtr;
typedef const rgb8_ptr_t RGB8ConstPtr;
typedef const rgb8_planar_ptr_t RGB8ConstPlanarPtr;
// typedef const iterator_traits<rgb8_planar_ptr_t>::pointer RGB8ConstPlanarPtr;
// constructing from values, references and other pointers
RGB8ConstPtr rgb8_const_ptr=NULL; ignore_unused_variable_warning(rgb8_const_ptr);
rgb8_ptr_t rgb8ptr=&rgb8;
rgb8=bgr8_pixel_t(30,20,10);
rgb8_planar_ptr_t rgb8_pptr=&rgb8;
++rgb8_pptr;
rgb8_pptr--;
rgb8_pptr[0]=rgb8;
RGB8ConstPlanarPtr rgb8_const_planar_ptr=&rgb8;
rgb8c_planar_ptr_t r8c=&rgb8;
r8c=&rgb8;
rgb8_pptr=&rgb8;
// rgb8_const_planar_ptr=&rgb16p; // error: incompatible bit depth
// iterator_traits<CMYK8>::pointer cmyk8_ptr_t=&rgb8; // error: incompatible pointer type
RGB8ConstPtr rgb8_const_ptr_err=rgb8ptr; // const pointer from non-regular pointer
ignore_unused_variable_warning(rgb8_const_ptr_err);
// dereferencing pointers to obtain references
rgb8_ref_t rgb8ref_2=*rgb8ptr; ignore_unused_variable_warning(rgb8ref_2);
assert(rgb8ref_2==rgb8);
// RGB8Ref rgb8ref_2_err=*rgb8_const_planar_ptr; // error: non-const reference from const pointer
rgb8_planar_ref_t rgb8planarref_3=*rgb8_pptr; // planar reference from planar pointer
assert(rgb8planarref_3==rgb8);
// RGB8Ref rgb8ref_3=*rgb8_planar_ptr_t; // error: non-planar reference from planar pointer
const rgb8_pixel_t crgb8=rgb8;
*rgb8_pptr=rgb8;
*rgb8_pptr=crgb8;
memunit_advance(rgb8_pptr,3);
memunit_advance(rgb8_pptr,-3);
}
*/
int main()
{
try
{
test_pixel_iterator();
return EXIT_SUCCESS;
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
catch (...)
{
return EXIT_FAILURE;
}
}
| 36.702065 | 199 | 0.704629 | [
"vector"
] |
a74769270ec44110a37aa7155fccec5946019a88 | 641 | cpp | C++ | Array/945_Minimum-Increment-to-Make-Array-Unique.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | Array/945_Minimum-Increment-to-Make-Array-Unique.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | Array/945_Minimum-Increment-to-Make-Array-Unique.cpp | YunWGui/LeetCode | 2587eca22195ec7d9263227554467ec4010cfe05 | [
"MIT"
] | null | null | null | /*
Title:
945. Minimum Increment to Make Array Unique
945. 使数组唯一的最小增量
Address:
https://leetcode-cn.com/problems/minimum-increment-to-make-array-unique/
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
sort( A.begin(), A.end() );
int cnt = 0;
for ( int i = 1; i < (int)A.size(); ++i ) {
if ( A[i - 1] >= A[i] ) {
cnt += A[i - 1] - A[i] + 1;
A[i] = A[i - 1] + 1;
}
}
return cnt;
}
};
int main()
{
return 0;
} | 17.324324 | 76 | 0.4961 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.