hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
14a84792214f67e5ec46a4fc15e00dbdc182cd16
16,702
cc
C++
hackt_docker/hackt/src/Object/lang/PRS_attribute_registry.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/PRS_attribute_registry.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/PRS_attribute_registry.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/lang/PRS_attribute_registry.cc" This defines the attribute actions for the cflat visitor. $Id: PRS_attribute_registry.cc,v 1.21 2010/09/01 22:14:20 fang Exp $ */ #include "util/static_trace.hh" DEFAULT_STATIC_TRACE_BEGIN #include <iostream> #include <map> #include "Object/lang/PRS_attribute_registry.hh" #include "Object/lang/cflat_printer.hh" #include "Object/expr/const_param_expr_list.hh" #include "Object/expr/pint_const.hh" #include "Object/expr/preal_const.hh" #include "Object/expr/expr_dump_context.hh" #include "Object/lang/PRS_attribute_common.hh" #include "main/cflat_options.hh" #include "common/TODO.hh" #include "util/memory/count_ptr.tcc" namespace HAC { namespace entity { namespace PRS { #include "util/using_ostream.hh" //----------------------------------------------------------------------------- // global initializers /** Locally modifiable to this unit only. */ static cflat_rule_attribute_registry_type __cflat_rule_attribute_registry; /** Public immutable reference */ const cflat_rule_attribute_registry_type& cflat_rule_attribute_registry(__cflat_rule_attribute_registry); //============================================================================= // class attribute_definition_entry method definitions //============================================================================= /** Utility function for registering an attribute class. */ template <class T> static size_t register_cflat_rule_attribute_class(void) { // typedef cflat_rule_attribute_registry_type::iterator iterator; typedef cflat_rule_attribute_registry_type::mapped_type mapped_type; const string k(T::name); mapped_type& m(__cflat_rule_attribute_registry[k]); if (m) { cerr << "Error: PRS attribute by the name \'" << k << "\' has already been registered!" << endl; THROW_EXIT; } m = cflat_rule_attribute_definition_entry(k, &T::main, &T::check_vals); // oddly, this is needed to force instantiation of the [] const operator const mapped_type& n __ATTRIBUTE_UNUSED_CTOR__((cflat_rule_attribute_registry.find(k)->second)); INVARIANT(n); return cflat_rule_attribute_registry.size(); } //============================================================================= /** Convenient home namespace for user-defined PRS rule attributes. Each class in this namespace represents an attribute. */ namespace cflat_rule_attributes { /** Macro for declaring and defining attribute classes. Here, the vistor_type is cflat_prs_printer. TODO: These classes should have hidden visibility. TODO: could also push name[] into the base class, but would we be creating an initialization order dependence? */ #define DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(class_name, att_name) \ DECLARE_PRS_RULE_ATTRIBUTE_CLASS(class_name, cflat_prs_printer) \ DEFINE_PRS_RULE_ATTRIBUTE_CLASS(class_name, att_name, \ register_cflat_rule_attribute_class) //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-after.texi @defmac after d Applies a fixed delay @var{d} to a single rule. Affects @command{hflat} output and @command{hacprsim} operation. @end defmac @defmac after_min d @defmacx after_max d Specifies upper and lower bounds on delays for a rule. The upper bound should be greater than or equal to the lower bound, however, this is not checked here. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(After, "after") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(AfterMin, "after_min") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(AfterMax, "after_max") /** Prints out "after x" before a rule in cflat. TODO: allow real-values. */ void After::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { ostream& o(p.os); o << "after "; v.at(0).is_a<const pint_const>()->dump(o, entity::expr_dump_context::default_value) << '\t'; } } void AfterMin::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { ostream& o(p.os); o << "after_min "; v.at(0).is_a<const pint_const>()->dump(o, entity::expr_dump_context::default_value) << '\t'; } } void AfterMax::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { ostream& o(p.os); o << "after_max "; v.at(0).is_a<const pint_const>()->dump(o, entity::expr_dump_context::default_value) << '\t'; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-rule-sizing.texi @defmac W width Specify the default transistor width for this rule. For uniformly sized stacks, writing this makes the rule much less cluttered than repeating sizes per literal. Widths can always be overridden per literal. @end defmac @defmac L length Specify the default transistor length for this rule. Lengths can always be overridden per literal. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Width, "W") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Length, "L") void Width::main(visitor_type& p, const values_type& v) { if (p.cfopts.size_prs) { INVARIANT(v.size() == 1); const preal_value_type s = v.front()->to_real_const(); p.os << "W=" << s << '\t'; } } void Length::main(visitor_type& p, const values_type& v) { if (p.cfopts.size_prs) { INVARIANT(v.size() == 1); const preal_value_type s = v.front()->to_real_const(); p.os << "L=" << s << '\t'; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-vt.texi @defmac hvt @defmacx lvt @defmacx svt If @option{hvt} is set, then emit all devices with in this particular rule with hvt (high voltage threshold), unless explicitly overridden in a node literal. If @option{lvt} is set, then emit all devices with in this particular rule with lvt (low voltage threshold), unless overridden. @option{svt} restores back to standard Vt as the default. When no parameter value is given, implicit value is 1. When multiple settings are given, the last one should take precedence. Default: svt @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(HVT, "hvt") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(LVT, "lvt") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(SVT, "svt") void HVT::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_LVS) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "hvt\t"; } } } void LVT::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_LVS) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "lvt\t"; } } } void SVT::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_LVS) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "svt\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-always_random.texi @defmac always_random b If @var{b} is true (1), rule delay is based on random exponential distribution. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Always_Random, "always_random") /** Prints out "always_random" before a rule in cflat. TODO: check to ensure use with after. */ void Always_Random::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "always_random\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-weak.texi @defmac weak b If @var{b} is true (1), rule is considered weak, e.g. feedback, and may be overpowered by non-weak rules. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Weak, "weak") /** Prints out "weak" before a rule in cflat. */ void Weak::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "weak\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-unstab.texi @defmac unstab b If @var{b} is true (1), rule is allowed to be unstable, as an exception. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Unstab, "unstab") /** Prints out "unstab" before a rule in cflat. */ void Unstab::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "unstab\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-comb.texi @defmac comb b If @var{b} is true (1), use combinational feedback. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Comb, "comb") /** Prints out "comb" before a rule in cflat. */ void Comb::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "comb\t"; } } #else // do nothing yet #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-keeper.texi @defmac keeper b For LVS, If @var{b} is true (1), staticize (explicitly). This attribute will soon be deprecated in favor of a node attribute @t{autokeeper}. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Keeper, "keeper") /** Prints out "keeper" before a rule in cflat. */ void Keeper::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "keeper\t"; } } #else // do nothing yet #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-iskeeper.texi @defmac iskeeper [b] If @var{b} is true (1), flag that this rule is part of a standard keeper. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(IsKeeper, "iskeeper") /** Prints out "iskeeper" before a rule in cflat. */ void IsKeeper::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "iskeeper\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-isckeeper.texi @defmac isckeeper [b] If @var{b} is true (1), flag that this rule is part of a combinational feedback keeper. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(IsCKeeper, "isckeeper") /** Prints out "isckeeper" before a rule in cflat. */ void IsCKeeper::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "ckeeper\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-diode.texi @defmac diode [b] If @var{b} is true (1), flag that this rule generates a diode-connected transistor. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Diode, "diode") /** Prints out "diode" before a rule in cflat. */ void Diode::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "diode\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-res.texi @defmac res [b] If @var{b} is true (1), flag that this rule is a fake resistor. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Res, "res") /** Prints out "res" before a rule in cflat. */ void Res::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "res\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-output.texi @defmac output b If @var{b} is true (1), staticize (explicitly). Q: should this really be a rule-attribute? better off as node-attribute? @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Output, "output") /** Prints out "comb" before a rule in cflat. */ void Output::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "output\t"; } } #else FINISH_ME(Fang); #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-loadcap.texi @defmac loadcap C Use @var{C} as load capacitance instead of inferring from configuration. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(LoadCap, "loadcap") /** Supposed to attach load to rule's output node? */ void LoadCap::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { // use real-value const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "keeper\t"; } } #else FINISH_ME(Fang); #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-reff.texi @defmac N_reff R @defmacx P_reff R Use @var{R} as effective resistance to override the automatically computed value in other back-end tools. NOTE: This is a hack that should be replaced with a proper implementation of the "fold" expression macro. Consider this attribute deprecated from the start. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(N_reff, "N_reff") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(P_reff, "P_reff") /** Do nothing? */ void N_reff::main(visitor_type& p, const values_type& v) { } void P_reff::main(visitor_type& p, const values_type& v) { } #undef DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS //============================================================================= } // end namespace cflat_rule_attributes //============================================================================= } // end namespace PRS } // end namespace entity } // end namespace HAC DEFAULT_STATIC_TRACE_END
26.427215
79
0.639983
broken-wheel
14af31dd7dbeb0f08817d4103a1a040b59e892d3
310
cpp
C++
class03/stringIO_1.cpp
jeremypedersen/cppZero
69fc8119fdcc8186fee50896ff378a3c55076fa7
[ "Unlicense" ]
null
null
null
class03/stringIO_1.cpp
jeremypedersen/cppZero
69fc8119fdcc8186fee50896ff378a3c55076fa7
[ "Unlicense" ]
null
null
null
class03/stringIO_1.cpp
jeremypedersen/cppZero
69fc8119fdcc8186fee50896ff378a3c55076fa7
[ "Unlicense" ]
null
null
null
// // Code by: Jeremy Pedersen // // Licensed under the BSD 2-clause license (FreeBSD license) // #include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Hello " << name << endl; return 0; }
15.5
61
0.570968
jeremypedersen
14b1f30932ea11b4f9d351496847f5b7f2da42a5
3,161
hpp
C++
code/src/core/maths/util.hpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
3
2020-04-29T14:55:58.000Z
2020-08-20T08:43:24.000Z
code/src/core/maths/util.hpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
1
2022-03-12T11:37:46.000Z
2022-03-12T20:17:38.000Z
code/src/core/maths/util.hpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
null
null
null
#pragma once #include <utility/type_traits.hpp> #include <cstdint> namespace core { namespace maths { template <typename T> struct constant { static const constexpr T pi = T(3.141592653589793238462643383279502884); }; using constantd = constant<double>; using constantf = constant<float>; template <typename T> class degree; template <typename T> class radian; template <typename T> class degree { public: using value_type = T; private: value_type value; public: degree() = default; explicit degree(const value_type value) : value(value) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value && mpl::is_different<U, T>::value>> degree(const degree<U> & degree) : value(degree.get()) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value>> degree(const radian<U> & radian) : value(value_type{radian.get()} / constant<value_type>::pi * value_type{180}) {} public: value_type get() const { return this->value; } public: friend radian<value_type> make_radian(const degree<value_type> & degree) { return radian<value_type>{value_type(degree.value / 180. * constantd::pi)}; } }; template <typename T> degree<T> make_degree(const T value) { return degree<T>{value}; } template <typename T, typename U> degree<T> make_degree(const degree<U> & degree) { return make_degree(T(degree.get())); } using degreef = degree<float>; using degreed = degree<double>; template <typename T> class radian { public: using value_type = T; private: value_type value; public: radian() = default; explicit radian(const value_type value) : value(value) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value && mpl::is_different<U, T>::value>> radian(const radian<U> & radian) : value(radian.get()) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value>> radian(const degree<U> & degree) : value(value_type{degree.get()} / value_type{180} * constant<value_type>::pi) {} public: value_type get() const { return this->value; } public: friend degree<value_type> make_degree(const radian<value_type> & radian) { return degree<value_type>{value_type(radian.value / constantd::pi * 180.)}; } }; template <typename T> radian<T> make_radian(const T value) { return radian<T>{value}; } template <typename T, typename U> radian<T> make_radian(const radian<U> & radian) { return make_radian(T(radian.get())); } using radianf = radian<float>; using radiand = radian<double>; inline constexpr int32_t interpolate_and_scale(int32_t min, int32_t max, int32_t x) { const uint32_t q = (2 * ((uint32_t(1) << 31) - 1)) / (uint32_t(max) - min); const uint32_t r = (2 * ((uint32_t(1) << 31) - 1)) % (uint32_t(max) - min); return (uint32_t(x) - min) * q - int32_t((uint32_t(1) << 31) - 1) + r * (uint32_t(x) - min) / (uint32_t(max) - min); } } }
25.699187
119
0.632711
shossjer
14b2618b82efd914bfe32ecdc0225c598ca0603d
439
cpp
C++
LargerString.cpp
Kalaiarasan-Hema/kalai
2e3060727f5a18d4ad85c3f81214805c3ed12f8e
[ "Apache-2.0" ]
null
null
null
LargerString.cpp
Kalaiarasan-Hema/kalai
2e3060727f5a18d4ad85c3f81214805c3ed12f8e
[ "Apache-2.0" ]
null
null
null
LargerString.cpp
Kalaiarasan-Hema/kalai
2e3060727f5a18d4ad85c3f81214805c3ed12f8e
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <iostream> using namespace std; class LargerString { int n,i,a=0; string s1,s2; void get() { cout<<"INPUT"<<endl; getline(cin,s1); getline(cin,s2); } void display() { cout<<"OUTPUT"<<endl; for(i=0;i<n;i++) { if(s1[i]>s2[i]) {cout<<s1;break;} else {cout<<s2;break;} } } public: LargerString() { get(); display(); } }; int main() { LargerString rs; return 0; }
11.864865
25
0.560364
Kalaiarasan-Hema
14b365fcf0c112818dbed3011888703a4ad4bf86
2,650
cpp
C++
winsys/textbox.cpp
fcarreiro/albertum
62d7c63bdcd59efd6aadc139d61c4569fb335544
[ "MIT" ]
null
null
null
winsys/textbox.cpp
fcarreiro/albertum
62d7c63bdcd59efd6aadc139d61c4569fb335544
[ "MIT" ]
null
null
null
winsys/textbox.cpp
fcarreiro/albertum
62d7c63bdcd59efd6aadc139d61c4569fb335544
[ "MIT" ]
null
null
null
#include "stdafx.h" /***********************************************************/ CTextBox::CTextBox() { ispassword=false; maxlen=0; prof=NULL; } CTextBox::~CTextBox() { } /***********************************************************/ bool CTextBox::wm_lbuttondown(int a_x, int a_y) { if(!CWindow::IsVisible()) return true; if( a_x < CWindow::x+CWindow::width+CWindow::parent->GetX() && a_x > CWindow::x+CWindow::parent->GetX() && a_y < CWindow::y+CWindow::height+CWindow::parent->GetY()+15 && a_y > CWindow::y+CWindow::parent->GetY()+15) { BringToTop(); } return true; } bool CTextBox::wm_keydown(char key) { if(!CWindow::IsActive() || !prof) return true; if(key>31) { if(maxlen) { if(CWindow::strCaption.length() >= maxlen) return true; } if(ispassword) { if(CWindow::strCaption.length()*(prof->metrics['*'].abcA+prof->metrics['*'].abcB+prof->metrics['*'].abcC)<width-10) CWindow::strCaption+=key; } else { if(_stringwidth(CWindow::strCaption.c_str(),(ABC*)&prof->metrics)<width-10) CWindow::strCaption+=key; } } else { if(key==8 && CWindow::strCaption.length()>0) CWindow::strCaption.erase(CWindow::strCaption.end()-1); } return true; } /***********************************************************/ bool CTextBox::Render(IDirectDrawSurface7* surface, PROFILE* prof) { RECT r,s; if(!IsVisible()) return true; s.top=0; s.left=81; s.right=120; s.bottom=15; r.top=CWindow::y+CWindow::parent->GetY()+15; r.left=CWindow::x+CWindow::parent->GetX(); r.right=CWindow::x+CWindow::parent->GetX()+CWindow::width; r.bottom=CWindow::y+CWindow::parent->GetY()+CWindow::height+15; back->Blt(&r, prof->sBitmap, &s, DDBLT_WAIT, NULL); if(!CWindow::IsActive()) { s.left+=40; s.right+=40; ++r.top; ++r.left; --r.right; --r.bottom; back->Blt(&r, prof->sBitmap, &s, DDBLT_WAIT, NULL); } else { // agregar cursor al final } if(CWindow::strCaption.length()==0) return true; if(!ispassword) { DXDrawText(CWindow::x+CWindow::parent->GetX()+2, CWindow::y+CWindow::parent->GetY()+17, CWindow::strCaption.c_str(), 12, NULL, CWindow::IsActive() ? 0xFFFFFF : 0x0, prof->fonthandle); } else { std::string asterisks; _fillstring(asterisks, strCaption, '*'); DXDrawText(CWindow::x+CWindow::parent->GetX()+2, CWindow::y+CWindow::parent->GetY()+17, asterisks.c_str(), 12, NULL, CWindow::IsActive() ? 0xFFFFFF : 0x0, prof->fonthandle); } return true; } /***********************************************************/
21.2
119
0.555094
fcarreiro
14b36efe9242e74ac6c6043d90227f4833511f91
5,513
cpp
C++
rviz_default_plugins/src/rviz_default_plugins/displays/pose/pose_display_selection_handler.cpp
romi2002/rviz
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/displays/pose/pose_display_selection_handler.cpp
romi2002/rviz
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/displays/pose/pose_display_selection_handler.cpp
romi2002/rviz
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
[ "BSD-3-Clause-Clear" ]
1
2020-04-29T07:08:07.000Z
2020-04-29T07:08:07.000Z
/* * Copyright (c) 2008, Willow Garage, Inc. * Copyright (c) 2018, Bosch Software Innovations GmbH. * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "rviz_default_plugins/displays/pose/pose_display_selection_handler.hpp" #ifdef _WIN32 # pragma warning(push) # pragma warning(disable:4996) #endif #include <OgreEntity.h> #ifdef _WIN32 # pragma warning(pop) #endif #include "rviz_rendering/objects/axes.hpp" #include "rviz_rendering/objects/arrow.hpp" #include "rviz_rendering/objects/shape.hpp" #include "rviz_common/interaction/selection_handler.hpp" #include "rviz_common/msg_conversions.hpp" #include "rviz_common/properties/vector_property.hpp" #include "rviz_common/properties/string_property.hpp" #include "rviz_common/properties/quaternion_property.hpp" #include "rviz_common/properties/enum_property.hpp" #include "rviz_common/display_context.hpp" #include "rviz_default_plugins/displays/pose/pose_display.hpp" namespace rviz_default_plugins { namespace displays { PoseDisplaySelectionHandler::PoseDisplaySelectionHandler( PoseDisplay * display, rviz_common::DisplayContext * context) : SelectionHandler(context), display_(display), frame_property_(nullptr), position_property_(nullptr), orientation_property_(nullptr) {} void PoseDisplaySelectionHandler::createProperties( const rviz_common::interaction::Picked & obj, rviz_common::properties::Property * parent_property) { (void) obj; rviz_common::properties::Property * cat = new rviz_common::properties::Property( "Pose " + display_->getName(), QVariant(), "", parent_property); properties_.push_back(cat); frame_property_ = new rviz_common::properties::StringProperty("Frame", "", "", cat); frame_property_->setReadOnly(true); position_property_ = new rviz_common::properties::VectorProperty( "Position", Ogre::Vector3::ZERO, "", cat); position_property_->setReadOnly(true); orientation_property_ = new rviz_common::properties::QuaternionProperty( "Orientation", Ogre::Quaternion::IDENTITY, "", cat); orientation_property_->setReadOnly(true); } rviz_common::interaction::V_AABB PoseDisplaySelectionHandler::getAABBs( const rviz_common::interaction::Picked & obj) { (void) obj; rviz_common::interaction::V_AABB aabbs; if (display_->pose_valid_) { /** with 'derive_world_bounding_box' set to 'true', the WorldBoundingBox is derived each time. setting it to 'false' results in the wire box not properly following the pose arrow, but it would be less computationally expensive. */ bool derive_world_bounding_box = true; if (display_->shape_property_->getOptionInt() == PoseDisplay::Arrow) { aabbs.push_back( display_->arrow_->getHead()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); aabbs.push_back( display_->arrow_->getShaft()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); } else { aabbs.push_back( display_->axes_->getXShape()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); aabbs.push_back( display_->axes_->getYShape()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); aabbs.push_back( display_->axes_->getZShape()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); } } return aabbs; } void PoseDisplaySelectionHandler::setMessage( geometry_msgs::msg::PoseStamped::ConstSharedPtr message) { // properties_.size() should only be > 0 after createProperties() // and before destroyProperties(), during which frame_property_, // position_property_, and orientation_property_ should be valid // pointers. if (properties_.size() > 0) { frame_property_->setStdString(message->header.frame_id); position_property_->setVector(rviz_common::pointMsgToOgre(message->pose.position)); orientation_property_->setQuaternion( rviz_common::quaternionMsgToOgre(message->pose.orientation)); } } } // namespace displays } // namespace rviz_default_plugins
40.536765
99
0.757482
romi2002
14b3e585a71ec7d513f1f6930eb9f51ae4c61d9c
588
cpp
C++
ch17/17_27.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch17/17_27.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch17/17_27.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
//exercise 17.27 //Write a program that reformats a nine-digit zip code as ddddd-dddd. #include <iostream> #include <regex> #include <string> using namespace std; string pattern = "(\\d{5})([.- ])?(\\d{4})"; string fmt = "$1-$3"; regex r(pattern); string s; int main(int argc, char const *argv[]) { while(getline(cin,s)) { smatch result; regex_search(s,result, r); if(!result.empty()) { cout<<result.format(fmt)<<endl; } else { cout<<"Sorry, No match."<<endl; } } return 0; }
16.333333
69
0.532313
zhang1990215
14b888620bbe845ebeb6d46313c059dd5d9b7b1f
2,282
hpp
C++
modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
82
2015-08-15T05:18:30.000Z
2019-04-11T15:18:06.000Z
modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
16
2015-08-13T09:38:34.000Z
2019-05-06T11:28:13.000Z
modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
86
2015-08-08T08:28:34.000Z
2019-04-18T08:27:22.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2020, Stefan Brüns <[email protected]> #ifndef _GRFMT_OPENJPEG_H_ #define _GRFMT_OPENJPEG_H_ #ifdef HAVE_OPENJPEG #include "grfmt_base.hpp" #include <openjpeg.h> namespace cv { namespace detail { struct OpjStreamDeleter { void operator()(opj_stream_t* stream) const { opj_stream_destroy(stream); } }; struct OpjCodecDeleter { void operator()(opj_codec_t* codec) const { opj_destroy_codec(codec); } }; struct OpjImageDeleter { void operator()(opj_image_t* image) const { opj_image_destroy(image); } }; struct OpjMemoryBuffer { OPJ_BYTE* pos{nullptr}; OPJ_BYTE* begin{nullptr}; OPJ_SIZE_T length{0}; OpjMemoryBuffer() = default; explicit OpjMemoryBuffer(cv::Mat& mat) : pos{ mat.ptr() }, begin{ mat.ptr() }, length{ mat.rows * mat.cols * mat.elemSize() } { } OPJ_SIZE_T availableBytes() const CV_NOEXCEPT { return begin + length - pos; } }; using StreamPtr = std::unique_ptr<opj_stream_t, detail::OpjStreamDeleter>; using CodecPtr = std::unique_ptr<opj_codec_t, detail::OpjCodecDeleter>; using ImagePtr = std::unique_ptr<opj_image_t, detail::OpjImageDeleter>; } // namespace detail class Jpeg2KOpjDecoder CV_FINAL : public BaseImageDecoder { public: Jpeg2KOpjDecoder(); ~Jpeg2KOpjDecoder() CV_OVERRIDE = default; ImageDecoder newDecoder() const CV_OVERRIDE; bool readData( Mat& img ) CV_OVERRIDE; bool readHeader() CV_OVERRIDE; private: detail::StreamPtr stream_{nullptr}; detail::CodecPtr codec_{nullptr}; detail::ImagePtr image_{nullptr}; detail::OpjMemoryBuffer opjBuf_; OPJ_UINT32 m_maxPrec = 0; }; class Jpeg2KOpjEncoder CV_FINAL : public BaseImageEncoder { public: Jpeg2KOpjEncoder(); ~Jpeg2KOpjEncoder() CV_OVERRIDE = default; bool isFormatSupported( int depth ) const CV_OVERRIDE; bool write( const Mat& img, const std::vector<int>& params ) CV_OVERRIDE; ImageEncoder newEncoder() const CV_OVERRIDE; }; } //namespace cv #endif #endif/*_GRFMT_OPENJPEG_H_*/
22.82
94
0.705083
artun3e
14ba48f492acad0e0b28b660d08abb08276c3eaa
37,523
cpp
C++
src/RenderEngine/Particles/CreatorPlugins.cpp
Shimrra/alo-viewer
16fb9ab094e6a93db55199d210b43089fb4f25a0
[ "MIT" ]
11
2017-01-18T08:58:52.000Z
2021-11-12T16:23:28.000Z
src/RenderEngine/Particles/CreatorPlugins.cpp
TheSuperPlayer/alo-viewer
616cb5a330453a50501d730d28c92059b1121651
[ "MIT" ]
2
2020-06-25T01:35:44.000Z
2020-06-25T01:38:44.000Z
src/RenderEngine/Particles/CreatorPlugins.cpp
TheSuperPlayer/alo-viewer
616cb5a330453a50501d730d28c92059b1121651
[ "MIT" ]
6
2017-02-06T18:12:09.000Z
2021-12-24T16:38:34.000Z
#include "RenderEngine/Particles/CreatorPlugins.h" #include "RenderEngine/Particles/ParticleSystem.h" #include "RenderEngine/Particles/PluginDefs.h" #include "RenderEngine/RenderEngine.h" #include "General/Exceptions.h" #include "General/Math.h" #include "General/Log.h" using namespace std; namespace Alamo { static const int ALIGNMENT_NONE = 0; static const int ALIGNMENT_FORWARD = 1; static const int ALIGNMENT_REVERSE = 2; static Matrix MakeAlignmentMatrix(const Vector3& dir) { return Matrix( Quaternion(Vector3(0, 0,1), PI/2) * Quaternion(Vector3(0, 1,0), PI/2 - dir.tilt()) * Quaternion(Vector3(0, 0,1), dir.zAngle()) ); } void PropertyGroup::Read(ChunkReader& reader) { if (reader.group()) { Verify(reader.next() == 1); Read(reader); Verify(reader.next() == -1); return; } m_type = (Type)reader.readInteger(); m_point = reader.readVector3(); m_position = reader.readVector3(); m_magnitude.min = reader.readFloat(); m_magnitude.max = reader.readFloat(); m_radius.min = reader.readFloat(); m_radius.max = reader.readFloat(); m_minPosition = reader.readVector3(); m_maxPosition = reader.readVector3(); m_sphereAngle.min = PI/2 * (1.0f - reader.readFloat()); m_sphereAngle.max = PI/2 * (1.0f - reader.readFloat()); m_sphereRadius.min = reader.readFloat(); m_sphereRadius.max = reader.readFloat(); m_cylRadius = reader.readFloat(); m_cylHeight.min = reader.readFloat(); m_cylHeight.max = reader.readFloat(); m_torusRadius = reader.readFloat(); m_tubeRadius = reader.readFloat(); } Vector3 PropertyGroup::SampleTorus(float torusRadius, float tubeRadius, bool hollow) { float radius = (hollow) ? tubeRadius : GetRandom(0.0f, tubeRadius); float zAngle = GetRandom(0.0f, 2*PI); Vector2 circle(GetRandom(0.0f, 2*PI)); circle.x = circle.x * radius + torusRadius; return Vector3( cos(zAngle) * circle.x, sin(zAngle) * circle.x, circle.y * radius); } Vector3 PropertyGroup::Sample(bool hollow) const { switch (m_type) { case DIRECTION: { float magnitude = (hollow) ? ((GetRandom(0.0f, 1.0f) < 0.5f) ? m_magnitude.min : m_magnitude.max) : GetRandom(m_magnitude.min, m_magnitude.max); return normalize(m_position) * magnitude; } case SPHERE: { float radius = (hollow) ? m_radius.max : GetRandom(m_radius.min, m_radius.max); return Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * radius; } case RANGE: return Vector3( GetRandom(m_minPosition.x, m_maxPosition.x), GetRandom(m_minPosition.y, m_maxPosition.y), GetRandom(m_minPosition.z, m_maxPosition.z) ); case SPHERICAL_RANGE: { float tilt, radius; if (!hollow) { tilt = GetRandom(m_sphereAngle .min, m_sphereAngle .max); radius = GetRandom(m_sphereRadius.min, m_sphereRadius.max); } else switch (GetRandom(0,100) % (m_sphereAngle.min == 0 ? 3 : 4)) { case 0: radius = m_sphereRadius.max; tilt = GetRandom(m_sphereAngle.min, m_sphereAngle.max); break; case 1: radius = m_sphereRadius.min; tilt = GetRandom(m_sphereAngle.min, m_sphereAngle.max); break; case 2: radius = GetRandom(m_sphereRadius.min, m_sphereRadius.max); tilt = m_sphereAngle.max; break; case 3: radius = GetRandom(m_sphereRadius.min, m_sphereRadius.max); tilt = m_sphereAngle.min; break; } float zAngle = GetRandom(0.0f, 2*PI); return Vector3(zAngle, tilt) * radius; } case CYLINDER: { float radius = (hollow) ? m_cylRadius : GetRandom(0.0f, m_cylRadius); return Vector3( Vector2(GetRandom(0.0f, 2*PI)) * radius, GetRandom(m_cylHeight.min, m_cylHeight.max) ); } case TORUS: return SampleTorus(m_torusRadius, m_tubeRadius, hollow); } return m_point; } // // PointCreatorPlugin // void PointCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); END_PARAM_LIST } float PointCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float PointCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long PointCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void PointCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3(0,0,0); p->velocity = Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void PointCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* PointCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void PointCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } PointCreatorPlugin::PointCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // TrailCreatorPlugin // void TrailCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_INT (100, m_parent); END_PARAM_LIST } float TrailCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float TrailCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long TrailCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void TrailCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { assert(parent != NULL); const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3(0,0,0); p->velocity = Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += parent->position; } void TrailCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* TrailCreatorPlugin::Initialize() { ParticleSystem& system = m_emitter.GetSystem(); if (m_parent < system.GetNumEmitters()) { return system.GetEmitter(m_parent).RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_BIRTH); } return NULL; } void TrailCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } TrailCreatorPlugin::TrailCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // SphereCreatorPlugin // void SphereCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_FLOAT(100, m_radius); END_PARAM_LIST } float SphereCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float SphereCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long SphereCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void SphereCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * m_radius; p->velocity = normalize(p->position) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void SphereCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* SphereCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void SphereCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } SphereCreatorPlugin::SphereCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // BoxCreatorPlugin // void BoxCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_FLOAT(100, m_length); PARAM_FLOAT(101, m_width); PARAM_FLOAT(102, m_height); END_PARAM_LIST } float BoxCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float BoxCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long BoxCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void BoxCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3( GetRandom(-0.5f, 0.5f) * m_length, GetRandom(-0.5f, 0.5f) * m_width, GetRandom(-0.5f, 0.5f) * m_height); p->velocity = normalize(p->position) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void BoxCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* BoxCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void BoxCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } BoxCreatorPlugin::BoxCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // TorusCreatorPlugin // void TorusCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_FLOAT(100, m_torusRadius); PARAM_FLOAT(101, m_tubeRadius); END_PARAM_LIST } float TorusCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float TorusCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long TorusCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void TorusCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = PropertyGroup::SampleTorus(m_torusRadius, m_tubeRadius, false); p->velocity = normalize(p->position) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void TorusCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* TorusCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void TorusCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } TorusCreatorPlugin::TorusCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // MeshCreatorPlugin // struct MeshCreatorBase::MeshCreatorData { const IRenderObject* m_object; const Model::Mesh* m_mesh; size_t m_subMesh; size_t m_vertex; }; void MeshCreatorBase::InitializeParticle(Particle* p, MeshCreatorData* data) const { p->position = Vector3(0,0,0); if (data->m_mesh != NULL) { const Model::Mesh* mesh = data->m_mesh; MASTER_VERTEX tmp; const MASTER_VERTEX* v = &tmp; switch (m_spawnLocation) { case MESH_ALL_VERTICES: v = &mesh->subMeshes[data->m_subMesh].vertices[data->m_vertex]; // Go to next vertex if (++data->m_vertex == mesh->subMeshes[data->m_subMesh].vertices.size()) { data->m_vertex = 0; data->m_subMesh = (data->m_subMesh + 1) % mesh->subMeshes.size(); } break; case MESH_RANDOM_VERTEX: { // Pick random submesh and vertex int subMesh = GetRandom(0, (int)mesh->subMeshes.size()); int vertex = GetRandom(0, (int)mesh->subMeshes[subMesh].vertices.size()); v = &mesh->subMeshes[subMesh].vertices[vertex]; break; } case MESH_RANDOM_SURFACE: { // Pick random submesh int subMesh = GetRandom(0, (int)mesh->subMeshes.size()); const Model::SubMesh& submesh = mesh->subMeshes[subMesh]; // Pick random face on submesh int face = GetRandom(0, (int)submesh.indices.size() / 3) * 3; const MASTER_VERTEX& v1 = submesh.vertices[submesh.indices[face + 0]]; const MASTER_VERTEX& v2 = submesh.vertices[submesh.indices[face + 1]]; const MASTER_VERTEX& v3 = submesh.vertices[submesh.indices[face + 2]]; // Pick random position on face (barycentric coordinates) float w1 = GetRandom(0.0f, 1.0f); float w2 = GetRandom(0.0f, 1.0f - w1); float w3 = 1.0f - w2 - w1; tmp.Position = v1.Position * w1 + v2.Position * w2 + v3.Position * w3; tmp.Normal = v1.Normal * w1 + v2.Normal * w2 + v3.Normal * w3; break; } } // Initialize particle based on vertex v const Matrix transform = data->m_object->GetBoneTransform(mesh->bone->index); Vector3 normal = Vector4(v->Normal, 0) * transform; Vector3 position = Vector4(v->Position, 1) * transform; p->position = position + normal * m_surfaceOffset; if (m_alignVelocityToNormal) { // Rotate +Z to normal p->velocity = Vector4(p->velocity, 0) * MakeAlignmentMatrix(normal); } } } MeshCreatorBase::MeshCreatorBase() { m_spawnLocation = MESH_RANDOM_SURFACE; m_alignVelocityToNormal = true; m_surfaceOffset = 0.0f; } void MeshCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); END_PARAM_LIST } float MeshCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float MeshCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long MeshCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void MeshCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->velocity = Vector3(0,0,speed); MeshCreatorBase::InitializeParticle(p, (MeshCreatorData*)data); p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; } size_t MeshCreatorPlugin::GetPrivateDataSize() const { return sizeof(MeshCreatorData); } void MeshCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { MeshCreatorData* mcd = (MeshCreatorData*)data; mcd->m_object = object; mcd->m_mesh = mesh; mcd->m_vertex = 0; mcd->m_subMesh = 0; } ParticleSystem::Emitter* MeshCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void MeshCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } MeshCreatorPlugin::MeshCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // ShapeCreatorPlugin // void ShapeCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); END_PARAM_LIST } float ShapeCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return (m_stopTime == 0 || currentTime < m_stopTime) ? (!m_bursting ? m_spawnInterval / m_particlePerInterval : m_spawnInterval) : -1; } float ShapeCreatorPlugin::GetInitialSpawnDelay(void* data) const { return m_startDelay; } unsigned long ShapeCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return m_bursting ? (unsigned long)m_particlePerInterval : 1; } void ShapeCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); p->spawnTime = time; p->position = Vector4(m_position.Sample(m_hollowPosition), 1) * transform; p->velocity = m_velocity.Sample(m_hollowVelocity); if (m_localVelocity) { p->velocity = Vector4(p->velocity, 0) * transform; } if (parent != NULL) { if (m_inheritVelocity) { float speed = parent->velocity.length(); p->velocity += normalize(parent->velocity) * min(speed * m_inheritedVelocityScale, m_maxInheritedVelocity); } // Add parent position (relative to emitter, otherwise we add emitter twice) p->position += parent->position - transform.getTranslation(); } p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; } void ShapeCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* ShapeCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } ShapeCreatorPlugin::ShapeCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } ShapeCreatorPlugin::ShapeCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params) : CreatorPlugin(emitter), ShapeCreator(params) { } // // OutwardVelocityShapeCreatorPlugin // void OutwardVelocityShapeCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_BOOL (300, m_outwardSpeed); END_PARAM_LIST } void OutwardVelocityShapeCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); } OutwardVelocityShapeCreatorPlugin::OutwardVelocityShapeCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter) { const string& name = emitter.GetSystem().GetName(); Log::WriteInfo("\"%s\" uses currently partially supported creator plugin", name.c_str()); } // // DeathCreatorPlugin // void DeathCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_CUSTOM(101, m_position); PARAM_BOOL (102, m_hollowPosition); PARAM_CUSTOM(103, m_velocity); PARAM_BOOL (104, m_hollowVelocity); PARAM_BOOL (105, m_localVelocity); PARAM_BOOL (106, m_inheritVelocity); PARAM_FLOAT (107, m_inheritedVelocityScale); PARAM_FLOAT (108, m_maxInheritedVelocity); PARAM_STRING(109, m_parentName); PARAM_INT (110, m_positionAlignment); PARAM_INT (111, m_velocityAlignment); END_PARAM_LIST } float DeathCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return -1; } float DeathCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } void DeathCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { assert(parent != NULL); ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); if (m_positionAlignment != ALIGNMENT_NONE || m_velocityAlignment != ALIGNMENT_NONE) { // Align Z with particle velocity vector if (m_velocityAlignment != ALIGNMENT_NONE) { p->velocity *= MakeAlignmentMatrix( (m_velocityAlignment == ALIGNMENT_REVERSE) ? -parent->velocity : parent->velocity); } if (m_positionAlignment != ALIGNMENT_NONE) { p->position *= MakeAlignmentMatrix( (m_positionAlignment == ALIGNMENT_REVERSE) ? -parent->position : parent->position); } } } ParticleSystem::Emitter* DeathCreatorPlugin::Initialize() { ParticleSystem& system = m_emitter.GetSystem(); if (m_parentEmitter != NULL) { return m_parentEmitter->RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_DEATH); } for (size_t i = 0; i < system.GetNumEmitters(); i++) { ParticleSystem::Emitter& e = system.GetEmitter(i); if (e.GetName() == m_parentName) { return e.RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_DEATH); } } return NULL; } DeathCreatorPlugin::DeathCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter), m_parentEmitter(NULL) { m_spawnInterval = 1.0f; m_bursting = true; m_startDelay = 0.0f; m_stopTime = 0.5f; m_hiresEmission = false; m_burstOnShown = true; } DeathCreatorPlugin::DeathCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params, ParticleSystem::Emitter* parentEmitter) : ShapeCreatorPlugin(emitter, params), m_parentEmitter(parentEmitter), m_positionAlignment(ALIGNMENT_NONE), m_velocityAlignment(ALIGNMENT_NONE) { m_spawnInterval = 1.0f; m_bursting = true; m_startDelay = 0.0f; m_stopTime = 0.5f; m_hiresEmission = false; m_burstOnShown = true; m_inheritVelocity = false; } // // EnhancedTrailCreatorPlugin // void EnhancedTrailCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_STRING(300, m_parentName); PARAM_INT (301, m_positionAlignment); PARAM_INT (302, m_velocityAlignment); END_PARAM_LIST } void EnhancedTrailCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { assert(parent != NULL); ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); if (m_positionAlignment != ALIGNMENT_NONE || m_velocityAlignment != ALIGNMENT_NONE) { // Align Z with particle velocity vector if (m_velocityAlignment != ALIGNMENT_NONE) { p->velocity *= MakeAlignmentMatrix( (m_velocityAlignment == ALIGNMENT_REVERSE) ? -parent->velocity : parent->velocity); } if (m_positionAlignment != ALIGNMENT_NONE) { p->position *= MakeAlignmentMatrix( (m_positionAlignment == ALIGNMENT_REVERSE) ? -parent->position : parent->position); } } } ParticleSystem::Emitter* EnhancedTrailCreatorPlugin::Initialize() { ParticleSystem& system = m_emitter.GetSystem(); if (m_parentEmitter != NULL) { return m_parentEmitter->RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_BIRTH); } for (size_t i = 0; i < system.GetNumEmitters(); i++) { ParticleSystem::Emitter& e = system.GetEmitter(i); if (e.GetName() == m_parentName) { return e.RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_BIRTH); } } return NULL; } EnhancedTrailCreatorPlugin::EnhancedTrailCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter), m_parentEmitter(NULL) { } EnhancedTrailCreatorPlugin::EnhancedTrailCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params, ParticleSystem::Emitter* parentEmitter) : ShapeCreatorPlugin(emitter, params), m_parentEmitter(parentEmitter), m_positionAlignment(ALIGNMENT_NONE), m_velocityAlignment(ALIGNMENT_NONE) { } // // EnhancedMeshCreatorPlugin // void EnhancedMeshCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_INT (105, m_spawnLocation); PARAM_BOOL (106, m_alignVelocityToNormal); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_FLOAT (200, m_surfaceOffset); END_PARAM_LIST } size_t EnhancedMeshCreatorPlugin::GetPrivateDataSize() const { return sizeof(MeshCreatorData); } unsigned long EnhancedMeshCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { MeshCreatorData* mcd = (MeshCreatorData*)data; unsigned long base = (mcd->m_mesh != NULL && m_spawnLocation == MESH_ALL_VERTICES ? (unsigned long)mcd->m_mesh->nVertices : 1); return base * ShapeCreatorPlugin::GetNumParticlesPerSpawn(data); } void EnhancedMeshCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); p->spawnTime = time; p->velocity = m_velocity.Sample(m_hollowVelocity); if (m_localVelocity) { p->velocity = Vector4(p->velocity, 0) * transform; } MeshCreatorBase::InitializeParticle(p, (MeshCreatorData*)data); p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; } void EnhancedMeshCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { MeshCreatorData* mcd = (MeshCreatorData*)data; mcd->m_object = object; mcd->m_mesh = mesh; mcd->m_vertex = 0; mcd->m_subMesh = 0; } EnhancedMeshCreatorPlugin::EnhancedMeshCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter) { m_position.m_type = PropertyGroup::POINT; m_position.m_point = Vector3(0,0,0); m_hollowPosition = false; } EnhancedMeshCreatorPlugin::EnhancedMeshCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params, unsigned long spawnLocation, float surfaceOffset) : ShapeCreatorPlugin(emitter, params) { m_spawnLocation = spawnLocation; m_surfaceOffset = surfaceOffset; m_alignVelocityToNormal = true; } // // HardwareSpawnerCreatorPlugin // void HardwareSpawnerCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (6000, m_particleCount); PARAM_FLOAT (6001, m_particleLifetime); PARAM_BOOL (6002, m_enableBursting); PARAM_CUSTOM(6003, m_position); PARAM_BOOL (6004, m_hollowPosition); PARAM_CUSTOM(6005, m_velocity); PARAM_BOOL (6006, m_hollowVelocity); PARAM_FLOAT3(6007, m_acceleration); PARAM_FLOAT (6008, m_attractAcceleration); PARAM_FLOAT3(6009, m_vortexAxis); PARAM_FLOAT (6010, m_vortexRotation); PARAM_FLOAT (6011, m_vortexAttraction); END_PARAM_LIST } float HardwareSpawnerCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return -1; } float HardwareSpawnerCreatorPlugin::GetInitialSpawnDelay(void* data) const { return -1; } unsigned long HardwareSpawnerCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return 0; } void HardwareSpawnerCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { } void HardwareSpawnerCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* HardwareSpawnerCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } HardwareSpawnerCreatorPlugin::HardwareSpawnerCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { const string& name = emitter.GetSystem().GetName(); Log::WriteInfo("\"%s\" uses currently unsupported creator plugin", name.c_str()); } // // AlignedShapeCreatorPlugin // void AlignedShapeCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_INT (200, m_positionAlignmentDirection); PARAM_INT (201, m_positionAlignment); PARAM_INT (202, m_velocityAlignmentDirection); PARAM_INT (203, m_velocityAlignment); PARAM_STRING(204, m_bone); END_PARAM_LIST } void AlignedShapeCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); } AlignedShapeCreatorPlugin::AlignedShapeCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter) { const string& name = emitter.GetSystem().GetName(); Log::WriteInfo("\"%s\" uses currently partially supported creator plugin", name.c_str()); } }
31.295246
156
0.677451
Shimrra
14be001cf3118bccaf3497cd6e40aefc040febf4
10,685
cpp
C++
lib/src/EBAMRTools/EBCoarToCoarRedist.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
10
2018-02-01T20:57:36.000Z
2022-03-17T02:57:49.000Z
lib/src/EBAMRTools/EBCoarToCoarRedist.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
19
2018-10-04T21:37:18.000Z
2022-02-25T16:20:11.000Z
lib/src/EBAMRTools/EBCoarToCoarRedist.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
11
2019-01-12T23:33:32.000Z
2021-08-09T15:19:50.000Z
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include "EBCoarToCoarRedist.H" #include "LayoutIterator.H" #include "BaseIVFactory.H" #include "VoFIterator.H" #include "EBCellFactory.H" #include "CH_Timer.H" #include "NamespaceHeader.H" /***********************/ /***********************/ void EBCoarToCoarRedist:: resetWeights(const LevelData<EBCellFAB>& a_modifier, const int& a_ivar) { CH_TIME("EBCoarToCoarRedist::resetWeights"); CH_assert(isDefined()); Interval srcInterv(a_ivar, a_ivar); Interval dstInterv(0,0); a_modifier.copyTo(srcInterv, m_densityCoar, dstInterv); //set the weights to mass weighting if the modifier //is the coarse density. for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { const IntVectSet& coarSet = m_setsCoar[dit()]; BaseIVFAB<VoFStencil>& massStenFAB = m_stenCoar[dit()]; const BaseIVFAB<VoFStencil>& volStenFAB = m_volumeStenc[dit()]; const BaseIVFAB<VoFStencil>& stanStenFAB = m_standardStenc[dit()]; const EBISBox& ebisBox = m_ebislCoar[dit()]; const EBCellFAB& modFAB = m_densityCoar[dit()]; for (VoFIterator vofit(coarSet, ebisBox.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& thisVoF = vofit(); VoFStencil stanSten = stanStenFAB(thisVoF, 0); VoFStencil oldSten = volStenFAB(thisVoF, 0); VoFStencil newSten; for (int isten = 0; isten < oldSten.size(); isten++) { const VolIndex& thatVoF = oldSten.vof(isten); Real weight =modFAB(thatVoF, a_ivar); newSten.add(thatVoF, weight); } //need normalize by the whole standard stencil Real sum = 0.0; for (int isten = 0; isten < stanSten.size(); isten++) { const VolIndex& thatVoF = stanSten.vof(isten); Real weight = modFAB(thatVoF, 0); Real volfrac = ebisBox.volFrac(thatVoF); //it is weight*volfrac that is normalized sum += weight*volfrac; } if (Abs(sum) > 0.0) { Real scaling = 1.0/sum; newSten *= scaling; } massStenFAB(thisVoF, 0) = newSten; } } } /**********************/ EBCoarToCoarRedist:: EBCoarToCoarRedist() { m_isDefined = false; } /**********************/ EBCoarToCoarRedist:: ~EBCoarToCoarRedist() { } /**********************/ void EBCoarToCoarRedist:: define(const DisjointBoxLayout& a_dblFine, const DisjointBoxLayout& a_dblCoar, const EBISLayout& a_ebislCoar, const Box& a_domainCoar, const int& a_nref, const int& a_nvar, int a_redistRad) { CH_TIME("EBCoarToCoarRedist::define"); m_isDefined = true; m_nComp = a_nvar; m_refRat = a_nref; m_domainCoar = a_domainCoar; m_gridsCoar = a_dblCoar; m_ebislCoar = a_ebislCoar; m_redistRad = a_redistRad; //define the intvectsets over which the objects live m_setsCoar.define(m_gridsCoar); m_stenCoar.define(m_gridsCoar); m_volumeStenc.define(m_gridsCoar); m_standardStenc.define(m_gridsCoar); //make sets for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { Box gridBox = m_gridsCoar.get(dit()); gridBox.grow(a_redistRad); gridBox &= m_domainCoar; //find the complement of what we really want IntVectSet ivsComplement(gridBox); for (LayoutIterator litFine = a_dblFine.layoutIterator(); litFine.ok(); ++litFine) { Box projBox = coarsen(a_dblFine.get(litFine()), m_refRat); ivsComplement -= projBox; } //now the set we want is the gridbox - complement IntVectSet& coarSet = m_setsCoar[dit()]; coarSet = IntVectSet(gridBox); coarSet -= ivsComplement; IntVectSet irregIVS = m_ebislCoar[dit()].getIrregIVS(gridBox); coarSet &= irregIVS; } defineDataHolders(); //initialize the buffers to zero setToZero(); } /**********************/ void EBCoarToCoarRedist:: define(const EBLevelGrid& a_eblgFine, const EBLevelGrid& a_eblgCoar, const int& a_nref, const int& a_nvar, const int& a_redistRad) { CH_TIME("EBCoarToCoarRedist::define"); m_isDefined = true; m_nComp = a_nvar; m_refRat = a_nref; m_redistRad = a_redistRad; m_domainCoar= a_eblgCoar.getDomain().domainBox(); m_gridsCoar = a_eblgCoar.getDBL(); m_ebislCoar = a_eblgCoar.getEBISL(); //define the intvectsets over which the objects live //make sets. m_setsCoar.define(m_gridsCoar); //need the set of points under the fine grid that //will redistribute to this box IntVectSet coveringIVS = a_eblgFine.getCoveringIVS(); coveringIVS.coarsen(m_refRat); for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { Box gridBox = m_gridsCoar.get(dit()); gridBox.grow(a_redistRad); gridBox &= m_domainCoar; m_setsCoar[dit()] = m_ebislCoar[dit()].getIrregIVS(gridBox); m_setsCoar[dit()] &= coveringIVS; } defineDataHolders(); //initialize the buffers to zero setToZero(); } /***/ void EBCoarToCoarRedist:: defineDataHolders() { CH_TIME("EBCoarToCoarRedist::defineDataHolders"); EBCellFactory ebcellfactcoar(m_ebislCoar); m_densityCoar.define(m_gridsCoar, 1, 2*m_redistRad*IntVect::Unit, ebcellfactcoar); m_stenCoar.define(m_gridsCoar); m_volumeStenc.define(m_gridsCoar); m_standardStenc.define(m_gridsCoar); RedistStencil rdStenCoar(m_gridsCoar, m_ebislCoar, m_domainCoar, m_redistRad); for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { BaseIVFAB<VoFStencil>& stenFAB = m_stenCoar[dit()]; BaseIVFAB<VoFStencil>& volStenFAB = m_volumeStenc[dit()]; BaseIVFAB<VoFStencil>& stanStenFAB = m_standardStenc[dit()]; const EBISBox& ebisBox = m_ebislCoar[dit()]; const IntVectSet& ivs = m_setsCoar[dit()]; const BaseIVFAB<VoFStencil>& rdStenFAB = rdStenCoar[dit()]; const Box& gridCoar = m_gridsCoar.get(dit()); stenFAB.define( ivs, ebisBox.getEBGraph(), 1); volStenFAB.define( ivs, ebisBox.getEBGraph(), 1); stanStenFAB.define(ivs, ebisBox.getEBGraph(), 1); for (VoFIterator vofit(ivs, ebisBox.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& srcVoF = vofit(); VoFStencil newStencil; const VoFStencil& stanSten = rdStenFAB(srcVoF, 0); for (int istan = 0; istan < stanSten.size(); istan++) { const VolIndex& dstVoF = stanSten.vof(istan); const Real& weight = stanSten.weight(istan); if (gridCoar.contains(dstVoF.gridIndex())) { newStencil.add(dstVoF, weight); } } //set both to volume weighted. can be changed later stenFAB(srcVoF, 0) = newStencil; volStenFAB(srcVoF, 0) = newStencil; stanStenFAB(srcVoF, 0) = stanSten; } } BaseIVFactory<Real> factCoar(m_ebislCoar, m_setsCoar); IntVect ivghost = m_redistRad*IntVect::Unit; m_regsCoar.define(m_gridsCoar, m_nComp, ivghost, factCoar); } /**********************/ void EBCoarToCoarRedist:: setToZero() { CH_TIME("EBCoarToCoarRedist::setToZero"); for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { m_regsCoar[dit()].setVal(0.0); } } /**********************/ void EBCoarToCoarRedist:: increment(const BaseIVFAB<Real>& a_coarMass, const DataIndex& a_coarDataIndex, const Interval& a_variables) { CH_TIME("EBCoarToCoarRedist::increment"); BaseIVFAB<Real>& coarBuf = m_regsCoar[a_coarDataIndex]; const EBISBox& ebisBox = m_ebislCoar[a_coarDataIndex]; const Box& gridBox = m_gridsCoar.get(a_coarDataIndex); IntVectSet ivs = ebisBox.getIrregIVS(gridBox); const IntVectSet& fabIVS = a_coarMass.getIVS(); const IntVectSet& bufIVS = m_setsCoar[a_coarDataIndex]; CH_assert(fabIVS.contains(ivs)); //only a subset of our points are in the set (only the ones covered by finer grids). ivs &= bufIVS; for (VoFIterator vofit(ivs, ebisBox.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& vof = vofit(); for (int ivar = a_variables.begin(); ivar <= a_variables.end(); ivar++) { coarBuf(vof, ivar) += a_coarMass(vof, ivar); } } } /**********************/ void EBCoarToCoarRedist:: redistribute(LevelData<EBCellFAB>& a_coarSolution, const Interval& a_variables) { CH_TIME("EBCoarToCoarRedist::redistribute"); m_regsCoar.exchange(a_variables); //at all points in the buffer, subtract off the redistributed values for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { const BaseIVFAB<Real>& regCoar = m_regsCoar[dit()]; const IntVectSet& ivsCoar = m_setsCoar[dit()]; const EBISBox& ebisBoxCoar = m_ebislCoar[dit()]; const BaseIVFAB<VoFStencil>& stenFAB = m_stenCoar[dit()]; const Box& coarBox = m_gridsCoar.get(dit()); EBCellFAB& solFAB = a_coarSolution[dit()]; for (VoFIterator vofit(ivsCoar,ebisBoxCoar.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& srcVoF = vofit(); const VoFStencil& vofsten = stenFAB(srcVoF, 0); for (int isten = 0; isten < vofsten.size(); isten++) { const Real& weight = vofsten.weight(isten); const VolIndex& dstVoF = vofsten.vof(isten); //since we are just using the input redist stencil, //have to check if out of bounds if (coarBox.contains(dstVoF.gridIndex())) { for (int ivar = a_variables.begin(); ivar <= a_variables.end(); ivar++) { Real dmFine = regCoar(srcVoF, ivar); //ucoar+= massfine/volcoar, ie. //ucoar+= (wcoar*dmCoar*volFracfine/volfraccoar)=massfine/volcoar Real dUCoar = dmFine*weight; //SUBTRACTING because this is re-redistribution. solFAB(dstVoF, ivar) -= dUCoar; } } } } } } /**********************/ bool EBCoarToCoarRedist:: isDefined() const { return m_isDefined; } /**********************/ #include "NamespaceFooter.H"
32.776074
87
0.611418
rmrsk
14c023b1f14cb5937e594eaa32b8870fdd3cf503
5,458
cpp
C++
D3D12_ModelAnimation/asdx/src/formats/asdxResMAT.cpp
ProjectAsura/D3D12Samples
f4756807106e998ec2de7621fdd9125582859ae9
[ "MIT" ]
12
2016-11-03T08:38:57.000Z
2022-02-19T01:31:22.000Z
D3D12_ModelAnimation/asdx/src/formats/asdxResMAT.cpp
ProjectAsura/D3D12Samples
f4756807106e998ec2de7621fdd9125582859ae9
[ "MIT" ]
null
null
null
D3D12_ModelAnimation/asdx/src/formats/asdxResMAT.cpp
ProjectAsura/D3D12Samples
f4756807106e998ec2de7621fdd9125582859ae9
[ "MIT" ]
13
2017-05-15T12:34:50.000Z
2021-11-30T13:28:04.000Z
//------------------------------------------------------------------------------------------------- // File : asdxResMAT.cpp // Desc : Project Asura MaterialSet Data Format (*.mts) Loader // Copyright(c) Project Asura. All right reserved. //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- // Includes //------------------------------------------------------------------------------------------------- #include <asdxLogger.h> #include "asdxResMAT.h" namespace /* anonymous */ { //------------------------------------------------------------------------------------------------- // Constant Values. //------------------------------------------------------------------------------------------------- static constexpr u32 MAT_VERSION = 0x000001; /////////////////////////////////////////////////////////////////////////////////////////////////// // MAT_FILE_HEADER structure /////////////////////////////////////////////////////////////////////////////////////////////////// struct MAT_FILE_HEADER { u8 Magic[4]; //!< マジックです. 'M', 'A', 'T', '\0' u32 Version; //!< ファイルバージョンです. }; /////////////////////////////////////////////////////////////////////////////////////////////////// // MAT_FILE_PATH structure /////////////////////////////////////////////////////////////////////////////////////////////////// struct MAT_FILE_PATH { char16 Path[256]; //!< パス名です. }; /////////////////////////////////////////////////////////////////////////////////////////////////// // MAT_MATERIAL structure /////////////////////////////////////////////////////////////////////////////////////////////////// struct MAT_MATERIAL { u32 PathCount; //!< テクスチャ数です. u32 PhongCount; //!< Phong BRDF 数です. u32 DisneyCount; //!< Disney BRDF 数です. }; } // namespace /* anonymous */ namespace asdx { //------------------------------------------------------------------------------------------------- // MATファイルからマテリアルリソースを読み込みます. //------------------------------------------------------------------------------------------------- bool LoadResMaterialFromMAT( const char16* filename, ResMaterial* pResult ) { if ( filename == nullptr || pResult == nullptr ) { ELOG( "Error : Invalid Argument." ); return false; } FILE* pFile; auto err = _wfopen_s( &pFile, filename, L"rb" ); if ( err != 0 ) { ELOG( "Error : File Open Failed. filename = %s", filename ); return false; } MAT_FILE_HEADER header; fread( &header, sizeof(header), 1, pFile ); if ( header.Magic[0] != 'M' || header.Magic[1] != 'A' || header.Magic[2] != 'T' || header.Magic[3] != '\0' ) { ELOG( "Error : Invalid File." ); fclose( pFile ); return false; } if ( header.Version != MAT_VERSION ) { ELOG( "Error : Invalid File Version." ); fclose( pFile ); return false; } MAT_MATERIAL material; fread( &material, sizeof(material), 1, pFile ); (*pResult).Paths .resize( material.PathCount ); (*pResult).Phong .resize( material.PhongCount ); (*pResult).Disney.resize( material.DisneyCount ); for( u32 i=0; i<material.PathCount; ++i ) { MAT_FILE_PATH texture; fread( &texture, sizeof(texture), 1, pFile ); (*pResult).Paths[i] = texture.Path; } for( u32 i=0; i<material.PhongCount; ++i ) { fread( &(*pResult).Phong[i], sizeof(ResPhong), 1, pFile ); } for( u32 i=0; i<material.DisneyCount; ++i ) { fread( &(*pResult).Disney[i], sizeof(ResDisney), 1, pFile ); } fclose( pFile ); return true; } //------------------------------------------------------------------------------------------------- // MATファイルに保存します. //------------------------------------------------------------------------------------------------- bool SaveResMaterialToMAT( const char16* filename, const ResMaterial* pMaterial ) { if ( filename == nullptr || pMaterial == nullptr ) { ELOG( "Error : Invalid Argument."); return false; } FILE* pFile; auto err = _wfopen_s( &pFile, filename, L"wb" ); if ( err != 0 ) { ELOG( "Error : File Open Failed." ); return false; } MAT_FILE_HEADER header; header.Magic[0] = 'M'; header.Magic[1] = 'A'; header.Magic[2] = 'T'; header.Magic[3] = '\0'; header.Version = MAT_VERSION; fwrite( &header, sizeof(header), 1, pFile ); MAT_MATERIAL material = {}; material.PathCount = static_cast<u32>( pMaterial->Paths.size() ); material.PhongCount = static_cast<u32>( pMaterial->Phong.size() ); material.DisneyCount = static_cast<u32>( pMaterial->Disney.size() ); fwrite( &material, sizeof(material), 1, pFile ); for( u32 i=0; i<material.PathCount; ++i ) { MAT_FILE_PATH texture = {}; wcscpy_s( texture.Path, pMaterial->Paths[i].c_str() ); fwrite( &texture, sizeof(texture), 1, pFile ); } for( u32 i=0; i<material.PhongCount; ++i ) { fwrite( &pMaterial->Phong[i], sizeof(ResPhong), 1, pFile ); } for( u32 i=0; i<material.DisneyCount; ++i ) { fwrite( &pMaterial->Disney[i], sizeof(ResDisney), 1, pFile ); } fclose( pFile ); return true; } } // namespace asdx
32.295858
100
0.411689
ProjectAsura
14c1aca82b13408a9064e316ec3a4375af729e78
663
cpp
C++
modules/ide_old/src/OptionPage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/OptionPage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/OptionPage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
#include "OptionPage_1.h" OptionPage_1::OptionPage_1(QWidget* parent) : QWidget(parent) { cssFileStrLstPtr = new QStringList(); cssFileLstWigPtr = new QListWidget(); scanForCssFiles(); outerLayout = new QGridLayout(); outerLayout->addWidget(cssFileLstWigPtr, 0, 0, Qt::AlignCenter); this->setLayout(outerLayout); } QStringList* OptionPage_1::scanForCssFiles() { QDir qssDir("./src/qss"); *cssFileStrLstPtr = qssDir.entryList(QDir::Files/*, sort*/); initCssOptionLstWig(); } void OptionPage_1::initCssOptionLstWig() { cssFileLstWigPtr->addItems(*cssFileStrLstPtr); } OptionPage_1::~OptionPage_1() { ; }
19.5
68
0.695324
DeepBlue14
14c2382a6fdefe166dc70b0171111b92fea69f8d
5,313
cpp
C++
GenesisSandbox/src/Layers/Sandbox2D.cpp
ivanchotom/Genesis
1e5536575bb85f38eb20c96a1ac6c8b2a026386b
[ "Apache-2.0" ]
1
2021-01-07T14:33:22.000Z
2021-01-07T14:33:22.000Z
GenesisSandbox/src/Layers/Sandbox2D.cpp
ivanchotom/Genesis
1e5536575bb85f38eb20c96a1ac6c8b2a026386b
[ "Apache-2.0" ]
null
null
null
GenesisSandbox/src/Layers/Sandbox2D.cpp
ivanchotom/Genesis
1e5536575bb85f38eb20c96a1ac6c8b2a026386b
[ "Apache-2.0" ]
null
null
null
#include "Sandbox2D.h" #include "ImGui/imgui.h" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include <chrono> static const uint32_t s_MapWidth = 24; static const char* s_MapTiles = "WWWWWWWWWWWWWWWWWWWWWWWW" "WWWWWWWWDDDDDWWWWWWWWWWW" "WWWWWDDDDDDDDDDDDWWWWWWW" "WWWWDDDDDDDDDDWWWDDDWWWW" "WWWWWDDDDDDDDDDDDDDWWWWW" "WWWWDDDDDDDDDDDDDDDWWWWW" "WWWWWDDDWWWDDDDDDDWWWWWW" "WWWWWDDDDDDDDDDDDDDWWWWW" "WWWWWDDDDDDDWWWWDDDWWWWW" "WWWWWWWDDDDDDDDDDWWWWWWW" "WWWWWWWWWDDDDDDWWWWWWWWW" "WWWWWWWWWWWDDDWWWWWWWWWW" "WWWWWWWWWWWWWWWWWWWWWWWW" "WWWWWWWWWWWWWWWWWWWWWWWW" ; Sandbox2D::Sandbox2D() : Layer("Sandbox2D"), m_CameraController(1280.0f / 720.0f, true) { } void Sandbox2D::OnAttach() { GS_PROFILE_FUNCTION(); m_CheckerboardTexture = GE::Texture2D::Create("assets/textures/Checkerboard.png"); m_SpriteSheet = GE::Texture2D::Create("assets/kenney/rpg/Spritesheet/RPGpack_sheet_2X.png"); m_TextureBarrel = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 1, 11 }, { 128, 128 }); m_TextureTree = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 2, 1 }, { 128, 128 }, {1, 2}); m_MapWidth = s_MapWidth; m_MapHeight = strlen(s_MapTiles) / s_MapWidth; s_TextureMap['W'] = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 11, 11 }, { 128, 128 }); s_TextureMap['D'] = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 6, 11 }, {128, 128} ); // Particle m_Particle.ColorBegin = { 254 / 255.0f, 212 / 255.0f, 123 / 255.0f, 1.0f }; m_Particle.ColorEnd = { 254 / 255.0f, 109 / 255.0f, 41 / 255.0f, 1.0f }; m_Particle.SizeBegin = 0.5f, m_Particle.SizeVariation = 0.3f, m_Particle.SizeEnd = 0.0f; m_Particle.LifeTime = 5.0f; m_Particle.Velocity = { 0.0f, 0.0f }; m_Particle.VelocityVariation = { 3.0f, 1.0f }; m_Particle.Position = { 0.0f, 0.0f }; m_CameraController.SetZoomLevel(5.0f); } void Sandbox2D::OnDetach() { GS_PROFILE_FUNCTION(); } void Sandbox2D::OnUpdate(GE::Timestep ts) { GS_PROFILE_FUNCTION(); //Update m_CameraController.OnUpdate(ts); //Render Prep GE::Renderer2D::ResetStats(); { GS_PROFILE_SCOPE("Renderer Prep"); GE::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 }); GE::RenderCommand::Clear(); } #if OLD_PATH //Render Draw { static float rotation = 0.0f; rotation += ts * 50.0f; GS_PROFILE_SCOPE("Renderer Draw"); GE::Renderer2D::BeginScene(m_CameraController.GetCamera()); GE::Renderer2D::DrawRotatedQuad({ 1.0f, 0.0f }, { 0.8f, 0.8f }, glm::radians(-45.0f), { 0.8f, 0.2f, 0.3f, 1.0f }); GE::Renderer2D::DrawQuad({ -1.0f, 0.0f }, { 0.8f, 0.8f }, { 0.8f, 0.2f, 0.3f, 1.0f }); GE::Renderer2D::DrawQuad({ 0.5f, -0.5f }, { 0.5f, 0.75f }, { 0.2f, 0.3f, 0.8f, 1.0f }); GE::Renderer2D::DrawQuad({ 0.0f, 0.0f, -0.1f}, { 20.0f, 20.0f }, m_CheckerboardTexture, 10.0f); GE::Renderer2D::DrawRotatedQuad({ -2.0f, 0.0f, 0.0f }, { 1.0f, 1.0f }, glm::radians(rotation) , m_CheckerboardTexture, 20.0f); GE::Renderer2D::EndScene(); GE::Renderer2D::BeginScene(m_CameraController.GetCamera()); for (float y = -5.0; y < 5.0f; y += 0.5f) { for (float x = -5.0; x < 5.0f; x += 0.5f) { glm::vec4 color = { (x + 5.0f) / 10.0f, 0.4f, (y + 5.0f) / 10.0f, 0.7f }; GE::Renderer2D::DrawQuad({x, y}, { 0.45f, 0.45f }, color); } } GE::Renderer2D::EndScene(); } #endif if (GE::Input::IsMouseButtonPressed(GE_MOUSE_BUTTON_LEFT)) { auto [x, y] = GE::Input::GetMousePosition(); auto width = GE::Application::Get().GetWindow().GetWidth(); auto height = GE::Application::Get().GetWindow().GetHeight(); auto bounds = m_CameraController.GetBounds(); auto pos = m_CameraController.GetCamera().GetPosition(); x = (x / width) * bounds.GetWidth() - bounds.GetWidth() * 0.5f; y = bounds.GetHeight() * 0.5f - (y / height) * bounds.GetHeight(); m_Particle.Position = { x + pos.x, y + pos.y }; for (int i = 0; i < 50; i++) m_ParticleSystem.Emit(m_Particle); } m_ParticleSystem.OnUpdate(ts); m_ParticleSystem.OnRender(m_CameraController.GetCamera()); GE::Renderer2D::BeginScene(m_CameraController.GetCamera()); for (uint32_t y = 0; y < m_MapHeight; y++) { for (uint32_t x = 0; x < m_MapWidth; x++) { char tileType = s_MapTiles[x + y * m_MapWidth]; GE::Ref<GE::SubTexture2D> texture; if (s_TextureMap.find(tileType) != s_TextureMap.end()) texture = s_TextureMap[tileType]; else texture = m_TextureBarrel; GE::Renderer2D::DrawQuad({ x - m_MapWidth / 2.0f, y - m_MapHeight / 2.0f, 0.5f }, { 1.0f, 1.0f }, texture); } } //GE::Renderer2D::DrawQuad({ 0.0f, 0.0f, 0.5f }, { 1.0f, 1.0f }, m_TextureStairs); //GE::Renderer2D::DrawQuad({ 1.0f, 0.0f, 0.5f }, { 1.0f, 1.0f }, m_TextureBarrel); //GE::Renderer2D::DrawQuad({ -1.0f, 0.0f, 0.5f }, { 1.0f, 2.0f }, m_TextureTree); GE::Renderer2D::EndScene(); } void Sandbox2D::OnImGuiRender() { GS_PROFILE_FUNCTION(); ImGui::Begin("Settings"); auto stats = GE::Renderer2D::GetStats(); ImGui::Text("Renderer2D Stats:"); ImGui::Text("Draw Calls: %d", stats.DrawCalls); ImGui::Text("Quads: %d", stats.QuadCount); ImGui::Text("Vertices: %d", stats.GetTotalVertexCount()); ImGui::Text("Indices: %d", stats.GetTotalIndexCount()); ImGui::ColorEdit4("Square Color", glm::value_ptr(m_SquareColor)); ImGui::End(); } void Sandbox2D::OnEvent(GE::Event& e) { m_CameraController.OnEvent(e); }
29.192308
128
0.673254
ivanchotom
14c28818c7186f1404beb0a4f68d8284e3844b3c
8,884
cpp
C++
thorlcr/activities/selfjoin/thselfjoinslave.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
thorlcr/activities/selfjoin/thselfjoinslave.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
thorlcr/activities/selfjoin/thselfjoinslave.cpp
jakesmith/HPCC-Platform
c3b9268c492e473176ea36e3e916c4a544f47561
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. 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 "jlib.hpp" #include "thselfjoinslave.ipp" #include "tsorts.hpp" #include "tsorta.hpp" #include "thactivityutil.ipp" #include "thorport.hpp" #include "thsortu.hpp" #include "thsortu.hpp" #include "thexception.hpp" #include "thbufdef.hpp" #include "thorxmlwrite.hpp" #define NUMSLAVEPORTS 2 // actually should be num MP tags class SelfJoinSlaveActivity : public CSlaveActivity { typedef CSlaveActivity PARENT; private: Owned<IThorSorter> sorter; IHThorJoinArg * helper; unsigned portbase; bool isLocal; bool isLightweight; Owned<IRowStream> strm; ICompare * compare; ISortKeySerializer * keyserializer; mptag_t mpTagRPC; Owned<IJoinHelper> joinhelper; CriticalSection joinHelperCrit; Owned<IBarrier> barrier; SocketEndpoint server; bool isUnstable() { // actually don't think currently supported by join but maybe will be sometime return false; } IRowStream * doLocalSelfJoin() { ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: Performing local self-join"); Owned<IThorRowLoader> iLoader = createThorRowLoader(*this, ::queryRowInterfaces(input), compare, isUnstable() ? stableSort_none : stableSort_earlyAlloc, rc_mixed, SPILL_PRIORITY_SELFJOIN); Owned<IRowStream> rs = iLoader->load(inputStream, abortSoon); mergeStats(stats, iLoader, spillStatistics); // Not sure of the best policy if rs spills later on. PARENT::stopInput(0); return rs.getClear(); } IRowStream * doGlobalSelfJoin() { ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: Performing global self-join"); sorter->Gather(::queryRowInterfaces(input), inputStream, compare, NULL, NULL, keyserializer, NULL, NULL, false, isUnstable(), abortSoon, NULL); PARENT::stopInput(0); if (abortSoon) { barrier->cancel(); return NULL; } if (!barrier->wait(false)) { Sleep(1000); // let original error through throw MakeThorException(TE_BarrierAborted,"SELFJOIN: Barrier Aborted"); } rowcount_t totalrows; return sorter->startMerge(totalrows); } public: SelfJoinSlaveActivity(CGraphElementBase *_container, bool _isLocal, bool _isLightweight) : CSlaveActivity(_container, joinActivityStatistics) { helper = static_cast <IHThorJoinArg *> (queryHelper()); isLocal = _isLocal||_isLightweight; isLightweight = _isLightweight; portbase = 0; compare = NULL; keyserializer = NULL; mpTagRPC = TAG_NULL; if (isLocal) setRequireInitData(false); appendOutputLinked(this); } ~SelfJoinSlaveActivity() { if(portbase) queryJobChannel().freePort(portbase, NUMSLAVEPORTS); } // IThorSlaveActivity virtual void init(MemoryBuffer & data, MemoryBuffer &slaveData) override { if (!isLocal) { mpTagRPC = container.queryJobChannel().deserializeMPTag(data); mptag_t barrierTag = container.queryJobChannel().deserializeMPTag(data); barrier.setown(container.queryJobChannel().createBarrier(barrierTag)); portbase = queryJobChannel().allocPort(NUMSLAVEPORTS); server.setLocalHost(portbase); sorter.setown(CreateThorSorter(this, server,&container.queryJob().queryIDiskUsage(),&queryJobChannel().queryJobComm(),mpTagRPC)); server.serialize(slaveData); } compare = helper->queryCompareLeft(); // NB not CompareLeftRight keyserializer = helper->querySerializeLeft(); // hopefully never need right if (isLightweight) ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: LIGHTWEIGHT"); else if(isLocal) ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: LOCAL"); else ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: GLOBAL"); } virtual void reset() override { PARENT::reset(); if (sorter) return; // JCSMORE loop - shouldn't have to recreate sorter between loop iterations if (!isLocal && TAG_NULL != mpTagRPC) sorter.setown(CreateThorSorter(this, server,&container.queryJob().queryIDiskUsage(),&queryJobChannel().queryJobComm(),mpTagRPC)); } virtual void kill() override { sorter.clear(); if (portbase) { queryJobChannel().freePort(portbase, NUMSLAVEPORTS); portbase = 0; } PARENT::kill(); } // IThorDataLink virtual void start() override { ActivityTimer s(slaveTimerStats, timeActivities); PARENT::start(); bool hintunsortedoutput = getOptBool(THOROPT_UNSORTED_OUTPUT, (JFreorderable & helper->getJoinFlags()) != 0); bool hintparallelmatch = getOptBool(THOROPT_PARALLEL_MATCH, hintunsortedoutput); // i.e. unsorted, implies use parallel by default, otherwise no point if (helper->getJoinFlags()&JFlimitedprefixjoin) { CriticalBlock b(joinHelperCrit); // use std join helper (less efficient but implements limited prefix) joinhelper.setown(createJoinHelper(*this, helper, this, hintparallelmatch, hintunsortedoutput)); } else { CriticalBlock b(joinHelperCrit); joinhelper.setown(createSelfJoinHelper(*this, helper, this, hintparallelmatch, hintunsortedoutput)); } if (isLightweight) strm.set(inputStream); else { strm.setown(isLocal ? doLocalSelfJoin() : doGlobalSelfJoin()); assertex(strm); // NB: PARENT::stopInput(0) will now have been called } joinhelper->init(strm, NULL, ::queryRowAllocator(queryInput(0)), ::queryRowAllocator(queryInput(0)), ::queryRowMetaData(queryInput(0))); } virtual void abort() override { CSlaveActivity::abort(); if (joinhelper) joinhelper->stop(); } virtual void stop() override { if (hasStarted()) { if (!isLocal) { barrier->wait(false); sorter->stopMerge(); } { CriticalBlock b(joinHelperCrit); joinhelper.clear(); } if (strm) { if (!isLightweight) // if lightweight strm=input and PARENT::stop handles input stop strm->stop(); strm.clear(); } } PARENT::stop(); } CATCH_NEXTROW() { ActivityTimer t(slaveTimerStats, timeActivities); if(joinhelper) { OwnedConstThorRow row = joinhelper->nextRow(); if (row) { dataLinkIncrement(); return row.getClear(); } } return NULL; } virtual bool isGrouped() const override { return false; } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) const override { initMetaInfo(info); info.buffersInput = true; info.unknownRowsOutput = true; } virtual void serializeStats(MemoryBuffer &mb) override { { CriticalBlock b(joinHelperCrit); rowcount_t p = joinhelper?joinhelper->getLhsProgress():0; stats.setStatistic(StNumLeftRows, p); mergeStats(stats, sorter, spillStatistics); // No danger of a race with reset() because that never replaces a valid sorter } CSlaveActivity::serializeStats(mb); } }; CActivityBase *createSelfJoinSlave(CGraphElementBase *container) { return new SelfJoinSlaveActivity(container, false, false); } CActivityBase *createLocalSelfJoinSlave(CGraphElementBase *container) { return new SelfJoinSlaveActivity(container, true, false); } CActivityBase *createLightweightSelfJoinSlave(CGraphElementBase *container) { return new SelfJoinSlaveActivity(container, true, true); }
35.536
196
0.624156
jeclrsg
14cd791727342165625c0ef8a0d101fa739a0fc9
680
cpp
C++
algorithms/sherlock.squares.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
1
2015-03-21T20:08:28.000Z
2015-03-21T20:08:28.000Z
algorithms/sherlock.squares.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
null
null
null
algorithms/sherlock.squares.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; long squares(unsigned long long a, unsigned long long b) { long square_count=0; if(a==1) square_count=sqrt(b); else { long root_a=sqrt(a); square_count=((long)sqrt(b))-((long)sqrt(a)); if((root_a*root_a)==a)++square_count; } return square_count; } void Run() { //enter value of T for testcase int T; cin>>T; unsigned long long array[T][2]; //enter value of a && b for T number of testcases for(int i=0; i<T; ++i) cin>>array[i][0]>>array[i][1]; for(int j=0; j<T; ++j) cout<<squares(array[j][0],array[j][1])<<endl; return; } int main() { Run(); return 0; }
18.378378
57
0.601471
kosmaz
14cef1c043ea48e9b645ea32f53e2080712d90d4
2,168
cpp
C++
automated-tests/src/dali-toolkit-internal/utc-Dali-ColorConversion.cpp
Coquinho/dali-toolkit
8fea8f2ae64923690519e0de039ce4af51271d9f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
automated-tests/src/dali-toolkit-internal/utc-Dali-ColorConversion.cpp
Coquinho/dali-toolkit
8fea8f2ae64923690519e0de039ce4af51271d9f
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-10-19T15:47:43.000Z
2020-10-19T15:47:43.000Z
automated-tests/src/dali-toolkit-internal/utc-Dali-ColorConversion.cpp
expertisesolutions/dali-toolkit
eac3e6ee30183868f1af12addd94e7f2fc467ed7
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017 Samsung Electronics 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 <dali-toolkit-test-suite-utils.h> #include <dali-toolkit/internal/helpers/color-conversion.h> using namespace Dali; using namespace Dali::Toolkit; void dali_color_conversion_startup(void) { test_return_value = TET_UNDEF; } void dali_color_conversion_cleanup(void) { test_return_value = TET_PASS; } int UtcDaliPropertyHelperConvertHtmlStringToColor(void) { tet_infoline( "Test to check whether An HTML style hex string can be converted" ); const std::string stringColor( "#FF0000" ); Vector4 result; DALI_TEST_CHECK( Toolkit::Internal::ConvertStringToColor( stringColor, result ) ); DALI_TEST_EQUALS( result, Color::RED, TEST_LOCATION ); END_TEST; } int UtcDaliPropertyHelperConvertStringPropertyToColor(void) { tet_infoline( "Test to check whether A Property value containing a string can be converted" ); const std::string stringColor( "#00FF00" ); Property::Value colorProperty( stringColor ); Vector4 result; DALI_TEST_CHECK( Toolkit::Internal::ConvertPropertyToColor( colorProperty, result ) ); DALI_TEST_EQUALS( result, Color::GREEN, TEST_LOCATION ); END_TEST; } int UtcDaliPropertyHelperConvertVector4PropertyToColor(void) { tet_infoline( "Test to check whether A Property value containing a string can be converted" ); const Vector4 color( 0.0, 0.0, 1.0, 1.0 ); Property::Value colorProperty( color ); Vector4 result; DALI_TEST_CHECK( Toolkit::Internal::ConvertPropertyToColor( colorProperty, result ) ); DALI_TEST_EQUALS( result, Color::BLUE, TEST_LOCATION ); END_TEST; }
28.155844
96
0.756919
Coquinho
14d3398986db3d9f743d401e31399fb4372bd89b
441
cpp
C++
kickStart/1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
kickStart/1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
kickStart/1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; int k = 1; while(t--){ int n; cin>>n; int a[n]; for(int i =0;i<n;i++){ cin>>a[i]; } int count = 0; for(int i=1;i<n-1;i++){ if(a[i]>a[i+1] && a[i]>a[i-1]){ count++; } } cout<<"Case #"<<k<<": "<<count<<endl; k++; } }
17.64
45
0.328798
Jonsy13
14d692f3e56c4c78e67497ad16165b97e8036063
20,100
cpp
C++
src/menu_io.cpp
digitalcraig/EtherTerm
4f994bb9ecbb48fbb77875d4d655b65a8b257d42
[ "Zlib" ]
106
2015-02-01T18:01:48.000Z
2022-02-10T04:51:11.000Z
src/menu_io.cpp
digitalcraig/EtherTerm
4f994bb9ecbb48fbb77875d4d655b65a8b257d42
[ "Zlib" ]
60
2015-02-01T18:00:39.000Z
2022-01-17T17:27:34.000Z
src/menu_io.cpp
digitalcraig/EtherTerm
4f994bb9ecbb48fbb77875d4d655b65a8b257d42
[ "Zlib" ]
16
2015-02-02T00:00:35.000Z
2021-08-17T01:42:58.000Z
#include "menu_io.hpp" #include "sequence_decoder.hpp" #include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <cstring> MenuIO::MenuIO(sequence_decoder_ptr &decoder, const std::string &program_path) : m_sequence_decoder(decoder) , m_program_path(program_path) { std::cout << "MenuIO Created!" << std::endl; } MenuIO::~MenuIO() { std::cout << "~MenuIO" << std::endl; } /** * @brief Right string padding * @param str * @param space */ void MenuIO::rightSpacing(std::string &str, const int &space) // Pad Right { if(space == 0) return; int s = str.size(); // if Line > Space, Erase to Make it match! if(s >= space) { str.erase(space, s - space); return; } for(int i = 0; i < (space-s); i++) str += ' '; } /** * @brief Left String Padding. * @param str * @param space */ void MenuIO::leftSpacing(std::string &str, const int &space) // Pad Left { if(space == 0) return; int s = str.size(); // if Line > Space, Erase to Make it match! if(s > space) { // Truncate to the last space digits. str.erase(0, s - space); return; } for(int i = 0; i < (space-s); i++) str.insert(0, 1, ' '); } /** * @brief Setup Text Input Fields * @param text * @param len */ void MenuIO::inputField(std::string &text, int &len) { std::string repeat; char formatted[1024]= {0}; char sTmp[3] = {0}; char sTmp2[3] = {0}; // Parse for Input String Modifiers std::string::size_type tempLength; std::string::size_type position; std::string::size_type stringSize; char INPUT_COLOR[255]= {0}; bool isColorOverRide = false; //found input color stringSize = text.size()-1; if(len == 0) { return; } // Override Input Length for ANSI position = text.find("|IN", 0); if(position != std::string::npos) { // Make sure we don't go past the bounds if(position+4 <= stringSize) { // (Unit Test Notes) // Need to Test if idDigit! And only if, both are // Then we cut these out and erase!, Otherwise // We only remove the |IN pipe sequence. if(isdigit(text[position+3]) && isdigit(text[position+4])) { sTmp[0] = text[position+3]; sTmp[1] = text[position+4]; text.erase(position, 5); tempLength = atoi(sTmp); if((signed)tempLength < len) len = tempLength; // Set new Length } else { text.erase(position, 3); } } } // Override Foreground/Background Input Field Colors position = text.find("|FB",0); if(position != std::string::npos) { // (Unit Test Notes) // Need to Test if isDigit! And only if, both are // Then we cut these out and erase!, Otherwise // We only remove the |FB pipe sequence. memset(&sTmp, 0, 3); memset(&sTmp2, 0, 3); // Make sure we don't go past the bounds if(position+6 <= stringSize) { if(isdigit(text[position+3]) && isdigit(text[position+4]) && isdigit(text[position+5]) && isdigit(text[position+6])) { sTmp[0] = text[position+3]; // Foreground 00-15 sTmp[1] = text[position+4]; sTmp2[0] = text[position+5]; // Background 16-23 sTmp2[1] = text[position+6]; text.erase(position, 7); sprintf(INPUT_COLOR, "|%s|%s", sTmp, sTmp2); isColorOverRide = true; } else { text.erase(position, 3); } } } // Pad len amount of spaces. if(len > 0) { repeat.insert(0, len, ' '); } // Set Default Input Color if none was passed. if(!isColorOverRide) { sprintf(INPUT_COLOR,"|00|19"); } // Format Input Field sprintf(formatted, "%s|07|16[%s%s|07|16]%s\x1b[%iD", (char *)text.c_str(), // Field Name INPUT_COLOR, // Field Fg,Bg Color repeat.c_str(), // Padding length of Field INPUT_COLOR, // Reset Input len+1); // Move back to starting position of field. text = formatted; } /* * Get Single Key Input (Blocking) * int MenuIO::getKey() { std::string inputSequence; while(!TheInputHandler::Instance()->isGlobalShutdown()) { // Catch updates when in the menu system. TheSequenceManager::Instance()->update(); if(TheInputHandler::Instance()->update()) { if(TheInputHandler::Instance()->getInputSequence(inputSequence)) break; } SDL_Delay(10); } // If Global Exit, return right away. if(TheInputHandler::Instance()->isGlobalShutdown()) { return EOF; } return inputSequence[0]; }*/ /* * Get Single Key Input (Non-Blocking) * * Not Used At this time. * int MenuIO::checkKey() { std::string inputSequence; if(TheInputHandler::Instance()->isGlobalShutdown()) { return EOF; } if(TheInputHandler::Instance()->update()) { inputSequence = TheInputHandler::Instance()->getInputSequence(); } else { SDL_Delay(10); return 0; } return inputSequence[0]; } */ /* * Get Input up to <ENTER> */ /* void MenuIO::getLine(char *line, // Returns Input into Line int length, // Max Input Length of String char *leadoff, // Data to Display in Default String {Optional} int hid) // If input is Echoed as hidden {Optional} { int sequence = 0; int secondSequence = 0; int i = 0; int Col = 0; int isEscapeSequence = 0; int cursorBlink = 0; bool startBlinking = false; std::string output; std::string input; std::string inputSequence; // Cursor Blinking. time_t ttime, ttime2; ttime = SDL_GetTicks(); #define DEL 0x7f // If were starting Off Input with a String already in buffer! display it! if(leadoff != 0) { input = leadoff; i = input.size(); Col = i; //TheSequenceManager::Instance()->decode(input); m_sequence_decoder->decodeEscSequenceData(input); } while(!TheInputHandler::Instance()->isGlobalShutdown()) { // Catch Screen updates when in the menu system. TheSequenceManager::Instance()->update(); if(TheInputHandler::Instance()->update() && !TheInputHandler::Instance()->isGlobalShutdown()) { // We got data, turn off the cursor! ttime = SDL_GetTicks(); startBlinking = false; cursorBlink = 0; // Get the Sequence. if(TheInputHandler::Instance()->getInputSequence(inputSequence)) { // Check for Abort, single ESC character. if(inputSequence == "\x1b" && inputSequence.size() == 1) { isEscapeSequence = false; strcpy(line,"\x1b"); return; } } } else { if(TheSequenceParser::Instance()->isCursorActive() && !TheInputHandler::Instance()->isGlobalShutdown()) { startBlinking = true; // Setup Timer for Blinking Cursor // Initial State = On, then Switch to off in next loop. if(cursorBlink % 2 == 0) { ttime2 = SDL_GetTicks(); if(startBlinking && (ttime2 - ttime) > 400) { TheRenderer::Instance()->renderCursorOffScreen(); TheRenderer::Instance()->drawTextureScreen(); --cursorBlink; ttime = SDL_GetTicks(); } } else { ttime2 = SDL_GetTicks(); if(startBlinking && (ttime2 - ttime) > 400) { TheRenderer::Instance()->renderCursorOnScreen(); TheRenderer::Instance()->drawTextureScreen(); ++cursorBlink; ttime = SDL_GetTicks(); } } } SDL_Delay(10); continue; } // Catch any shutdown here before doing anymore. if(TheInputHandler::Instance()->isGlobalShutdown()) { return; } sequence = inputSequence[0]; if(sequence == '\r') { sequence = '\n'; } // Escape in this case, ignore, later add movement in string if((int)sequence == 27) { if(inputSequence.size() >= 3) secondSequence = inputSequence[2]; isEscapeSequence = true; } else { isEscapeSequence = false; } // Catch all Escaped Keys for Cursor Movement if(isEscapeSequence) { switch(secondSequence) { case '3' : // Delete if(i != 0 || Col != 0) { sequenceToAnsi("\x1b[D \x1b[D"); input.erase(Col-1,1); --i; --Col; } break; default : break; } } else if((int)sequence == 25) { // CTRL Y - Clear Line input.erase(); i = Col; for(; i != 0; i--) { sequenceToAnsi("\x1b[D \x1b[D"); } i = 0; Col = i; } // delete 127 // Do destructive backspace // on VT100 Terms 127 DEL == BS! // Since we have no DELETE in this, delete on 1 liens will works like BS. else if((int)sequence == 0x08 || (int)sequence == 207 || (int)sequence == 0x7f) { if(i != 0 || Col != 0) { sequenceToAnsi("\x1b[D \x1b[D"); input.erase(Col-1,1); --i; --Col; } } // Normal Key Input, Letters & numbers else if((int)sequence > 31 && (int)sequence < 126) { if(i != length-1) { if(hid) { sequenceToAnsi("*"); } else { output = sequence; sequenceToAnsi(output); } input += sequence; ++i; ++Col; } } else if(sequence == '\r' || sequence == '\n') { strncpy(line, (char *)input.c_str(), length); break; } } // If Global Exit, return right away. if(TheInputHandler::Instance()->isGlobalShutdown()) { return; } } */ /** * @brief Foreground ESC Sequence Translation * @param data * @param fg */ void MenuIO::foregroundColorSequence(char *data, int fg) { switch(fg) { case 0: strcat(data, "x[0;30m"); break; case 1: strcat(data, "x[0;34m"); break; case 2: strcat(data, "x[0;32m"); break; case 3: strcat(data, "x[0;36m"); break; case 4: strcat(data, "x[0;31m"); break; case 5: strcat(data, "x[0;35m"); break; case 6: strcat(data, "x[0;33m"); break; case 7: strcat(data, "x[0;37m"); break; case 8: strcat(data, "x[1;30m"); break; case 9: strcat(data, "x[1;34m"); break; case 10: strcat(data, "x[1;32m"); break; case 11: strcat(data, "x[1;36m"); break; case 12: strcat(data, "x[1;31m"); break; case 13: strcat(data, "x[1;35m"); break; case 14: strcat(data, "x[1;33m"); break; case 15: strcat(data, "x[1;37m"); break; default : break; } data[0] = '\x1b'; } /** * @brief Background ESC Sequence Translation * @param data * @param bg */ void MenuIO::backgroundColorSequence(char *data, int bg) { switch(bg) { case 16: strcat(data, "x[40m"); break; case 17: strcat(data, "x[44m"); break; case 18: strcat(data, "x[42m"); break; case 19: strcat(data, "x[46m"); break; case 20: strcat(data, "x[41m"); break; case 21: strcat(data, "x[45m"); break; case 22: strcat(data, "x[43m"); break; case 23: strcat(data, "x[47m"); break; // Default to none. case 24: strcat(data, "x[0m"); break; default : break; } data[0] = '\x1b'; } /** * @brief Parses MCI and PIPE Codes to ANSI Sequences * @param sequence */ void MenuIO::sequenceToAnsi(const std::string &sequence) { std::string::size_type id1 = 0; // Pipe Position char pipe_sequence[3]; // Holds 1, 2nd digit of Pipe char pipe_position1[3]; // Hold XY Pos for ANSI Position Codes char pipe_position2[3]; // Hold XY Pos for ANSI Position Codes char esc_sequence[1024]; // Holds Converted Pipe 2 ANSI std::string data_string = sequence; #define SP 0x20 // Search for First Pipe while(id1 != std::string::npos) { id1 = data_string.find("|", id1); if(id1 != std::string::npos && id1+2 < data_string.size()) { memset(&pipe_sequence,0,sizeof(pipe_sequence)); memset(&esc_sequence,0,sizeof(esc_sequence)); pipe_sequence[0] = data_string[id1+1]; // Get First # after Pipe pipe_sequence[1] = data_string[id1+2]; // Get Second Number After Pipe if(pipe_sequence[0] == '\0' || pipe_sequence[0] == '\r' || pipe_sequence[0] == EOF) break; if(pipe_sequence[1] == '\0' || pipe_sequence[1] == '\r' || pipe_sequence[0] == EOF) break; //std::cout << "\r\n*** pipe_sequence: " << pipe_sequence << std::endl; if(isdigit(pipe_sequence[0]) && isdigit(pipe_sequence[1])) { std::string temp_sequence = ""; std::string::size_type type; temp_sequence += pipe_sequence[0]; temp_sequence += pipe_sequence[1]; int pipe_color_value = 0; try { pipe_color_value = std::stoi(temp_sequence, &type); if(pipe_color_value >= 0 && pipe_color_value < 16) { foregroundColorSequence(esc_sequence, pipe_color_value); } else if(pipe_color_value >= 16 && pipe_color_value < 24) { backgroundColorSequence(esc_sequence, pipe_color_value); } else { ++id1; } // Replace pipe code with ANSI Sequence if(strcmp(esc_sequence,"") != 0) { data_string.replace(id1, 3, esc_sequence); } } catch(const std::invalid_argument& ia) { std::cout << "Invalid argument: " << ia.what() << '\n'; ++id1; } } // Else not a Pipe Color / Parse for Screen Modification else if(pipe_sequence[0] == 'C') { // Carriage Return / New Line if(strcmp(pipe_sequence,"CR") == 0) { backgroundColorSequence(esc_sequence, 16); // Clear Background Attribute first strcat(esc_sequence,"\r\n"); data_string.replace(id1, 3, esc_sequence); id1 = 0; } // Clear Screen else if(strcmp(pipe_sequence,"CS") == 0) { backgroundColorSequence(esc_sequence, 16); // Set Scroll Region, Clear Background, Then Home Cursor. strcat(esc_sequence,"\x1b[2J\x1b[1;1H"); data_string.replace(id1, 3, esc_sequence); id1 = 0; } } else { if(strcmp(pipe_sequence,"XY") == 0 && id1+6 < data_string.size()) { memset(&pipe_position1, 0, sizeof(pipe_position1)); memset(&pipe_position2, 0, sizeof(pipe_position2)); // X Pos pipe_position1[0] = data_string[id1+3]; pipe_position1[1] = data_string[id1+4]; // Y Pos pipe_position2[0] = data_string[id1+5]; pipe_position2[1] = data_string[id1+6]; // Clear Background Attribute first backgroundColorSequence(esc_sequence, 16); char char_replacement[2048] = {0}; sprintf(char_replacement,"%s\x1b[%i;%iH", esc_sequence, atoi(pipe_position2), atoi(pipe_position1)); data_string.replace(id1, 7, char_replacement); } else { // End of the Line, nothing parsed out so // Skip ahead past current code. ++id1; } } } else { break; } id1 = data_string.find("|",id1); } m_sequence_decoder->decodeEscSequenceData(data_string); } /** * @brief Reads in ANSI text file and pushes to Display * @param file_name */ void MenuIO::displayMenuAnsi(const std::string &file_name) { std::string path = m_program_path; #ifdef _WIN32 path.append("assets\\directory\\"); #else path.append("assets/directory/"); #endif path.append(file_name); std::string buff; FILE *fp; int sequence = 0; if((fp = fopen(path.c_str(), "r+")) == nullptr) { std::cout << "MenuIO displayAnsiFile(): not found: " << std::endl << path << std::endl; return; } do { sequence = getc(fp); if(sequence != EOF) buff += sequence; } while(sequence != EOF); fclose(fp); // Send to the Sequence Manager. m_sequence_decoder->decodeEscSequenceData(buff); }
27.198917
121
0.455174
digitalcraig
14d7bdb2822f5bcdc8414f3ab70607112b6e2e82
7,861
cpp
C++
SpoutSDK/Example/Cinder/source/CinderSpoutReceiver.cpp
f-tischler/Spout2
0173a81ebcbc63c96c020e92563359c4f8e0791f
[ "BSD-2-Clause" ]
null
null
null
SpoutSDK/Example/Cinder/source/CinderSpoutReceiver.cpp
f-tischler/Spout2
0173a81ebcbc63c96c020e92563359c4f8e0791f
[ "BSD-2-Clause" ]
null
null
null
SpoutSDK/Example/Cinder/source/CinderSpoutReceiver.cpp
f-tischler/Spout2
0173a81ebcbc63c96c020e92563359c4f8e0791f
[ "BSD-2-Clause" ]
null
null
null
/* Basic Spout receiver for Cinder Uses the Spout SDK Based on the RotatingBox CINDER example without much modification Nothing fancy about this, just the basics. Search for "SPOUT" to see what is required ========================================================================== Copyright (C) 2014-2017 Lynn Jarvis. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ========================================================================== 11.05.14 - used updated Spout Dll with host fbo option and rgba 04.06.14 - used updated Spout Dll 04/06 with host fbo option removed - added Update function - moved receiver initialization from Setup to Update for sender detection 11.07.14 - changed to Spout SDK instead of the dll 29.09.14 - update with with SDK revision 12.10.14 - recompiled for release 03.01.15 - SDK recompile - SpoutPanel detected from registry install path 04.02.15 - SDK recompile for default DX9 (see SpoutGLDXinterop.h) 14.02.15 - SDK recompile for default DX11 and auto compatibility detection (see SpoutGLDXinterop.cpp) 21.05.15 - Added optional SetDX9 call - Recompiled for both DX9 and DX11 for new installer 26.05.15 - Recompile for revised SpoutPanel registry write of sender name 01.07.15 - Convert project to VS2012 - add a window title 30.03.16 - Rebuild for 2.005 release - VS2012 /MT 17.01.16 - Rebuild for 2.006 release - VS2012 /MT */ #include "cinder/app/AppBasic.h" #include "cinder/gl/Texture.h" // -------- SPOUT ------------- #include "..\..\..\SpoutSDK\Spout.h" // ---------------------------- using namespace ci; using namespace ci::app; class SpoutBoxApp : public AppBasic { public: void setup(); void draw(); void update(); void mouseDown(MouseEvent event); // -------- SPOUT ------------- SpoutReceiver spoutreceiver; // Create a Spout receiver object void prepareSettings(Settings *settings); void shutdown(); bool bInitialized; // true if a sender initializes OK bool bDoneOnce; // only try to initialize once bool bMemoryMode; // tells us if texture share compatible unsigned int g_Width, g_Height; // size of the texture being sent out char SenderName[256]; // sender name gl::Texture spoutTexture; // Local Cinder texture used for sharing // ---------------------------- }; // -------- SPOUT ------------- void SpoutBoxApp::prepareSettings(Settings *settings) { g_Width = 320; // set global width and height to something g_Height = 240; // they need to be reset when the receiver connects to a sender settings->setTitle("CinderSpoutReceiver"); settings->setWindowSize( g_Width, g_Height ); settings->setFullScreen( false ); settings->setResizable( true ); // allowed for a receiver settings->setFrameRate( 60.0f ); } // ---------------------------- void SpoutBoxApp::setup() { } void SpoutBoxApp::update() { unsigned int width, height; // -------- SPOUT ------------- if(!bInitialized) { // This is a receiver, so the initialization is a little more complex than a sender // The receiver will attempt to connect to the name it is sent. // Alternatively set the optional bUseActive flag to attempt to connect to the active sender. // If the sender name is not initialized it will attempt to find the active sender // If the receiver does not find any senders the initialization will fail // and "CreateReceiver" can be called repeatedly until a sender is found. // "CreateReceiver" will update the passed name, and dimensions. SenderName[0] = NULL; // the name will be filled when the receiver connects to a sender width = g_Width; // pass the initial width and height (they will be adjusted if necessary) height = g_Height; // Initialize a receiver if(spoutreceiver.CreateReceiver(SenderName, width, height, true)) { // true to find the active sender // Optionally test for texture share compatibility // bMemoryMode informs us whether Spout initialized for texture share or memory share bMemoryMode = spoutreceiver.GetMemoryShareMode(); // Is the size of the detected sender different from the current texture size ? // This is detected for both texture share and memoryshare if(width != g_Width || height != g_Height) { // Reset the global width and height g_Width = width; g_Height = height; // Reset the local receiving texture size spoutTexture = gl::Texture(g_Width, g_Height); // reset render window setWindowSize(g_Width, g_Height); } bInitialized = true; } else { // Receiver initialization will fail if no senders are running // Keep trying until one starts } } // endif not initialized // ---------------------------- } // -------- SPOUT ------------- void SpoutBoxApp::shutdown() { spoutreceiver.ReleaseReceiver(); } void SpoutBoxApp::mouseDown(MouseEvent event) { // Select a sender if( event.isRightDown() ) { spoutreceiver.SelectSenderPanel(); } } // ---------------------------- void SpoutBoxApp::draw() { unsigned int width, height; char txt[256]; gl::setMatricesWindow( getWindowSize() ); gl::clear(); gl::color( Color( 1, 1, 1 ) ); // Save current global width and height - they will be changed // by receivetexture if the sender changes dimensions width = g_Width; height = g_Height; // // Try to receive the texture at the current size // // NOTE : if ReceiveTexture is called with a framebuffer object bound, // include the FBO id as an argument so that the binding is restored afterwards // because Spout uses an fbo for intermediate rendering if(bInitialized) { if(spoutreceiver.ReceiveTexture(SenderName, width, height, spoutTexture.getId(), spoutTexture.getTarget())) { // Width and height are changed for sender change so the local texture has to be resized. if(width != g_Width || height != g_Height ) { // The sender dimensions have changed - update the global width and height g_Width = width; g_Height = height; // Update the local texture to receive the new dimensions spoutTexture = gl::Texture(g_Width, g_Height); // reset render window setWindowSize(g_Width, g_Height); return; // quit for next round } // Otherwise draw the texture and fill the screen gl::draw(spoutTexture, getWindowBounds()); // Show the user what it is receiving gl::enableAlphaBlending(); sprintf_s(txt, "Receiving from [%s]", SenderName); gl::drawString( txt, Vec2f( toPixels( 20 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); sprintf_s(txt, "fps : %2.2d", (int)getAverageFps()); gl::drawString( txt, Vec2f(getWindowWidth() - toPixels( 100 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); gl::drawString( "RH click to select a sender", Vec2f( toPixels( 20 ), getWindowHeight() - toPixels( 40 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); gl::disableAlphaBlending(); return; // received OK } } gl::enableAlphaBlending(); gl::drawString( "No sender detected", Vec2f( toPixels( 20 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); gl::disableAlphaBlending(); // ---------------------------- } CINDER_APP_BASIC( SpoutBoxApp, RendererGl )
35.570136
165
0.671416
f-tischler
14dd25fbae2effecb6bffdd2e067030137e52ee0
4,155
cc
C++
src/projects/attractors/attractor_system_blueprint.cc
frtru/GemParticles
7447c4720f902be9686bbed2a490368374fc614a
[ "MIT" ]
19
2017-03-02T21:13:40.000Z
2022-03-24T03:14:10.000Z
src/projects/attractors/attractor_system_blueprint.cc
frtru/GemParticles
7447c4720f902be9686bbed2a490368374fc614a
[ "MIT" ]
46
2016-10-12T22:56:05.000Z
2020-07-06T06:13:45.000Z
OpenGL_Project/src/projects/attractors/attractor_system_blueprint.cc
felixyf0124/COMP477_F19_A2
80f96e130ef2715c3f10de25d1b973a60cc440e5
[ "MIT" ]
5
2017-03-03T02:13:15.000Z
2021-05-02T12:25:20.000Z
/************************************************************************* * Copyright (c) 2016 Fran�ois Trudel * * 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. *************************************************************************/ #include "projects/attractors/attractor_system_blueprint.hh" //C system files //C++ system files #include <memory> #include <limits> //Other libraries' .h files //Your project's .h files #include "core/particle_module.hh" #include "emitters/spherical_stream_emitter.hh" #include "renderers/core_opengl_renderer.hh" //Project specific components #include "projects/attractors/attractor_particle_system.hh" #include "projects/attractors/avx_particle_attractor.hh" namespace gem { namespace particle { namespace attractor_project { namespace blueprint { namespace attractor_system_builder { namespace { const glm::f32vec3 _ZeroVector = glm::f32vec3(0.0f, 0.0f, 0.0f); // Instead of using setters for every attribute, might as well put them public. // These parameters will be used during the Create() function to properly build the particle system glm::vec4 _HotColor = { 0.8235294117647059f, 0.0941176470588235f, 0.1803921568627451f, 1.0f }; glm::vec4 _ColdColor = { 0.1294117647058824f, 0.1607843137254902, 0.6392156862745098, 1.0f }; glm::f32vec3 _POI = { 1.0f, 1.0f, 1.0f }; float _InitialRadius = 1.0f; float _AccelerationRate = 0.0f; float _MaxDistance = 6.0f; std::size_t _ParticleCount = 1000000u; std::string _ParticleSystemName; // Handles on the dynamics to hand them over to the event handler // There are only used during the construction of the particle system std::shared_ptr< ParticleAttractor > _AttractorDynamicHandle; std::shared_ptr< ProximityColorUpdater > _ProximityColorUpdaterHandle; } void Create() { _AttractorDynamicHandle = std::make_shared<ParticleAttractor>(_POI, _AccelerationRate); _ProximityColorUpdaterHandle = std::make_shared<ProximityColorUpdater>(_POI, _HotColor, _ColdColor, _MaxDistance); auto wEmitter = std::make_shared<SphericalStreamEmitter>(_POI, _ZeroVector, _InitialRadius, 0.0f, std::numeric_limits<double>::max()); auto wParticleSystem = std::make_unique<ParticleSystem<LifeDeathCycle::Disabled> >(_ParticleCount, _ParticleSystemName, wEmitter); wParticleSystem->BindRenderer(std::make_shared<CoreGLRenderer>()); wParticleSystem->AddDynamic(_AttractorDynamicHandle); wParticleSystem->AddDynamic(_ProximityColorUpdaterHandle); particle_module::AddSystem(std::move(wParticleSystem)); } std::shared_ptr< ParticleAttractor > GetAttractorHandle() { return _AttractorDynamicHandle; } std::shared_ptr< ProximityColorUpdater > GetProximityColorUpdaterHandle() { return _ProximityColorUpdaterHandle; } void SetHotColor(const glm::vec4 &color) { _HotColor = color; } void SetColdColor(const glm::vec4 &color) { _ColdColor = color; } void SetPOI(const glm::f32vec3 &pos) { _POI = pos; } void SetInitialRadius(float radius) { _InitialRadius = radius; } void SetAccelerationRate(float rate) { _AccelerationRate = rate; } void SetMaxDistance(float distance) { _MaxDistance = distance; } void SetParticleCount(std::size_t count) { _ParticleCount = count; } void SetParticleSystemName(const std::string &name) { _ParticleSystemName = name; } } /* namespace attractor_system_builder */ } /* namespace blueprint */ } /* namespace attractor_project */ } /* namespace particle */ } /* namespace gem */
50.670732
136
0.711913
frtru
14dfc88d136480df8c85d062485ac70518677c59
3,687
cpp
C++
src/ItemFactory.cpp
zethon/ttvg
51d79ee3154669447dd522731aa0f7057e723abd
[ "MIT" ]
2
2020-11-02T20:51:36.000Z
2021-12-20T21:53:41.000Z
src/ItemFactory.cpp
zethon/ttvg
51d79ee3154669447dd522731aa0f7057e723abd
[ "MIT" ]
41
2020-07-20T16:37:48.000Z
2022-03-27T00:52:06.000Z
src/ItemFactory.cpp
zethon/ttvg
51d79ee3154669447dd522731aa0f7057e723abd
[ "MIT" ]
1
2020-11-02T20:51:37.000Z
2020-11-02T20:51:37.000Z
#include <boost/filesystem.hpp> #include <lua/lua.hpp> #include <fmt/core.h> #include "Item.h" #include "ItemFactory.h" #include "TTLua.h" namespace tt { namespace { ItemFactory* checkItemFactory(lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, ITEMFACTORY_LUA_IDX); int type = lua_type(L, -1); if (type != LUA_TLIGHTUSERDATA) { return nullptr; } ItemFactory* state = static_cast<ItemFactory*>(lua_touserdata(L, -1)); if (!state) { return nullptr; } lua_pop(L, 1); return state; } int ItemFactory_createItem(lua_State* L) { auto fact = checkItemFactory(L); const auto itemname = lua_tostring(L, 1); std::size_t size = sizeof(ItemPtr); void* userdata = lua_newuserdata(L, size); // create a shared_ptr in the space Lua allocated // for us, so if we never assign this to anyone/thing // else it should gt deleted new(userdata) ItemPtr{fact->createItem(itemname)}; luaL_setmetatable(L, Item::CLASS_NAME); return 1; } } // anonymous namespace const struct luaL_Reg ItemFactory::LuaMethods[] = { {"createItem", ItemFactory_createItem}, {nullptr, nullptr} }; // // Default item size. // Might want this to be the same as a "tile size" on the map. // constexpr auto DEFAULT_ITEM_WIDTH = 36.0f; constexpr auto DEFAULT_ITEM_HEIGHT = 36.0f; ItemFactory::ItemFactory(ResourceManager& resMgr) : _resources { resMgr } { } /** * * Create an Item from the specified name. * */ ItemPtr ItemFactory::createItem(const std::string& name, const ItemCallbacks& callbacks) { std::string jsonFile = _resources.getFilename(fmt::format("items/{}.json", name)); if( !boost::filesystem::exists(jsonFile) ) { auto error = fmt::format("file '{}' not found", jsonFile); throw std::runtime_error(error); } std::ifstream file(jsonFile.c_str()); nl::json json; if(file.is_open()) { file >> json; } std::string textureFile = fmt::format("items/{}.png", name); sf::Texture* texture = _resources.cacheTexture(textureFile); // // By default, scale item image to tile size. // int width = texture->getSize().x; int height = texture->getSize().y; float scaleX = DEFAULT_ITEM_WIDTH / width; float scaleY = DEFAULT_ITEM_HEIGHT / height; // // Optionally allow for item author to specify // size and scale. // if( json.find("image-attr") != json.end()) { nl::json children = json["image-attr"]; if (children.find("width") != children.end() && children.find("height") != children.end() && children.find("scale-x") != children.end() && children.find("scale-y") != children.end()) { width = json["image-attr"]["width"]; height = json["image-attr"]["height"]; scaleX = json["image-attr"]["scale-x"]; scaleY = json["image-attr"]["scale-y"]; } } auto item = std::make_shared<Item>( name, *texture, sf::Vector2i{ width, height } ); item->setScale(scaleX, scaleY); if(json.find("name") != json.end()) { item->setName(json["name"]); } if(json.find("description") != json.end()) { item->setDescription(json["description"]); } if(json.find("obtainable") != json.end()) { item->setObtainable(json["obtainable"]); } item->callbacks = callbacks; return item; } } // namespace tt
22.900621
74
0.578248
zethon
14e0ecc6593bddabb738b8c9545f982121bb21fc
52
cpp
C++
src/endian.cpp
u3shit/stcm-editor
2bf6576ad4e86ef7cae602182b90cfe2246a1565
[ "WTFPL" ]
56
2016-03-20T19:44:55.000Z
2021-09-03T13:08:16.000Z
src/endian.cpp
u3shit/stcm-editor
2bf6576ad4e86ef7cae602182b90cfe2246a1565
[ "WTFPL" ]
23
2016-06-09T21:09:28.000Z
2021-05-10T10:46:18.000Z
src/endian.cpp
u3shit/stcm-editor
2bf6576ad4e86ef7cae602182b90cfe2246a1565
[ "WTFPL" ]
12
2016-09-12T11:03:15.000Z
2021-07-04T06:10:06.000Z
#include "endian.hpp" #include "endian.binding.hpp"
17.333333
29
0.75
u3shit
14e549408580d37599d215c3be8c2bbe495ac395
349
cpp
C++
leetcode121.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode121.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode121.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
class Solution { public: int maxProfit(vector<int>& prices) { int Max = 0; int buy = INT_MIN; int sale = 0; for(auto price: prices) { if(-price > buy) buy = -price; if(buy + price > sale) sale = buy + price; } return sale; } };
19.388889
40
0.418338
SJTUGavinLiu
14e770757b4c2e2718dc9d8cf3d1dd3b3c8c34c3
637
cpp
C++
src/ButtonJoystick.cpp
stevendaniluk/SimRacingInputs
ca23999b9ed56acfc76c0e38ad4560476192cac9
[ "WTFPL" ]
null
null
null
src/ButtonJoystick.cpp
stevendaniluk/SimRacingInputs
ca23999b9ed56acfc76c0e38ad4560476192cac9
[ "WTFPL" ]
null
null
null
src/ButtonJoystick.cpp
stevendaniluk/SimRacingInputs
ca23999b9ed56acfc76c0e38ad4560476192cac9
[ "WTFPL" ]
null
null
null
#include <Arduino.h> #include "ButtonJoystick.h" ButtonJoystick::ButtonJoystick(Joystick_* joystick, uint8_t key, uint8_t pin, bool low_on = true) : ButtonInput::ButtonInput(pin, low_on) , joystick_(joystick) , key_(key) {} ButtonJoystick::ButtonJoystick(Joystick_* joystick, uint8_t key, uint8_t pin, int range_low, int range_high) : ButtonInput::ButtonInput(pin, range_low, range_high) , joystick_(joystick) , key_(key) {} void ButtonJoystick::send(bool pressed) const { #ifdef SIM_SERIAL_DEBUG Serial.print(key_); Serial.print(" state: "); Serial.println(pressed); #else joystick_->setButton(key_, pressed); #endif }
27.695652
108
0.748823
stevendaniluk
14e79150cb86102e088502d9aa01e3f9b95523ac
2,952
hpp
C++
qir/qat/ValidationPass/ValidationPassConfiguration.hpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/ValidationPass/ValidationPassConfiguration.hpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/ValidationPass/ValidationPassConfiguration.hpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
#pragma once // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "Commandline/ConfigurationManager.hpp" #include "QatTypes/QatTypes.hpp" #include <functional> #include <set> namespace microsoft { namespace quantum { struct OpcodeValue { String id{""}; String predicate{""}; OpcodeValue(String const& name, String const& fi = "") : id{name} , predicate{fi} { } OpcodeValue() = default; OpcodeValue(OpcodeValue&&) = default; OpcodeValue(OpcodeValue const&) = default; OpcodeValue& operator=(OpcodeValue&&) = default; OpcodeValue& operator=(OpcodeValue const&) = default; bool operator==(OpcodeValue const& other) const { return id == other.id && predicate == other.predicate; } }; } // namespace quantum } // namespace microsoft namespace std { template <> struct hash<microsoft::quantum::OpcodeValue> { size_t operator()(microsoft::quantum::OpcodeValue const& x) const { hash<std::string> hasher; return hasher(x.id + "." + x.predicate); } }; } // namespace std namespace microsoft { namespace quantum { class ValidationPassConfiguration { public: using Set = std::unordered_set<std::string>; using OpcodeSet = std::unordered_set<OpcodeValue>; // Setup and construction // ValidationPassConfiguration() = default; /// Setup function that adds the configuration flags to the ConfigurationManager. See the /// ConfigurationManager documentation for more details on how the setup process is implemented. void setup(ConfigurationManager& config); static ValidationPassConfiguration fromProfileName(String const& name); OpcodeSet const& allowedOpcodes() const; Set const& allowedExternalCallNames() const; bool allowInternalCalls() const; bool allowlistOpcodes() const; bool allowlistExternalCalls() const; bool allowlistPointerTypes() const; Set const& allowedPointerTypes() const; String profileName() const; private: void addAllowedExternalCall(String const& name); void addAllowedOpcode(String const& name); void addAllowedPointerType(String const& name); String profile_name_{"null"}; OpcodeSet opcodes_{}; Set external_calls_{}; Set allowed_pointer_types_{}; bool allowlist_opcodes_{true}; bool allowlist_external_calls_{true}; bool allow_internal_calls_{false}; bool allowlist_pointer_types_{false}; bool allow_primitive_return_{true}; bool allow_struct_return_{true}; bool allow_pointer_return_{true}; }; } // namespace quantum } // namespace microsoft
27.849057
104
0.631098
troelsfr
14e9189d89d5f3b2ce772f522dd64dda00ab0936
9,010
cpp
C++
LargeBarrelAnalysis/HitFinderTools.cpp
nenprio/j-pet-framework-examples
b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e
[ "Apache-2.0" ]
null
null
null
LargeBarrelAnalysis/HitFinderTools.cpp
nenprio/j-pet-framework-examples
b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e
[ "Apache-2.0" ]
1
2020-07-15T12:47:16.000Z
2020-07-15T12:47:16.000Z
LargeBarrelAnalysis/HitFinderTools.cpp
nenprio/j-pet-framework-examples
b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e
[ "Apache-2.0" ]
null
null
null
/** * @copyright Copyright 2018 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file HitFinderTools.cpp */ using namespace std; #include "UniversalFileLoader.h" #include "HitFinderTools.h" #include <TMath.h> #include <vector> #include <cmath> #include <map> /** * Helper method for sotring signals in vector */ void HitFinderTools::sortByTime(vector<JPetPhysSignal>& sigVec) { sort(sigVec.begin(), sigVec.end(), [](const JPetPhysSignal & sig1, const JPetPhysSignal & sig2) { return sig1.getTime() < sig2.getTime(); } ); } /** * Method distributing Signals according to Scintillator they belong to */ map<int, vector<JPetPhysSignal>> HitFinderTools::getSignalsBySlot( const JPetTimeWindow* timeWindow, bool useCorrupts ){ map<int, vector<JPetPhysSignal>> signalSlotMap; if (!timeWindow) { WARNING("Pointer of Time Window object is not set, returning empty map"); return signalSlotMap; } const unsigned int nSignals = timeWindow->getNumberOfEvents(); for (unsigned int i = 0; i < nSignals; i++) { auto physSig = dynamic_cast<const JPetPhysSignal&>(timeWindow->operator[](i)); if(!useCorrupts && physSig.getRecoFlag() == JPetBaseSignal::Corrupted) { continue; } int slotID = physSig.getBarrelSlot().getID(); auto search = signalSlotMap.find(slotID); if (search == signalSlotMap.end()) { vector<JPetPhysSignal> tmp; tmp.push_back(physSig); signalSlotMap.insert(pair<int, vector<JPetPhysSignal>>(slotID, tmp)); } else { search->second.push_back(physSig); } } return signalSlotMap; } /** * Loop over all Scins invoking matching procedure */ vector<JPetHit> HitFinderTools::matchAllSignals( map<int, vector<JPetPhysSignal>>& allSignals, const map<unsigned int, vector<double>>& velocitiesMap, double timeDiffAB, int refDetScinId, JPetStatistics& stats, bool saveHistos ) { vector<JPetHit> allHits; for (auto& slotSigals : allSignals) { // Loop for Reference Detector ID if (slotSigals.first == refDetScinId) { for (auto refSignal : slotSigals.second) { auto refHit = createDummyRefDetHit(refSignal); allHits.push_back(refHit); } continue; } // Loop for other slots than reference one auto slotHits = matchSignals( slotSigals.second, velocitiesMap, timeDiffAB, stats, saveHistos ); allHits.insert(allHits.end(), slotHits.begin(), slotHits.end()); } return allHits; } /** * Method matching signals on the same Scintillator */ vector<JPetHit> HitFinderTools::matchSignals( vector<JPetPhysSignal>& slotSignals, const map<unsigned int, vector<double>>& velocitiesMap, double timeDiffAB, JPetStatistics& stats, bool saveHistos ) { vector<JPetHit> slotHits; vector<JPetPhysSignal> remainSignals; sortByTime(slotSignals); while (slotSignals.size() > 0) { auto physSig = slotSignals.at(0); if(slotSignals.size() == 1){ remainSignals.push_back(physSig); break; } for (unsigned int j = 1; j < slotSignals.size(); j++) { if (slotSignals.at(j).getTime() - physSig.getTime() < timeDiffAB) { if (physSig.getPM().getSide() != slotSignals.at(j).getPM().getSide()) { auto hit = createHit( physSig, slotSignals.at(j), velocitiesMap, stats, saveHistos ); slotHits.push_back(hit); slotSignals.erase(slotSignals.begin() + j); slotSignals.erase(slotSignals.begin() + 0); break; } else { if (j == slotSignals.size() - 1) { remainSignals.push_back(physSig); slotSignals.erase(slotSignals.begin() + 0); break; } else { continue; } } } else { remainSignals.push_back(physSig); slotSignals.erase(slotSignals.begin() + 0); break; } } } if(remainSignals.size()>0 && saveHistos){ stats.getHisto1D("remain_signals_per_scin") ->Fill((float)(remainSignals.at(0).getPM().getScin().getID()), remainSignals.size()); } return slotHits; } /** * Method for Hit creation - setting all fields, that make sense here */ JPetHit HitFinderTools::createHit( const JPetPhysSignal& signal1, const JPetPhysSignal& signal2, const map<unsigned int, vector<double>>& velocitiesMap, JPetStatistics& stats, bool saveHistos ) { JPetPhysSignal signalA; JPetPhysSignal signalB; if (signal1.getPM().getSide() == JPetPM::SideA) { signalA = signal1; signalB = signal2; } else { signalA = signal2; signalB = signal1; } auto radius = signalA.getPM().getBarrelSlot().getLayer().getRadius(); auto theta = TMath::DegToRad() * signalA.getPM().getBarrelSlot().getTheta(); auto velocity = UniversalFileLoader::getConfigurationParameter( velocitiesMap, getProperChannel(signalA) ); checkTheta(theta); JPetHit hit; hit.setSignalA(signalA); hit.setSignalB(signalB); hit.setTime((signalA.getTime() + signalB.getTime()) / 2.0); hit.setQualityOfTime(-1.0); hit.setTimeDiff(signalB.getTime() - signalA.getTime()); hit.setQualityOfTimeDiff(-1.0); hit.setEnergy(-1.0); hit.setQualityOfEnergy(-1.0); hit.setScintillator(signalA.getPM().getScin()); hit.setBarrelSlot(signalA.getPM().getBarrelSlot()); hit.setPosX(radius * cos(theta)); hit.setPosY(radius * sin(theta)); hit.setPosZ(velocity * hit.getTimeDiff() / 2000.0); if(signalA.getRecoFlag() == JPetBaseSignal::Good && signalB.getRecoFlag() == JPetBaseSignal::Good) { hit.setRecoFlag(JPetHit::Good); if(saveHistos) { stats.getHisto1D("good_vs_bad_hits")->Fill(1); stats.getHisto2D("time_diff_per_scin") ->Fill(hit.getTimeDiff(), (float)(hit.getScintillator().getID())); stats.getHisto2D("hit_pos_per_scin") ->Fill(hit.getPosZ(), (float)(hit.getScintillator().getID())); } } else if (signalA.getRecoFlag() == JPetBaseSignal::Corrupted || signalB.getRecoFlag() == JPetBaseSignal::Corrupted){ hit.setRecoFlag(JPetHit::Corrupted); if(saveHistos) { stats.getHisto1D("good_vs_bad_hits")->Fill(2); } } else { hit.setRecoFlag(JPetHit::Unknown); if(saveHistos) { stats.getHisto1D("good_vs_bad_hits")->Fill(3); } } return hit; } /** * Method for Hit creation in case of reference detector. * Setting only some necessary fields. */ JPetHit HitFinderTools::createDummyRefDetHit(const JPetPhysSignal& signalB) { JPetHit hit; hit.setSignalB(signalB); hit.setTime(signalB.getTime()); hit.setQualityOfTime(-1.0); hit.setTimeDiff(0.0); hit.setQualityOfTimeDiff(-1.0); hit.setEnergy(-1.0); hit.setQualityOfEnergy(-1.0); hit.setScintillator(signalB.getPM().getScin()); hit.setBarrelSlot(signalB.getPM().getBarrelSlot()); return hit; } /** * Helper method for getting TOMB channel */ int HitFinderTools::getProperChannel(const JPetPhysSignal& signal) { auto someSigCh = signal.getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrValue)[0]; return someSigCh.getTOMBChannel().getChannel(); } /** * Helper method for checking if theta is in radians */ void HitFinderTools::checkTheta(const double& theta) { if (theta > 2 * TMath::Pi()) { WARNING("Probably wrong values of Barrel Slot theta - conversion to radians failed. Check please."); } } /** * Calculation of the total TOT of the hit - Time over Threshold: * the sum of the TOTs on all of the thresholds (1-4) and on the both sides (A,B) */ double HitFinderTools::calculateTOT(const JPetHit& hit) { double tot = 0.0; auto sigALead = hit.getSignalA().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum); auto sigBLead = hit.getSignalB().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum); auto sigATrail = hit.getSignalA().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum); auto sigBTrail = hit.getSignalB().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum); if (sigALead.size() > 0 && sigATrail.size() > 0){ for (unsigned i = 0; i < sigALead.size() && i < sigATrail.size(); i++){ tot += (sigATrail.at(i).getValue() - sigALead.at(i).getValue()); } } if (sigBLead.size() > 0 && sigBTrail.size() > 0){ for (unsigned i = 0; i < sigBLead.size() && i < sigBTrail.size(); i++){ tot += (sigBTrail.at(i).getValue() - sigBLead.at(i).getValue()); } } return tot; }
33.619403
104
0.681798
nenprio
14e9e47c065834ccf1e618fe1828066c4175e948
11,407
cpp
C++
libmetartc2/src/yangencoder/YangFfmpegEncoderMeta.cpp
zhoulipeng/metaRTC
c466cced24e99ee43132378ced0311036ddbbfa0
[ "MIT" ]
1
2022-01-20T03:07:07.000Z
2022-01-20T03:07:07.000Z
libmetartc2/src/yangencoder/YangFfmpegEncoderMeta.cpp
zhoulipeng/metaRTC
c466cced24e99ee43132378ced0311036ddbbfa0
[ "MIT" ]
null
null
null
libmetartc2/src/yangencoder/YangFfmpegEncoderMeta.cpp
zhoulipeng/metaRTC
c466cced24e99ee43132378ced0311036ddbbfa0
[ "MIT" ]
null
null
null
/* * YangFfmpegEncoderMeta.cpp * * Created on: 2020年9月26日 * Author: yang */ #include "YangFfmpegEncoderMeta.h" #include "YangVideoEncoderFfmpeg.h" #include <yangutil/sys/YangLog.h> #include <yangavutil/video/YangMeta.h> YangFfmpegEncoderMeta::YangFfmpegEncoderMeta() { #if Yang_Ffmpeg_UsingSo unloadLib(); #endif } YangFfmpegEncoderMeta::~YangFfmpegEncoderMeta() { #if Yang_Ffmpeg_UsingSo unloadLib(); m_lib.unloadObject(); m_lib1.unloadObject(); #endif } #if Yang_Ffmpeg_UsingSo void YangFfmpegEncoderMeta::loadLib() { yang_av_buffer_unref = (void (*)(AVBufferRef **buf)) m_lib1.loadFunction( "av_buffer_unref"); yang_av_hwframe_ctx_init = (int32_t (*)(AVBufferRef *ref)) m_lib1.loadFunction( "av_hwframe_ctx_init"); yang_av_frame_alloc = (AVFrame* (*)(void)) m_lib1.loadFunction( "av_frame_alloc"); yang_av_image_get_buffer_size = (int32_t (*)(enum AVPixelFormat pix_fmt, int32_t width, int32_t height, int32_t align)) m_lib1.loadFunction( "av_image_get_buffer_size"); yang_av_hwdevice_ctx_create = (int32_t (*)(AVBufferRef **device_ctx, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int32_t flags)) m_lib1.loadFunction("av_hwdevice_ctx_create"); yang_av_hwframe_transfer_data = (int32_t (*)(AVFrame *dst, const AVFrame *src, int32_t flags)) m_lib1.loadFunction("av_hwframe_transfer_data"); yang_av_free = (void (*)(void *ptr)) m_lib1.loadFunction("av_free"); yang_av_frame_free = (void (*)(AVFrame **frame)) m_lib1.loadFunction( "av_frame_free"); yang_av_buffer_ref = (AVBufferRef* (*)(AVBufferRef *buf)) m_lib1.loadFunction( "av_buffer_ref"); yang_av_image_fill_arrays = (int32_t (*)(uint8_t *dst_data[4], int32_t dst_linesize[4], const uint8_t *src, enum AVPixelFormat pix_fmt, int32_t width, int32_t height, int32_t align)) m_lib1.loadFunction( "av_image_fill_arrays"); yang_av_hwframe_ctx_alloc = (AVBufferRef* (*)(AVBufferRef *device_ctx)) m_lib1.loadFunction( "av_hwframe_ctx_alloc"); yang_av_hwframe_get_buffer = (int32_t (*)(AVBufferRef *hwframe_ctx, AVFrame *frame, int32_t flags)) m_lib1.loadFunction( "av_hwframe_get_buffer"); yang_av_malloc = (void* (*)(size_t size)) m_lib1.loadFunction("av_malloc"); yang_avcodec_alloc_context3 = (AVCodecContext* (*)(const AVCodec *codec)) m_lib.loadFunction( "avcodec_alloc_context3"); yang_av_init_packet = (void (*)(AVPacket *pkt)) m_lib.loadFunction( "av_init_packet"); yang_avcodec_find_encoder_by_name = (AVCodec* (*)(const char *name)) m_lib.loadFunction( "avcodec_find_encoder_by_name"); yang_avcodec_open2 = (int32_t (*)(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)) m_lib.loadFunction("avcodec_open2"); yang_avcodec_send_frame = (int32_t (*)(AVCodecContext *avctx, const AVFrame *frame)) m_lib.loadFunction("avcodec_send_frame"); yang_avcodec_receive_packet = (int32_t (*)(AVCodecContext *avctx, AVPacket *avpkt)) m_lib.loadFunction("avcodec_receive_packet"); yang_avcodec_close = (int32_t (*)(AVCodecContext *avctx)) m_lib.loadFunction( "avcodec_close"); } void YangFfmpegEncoderMeta::unloadLib() { yang_av_hwframe_ctx_alloc = NULL; yang_av_hwframe_ctx_init = NULL; yang_av_buffer_unref = NULL; yang_avcodec_find_encoder_by_name = NULL; yang_av_hwdevice_ctx_create = NULL; yang_av_frame_alloc = NULL; yang_avcodec_open2 = NULL; yang_av_image_get_buffer_size = NULL; yang_av_malloc = NULL; yang_av_image_fill_arrays = NULL; yang_av_init_packet = NULL; yang_av_hwframe_get_buffer = NULL; yang_av_hwframe_transfer_data = NULL; yang_avcodec_send_frame = NULL; yang_avcodec_receive_packet = NULL; yang_av_frame_free = NULL; yang_avcodec_close = NULL; yang_av_free = NULL; } #endif #define HEX2BIN(a) (((a)&0x40)?((a)&0xf)+9:((a)&0xf)) //void ConvertYCbCr2BGR(uint8_t *pYUV,uint8_t *pBGR,int32_t iWidth,int32_t iHeight); //void ConvertRGB2YUV(int32_t w,int32_t h,uint8_t *bmp,uint8_t *yuv); //int32_t g_m_fx2=2; void YangFfmpegEncoderMeta::yang_find_next_start_code(YangVideoCodec pve,uint8_t *buf,int32_t bufLen,int32_t *vpsPos,int32_t *vpsLen,int32_t *spsPos,int32_t *spsLen,int32_t *ppsPos,int32_t *ppsLen) { int32_t i = 0; // printf("\n**********************extradate.....=%d\n",bufLen); // for(int32_t j=0;j<bufLen;j++) printf("%02x,",*(buf+j)); //printf("\n*************************************\n"); *spsPos=0;*ppsPos=0; if(pve==Yang_VED_265) { *vpsPos=0; while(i<bufLen-3){ if (buf[i] == 0 && buf[i + 1] == 0 &&buf[i + 2] == 0&& buf[i + 3] == 1){ *vpsPos=i+4; i+=4; break; } i++; } } while (i <bufLen-3) { if (buf[i] == 0 && buf[i + 1] == 0 &&buf[i + 2] == 0&& buf[i + 3] == 1){ if(pve==Yang_VED_265) *vpsLen=i-4; *spsPos=i+4; i+=4; break; } i++; } while (i <bufLen-3) { if (buf[i] == 0 && buf[i + 1] == 0 &&buf[i + 2] == 0&& buf[i + 3] == 1){ *spsLen=i-*spsPos; *ppsPos=i+4; *ppsLen=bufLen-*ppsPos; break; } i++; } } int32_t YangFfmpegEncoderMeta::set_hwframe_ctx(AVPixelFormat ctxformat,AVPixelFormat swformat,YangVideoInfo *yvp,AVCodecContext *ctx, AVBufferRef *hw_device_ctx,int32_t pwid,int32_t phei) { AVBufferRef *hw_frames_ref; AVHWFramesContext *frames_ctx = NULL; int32_t err = 0; int32_t ret=0; if (!(hw_frames_ref = yang_av_hwframe_ctx_alloc(hw_device_ctx))) { yang_error("Failed to create VAAPI frame context.\n"); return -1; } frames_ctx = (AVHWFramesContext*) (hw_frames_ref->data); frames_ctx->format = ctxformat; frames_ctx->sw_format = swformat; frames_ctx->width = pwid; frames_ctx->height = phei; frames_ctx->initial_pool_size = 0; if ((err = yang_av_hwframe_ctx_init(hw_frames_ref)) < 0) { yang_error("Failed to initialize VAAPI frame context.Error code: %d\n", ret); yang_av_buffer_unref(&hw_frames_ref); return err; } ctx->hw_frames_ctx = yang_av_buffer_ref(hw_frames_ref); ctx->hw_device_ctx = yang_av_buffer_ref(hw_device_ctx); // ctx->hwaccel_flags=1; if (!ctx->hw_frames_ctx) err = AVERROR(ENOMEM); yang_av_buffer_unref(&hw_frames_ref); return err; } enum AVPixelFormat get_hw_format22(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Intel) return AV_PIX_FMT_VAAPI; if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Nvdia) return AV_PIX_FMT_CUDA; if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Android) return AV_PIX_FMT_MEDIACODEC; return AV_PIX_FMT_VAAPI; } void YangFfmpegEncoderMeta::yang_getSpsPps(YangH2645Conf *pconf, YangVideoInfo *p_yvp, YangVideoEncInfo *penc) { #if Yang_Ffmpeg_UsingSo m_lib.loadObject("libavcodec"); m_lib1.loadObject("libavutil"); loadLib(); #endif YangVideoCodec m_encoderType=(YangVideoCodec)p_yvp->videoEncoderType; YangVideoHwType m_hwType=(YangVideoHwType)p_yvp->videoEncHwType; AVCodec *m_codec=NULL; AVCodecContext *m_codecCtx = NULL; AVBufferRef *hw_device_ctx=NULL; //hevc_vaapi nvenc nvdec vdpau h264_nvenc if(m_encoderType==Yang_VED_264){ if(m_hwType==YangV_Hw_Intel) m_codec = yang_avcodec_find_encoder_by_name("h264_vaapi");//avcodec_find_encoder(AV_CODEC_ID_H264); if(m_hwType==YangV_Hw_Nvdia) m_codec = yang_avcodec_find_encoder_by_name("h264_nvenc"); if(m_hwType==YangV_Hw_Android) m_codec = yang_avcodec_find_encoder_by_name("h264_mediacodec"); }else if(m_encoderType==Yang_VED_265){ if(m_hwType==YangV_Hw_Intel) m_codec = yang_avcodec_find_encoder_by_name("hevc_vaapi"); if(m_hwType==YangV_Hw_Nvdia) m_codec = yang_avcodec_find_encoder_by_name("hevc_nvenc"); if(m_hwType==YangV_Hw_Android) m_codec = yang_avcodec_find_encoder_by_name("hevc_mediacodec"); } m_codecCtx = yang_avcodec_alloc_context3(m_codec); YangVideoEncoderFfmpeg::initParam(m_codecCtx,p_yvp,penc); m_codecCtx->get_format = get_hw_format22; // AV_PIX_FMT_NV12;//get_hw_format; int32_t ret=0; //AV_HWDEVICE_TYPE_CUDA YangVideoEncoderFfmpeg::g_hwType=(YangVideoHwType)p_yvp->videoEncHwType; if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Intel){ ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI,"/dev/dri/renderD128", NULL, 0); m_codecCtx->pix_fmt = AV_PIX_FMT_VAAPI; }else if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Nvdia){ ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA,"CUDA", NULL, 0); m_codecCtx->pix_fmt = AV_PIX_FMT_CUDA; }else if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Android){ ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_MEDIACODEC,"MEDIACODEC", NULL, 0); m_codecCtx->pix_fmt = AV_PIX_FMT_MEDIACODEC; } //YangVideoEncoderFfmpeg::g_hwType=m_codecCtx->pix_fmt ; if(ret<0){ printf("\nhw create error!..ret=%d\n",ret); exit(1); } //ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA,"CUDA", NULL, 0); //AV_PIX_FMT_NV12;//AV_PIX_FMT_VAAPI;AV_PIX_FMT_YUV420P;//AV_PIX_FMT_CUDA //AV_PIX_FMT_CUDA AVPixelFormat ctxformat,swformat; if(p_yvp->videoEncHwType==YangV_Hw_Intel) ctxformat = AV_PIX_FMT_VAAPI; if(p_yvp->videoEncHwType==YangV_Hw_Nvdia) ctxformat = AV_PIX_FMT_CUDA; if(p_yvp->videoEncHwType==YangV_Hw_Android) ctxformat = AV_PIX_FMT_MEDIACODEC; if(p_yvp->bitDepth==8) swformat = AV_PIX_FMT_NV12; if(p_yvp->bitDepth==10) swformat = AV_PIX_FMT_P010; if(p_yvp->bitDepth==16) swformat = AV_PIX_FMT_P016; if ((ret = set_hwframe_ctx(ctxformat,swformat,p_yvp,m_codecCtx, hw_device_ctx, p_yvp->outWidth, p_yvp->outHeight)) < 0) { printf("Failed to set hwframe context.\n"); //goto close; } m_codecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; ret = yang_avcodec_open2(m_codecCtx, m_codec, NULL); if (ret < 0){ printf("\navcodec_open2 failure................\n"); exit(1); } int32_t vpsPos=0,vpsLen=0; int32_t spsPos=0,ppsPos=0; int32_t spsLen=0,ppsLen=0; yang_find_next_start_code(m_encoderType,m_codecCtx->extradata,m_codecCtx->extradata_size,&vpsPos,&vpsLen,&spsPos,&spsLen,&ppsPos,&ppsLen); if(m_encoderType==Yang_VED_265) { pconf->vpsLen=vpsLen; memcpy(pconf->vps,m_codecCtx->extradata+vpsPos,vpsLen); //printf("\n**************vpsLen===%d...\n",pconf->vpsLen); //for(int32_t i=0;i<pconf->vpsLen;i++) printf("%02x,",pconf->vps[i]); } pconf->spsLen=spsLen; pconf->ppsLen=ppsLen; memcpy(pconf->sps,m_codecCtx->extradata+spsPos,spsLen); memcpy(pconf->pps,m_codecCtx->extradata+ppsPos,ppsLen); yang_av_buffer_unref(&hw_device_ctx); if (m_codecCtx){ yang_avcodec_close(m_codecCtx); yang_av_free(m_codecCtx); } m_codecCtx = NULL; } //Conf264 t_conf264; void YangFfmpegEncoderMeta::yang_initVmd(YangVideoMeta *p_vmd, YangVideoInfo *p_yvp, YangVideoEncInfo *penc) { if (!p_vmd->isInit) { yang_getSpsPps(&p_vmd->mp4Meta, p_yvp,penc); if(p_yvp->videoEncoderType==Yang_VED_264) yang_getConfig_Flv_H264(&p_vmd->mp4Meta, p_vmd->livingMeta.buffer,&p_vmd->livingMeta.bufLen); if(p_yvp->videoEncoderType==Yang_VED_265) yang_getConfig_Flv_H265(&p_vmd->mp4Meta, p_vmd->livingMeta.buffer,&p_vmd->livingMeta.bufLen); // yang_getH265Config_Flv(&p_vmd->mp4Meta, p_vmd->flvMeta.buffer, &p_vmd->flvMeta.bufLen); p_vmd->isInit = 1; } }
39.470588
197
0.721048
zhoulipeng
14eb26ca8cef187940b640d6857f6d548271a543
682
hpp
C++
source/forge/vulkan/device.hpp
aegooby/forge
972e811ef7e454c2a862cc575fd4355a84a83ad0
[ "Apache-2.0" ]
null
null
null
source/forge/vulkan/device.hpp
aegooby/forge
972e811ef7e454c2a862cc575fd4355a84a83ad0
[ "Apache-2.0" ]
null
null
null
source/forge/vulkan/device.hpp
aegooby/forge
972e811ef7e454c2a862cc575fd4355a84a83ad0
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../__common.hpp" #include "common.hpp" namespace forge { namespace vulkan { class device { private: class context& context; public: struct queue { std::uint32_t index = ~0u; vk::Queue queue; }; /** @brief Represents the GPU used. */ vk::PhysicalDevice physical; /** @brief Interface for physical device(s). */ vk::UniqueDevice logical; struct queues { queue graphics; queue present; bool same(); std::vector<std::uint32_t> indices(); } queues; device(class context&); void start(); }; } // namespace vulkan } // namespace forge
17.487179
51
0.576246
aegooby
14f5393ec096ee23599774671ff019f7efe9fb00
455
hh
C++
src/phantasm-hardware-interface/vulkan/common/debug_callback.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
6
2020-12-09T13:53:26.000Z
2021-12-24T14:13:17.000Z
src/phantasm-hardware-interface/vulkan/common/debug_callback.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
5
2020-01-29T09:46:36.000Z
2020-09-04T16:15:53.000Z
src/phantasm-hardware-interface/vulkan/common/debug_callback.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
null
null
null
#pragma once #include <phantasm-hardware-interface/vulkan/loader/volk.hh> namespace phi::vk::detail { VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, VkDebugUtilsMessengerCallbackDataEXT const* callback_data, void* user_data); }
35
104
0.593407
project-arcana
14f59e5b89402ef03b8e4a61b2a3f80717043c07
15,068
cpp
C++
Projects/TestShadow/src/TestScene.cpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
Projects/TestShadow/src/TestScene.cpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
Projects/TestShadow/src/TestScene.cpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <vector> #include <stdio.h> #include "TestScene.hpp" #include "MapHelper.hpp" #include "GraphicsUtilities.h" #include "TextureUtilities.h" #include "Sphere.h" #include "Plane.h" #include "Helmet.h" #include "AnimPeople.h" #include "InputController.hpp" #include "Actor.h" #include "FastRand.hpp" namespace Diligent { SampleBase* CreateSample() { return new TestScene(); } void TestScene::GetEngineInitializationAttribs(RENDER_DEVICE_TYPE DeviceType, EngineCreateInfo& EngineCI, SwapChainDesc& SCDesc) { SampleBase::GetEngineInitializationAttribs(DeviceType, EngineCI, SCDesc); EngineCI.Features.DepthClamp = DEVICE_FEATURE_STATE_OPTIONAL; // We do not need the depth buffer from the swap chain in this sample SCDesc.DepthBufferFormat = TEX_FORMAT_UNKNOWN; } void TestScene::Initialize(const SampleInitInfo& InitInfo) { SampleBase::Initialize(InitInfo); Init = InitInfo; CreateRenderPass(); m_Camera.SetPos(float3(5.0f, 0.0f, 0.0f)); m_Camera.SetRotation(PI_F / 2.f, 0, 0); m_Camera.SetRotationSpeed(0.005f); m_Camera.SetMoveSpeed(5.f); m_Camera.SetSpeedUpScales(5.f, 10.f); // Create a shader source stream factory to load shaders from files. RefCntAutoPtr<IShaderSourceInputStreamFactory> pShaderSourceFactory; m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(nullptr, &pShaderSourceFactory); envMaps.reset(new EnvMap(Init, m_BackgroundMode, m_pRenderPass)); ambientlight.reset(new AmbientLight(Init, m_pRenderPass, pShaderSourceFactory)); PointLight* light1 = new PointLight(Init, m_pRenderPass, pShaderSourceFactory); light1->setLocation(float3(-1, 0, 0)); light1->setColor(float3(1, 0, 0)); PointLight* light2 = new PointLight(Init, m_pRenderPass, pShaderSourceFactory); light2->setLocation(float3(0, 0, 0)); light2->setColor(float3(0, 1, 0)); PointLight *light3 = new PointLight(Init, m_pRenderPass, pShaderSourceFactory); light3->setLocation(float3(1, 0, 0)); light3->setColor(float3(0, 0, 1)); lights.emplace_back(light1); lights.emplace_back(light2); lights.emplace_back(light3); Helmet* casque1 = new Helmet(Init, m_BackgroundMode, m_pRenderPass); casque1->setPosition(float3(-1, 0, 0)); Helmet* casque2 = new Helmet(Init, m_BackgroundMode, m_pRenderPass); casque2->setPosition(float3(0, 0, 0)); Helmet* casque3 = new Helmet(Init, m_BackgroundMode, m_pRenderPass); casque3->setPosition(float3(1, 0, 0)); Plane* sol = new Plane(Init, m_BackgroundMode, m_pRenderPass); sol->setPosition(float3(0, -0.25, 0)); actors.emplace_back(casque1); actors.emplace_back(casque2); actors.emplace_back(casque3); actors.emplace_back(sol); } void TestScene::CreateRenderPass() { // Attachment 0 - Color buffer // Attachment 1 - Depth Z // Attachment 2 - Depth buffer // Attachment 3 - Final color buffer constexpr Uint32 NumAttachments = 4; // Prepare render pass attachment descriptions RenderPassAttachmentDesc Attachments[NumAttachments]; Attachments[0].Format = TEX_FORMAT_RGBA8_UNORM; Attachments[0].InitialState = RESOURCE_STATE_RENDER_TARGET; Attachments[0].FinalState = RESOURCE_STATE_INPUT_ATTACHMENT; Attachments[0].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[0].StoreOp = ATTACHMENT_STORE_OP_DISCARD; // We will not need the result after the end of the render pass Attachments[1].Format = TEX_FORMAT_R32_FLOAT; Attachments[1].InitialState = RESOURCE_STATE_RENDER_TARGET; Attachments[1].FinalState = RESOURCE_STATE_INPUT_ATTACHMENT; Attachments[1].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[1].StoreOp = ATTACHMENT_STORE_OP_DISCARD; // We will not need the result after the end of the render pass Attachments[2].Format = DepthBufferFormat; Attachments[2].InitialState = RESOURCE_STATE_DEPTH_WRITE; Attachments[2].FinalState = RESOURCE_STATE_DEPTH_WRITE; Attachments[2].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[2].StoreOp = ATTACHMENT_STORE_OP_DISCARD; // We will not need the result after the end of the render pass Attachments[3].Format = m_pSwapChain->GetDesc().ColorBufferFormat; Attachments[3].InitialState = RESOURCE_STATE_RENDER_TARGET; Attachments[3].FinalState = RESOURCE_STATE_RENDER_TARGET; Attachments[3].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[3].StoreOp = ATTACHMENT_STORE_OP_STORE; // Subpass 1 - Render G-buffer // Subpass 2 - Lighting constexpr Uint32 NumSubpasses = 2; // Prepar subpass descriptions SubpassDesc Subpasses[NumSubpasses]; // clang-format off // Subpass 0 attachments - 2 render targets and depth buffer AttachmentReference RTAttachmentRefs0[] = { {0, RESOURCE_STATE_RENDER_TARGET}, {1, RESOURCE_STATE_RENDER_TARGET} }; AttachmentReference DepthAttachmentRef0 = {2, RESOURCE_STATE_DEPTH_WRITE}; // Subpass 1 attachments - 1 render target, depth buffer, 2 input attachments AttachmentReference RTAttachmentRefs1[] = { {3, RESOURCE_STATE_RENDER_TARGET} }; AttachmentReference DepthAttachmentRef1 = {2, RESOURCE_STATE_DEPTH_WRITE}; AttachmentReference InputAttachmentRefs1[] = { {0, RESOURCE_STATE_INPUT_ATTACHMENT}, {1, RESOURCE_STATE_INPUT_ATTACHMENT} }; // clang-format on Subpasses[0].RenderTargetAttachmentCount = _countof(RTAttachmentRefs0); Subpasses[0].pRenderTargetAttachments = RTAttachmentRefs0; Subpasses[0].pDepthStencilAttachment = &DepthAttachmentRef0; Subpasses[1].RenderTargetAttachmentCount = _countof(RTAttachmentRefs1); Subpasses[1].pRenderTargetAttachments = RTAttachmentRefs1; Subpasses[1].pDepthStencilAttachment = &DepthAttachmentRef1; Subpasses[1].InputAttachmentCount = _countof(InputAttachmentRefs1); Subpasses[1].pInputAttachments = InputAttachmentRefs1; // We need to define dependency between subpasses 0 and 1 to ensure that // all writes are complete before we use the attachments for input in subpass 1. SubpassDependencyDesc Dependencies[1]; Dependencies[0].SrcSubpass = 0; Dependencies[0].DstSubpass = 1; Dependencies[0].SrcStageMask = PIPELINE_STAGE_FLAG_RENDER_TARGET; Dependencies[0].DstStageMask = PIPELINE_STAGE_FLAG_PIXEL_SHADER; Dependencies[0].SrcAccessMask = ACCESS_FLAG_RENDER_TARGET_WRITE; Dependencies[0].DstAccessMask = ACCESS_FLAG_SHADER_READ; RenderPassDesc RPDesc; RPDesc.Name = "Deferred shading render pass desc"; RPDesc.AttachmentCount = _countof(Attachments); RPDesc.pAttachments = Attachments; RPDesc.SubpassCount = _countof(Subpasses); RPDesc.pSubpasses = Subpasses; RPDesc.DependencyCount = _countof(Dependencies); RPDesc.pDependencies = Dependencies; m_pDevice->CreateRenderPass(RPDesc, &m_pRenderPass); VERIFY_EXPR(m_pRenderPass != nullptr); } RefCntAutoPtr<IFramebuffer> TestScene::CreateFramebuffer(ITextureView* pDstRenderTarget) { const auto& RPDesc = m_pRenderPass->GetDesc(); const auto& SCDesc = m_pSwapChain->GetDesc(); // Create window-size offscreen render target TextureDesc TexDesc; TexDesc.Name = "Color G-buffer"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_INPUT_ATTACHMENT; TexDesc.Format = RPDesc.pAttachments[0].Format; TexDesc.Width = SCDesc.Width; TexDesc.Height = SCDesc.Height; TexDesc.MipLevels = 1; // Define optimal clear value TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = 0.f; TexDesc.ClearValue.Color[1] = 0.f; TexDesc.ClearValue.Color[2] = 0.f; TexDesc.ClearValue.Color[3] = 0.f; RefCntAutoPtr<ITexture> pColorBuffer; m_pDevice->CreateTexture(TexDesc, nullptr, &pColorBuffer); // OpenGL does not allow combining swap chain render target with any // other render target, so we have to create an auxiliary texture. RefCntAutoPtr<ITexture> pOpenGLOffsreenColorBuffer; if (pDstRenderTarget == nullptr) { TexDesc.Name = "OpenGL Offscreen Render Target"; TexDesc.Format = SCDesc.ColorBufferFormat; m_pDevice->CreateTexture(TexDesc, nullptr, &pOpenGLOffsreenColorBuffer); pDstRenderTarget = pOpenGLOffsreenColorBuffer->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); } TexDesc.Name = "Depth Z G-buffer"; TexDesc.Format = RPDesc.pAttachments[1].Format; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = 1.f; TexDesc.ClearValue.Color[1] = 1.f; TexDesc.ClearValue.Color[2] = 1.f; TexDesc.ClearValue.Color[3] = 1.f; RefCntAutoPtr<ITexture> pDepthZBuffer; m_pDevice->CreateTexture(TexDesc, nullptr, &pDepthZBuffer); TexDesc.Name = "Depth buffer"; TexDesc.Format = RPDesc.pAttachments[2].Format; TexDesc.BindFlags = BIND_DEPTH_STENCIL; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.DepthStencil.Depth = 1.f; TexDesc.ClearValue.DepthStencil.Stencil = 0; RefCntAutoPtr<ITexture> pDepthBuffer; m_pDevice->CreateTexture(TexDesc, nullptr, &pDepthBuffer); ITextureView* pAttachments[] = // { pColorBuffer->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET), pDepthZBuffer->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET), pDepthBuffer->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL), pDstRenderTarget // }; FramebufferDesc FBDesc; FBDesc.Name = "G-buffer framebuffer"; FBDesc.pRenderPass = m_pRenderPass; FBDesc.AttachmentCount = _countof(pAttachments); FBDesc.ppAttachments = pAttachments; RefCntAutoPtr<IFramebuffer> pFramebuffer; m_pDevice->CreateFramebuffer(FBDesc, &pFramebuffer); VERIFY_EXPR(pFramebuffer != nullptr); ColorBuffer = pColorBuffer; DepthZBuffer = pDepthZBuffer; return pFramebuffer; } IFramebuffer* TestScene::GetCurrentFramebuffer() { auto* pCurrentBackBufferRTV = m_pDevice->GetDeviceCaps().IsGLDevice() ? nullptr : m_pSwapChain->GetCurrentBackBufferRTV(); auto fb_it = m_FramebufferCache.find(pCurrentBackBufferRTV); if (fb_it != m_FramebufferCache.end()) { return fb_it->second; } else { auto it = m_FramebufferCache.emplace(pCurrentBackBufferRTV, CreateFramebuffer(pCurrentBackBufferRTV)); VERIFY_EXPR(it.second); return it.first->second; } } // Render a frame void TestScene::Render() { auto* pFramebuffer = GetCurrentFramebuffer(); ambientlight->CreateSRB(ColorBuffer, DepthZBuffer); for (auto light : lights) { light->CreateSRB(ColorBuffer, DepthZBuffer); } BeginRenderPassAttribs RPBeginInfo; RPBeginInfo.pRenderPass = m_pRenderPass; RPBeginInfo.pFramebuffer = pFramebuffer; OptimizedClearValue ClearValues[4]; // Color ClearValues[0].Color[0] = 0.f; ClearValues[0].Color[1] = 0.f; ClearValues[0].Color[2] = 0.f; ClearValues[0].Color[3] = 0.f; // Depth Z ClearValues[1].Color[0] = 1.f; ClearValues[1].Color[1] = 1.f; ClearValues[1].Color[2] = 1.f; ClearValues[1].Color[3] = 1.f; // Depth buffer ClearValues[2].DepthStencil.Depth = 1.f; // Final color buffer ClearValues[3].Color[0] = 0.0625f; ClearValues[3].Color[1] = 0.0625f; ClearValues[3].Color[2] = 0.0625f; ClearValues[3].Color[3] = 0.f; RPBeginInfo.pClearValues = ClearValues; RPBeginInfo.ClearValueCount = _countof(ClearValues); RPBeginInfo.StateTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; m_pImmediateContext->BeginRenderPass(RPBeginInfo); for (auto actor : actors) { if (actor->getState() == Actor::ActorState::Active) { actor->RenderActor(m_Camera, false); } } m_pImmediateContext->NextSubpass(); envMaps->RenderActor(m_Camera, false); ambientlight->RenderActor(m_Camera, false); for (auto light : lights) { light->RenderActor(m_Camera, false); } m_pImmediateContext->EndRenderPass(); if (m_pDevice->GetDeviceCaps().IsGLDevice()) { // In OpenGL we now have to copy our off-screen buffer to the default framebuffer auto* pOffscreenRenderTarget = pFramebuffer->GetDesc().ppAttachments[3]->GetTexture(); auto* pBackBuffer = m_pSwapChain->GetCurrentBackBufferRTV()->GetTexture(); CopyTextureAttribs CopyAttribs{pOffscreenRenderTarget, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, pBackBuffer, RESOURCE_STATE_TRANSITION_MODE_TRANSITION}; m_pImmediateContext->CopyTexture(CopyAttribs); } } void TestScene::Update(double CurrTime, double ElapsedTime) { SampleBase::Update(CurrTime, ElapsedTime); m_Camera.Update(m_InputController, static_cast<float>(ElapsedTime)); // Animate Actors for (auto actor : actors) { actor->Update(CurrTime, ElapsedTime); } for (auto light : lights) { light->UpdateActor(CurrTime, ElapsedTime); } //if (m_InputController.IsKeyDown(InputKeys::MoveBackward)) // actors.back()->setState(Actor::ActorState::Dead); } void TestScene::removeActor(Actor* actor) { auto iter = std::find(begin(actors), end(actors), actor); if (iter != end(actors)) { std::iter_swap(iter, end(actors) - 1); actors.pop_back(); } } } // namespace Diligent
35.537736
128
0.708123
JorisSAN
14f5ab3a1550bd0d3946bf255f65796998f5fb5e
1,405
cpp
C++
tools/rcomp-src/lib/BSymbolTable.cpp
Aaron-Goldman/creative-engine
c1f0a89cefe77415fc03283277e4472d771b6ebc
[ "MIT" ]
13
2019-06-13T03:30:58.000Z
2022-01-20T01:20:37.000Z
tools/rcomp-src/lib/BSymbolTable.cpp
Aaron-Goldman/creative-engine
c1f0a89cefe77415fc03283277e4472d771b6ebc
[ "MIT" ]
21
2019-07-15T14:11:20.000Z
2020-11-08T18:14:03.000Z
tools/rcomp-src/lib/BSymbolTable.cpp
Aaron-Goldman/creative-engine
c1f0a89cefe77415fc03283277e4472d771b6ebc
[ "MIT" ]
12
2019-05-29T14:30:38.000Z
2021-02-03T10:07:41.000Z
#include "BSymbolTable.h" // hash a string to a value between 0-255 static TInt16 hash(const char *s) { // this routine is stupid simple. There are other hash algorithms that produce a better distribution of hash values. // better distribution makes it so one bucket list doesn't get huge while others are empty. // better distribution probably comes at a CPU processing cost, though. // for our purposes, this is fine. TInt v = 0; while (*s != '\0') { v += *s; s++; } return v%256; } BSymbolTable::BSymbolTable() { // } BSymbolTable::~BSymbolTable() { // } BSymbol *BSymbolTable::LookupSymbol(const char *name) { TInt h = hash(name); BSymbolList &bucket = buckets[h]; for (BSymbol *sym = bucket.First(); !bucket.End(sym); sym=bucket.Next(sym)) { if (strcmp(sym->name, name) == 0) { return sym; } } return ENull; } TBool BSymbolTable::AddSymbol(const char *aName, TUint32 aValue, TAny *aPtr) { BSymbol *sym = LookupSymbol(aName); if (sym) { // already exists if (sym->value == aValue && sym->aptr == aPtr) { // trying to add a duplicate, pretend it succeeded) return ETrue; } else { // trying to add same name with different value! return EFalse; } } // doesn't exist, we'll add it TInt h = hash(aName); sym = new BSymbol(aName, aValue, aPtr); buckets[h].AddTail(*sym); return ETrue; }
25.089286
119
0.639146
Aaron-Goldman
14f872707c041bd974f3a0aca60b326a40771979
7,972
cpp
C++
LibRaw/src/decoders/decoders_libraw_dcrdefs.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
497
2019-06-20T09:52:58.000Z
2022-03-31T12:56:49.000Z
LibRaw/src/decoders/decoders_libraw_dcrdefs.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
58
2019-06-19T10:53:49.000Z
2022-02-14T22:43:18.000Z
LibRaw/src/decoders/decoders_libraw_dcrdefs.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
57
2019-07-08T16:08:01.000Z
2022-03-12T15:00:04.000Z
/* -*- C++ -*- * Copyright 2019-2020 LibRaw LLC ([email protected]) * LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). */ #include "../../internal/dcraw_defs.h" void LibRaw::nikon_coolscan_load_raw() { if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); for (int row = 0; row < raw_height; row++) { if(tiff_bps <=8) fread(buf, 1, bufsize, ifp); else read_shorts(ubuf,width*3); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (is_NikonTransfer == 2) { // it is also (tiff_bps == 8) for (int col = 0; col < width; col++) { ip[col][0] = ((float)curve[buf[col * 3]]) / 255.0f; ip[col][1] = ((float)curve[buf[col * 3 + 1]]) / 255.0f; ip[col][2] = ((float)curve[buf[col * 3 + 2]]) / 255.0f; ip[col][3] = 0; } } else if (tiff_bps <= 8) { for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } } else { for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } } free(buf); } void LibRaw::broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; ushort _raw_stride = (ushort)load_flags; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + _raw_stride, 1, _raw_stride, ifp) < _raw_stride) derror(); FORC(_raw_stride) data[c] = data[_raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void LibRaw::android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void LibRaw::android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void LibRaw::unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < (int)maximum) ; for (row = raw_height - 1; row >= 0; row--) { checkCancel(); read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } #ifdef USE_6BY9RPI void LibRaw::rpi_load_raw8() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = raw_width; else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw8()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp++, col++) RAW(row, col + c) = dp[c]; } free(data); maximum = 0xff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void LibRaw::rpi_load_raw12() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = (raw_width * 3 + 1) / 2; else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw12()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 3, col += 2) FORC(2) RAW(row, col + c) = (dp[c] << 4) | (dp[2] >> (c << 2) & 0xF); } free(data); maximum = 0xfff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void LibRaw::rpi_load_raw14() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = ((raw_width * 7) + 3) >> 2; else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw14()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 7, col += 4) { RAW(row, col + 0) = (dp[0] << 6) | (dp[4] >> 2); RAW(row, col + 1) = (dp[1] << 6) | ((dp[4] & 0x3) << 4) | ((dp[5] & 0xf0) >> 4); RAW(row, col + 2) = (dp[2] << 6) | ((dp[5] & 0xf) << 2) | ((dp[6] & 0xc0) >> 6); RAW(row, col + 3) = (dp[3] << 6) | ((dp[6] & 0x3f) << 2); } } free(data); maximum = 0x3fff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void LibRaw::rpi_load_raw16() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = (raw_width * 2); else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw16()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 2, col++) RAW(row, col + c) = (dp[1] << 8) | dp[0]; } free(data); maximum = 0xffff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } #endif
27.874126
83
0.546162
lcsteyn
14f9c3b396b7d23e09f4c84c111d35d4f788a86e
10,281
cc
C++
lite/backends/cuda/math/gemm.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/backends/cuda/math/gemm.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/backends/cuda/math/gemm.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/backends/cuda/math/gemm.h" #include <iostream> #include "lite/core/device_info.h" namespace paddle { namespace lite { namespace cuda { namespace math { template <typename PTypeIn, typename PTypeOut> bool Gemm<PTypeIn, PTypeOut>::init(const bool trans_a, bool trans_b, const int m, const int n, const int k, Context<TARGET(kCUDA)> *ctx) { if (cu_handle_ == nullptr) { this->exe_stream_ = ctx->exec_stream(); CUBLAS_CALL(cublasCreate(&cu_handle_)); CUBLAS_CALL(cublasSetMathMode(cu_handle_, CUBLAS_TENSOR_OP_MATH)); CUBLAS_CALL(cublasSetStream(cu_handle_, this->exe_stream_)); } lda_ = (!trans_a) ? k : m; ldb_ = (!trans_b) ? n : k; ldc_ = n; m_ = m; n_ = n; k_ = k; cu_trans_a_ = trans_a ? CUBLAS_OP_T : CUBLAS_OP_N; cu_trans_b_ = trans_b ? CUBLAS_OP_T : CUBLAS_OP_N; return true; } template <typename PTypeIn, typename PTypeOut> bool Gemm<PTypeIn, PTypeOut>::init(const bool trans_a, bool trans_b, const int m, const int n, const int k, const int lda, const int ldb, const int ldc, Context<TARGET(kCUDA)> *ctx) { if (cu_handle_ == nullptr) { this->exe_stream_ = ctx->exec_stream(); CUBLAS_CALL(cublasCreate(&cu_handle_)); CUBLAS_CALL(cublasSetMathMode(cu_handle_, CUBLAS_TENSOR_OP_MATH)); CUBLAS_CALL(cublasSetStream(cu_handle_, this->exe_stream_)); } m_ = m; n_ = n; k_ = k; lda_ = lda; ldb_ = ldb; ldc_ = ldc; cu_trans_a_ = trans_a ? CUBLAS_OP_T : CUBLAS_OP_N; cu_trans_b_ = trans_b ? CUBLAS_OP_T : CUBLAS_OP_N; return true; } template <> bool Gemm<float, float>::run(const float alpha, const float beta, const float *a, const float *b, float *c, Context<TARGET(kCUDA)> *ctx) { CUBLAS_CALL(cublasSgemm(cu_handle_, cu_trans_b_, cu_trans_a_, n_, m_, k_, &alpha, b, ldb_, a, lda_, &beta, c, ldc_)); return true; } template <> bool Gemm<half, half>::run(const half alpha, const half beta, const half *a, const half *b, half *c, Context<TARGET(kCUDA)> *ctx) { CUBLAS_CALL(cublasHgemm(cu_handle_, cu_trans_b_, cu_trans_a_, n_, m_, k_, &alpha, b, ldb_, a, lda_, &beta, c, ldc_)); return true; } template class Gemm<float, float>; template class Gemm<half, half>; // LtGemm template <typename T> class cublasTypeWrapper; template <> class cublasTypeWrapper<float> { public: static const cudaDataType_t type = CUDA_R_32F; }; template <> class cublasTypeWrapper<half> { public: static const cudaDataType_t type = CUDA_R_16F; }; #if (CUBLAS_VER_MAJOR * 10 + CUBLAS_VER_MINOR) == 101 template <typename PTypeIn, typename PTypeOut> bool LtGemm<PTypeIn, PTypeOut>::init(const bool trans_a, const bool trans_b, const int m, const int n, const int k, Context<TARGET(kCUDA)> *ctx) { int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; return this->init(trans_a, trans_b, m, n, k, lda, ldb, ldc, ctx); } template <typename PTypeIn, typename PTypeOut> bool LtGemm<PTypeIn, PTypeOut>::init(const bool trans_a, const bool trans_b, const int m, const int n, const int k, const int lda, const int ldb, const int ldc, Context<TARGET(kCUDA)> *ctx) { if (handle_ == nullptr) { this->exe_stream_ = ctx->exec_stream(); CUBLAS_CALL(cublasLtCreate(&handle_)); } m_ = m; n_ = n; k_ = k; lda_ = lda; ldb_ = ldb; ldc_ = ldc; cu_trans_a_ = trans_a ? CUBLAS_OP_T : CUBLAS_OP_N; cu_trans_b_ = trans_b ? CUBLAS_OP_T : CUBLAS_OP_N; // create operation desciriptor; see cublasLtMatmulDescAttributes_t for // details about defaults; here we just need to set the transforms for A and B CUBLAS_CALL(cublasLtMatmulDescCreate(&matmul_desc_, cublasTypeWrapper<PTypeOut>::type)); CUBLAS_CALL(cublasLtMatmulDescSetAttribute(matmul_desc_, CUBLASLT_MATMUL_DESC_TRANSA, &cu_trans_b_, sizeof(cu_trans_b_))); CUBLAS_CALL(cublasLtMatmulDescSetAttribute(matmul_desc_, CUBLASLT_MATMUL_DESC_TRANSA, &cu_trans_a_, sizeof(cu_trans_a_))); // create matrix descriptors, we are good with the details here so no need to // set any extra attributes CUBLAS_CALL(cublasLtMatrixLayoutCreate(&a_desc_, cublasTypeWrapper<PTypeOut>::type, trans_a == false ? k : m, trans_a == false ? m : k, lda)); CUBLAS_CALL(cublasLtMatrixLayoutCreate(&b_desc_, cublasTypeWrapper<PTypeOut>::type, trans_b == false ? n : k, trans_b == false ? k : n, ldb)); CUBLAS_CALL(cublasLtMatrixLayoutCreate( &c_desc_, cublasTypeWrapper<PTypeOut>::type, n, m, ldc)); // create preference handle; here we could use extra attributes to disable // tensor ops or to make sure algo selected will work with badly aligned A, B, // C; here for simplicity we just assume A,B,C are always well aligned (e.g. // directly come from cudaMalloc) CUBLAS_CALL(cublasLtMatmulPreferenceCreate(&preference_)); if (!workspace_) { CUDA_CALL(cudaMalloc(&this->workspace_, workspace_size_)); } CUBLAS_CALL(cublasLtMatmulPreferenceSetAttribute( preference_, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &workspace_size_, sizeof(workspace_size_))); // we just need the best available heuristic to try and run matmul. There is // no guarantee this will work, e.g. if A is badly aligned, you can request // more (e.g. 32) algos and try to run them one by one until something works CUBLAS_CALL(cublasLtMatmulAlgoGetHeuristic(handle_, matmul_desc_, b_desc_, a_desc_, c_desc_, c_desc_, preference_, 1, &heuristic_result_, &returned_results_)); if (returned_results_ == 0) { LOG(FATAL) << "cuBLAS API failed with status " << CUBLAS_STATUS_NOT_SUPPORTED; } return true; } template <typename PTypeIn, typename PTypeOut> bool LtGemm<PTypeIn, PTypeOut>::run(const PTypeOut alpha, const PTypeOut beta, const PTypeIn *a, const PTypeIn *b, PTypeOut *c, Context<TARGET(kCUDA)> *ctx) { CUBLAS_CALL(cublasLtMatmul(handle_, matmul_desc_, &alpha, b, b_desc_, a, a_desc_, &beta, c, c_desc_, c, c_desc_, &heuristic_result_.algo, workspace_, workspace_size_, this->exe_stream_)); return true; } template class LtGemm<float, float>; template class LtGemm<half, half>; #endif } // namespace math } // namespace cuda } // namespace lite } // namespace paddle
36.717857
80
0.474273
wanglei91
0904bfee413fd4264bf1b9927aca82724a143515
592
cpp
C++
Effective-Modern-C++/include/item22/widget.cpp
AndrewAndJenny/AlgorithmTrain
4f6e1b723d7776d1ce4927f84d70da5e56aa9e96
[ "MIT" ]
19
2021-01-09T09:03:03.000Z
2021-12-09T10:37:23.000Z
Effective-Modern-C++/include/item22/widget.cpp
AndrewAndJenny/AlgorithmTrain
4f6e1b723d7776d1ce4927f84d70da5e56aa9e96
[ "MIT" ]
1
2021-03-28T01:06:41.000Z
2021-04-05T08:31:31.000Z
Effective-Modern-C++/include/item22/widget.cpp
AndrewAndJenny/AlgorithmTrain
4f6e1b723d7776d1ce4927f84d70da5e56aa9e96
[ "MIT" ]
2
2021-01-27T06:20:29.000Z
2021-07-07T04:58:14.000Z
#include "gadget.h" #include "widget.h" #include <string> #include <vector> struct Widget::Impl //跟之前⼀样 { std::string name; std::vector<double> data; Gadget g1, g2, g3; }; Widget::Widget() :pImpl(std::make_unique<Impl>()){ } //根据Item 21, 通过std::make_shared来创建std::unique_ptr Widget::~Widget() = default; //同上述代码效果⼀致 Widget::Widget(Widget&& rhs) = default; //在这⾥定义 Widget& Widget::operator=(Widget&& rhs) = default; Widget::Widget(const Widget& rhs) :pImpl(std::make_unique<Impl>(*rhs.pImpl)) {} Widget& Widget::operator=(const Widget& rhs) { *pImpl = *rhs.pImpl; return *this; }
21.142857
87
0.679054
AndrewAndJenny
0904ceb13629470931a2aedbfcd7f852495e2713
317
cpp
C++
Source/Kernel/Devices/Drivers/VMware/Mouse/MouseDriver.cpp
jbatonnet/System
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
[ "MIT" ]
3
2020-04-24T20:23:24.000Z
2022-01-06T22:27:01.000Z
Source/Kernel/Devices/Drivers/VMware/Mouse/MouseDriver.cpp
jbatonnet/system
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
[ "MIT" ]
null
null
null
Source/Kernel/Devices/Drivers/VMware/Mouse/MouseDriver.cpp
jbatonnet/system
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
[ "MIT" ]
1
2021-06-25T17:35:08.000Z
2021-06-25T17:35:08.000Z
#include <Kernel/Devices/DeviceManager.h> #include "MouseDriver.h" #include "MouseDevice.h" #include "Mouse.h" using namespace System::Devices; MouseDriver::MouseDriver() { } void MouseDriver::Load() { Device* device = new MouseDevice(); DeviceManager::AddDevice(device); } void MouseDriver::Unload() { }
15.095238
41
0.719243
jbatonnet
09090593b10866d99df7843392491aeb21458c68
29,133
cpp
C++
source/core/tjs2/tjsOctPack.cpp
metarin/krkrv
42e5c23483539e2bc1e8d6858548cf13165494e1
[ "BSD-3-Clause" ]
null
null
null
source/core/tjs2/tjsOctPack.cpp
metarin/krkrv
42e5c23483539e2bc1e8d6858548cf13165494e1
[ "BSD-3-Clause" ]
null
null
null
source/core/tjs2/tjsOctPack.cpp
metarin/krkrv
42e5c23483539e2bc1e8d6858548cf13165494e1
[ "BSD-3-Clause" ]
null
null
null
#include "tjsCommHead.h" #include <map> #include <vector> #include <string> #include "tjsArray.h" #include "tjsError.h" namespace TJS { enum OctPackType { OctPack_ascii, // a : ASCII string(ヌル文字が補完される) OctPack_ASCII, // A : ASCII string(スペースが補完される) OctPack_bitstring, // b : bit string(下位ビットから上位ビットの順) OctPack_BITSTRING, // B : bit string(上位ビットから下位ビットの順) OctPack_char, // c : 符号付き1バイト数値(-128 ~ 127) OctPack_CHAR, // C : 符号無し1バイト数値(0~255) OctPack_double, // d : 倍精度浮動小数点 OctPack_float, // f : 単精度浮動小数点 OctPack_hex, // h : hex string(low nybble first) OctPack_HEX, // H : hex string(high nybble first) OctPack_int, // i : 符号付きint数値(通常4バイト) OctPack_INT, // I : 符号無しint数値(通常4バイト) OctPack_long, // l : 符号付きlong数値(通常4バイト) OctPack_LONG, // L : 符号無しlong数値(通常4バイト) OctPack_noshort, // n : short数値(ネットワークバイトオーダ) network byte order short OctPack_NOLONG, // N : long数値(ネットワークバイトオーダ) network byte order long OctPack_pointer, // p : 文字列へのポインタ null terminate char OctPack_POINTER, // P : 構造体(固定長文字列)へのポインタ fix length char OctPack_short, // s : 符号付きshort数値(通常2バイト) sign OctPack_SHORT, // S : 符号無しshort数値(通常2バイト) unsign OctPack_leshort, // v : リトルエンディアンによるshort値 little endian short OctPack_LELONG, // V : リトルエンディアンによるlong値 little endian long OctPack_uuencode, // u : uuencodeされた文字列 OctPack_BRE, // w : BER圧縮された整数値 OctPack_null, // x : ヌル文字 OctPack_NULL, // X : back up a byte OctPack_fill, // @ : 絶対位置までヌル文字を埋める OctPack_base64, // m : Base64 encode / decode OctPack_EOT }; static const tjs_char OctPackChar[OctPack_EOT] = { TJS_W('a'), TJS_W('A'), TJS_W('b'), TJS_W('B'), TJS_W('c'), TJS_W('C'), TJS_W('d'), TJS_W('f'), TJS_W('h'), TJS_W('H'), TJS_W('i'), TJS_W('I'), TJS_W('l'), TJS_W('L'), TJS_W('n'), TJS_W('N'), TJS_W('p'), TJS_W('P'), TJS_W('s'), TJS_W('S'), TJS_W('v'), TJS_W('V'), TJS_W('u'), TJS_W('w'), TJS_W('x'), TJS_W('X'), TJS_W('@'), TJS_W('m'), }; static bool OctPackMapInit = false; static std::map<tjs_char,tjs_int> OctPackMap; static void OctPackMapInitialize() { if( OctPackMapInit ) return; for( tjs_int i = 0; i < OctPack_EOT; i++ ) { OctPackMap.insert( std::map<tjs_char,tjs_int>::value_type( OctPackChar[i], i ) ); } OctPackMapInit = true; } struct OctPackTemplate { OctPackType Type; tjs_int Length; }; static const tjs_char* ParseTemplateLength( OctPackTemplate& result, const tjs_char* c ) { if( *c ) { if( *c == TJS_W('*') ) { c++; result.Length = -1; // tail list } else if( *c >= TJS_W('0') && *c <= TJS_W('9') ) { tjs_int num = 0; while( *c && ( *c >= TJS_W('0') && *c <= TJS_W('9') ) ) { num *= 10; num += *c - TJS_W('0'); c++; } result.Length = num; } else { result.Length = 1; } } else { result.Length = 1; } return c; } static void ParsePackTemplate( std::vector<OctPackTemplate>& result, const tjs_char* templ ) { OctPackMapInitialize(); const tjs_char* c = templ; while( *c ) { std::map<tjs_char,tjs_int>::iterator f = OctPackMap.find( *c ); if( f == OctPackMap.end() ) { TJS_eTJSError( TJSUnknownPackUnpackTemplateCharcter ); } else { c++; OctPackTemplate t; t.Type = static_cast<OctPackType>(f->second); c = ParseTemplateLength( t, c ); result.push_back( t ); } } } static void AsciiToBin( std::vector<tjs_uint8>& bin, const ttstr& arg, tjs_nchar fillchar, tjs_int len ) { const tjs_char* str = arg.c_str(); if( len < 0 ) len = arg.length(); tjs_int i = 0; for( ; i < len && *str != TJS_W('\0'); str++, i++ ) { bin.push_back( (tjs_uint8)*str ); } for( ; i < len; i++ ) { bin.push_back( fillchar ); } } // mtol : true : 上位ビットから下位ビット, false : 下位ビットから上位ビット // 指定した数値の方が大きくても、その分は無視 static void BitStringToBin( std::vector<tjs_uint8>& bin, const ttstr& arg, bool mtol, tjs_int len ) { const tjs_char* str = arg.c_str(); if( len < 0 ) len = arg.length(); tjs_uint8 val = 0; tjs_int pos = 0; if( mtol ) { pos = 7; for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str == TJS_W('0') ) { // val |= 0; } else if( *str == TJS_W('1') ) { val |= 1 << pos; } else { TJS_eTJSError( TJSUnknownBitStringCharacter ); } if( pos == 0 ) { bin.push_back( val ); pos = 7; val = 0; } else { pos--; } } if( pos < 7 ) { bin.push_back( val ); } } else { for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str == TJS_W('0') ) { // val |= 0; } else if( *str == TJS_W('1') ) { val |= 1 << pos; } else { TJS_eTJSError( TJSUnknownBitStringCharacter ); } if( pos == 7 ) { bin.push_back( val ); pos = val = 0; } else { pos++; } } if( pos ) { bin.push_back( val ); } } } // mtol static void HexToBin( std::vector<tjs_uint8>& bin, const ttstr& arg, bool mtol, tjs_int len ) { const tjs_char* str = arg.c_str(); if( len < 0 ) len = arg.length(); tjs_uint8 val = 0; tjs_int pos = 0; if( mtol ) { // 上位ニブルが先 pos = 1; for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str >= TJS_W('0') && *str <= TJS_W('9') ) { val |= (*str - TJS_W('0')) << (pos*4); } else if( *str >= TJS_W('a') && *str <= TJS_W('f') ) { val |= (*str - TJS_W('a') + 10) << (pos*4); } else if( *str >= TJS_W('A') && *str <= TJS_W('E') ) { val |= (*str - TJS_W('A') + 10) << (pos*4); } else { TJS_eTJSError( TJSUnknownHexStringCharacter ); } if( pos == 0 ) { bin.push_back( val ); pos = 1; val = 0; } else { pos--; } } if( pos < 1 ) { bin.push_back( val ); } } else { // 下位ニブルが先 for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str >= TJS_W('0') && *str <= TJS_W('9') ) { val |= (*str - TJS_W('0')) << (pos*4); } else if( *str >= TJS_W('a') && *str <= TJS_W('f') ) { val |= (*str - TJS_W('a') + 10) << (pos*4); } else if( *str >= TJS_W('A') && *str <= TJS_W('E') ) { val |= (*str - TJS_W('A') + 10) << (pos*4); } else { TJS_eTJSError( TJSUnknownHexStringCharacter ); } if( pos ) { bin.push_back( val ); pos = val = 0; } else { pos++; } } if( pos ) { bin.push_back( val ); } } } // TRet : 最終的に出力する型 // TTmp : 一時的に出力する型 variant は一時的に tjs_int にしないといけないなど template<typename TRet, typename TTmp, int NBYTE, typename TRetTmp> static void ReadNumberLE( std::vector<tjs_uint8>& result, const std::vector<tTJSVariant>& args, tjs_int numargs, tjs_int& argindex, tjs_int len ) { if( len < 0 ) len = numargs - argindex; if( (len+argindex) > numargs ) len = numargs - argindex; for( tjs_int a = 0; a < len; a++ ) { TRet c = (TRet)(TTmp)args[argindex+a]; TRetTmp val = *(TRetTmp*)&c; for( int i = 0; i < NBYTE; i++ ) { TRetTmp tmp = ( val >> (i*8) ) & 0xFF; result.push_back( (tjs_uint8)tmp ); // little endian } } argindex += len-1; } template<typename TRet, typename TTmp, int NBYTE, typename TRetTmp> static void ReadNumberBE( std::vector<tjs_uint8>& result, const std::vector<tTJSVariant>& args, tjs_int numargs, tjs_int& argindex, tjs_int len ) { if( len < 0 ) len = numargs - argindex; if( (len+argindex) > numargs ) len = numargs - argindex; for( tjs_int a = 0; a < len; a++ ) { TRet c = (TRet)(TTmp)args[argindex+a]; for( int i = 0; i < NBYTE; i++ ) { result.push_back( ((*(TRetTmp*)&c)&(0xFF<<((NBYTE-1-i)*8)))>>((NBYTE-1-i)*8) ); // big endian } } argindex += len-1; } #if TJS_HOST_IS_BIG_ENDIAN # define ReadNumber ReadNumberBE #else # define ReadNumber ReadNumberLE #endif // from base64 plug-in (C) 2009 Kiyobee // 扱いやすいように一部書き換えている // inbuf の内容を base64 エンコードして、outbuf に文字列として出力 // outbuf のサイズは、insize / 4 * 3 必要 // outbuf のサイズは、(insize+2)/3 * 4 必要 static void encodeBase64( const tjs_uint8* inbuf, tjs_uint insize, tjs_string& outbuf) { outbuf.reserve( outbuf.size() + ((insize+2)/3) * 4 ); static const char* base64str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; tjs_int insize_3 = insize - 3; tjs_int outptr = 0; tjs_int i; for(i=0; i<=insize_3; i+=3) { outbuf.push_back( base64str[ (inbuf[i ] >> 2) & 0x3F ] ); outbuf.push_back( base64str[((inbuf[i ] << 4) & 0x30) | ((inbuf[i+1] >> 4) & 0x0F)] ); outbuf.push_back( base64str[((inbuf[i+1] << 2) & 0x3C) | ((inbuf[i+2] >> 6) & 0x03)] ); outbuf.push_back( base64str[ (inbuf[i+2] ) & 0x3F ] ); } switch(insize % 3) { case 2: outbuf.push_back( base64str[ (inbuf[i ] >> 2) & 0x3F ] ); outbuf.push_back( base64str[((inbuf[i ] << 4) & 0x30) | ((inbuf[i+1] >> 4) & 0x0F)] ); outbuf.push_back( base64str[ (inbuf[i+1] << 2) & 0x3C ] ); outbuf.push_back( '=' ); break; case 1: outbuf.push_back( base64str[ (inbuf[i ] >> 2) & 0x3F ] ); outbuf.push_back( base64str[ (inbuf[i ] << 4) & 0x30 ] ); outbuf.push_back( '=' ); outbuf.push_back( '=' ); break; } } static void decodeBase64( const tjs_string& inbuf, std::vector<tjs_uint8>& outbuf ) { tjs_int len = (tjs_int)inbuf.length(); const tjs_char* data = inbuf.c_str(); if( len < 4 ) { // too short return; } outbuf.reserve( len / 4 * 3 ); static const tjs_int base64tonum[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; tjs_int dptr = 0; tjs_int len_4 = len - 4; while( dptr < len_4 ) { outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 2) | (base64tonum[data[dptr+1]] >> 4) ) ); dptr++; outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 4) | (base64tonum[data[dptr+1]] >> 2) ) ); dptr++; outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 6) | (base64tonum[data[dptr+1]]) ) ); dptr+=2; } outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 2) | (base64tonum[data[dptr+1]] >> 4) )) ; dptr++; tjs_uint8 tmp = static_cast<tjs_uint8>( base64tonum[data[dptr++]] << 4 ); if( data[dptr] != TJS_W('=') ) { tmp |= base64tonum[data[dptr]] >> 2; outbuf.push_back( tmp ); tmp = base64tonum[data[dptr++]] << 6; if( data[dptr] != TJS_W('=') ) { tmp |= base64tonum[data[dptr]]; outbuf.push_back( tmp ); } } } static tTJSVariantOctet* Pack( const std::vector<OctPackTemplate>& templ, const std::vector<tTJSVariant>& args ) { tjs_int numargs = static_cast<tjs_int>(args.size()); std::vector<tjs_uint8> result; tjs_size count = templ.size(); tjs_int argindex = 0; for( tjs_size i = 0; i < count && argindex < numargs; argindex++ ) { OctPackType t = templ[i].Type; tjs_int len = templ[i].Length; switch( t ) { case OctPack_ascii: // a : ASCII string(ヌル文字が補完される) AsciiToBin( result, args[argindex], '\0', len ); break; case OctPack_ASCII: // A : ASCII string(スペースが補完される) AsciiToBin( result, args[argindex], ' ', len ); break; case OctPack_bitstring: // b : bit string(下位ビットから上位ビットの順) BitStringToBin( result, args[argindex], false, len ); break; case OctPack_BITSTRING: // B : bit string(上位ビットから下位ビットの順) BitStringToBin( result, args[argindex], true, len ); break; case OctPack_char: // c : 符号付き1バイト数値(-128 ~ 127) ReadNumber<tjs_int8,tjs_int,1,tjs_int8>( result, args, numargs, argindex, len ); break; case OctPack_CHAR: // C : 符号無し1バイト数値(0~255) ReadNumber<tjs_uint8,tjs_int,1,tjs_uint8>( result, args, numargs, argindex, len ); break; case OctPack_double: // d : 倍精度浮動小数点 ReadNumber<tjs_real,tjs_real,8,tjs_uint64>( result, args, numargs, argindex, len ); break; case OctPack_float: // f : 単精度浮動小数点 ReadNumber<float,tjs_real,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_hex: // h : hex string(low nybble first) HexToBin( result, args[argindex], false, len ); break; case OctPack_HEX: // H : hex string(high nybble first) HexToBin( result, args[argindex], true, len ); break; case OctPack_int: // i : 符号付きint数値(通常4バイト) case OctPack_long: // l : 符号付きlong数値(通常4バイト) ReadNumber<tjs_int,tjs_int,4,tjs_int32>( result, args, numargs, argindex, len ); break; case OctPack_INT: // I : 符号無しint数値(通常4バイト) case OctPack_LONG: // L : 符号無しlong数値(通常4バイト) ReadNumber<tjs_uint,tjs_int64,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_noshort: // n : unsigned short数値(ネットワークバイトオーダ) network byte order short ReadNumberBE<tjs_uint16,tjs_int,2,tjs_uint16>( result, args, numargs, argindex, len ); break; case OctPack_NOLONG: // N : unsigned long数値(ネットワークバイトオーダ) network byte order long ReadNumberBE<tjs_uint,tjs_int64,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_pointer: // p : 文字列へのポインタ null terminate char case OctPack_POINTER: // P : 構造体(固定長文字列)へのポインタ fix length char // TODO break; case OctPack_short: // s : 符号付きshort数値(通常2バイト) sign ReadNumber<tjs_int16,tjs_int,2,tjs_int16>( result, args, numargs, argindex, len ); break; case OctPack_SHORT: // S : 符号無しshort数値(通常2バイト) unsign ReadNumber<tjs_uint16,tjs_int,2,tjs_uint16>( result, args, numargs, argindex, len ); break; case OctPack_leshort: // v : リトルエンディアンによるunsigned short値 little endian short ReadNumberLE<tjs_uint16,tjs_int,2,tjs_uint16>( result, args, numargs, argindex, len ); break; case OctPack_LELONG: // V : リトルエンディアンによるunsigned long値 little endian long ReadNumberLE<tjs_uint,tjs_int64,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_uuencode: // u : uuencodeされた文字列 TJS_eTJSError( TJSNotSupportedUuencode ); break; case OctPack_BRE: // w : BER圧縮された整数値 TJS_eTJSError( TJSNotSupportedBER ); break; case OctPack_null: // x : ヌル文字 for( tjs_int a = 0; a < len; a++ ) { result.push_back( 0 ); } argindex--; break; case OctPack_NULL: // X : back up a byte for( tjs_int a = 0; a < len; a++ ) { result.pop_back(); } argindex--; break; case OctPack_fill: { // @ : 絶対位置までヌル文字を埋める tjs_size count = result.size(); for( tjs_size i = count; i < (tjs_size)len; i++ ) { result.push_back( 0 ); } argindex--; break; } case OctPack_base64: { // m : Base64 encode / decode ttstr tmp = args[argindex]; decodeBase64( tmp.AsStdString(), result ); break; } } if( len >= 0 ) { // '*' の時は-1が入り、リストの末尾まで読む i++; } } if( result.size() > 0 ) return TJSAllocVariantOctet( &(result[0]), (tjs_uint)result.size() ); else return NULL; } static void BinToAscii( const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len, ttstr& result ) { //std::vector<tjs_nchar> tmp(len+1); std::vector<tjs_nchar> tmp; tmp.reserve(len+1); for( tjs_int i = 0; i < static_cast<tjs_int>(len) && data != tail; data++, i++ ) { if( (*data) != '\0' ) { tmp.push_back( (tjs_nchar)*data ); } } tmp.push_back( (tjs_nchar)'\0' ); result = tTJSString( &(tmp[0]) ); } // mtol : true : 上位ビットから下位ビット, false : 下位ビットから上位ビット // 指定した数値の方が大きくても、その分は無視 static void BinToBitString( const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len, ttstr& result, bool mtol ) { //std::vector<tjs_char> tmp(len+1); std::vector<tjs_char> tmp; tmp.reserve(len+1); tjs_int pos = 0; if( mtol ) { for( ; data < tail; data++ ) { for( tjs_int i = 0; i < 8 && pos < static_cast<tjs_int>(len); i++, pos++ ) { if( (*data)&(0x01<<(7-i)) ) { tmp.push_back( TJS_W('1') ); } else { tmp.push_back( TJS_W('0') ); } } if( pos >= static_cast<tjs_int>(len) ) break; } } else { for( ; data < tail; data++ ) { for( tjs_int i = 0; i < 8 && pos < static_cast<tjs_int>(len); i++, pos++ ) { if( (*data)&(0x01<<i) ) { tmp.push_back( TJS_W('1') ); } else { tmp.push_back( TJS_W('0') ); } } if( pos >= static_cast<tjs_int>(len) ) break; } } tmp.push_back( TJS_W('\0') ); result = tTJSString( &(tmp[0]) ); } // TRet : 最終的に出力する型 template<typename TRet, int NBYTE> static void BinToNumberLE( std::vector<TRet>& result, const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len ) { if( len < 0 ) len = (tjs_uint)(((tail - data)+NBYTE-1)/NBYTE); if( (data+len*NBYTE) < tail ) tail = data+len*NBYTE; TRet val = 0; tjs_uint bytes = 0; for( ; data < tail; data++ ) { val |= (*data) << (bytes*8); if( bytes >= (NBYTE-1) ) { // little endian bytes = 0; result.push_back( val ); val = 0; } else { bytes++; } } if( bytes ) { result.push_back( val ); } } template<typename TRet, typename TTmp, int NBYTE> static void BinToNumberLEReal( std::vector<TRet>& result, const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len ) { if( len < 0 ) len = (tjs_uint)(((tail - data)+NBYTE-1)/NBYTE); if( (data+len*NBYTE) < tail ) tail = data+len*NBYTE; TTmp val = 0; tjs_uint bytes = 0; for( ; data < tail; data++ ) { val |= (TTmp)(*data) << (bytes*8); if( bytes >= (NBYTE-1) ) { // little endian bytes = 0; result.push_back( *(TRet*)&val ); val = 0; } else { bytes++; } } if( bytes ) { result.push_back( *(TRet*)&val ); } } template<typename TRet, int NBYTE> static void BinToNumberBE( std::vector<TRet>& result, const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len ) { if( len < 0 ) len = (tjs_uint)(((tail - data)+NBYTE-1)/NBYTE); if( (data+len*NBYTE) < tail ) tail = data+len*NBYTE; TRet val = 0; tjs_uint bytes = NBYTE-1; for( ; data < tail; data++ ) { val |= (*data) << (bytes*8); if( bytes == 0 ) { // big endian bytes = NBYTE-1; result.push_back( val ); val = 0; } else { bytes--; } } if( bytes < (NBYTE-1) ) { result.push_back( val ); } } #if TJS_HOST_IS_BIG_ENDIAN # define BinToNumber BinToNumberBE #else # define BinToNumber BinToNumberLE # define BinToReal BinToNumberLEReal #endif // mtol static void BinToHex( const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len, ttstr& result, bool mtol ) { if( (data+len) < tail ) tail = data+(len+1)/2; //std::vector<tjs_char> tmp(len+1); std::vector<tjs_char> tmp; tmp.reserve(len+1); tjs_int pos = 0; if( mtol ) { // 上位ニブルが先 pos = 1; for( tjs_int i = 0; i < static_cast<tjs_int>(len) && data < tail; i++ ) { tjs_char ch = ((*data)&(0xF<<(pos*4)))>>(pos*4); if( ch > 9 ) { ch = TJS_W('A') + (ch-10); } else { ch = TJS_W('0') + ch; } tmp.push_back( ch ); if( pos == 0 ) { pos = 1; data++; } else { pos--; } } } else { // 下位ニブルが先 for( tjs_int i = 0; i < static_cast<tjs_int>(len) && data < tail; i++ ) { tjs_char ch = ((*data)&(0xF<<(pos*4)))>>(pos*4); if( ch > 9 ) { ch = TJS_W('A') + (ch-10); } else { ch = TJS_W('0') + ch; } tmp.push_back( ch ); if( pos ) { pos = 0; data++; } else { pos++; } } } tmp.push_back( TJS_W('\0') ); result = tTJSString( &(tmp[0]) ); } static iTJSDispatch2* Unpack( const std::vector<OctPackTemplate>& templ, const tjs_uint8 *data, tjs_uint length ) { tTJSArrayObject* result = reinterpret_cast<tTJSArrayObject*>( TJSCreateArrayObject() ); tTJSArrayNI *ni; if(TJS_FAILED(result->NativeInstanceSupport(TJS_NIS_GETINSTANCE, TJSGetArrayClassID(), (iTJSNativeInstance**)&ni))) TJS_eTJSError(TJSSpecifyArray); const tjs_uint8 *current = data; const tjs_uint8 *tail = data + length; tjs_size len = length; tjs_size count = templ.size(); tjs_int argindex = 0; for( tjs_int i = 0; i < (tjs_int)count && current < tail; argindex++ ) { OctPackType t = templ[i].Type; tjs_size len = templ[i].Length; switch( t ) { case OctPack_ascii:{ // a : ASCII string(ヌル文字が補完される) if( len < 0 ) len = (tail - current); ttstr ret; BinToAscii( current, tail, (tjs_uint)len, ret ); result->Add( ni, tTJSVariant( ret ) ); current += len; break; } case OctPack_ASCII: { // A : ASCII string(スペースが補完される) if( len < 0 ) len = (tail - current); ttstr ret; BinToAscii( current, tail, (tjs_uint)len, ret ); result->Add( ni, tTJSVariant( ret ) ); current += len; break; } case OctPack_bitstring: { // b : bit string(下位ビットから上位ビットの順) if( len < 0 ) len = (tail - current)*8; ttstr ret; BinToBitString( current, tail, (tjs_uint)len, ret, false ); result->Add( ni, tTJSVariant( ret ) ); current += (len+7)/8; break; } case OctPack_BITSTRING: { // B : bit string(上位ビットから下位ビットの順) if( len < 0 ) len = (tail - current)*8; ttstr ret; BinToBitString( current, tail, (tjs_uint)len, ret, true ); result->Add( ni, tTJSVariant( ret ) ); current += (len+7)/8; break; } case OctPack_char: { // c : 符号付き1バイト数値(-128 ~ 127) if( len < 0 ) len = tail - current; std::vector<tjs_int8> ret; BinToNumber<tjs_int8,1>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_int8>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len; break; } case OctPack_CHAR: { // C : 符号無し1バイト数値(0~255) if( len < 0 ) len = tail - current; std::vector<tjs_uint8> ret; BinToNumber<tjs_uint8,1>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint8>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len; break; } case OctPack_double: { // d : 倍精度浮動小数点 if( len < 0 ) len = (tail - current)/8; std::vector<tjs_real> ret; BinToReal<tjs_real,tjs_uint64,8>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_real>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_real)*iter ) ); } current += len*8; break; } case OctPack_float: { // f : 単精度浮動小数点 if( len < 0 ) len = (tail - current)/4; std::vector<float> ret; BinToReal<float,tjs_uint32,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<float>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_real)*iter ) ); } current += len*4; break; } case OctPack_hex: { // h : hex string(low nybble first) if( len < 0 ) len = (tail - current)*2; ttstr ret; BinToHex( current, tail, (tjs_uint)len, ret, false ); result->Add( ni, tTJSVariant( ret ) ); current += (len+1)/2; break; } case OctPack_HEX: { // H : hex string(high nybble first) if( len < 0 ) len = (tail - current)*2; ttstr ret; BinToHex( current, tail, (tjs_uint)len, ret, true ); result->Add( ni, tTJSVariant( ret ) ); current += (len+1)/2; break; } case OctPack_int: // i : 符号付きint数値(通常4バイト) case OctPack_long: { // l : 符号付きlong数値(通常4バイト) if( len < 0 ) len = (tail - current)/4; std::vector<tjs_int> ret; BinToNumber<tjs_int,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_int>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*4; break; } case OctPack_INT: // I : 符号無しint数値(通常4バイト) case OctPack_LONG: { // L : 符号無しlong数値(通常4バイト) if( len < 0 ) len = (tail - current)/4; std::vector<tjs_uint> ret; BinToNumber<tjs_uint,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_int64)*iter ) ); } current += len*4; break; } case OctPack_noshort: { // n : unsigned short数値(ネットワークバイトオーダ) network byte order short if( len < 0 ) len = (tail - current)/2; std::vector<tjs_uint16> ret; BinToNumberBE<tjs_uint16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_NOLONG: { // N : unsigned long数値(ネットワークバイトオーダ) network byte order long if( len < 0 ) len = ((tail - current)/4); std::vector<tjs_uint> ret; BinToNumberBE<tjs_uint,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_int64)*iter ) ); } current += len*4; break; } case OctPack_pointer: // p : 文字列へのポインタ null terminate char TJS_eTJSError( TJSNotSupportedUnpackLP ); break; case OctPack_POINTER: // P : 構造体(固定長文字列)へのポインタ fix length char TJS_eTJSError( TJSNotSupportedUnpackP ); break; case OctPack_short: { // s : 符号付きshort数値(通常2バイト) sign if( len < 0 ) len = ((tail - current)/2); std::vector<tjs_int16> ret; BinToNumber<tjs_int16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_int16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_SHORT: { // S : 符号無しshort数値(通常2バイト) unsign if( len < 0 ) len = ((tail - current)/2); std::vector<tjs_uint16> ret; BinToNumber<tjs_uint16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_leshort: { // v : リトルエンディアンによるunsigned short値 little endian short if( len < 0 ) len = ((tail - current)/2); std::vector<tjs_uint16> ret; BinToNumberLE<tjs_uint16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_LELONG: { // V : リトルエンディアンによるunsigned long値 little endian long if( len < 0 ) len = ((tail - current)/4); std::vector<tjs_uint> ret; BinToNumberLE<tjs_uint,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_int64)*iter ) ); } current += len*4; break; } case OctPack_uuencode: // u : uuencodeされた文字列 TJS_eTJSError( TJSNotSupportedUuencode ); break; case OctPack_BRE: // w : BER圧縮された整数値 TJS_eTJSError( TJSNotSupportedBER ); break; case OctPack_null: // x : ヌル文字 if( len < 0 ) len = (tail - current); for( tjs_int x = 0; x < (tjs_int)len; x++ ) { current++; } break; case OctPack_NULL: // X : back up a byte if( len < 0 ) len = (current - data); for( tjs_int x = 0; x < (tjs_int)len; x++ ) { if( data != current ) current--; else break; } break; case OctPack_fill: { // @ : 絶対位置までヌル文字を埋める if( len < 0 ) len = (tail - current); current = &(data[len]); break; } case OctPack_base64: { // m : Base64 encode / decode tjs_string ret; encodeBase64( current, (tjs_uint)(tail-current), ret ); result->Add( ni, tTJSVariant( ret.c_str() ) ); current = tail; break; } } i++; } return result; } tjs_error TJSOctetPack( tTJSVariant **args, tjs_int numargs, const std::vector<tTJSVariant>& items, tTJSVariant *result ) { if( numargs < 1 ) return TJS_E_BADPARAMCOUNT; if( args[0]->Type() != tvtString ) return TJS_E_INVALIDPARAM; if( result ) { std::vector<OctPackTemplate> templ; ParsePackTemplate( templ, ((ttstr)*args[0]).c_str() ); tTJSVariantOctet* oct = Pack( templ, items ); *result = oct; if( oct ) oct->Release(); else *result = tTJSVariant((iTJSDispatch2*)NULL,(iTJSDispatch2*)NULL); } return TJS_S_OK; } tjs_error TJSOctetUnpack( const tTJSVariantOctet * target, tTJSVariant **args, tjs_int numargs, tTJSVariant *result ) { if( numargs < 1 ) return TJS_E_BADPARAMCOUNT; if( args[0]->Type() != tvtString ) return TJS_E_INVALIDPARAM; if( !target ) return TJS_E_INVALIDPARAM; if( result ) { std::vector<OctPackTemplate> templ; ParsePackTemplate( templ, ((ttstr)*args[0]).c_str() ); iTJSDispatch2* disp = Unpack( templ, target->GetData(), target->GetLength() ); *result = tTJSVariant(disp,disp); if( disp ) disp->Release(); } return TJS_S_OK; } } // namespace TJS
32.770529
147
0.600144
metarin
090ad33ddc5f7ee52ea84fc6e6ae207604f628a5
5,283
cpp
C++
Private/HTNWorldState.cpp
ThomasWilliamWallace/htn_planner
689192a3c3a7c6668bb1bc1192229d8eaef66f26
[ "MIT" ]
2
2020-08-30T17:05:29.000Z
2020-12-02T17:13:42.000Z
Private/HTNWorldState.cpp
ThomasWilliamWallace/htn_planner
689192a3c3a7c6668bb1bc1192229d8eaef66f26
[ "MIT" ]
null
null
null
Private/HTNWorldState.cpp
ThomasWilliamWallace/htn_planner
689192a3c3a7c6668bb1bc1192229d8eaef66f26
[ "MIT" ]
null
null
null
#include "HTNWorldState.h" #include <cmath> #include "PlayerData.h" #include "AbstractItem.h" #include "pLog.h" #include <sstream> #include "Missions.h" //*********************************************************** HTNWorldState::HTNWorldState(UPlayerData* playerPtr, PlayerMap& playerMap, std::vector<RealItemType*>& realItems, UPlayerData* requester, std::vector<UPlayerData*> attackers, std::vector<UPlayerData*> playersInTheRoom, float health, float sanity, float strength, float agility, float intelligence): m_ptrToSelf(playerPtr), m_health(health), m_sanity(sanity), m_strength(strength), m_agility(agility), m_intelligence(intelligence), m_evading(m_ptrToSelf->lastAction->m_action == EActions::evade), m_location(m_ptrToSelf->locationClass.location), m_missionClass(playerPtr->missionClass), m_requester(requester), m_attackers(attackers), m_playersInTheRoom(playersInTheRoom) { for (auto &item : realItems) { m_items.push_back(std::make_shared<SimItem>(CreateSimFromRealItem::CreateSimFromRealItem, item)); if ((m_items.back()->m_carryingPlayer) == m_ptrToSelf) { m_itemCarriedPtr = m_items.back(); } } // std::cout << "constructed HTNWorldState.m_items:\n"; // for (auto& itemPtr : m_items) // { // std::cout << itemPtr << "; realItem=" << itemPtr->m_realItem << "\n"; // } // std::cout << "\n"; } HTNWorldState::HTNWorldState(HTNWorldState const& ws2): m_ptrToSelf(ws2.m_ptrToSelf), m_health(ws2.m_health), m_sanity(ws2.m_sanity), m_strength(ws2.m_strength), m_agility(ws2.m_agility), m_intelligence(ws2.m_intelligence), m_evading(ws2.m_evading), m_location(ws2.m_location), m_missionClass(ws2.m_missionClass), m_itemCarriedPtr(nullptr), m_requester(ws2.m_requester), m_attackers(ws2.m_attackers), m_playersInTheRoom(ws2.m_playersInTheRoom) { for (auto &item : ws2.m_items) { m_items.emplace_back(std::make_shared<SimItem>(*(item.get()))); m_items.back()->m_realItem = item->m_realItem; if (ws2.m_itemCarriedPtr != nullptr && ws2.m_itemCarriedPtr->m_realItem == item->m_realItem) { m_itemCarriedPtr = m_items.back(); } } // std::cout << "COPY constructed HTNWorldState.m_items:\n"; // for (auto& itemPtr : m_items) // { // std::cout << itemPtr << "; realItem=" << itemPtr->m_realItem << "\n"; // } // std::cout << "\n"; } HTNWorldState& HTNWorldState::operator=(HTNWorldState const& ws2) { m_ptrToSelf = ws2.m_ptrToSelf; m_health = ws2.m_health; m_sanity = ws2.m_sanity; m_strength = ws2.m_strength; m_agility = ws2.m_agility; m_intelligence = ws2.m_intelligence; m_evading = ws2.m_evading; m_location = ws2.m_location; m_itemCarriedPtr = nullptr; m_requester = ws2.m_requester; m_attackers = ws2.m_attackers; m_playersInTheRoom = ws2.m_playersInTheRoom; m_items.clear(); for (auto &item : ws2.m_items) { m_items.emplace_back(std::make_shared<SimItem>(*(item.get()))); m_items.back()->m_realItem = item->m_realItem; if (ws2.m_itemCarriedPtr == item) { m_itemCarriedPtr = m_items.back(); } } // std::cout << "ASSIGNMENT constructed HTNWorldState.m_items:\n"; // for (auto& itemPtr : m_items) // { // std::cout << itemPtr << "; realItem=" << itemPtr->m_realItem << "\n"; // } // std::cout << "\n"; m_missionClass = ws2.m_missionClass; return *this; } void HTNWorldState::Print() { std::stringstream ss; ss << "HTNWorldState::Print\n"; ss << "m_health:" << m_health << "\n"; ss << "m_sanity:" << m_sanity << "\n"; ss << "m_strength:" << m_strength << "\n"; ss << "m_agility:" << m_agility << "\n"; ss << "m_intelligence:" << m_intelligence << "\n"; ss << "m_evading:" << m_evading << "\n"; ss << "m_location:" << static_cast<int>(m_location) << "\n"; ss << "m_ptrToSelf:" << m_ptrToSelf << "\n"; ss << "m_itemCarriedPtr:" << GetRaw(m_itemCarriedPtr) << "\n"; ss << "m_requester:" << m_requester << "\n"; for (auto &simItem : m_items) { ss << "SimItem: " << simItem->ToString() << " carried by "; if (simItem->m_carryingPlayer != nullptr) { ss << simItem->m_carryingPlayer->m_playerName; } else { ss << "NULLPTR"; } ss << " in the " << simItem->m_locationClass.ToString() << " with a link to real item " << simItem << "\n"; } for (auto &p : m_attackers) { ss << "Being attacked by player " << p->m_playerName << " in the " << LocationToString(m_location) << ".\n"; } for (auto &p : m_playersInTheRoom) { if (p != nullptr) ss << "PlayerData " << p->m_playerName << " is also in the " << LocationToString(m_location) << ".\n"; else ThrowException("ERROR NULL PLAYERDATA VALUE"); } ss << "]\n"; // ss << "m_missionClass:" << m_missionClass->MissionName() << "\n"; pLog(ss); } bool HTNWorldState::IsInTheRoom(UPlayerData const& playerPtr) const { for (auto &p : m_playersInTheRoom) { if (p == &playerPtr) { return true; } } return false; }
32.213415
118
0.609881
ThomasWilliamWallace
090b808402fce273cb8c666bb99d5fc9f37f149a
857
cpp
C++
eval_server/src/answer.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
1
2016-11-02T08:42:05.000Z
2016-11-02T08:42:05.000Z
eval_server/src/answer.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
null
null
null
eval_server/src/answer.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
null
null
null
#include "answer.hpp" // 🍣🍣🍣 解答変換 🍣🍣🍣 void Answer::convert(std::string const& s) { answer_type al; answer_atom a; std::istringstream ss; ss.str(s); int nl; // 選択回数 ss >> nl; for(int i = 0; i < nl; i++) { std::string pos; ss >> pos; point_type ipos{std::stoi(pos.substr(0, 1), nullptr, 16), std::stoi(pos.substr(1, 1), nullptr, 16)}; if(ipos.x == -1 || ipos.y == -1) { outerr << "ERROR: illegal position: \"" + pos + "\"\n"; return; } else a.position = ipos; int nx; // 交換回数 ss >> nx; std::string move(""); ss >> move; a.actions = std::move(move); al.list.push_back(a); } final_answer = al; outerr << "STATUS: submitted answer was loaded successfully\n" << std::endl; sane = true; }
23.805556
108
0.493582
tnct-spc
090b83580727fe842d882ffad58bdb622651caed
3,591
cpp
C++
src-plugins/itkProcessRegistrationDiffeomorphicDemons/itkProcessRegistrationDiffeomorphicDemonsPlugin.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/itkProcessRegistrationDiffeomorphicDemons/itkProcessRegistrationDiffeomorphicDemonsPlugin.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/itkProcessRegistrationDiffeomorphicDemons/itkProcessRegistrationDiffeomorphicDemonsPlugin.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "itkProcessRegistrationDiffeomorphicDemons.h" #include "itkProcessRegistrationDiffeomorphicDemonsPlugin.h" #include "itkProcessRegistrationDiffeomorphicDemonsToolBox.h" #include <dtkLog/dtkLog.h> // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsPluginPrivate // ///////////////////////////////////////////////////////////////// class itkProcessRegistrationDiffeomorphicDemonsPluginPrivate { public: // Class variables go here. }; // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsPlugin // ///////////////////////////////////////////////////////////////// itkProcessRegistrationDiffeomorphicDemonsPlugin::itkProcessRegistrationDiffeomorphicDemonsPlugin(QObject *parent) : dtkPlugin(parent), d(new itkProcessRegistrationDiffeomorphicDemonsPluginPrivate) { } itkProcessRegistrationDiffeomorphicDemonsPlugin::~itkProcessRegistrationDiffeomorphicDemonsPlugin() { delete d; d = NULL; } bool itkProcessRegistrationDiffeomorphicDemonsPlugin::initialize() { if (!itkProcessRegistrationDiffeomorphicDemons::registered()) { dtkWarn() << "Unable to register itkProcessRegistrationDiffeomorphicDemons type"; } if (!itkProcessRegistrationDiffeomorphicDemonsToolBox::registered()) { dtkWarn() << "Unable to register itkProcessRegistrationDiffeomorphicDemons toolbox"; } return true; } bool itkProcessRegistrationDiffeomorphicDemonsPlugin::uninitialize() { return true; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::name() const { return "itkProcessRegistrationDiffeomorphicDemonsPlugin"; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::contact() const { return QString::fromUtf8("[email protected]"); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::authors() const { QStringList list; list << QString::fromUtf8("Benoît Bleuzé"); return list; } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::contributors() const { QStringList list; list << "Vincent Garcia"; return list; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::description() const { return tr("Applies the diffeomorphic demons as they can be found in itk. Converts any type of image to float before applying the change, since the diffeomorphic demons only work on float images <br/> see: <a href=\"http://www.insight-journal.org/browse/publication/154\" > http://www.insight-journal.org/browse/publication/154 </a>"); } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::version() const { return ITKPROCESSREGISTRATIONDIFFEOMORPHICDEMONSPLUGIN_VERSION; } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::dependencies() const { return QStringList(); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::tags() const { return QStringList(); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::types() const { return QStringList() << "itkProcessRegistrationDiffeomorphicDemons"; } Q_EXPORT_PLUGIN2(itkProcessRegistrationDiffeomorphicDemonsPlugin, itkProcessRegistrationDiffeomorphicDemonsPlugin)
31.5
338
0.714286
ocommowi
0917f3eadd5ec51630c65b8da746d9d063c79f7a
22,393
cpp
C++
mainwindow.cpp
mastercad/DBManager
aed1c515a6b3a3ad6d4ecbf42c2e8b44c9a41498
[ "Libpng", "Zlib" ]
null
null
null
mainwindow.cpp
mastercad/DBManager
aed1c515a6b3a3ad6d4ecbf42c2e8b44c9a41498
[ "Libpng", "Zlib" ]
null
null
null
mainwindow.cpp
mastercad/DBManager
aed1c515a6b3a3ad6d4ecbf42c2e8b44c9a41498
[ "Libpng", "Zlib" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "textedit.h" #include "newconnectionwizard.h" #include "connectionmanager.h" #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> #include <QSqlQueryModel> #include <QSqlRecord> #include <QSqlField> #include <QToolBar> #include <QAction> #include <QFileDialog> #include <QMessageBox> #include <QTreeWidgetItem> #include <QElapsedTimer> #include <QNetworkRequest> #include <QDateTime> #include <QList> #include <QUrl> #include <QCompleter> #include <QWizard> #include <QWizardPage> #include <QMenu> #include <QDomDocument> #include <QXmlStreamWriter> #include <QXmlStreamReader> #include <QFile> #include <QToolButton> #include <QXmlStreamReader> #include <QDir> #include <QTimer> #include <QProgressDialog> #include <QProcess> #include <QPropertyAnimation> #include <QDate> #include <QDebug> #include "defaults.h" // Driver not loaded // Access denied for user 'root'@'172.19.0.1' (using password: YES) // Unknown database 'retro_board' /** * @brief MainWindow::MainWindow * @param parent */ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QMainWindow::showMaximized(); connectionFactory = new ConnectionFactory(this); connectionInfoFactory = new ConnectionInfoFactory; connectionInfoFactory->setConnections(&connections); setWindowTitle(QString("%1").arg("Database Manager")); QIcon executeIcon(":/icons/ausfuehren_schatten.png"); ui->btnQueryExecute->setIcon(executeIcon); ui->queryResult->setSortingEnabled(true); ui->btnQuerySave->hide(); releaseNotesManager = new ReleaseNotesManager(this->ui->sideBarContainer, this->ui->sideBarLayout, parent); this->currentQueryRequests = new QMap<int, QString>; this->updateManager = new UpdateManager(this); this->ui->queryResult->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); /* QToolButton *tb = new QToolButton(); tb->setText("+"); // Add empty, not enabled tab to tabWidget ui->tabWidget->addTab(new QLabel("Add tabs by pressing \"+\""), QString()); ui->tabWidget->setTabEnabled(0, false); // Add tab button to current tab. Button will be enabled, but tab -- not ui->tabWidget->tabBar()->setTabButton(0, QTabBar::LeftSide, tb); */ ui->tabWidget->clear(); QIcon icon(":/icons/add_schatten.png"); ui->tabWidget->addTab(new QLabel(""), icon, QString("")); ui->tabWidget->setTabsClosable(true); ui->tabWidget->setMovable(false); auto tabBar = ui->tabWidget->tabBar(); tabBar->tabButton(0, QTabBar::RightSide)->hide(); newTab(); connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onChangeTab(int))); connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int))); ui->menuVerbinden->menuAction()->setVisible(false); ui->menuVerbinden->hideTearOffMenu(); loadConnectionInfos(); ui->databaseList->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->btnQueryExecute, SIGNAL(clicked(bool)), this, SLOT(onExecuteQueryClicked())); connect(ui->actionClose, SIGNAL(triggered(bool)), this, SLOT(close())); connect(ui->actionEditConnection, SIGNAL(triggered(bool)), this, SLOT(openConnectionManagerWindow())); connect(ui->actionNewConnection, SIGNAL(triggered(bool)), this, SLOT(openNewConnectionWindow())); connect(ui->menuVerbinden, SIGNAL(triggered(QAction*)), this, SLOT(onEstablishNewConnection(QAction*))); connect(&this->connections, SIGNAL(changed()), this, SLOT(createConnectionSubMenu())); connect(&this->connections, SIGNAL(changed()), this, SLOT(saveConnectionInfos())); connect(ui->btnQuerySave, SIGNAL(clicked()), this, SLOT(saveQuery())); connect(ui->btnQueryLoad, SIGNAL(clicked()), this, SLOT(loadQuery())); connect(ui->actionAboutDBManager, SIGNAL(triggered()), this, SLOT(showAboutText())); connect(ui->actionCheckForUpdates, SIGNAL(triggered()), this->updateManager, SLOT(checkUpdateAvailable())); connect(ui->actionReleaseNotes, SIGNAL(triggered(bool)), this, SLOT(showReleaseNotes())); this->updateManager->checkUpdateAvailable(false); } void MainWindow::enableReleaseNotesButton() { QMenuBar* releaseNotesBar = new QMenuBar(ui->menuBar); QAction* releaseNotes = new QAction(QIcon(":/icons/release_notes.png"), ""); releaseNotesBar->addAction(releaseNotes); releaseNotesBar->setVisible(true); this->ui->menuBar->setCornerWidget(releaseNotesBar); connect(releaseNotes, SIGNAL(triggered()), this, SLOT(showReleaseNotes())); } void MainWindow::showReleaseNotes() { releaseNotesManager->toggle(); } void MainWindow::onChangeTab(int index) { // qDebug() << "OnChangeTab " << index; if (index == this->ui->tabWidget->count() - 1) { newTab(); } else { // this->currentTabIndex = index; this->handleChangedQueryRequest(); } } void MainWindow::closeTab(int index) { // qDebug() << "Tabs: " << this->ui->tabWidget->count(); // qDebug() << "Index: " << index; if (2 < this->ui->tabWidget->count() && index < (this->ui->tabWidget->count() - 1) ) { this->ui->tabWidget->removeTab(index); // this->currentTabIndex = this->currentTabIndex - 1; if (this->currentQueryRequests->contains(index)) { // this->currentQueryRequests->remove(this->currentTabIndex); this->currentQueryRequests->remove(ui->tabWidget->currentIndex()); } // reindex map QMap<int, QString>* newMap = new QMap<int, QString>(); QMapIterator<int, QString> mapIterator(*this->currentQueryRequests); int index = 0; while (mapIterator.hasNext()) { mapIterator.next(); (*newMap)[index] = mapIterator.value(); index++; } this->currentQueryRequests = newMap; } } void MainWindow::newTab() { int position = ui->tabWidget->count() - 1; TextEdit* textEdit = new TextEdit(dbConnection, this); if (nullptr != dbConnection && nullptr != dbConnection->getKeywords() ) { highlighter = new Highlighter(textEdit->document(), dbConnection->getKeywords()); } connect(textEdit, SIGNAL(textChanged()), this, SLOT(handleChangedQueryRequest())); ui->tabWidget->insertTab(position, textEdit, QString(tr("New tab"))); ui->tabWidget->setCurrentIndex(position); } void MainWindow::handleChangedQueryRequest() { // QString query = ui->queryRequest->toPlainText(); // TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->currentTabIndex)); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); QString query = textEdit->toPlainText(); // if (!query.isEmpty() // && ((this->currentQueryRequests->contains(this->currentTabIndex) // && query != (*this->currentQueryRequests)[this->currentTabIndex]) // || false == this->currentQueryRequests->contains(this->currentTabIndex) // ) // ) { if (!query.isEmpty() && ((this->currentQueryRequests->contains(this->ui->tabWidget->currentIndex()) && query != (*this->currentQueryRequests)[this->ui->tabWidget->currentIndex()]) || false == this->currentQueryRequests->contains(this->ui->tabWidget->currentIndex()) ) ) { markAsUnsaved(true); showQuerySaveIcon(); } else { markAsUnsaved(isUnsaved()); hideQuerySaveIcon(); } } void MainWindow::showQuerySaveIcon() { ui->btnQuerySave->show(); } void MainWindow::hideQuerySaveIcon() { ui->btnQuerySave->hide(); } void MainWindow::saveQuery() { // TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->currentTabIndex)); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); QString query = textEdit->toPlainText(); QString queryFileName = QFileDialog::getSaveFileName( this, tr("Save Current Query"), "", tr("Sql Files (*.sql);;All Files (*)") ); if (queryFileName.isEmpty()) { return; } else { // qDebug() << "Save in file: " << queryFileName; QFile file(queryFileName); if (!file.open(QIODevice::WriteOnly)) { QMessageBox::information( this, tr("Unable to open file"), file.errorString() ); return; } QDataStream out(&file); out.setVersion(QDataStream::Qt_4_5); out << query; // (*this->currentQueryRequests)[this->currentTabIndex] = query; (*this->currentQueryRequests)[this->ui->tabWidget->currentIndex()] = query; this->markAsUnsaved(false); this->hideQuerySaveIcon(); } } void MainWindow::loadQuery() { QString queryFileName = QFileDialog::getOpenFileName( this, tr("Open Address Book"), "", tr("Sql Files (*.sql);;All Files (*)") ); if (queryFileName.isEmpty()) { return; } else { QFile file(queryFileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::information( this, tr("Unable to open file"), file.errorString() ); return; } QString query; QDataStream in(&file); in.setVersion(QDataStream::Qt_4_5); in >> query; // (*this->currentQueryRequests)[this->currentTabIndex] = query; (*this->currentQueryRequests)[this->ui->tabWidget->currentIndex()] = query; hideQuerySaveIcon(); markAsUnsaved(false); // TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->currentTabIndex)); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); textEdit->setText(query); } } void MainWindow::openNewConnectionWindow() { NewConnectionWizard wizard; if (wizard.exec()) { if (nullptr != dbConnection) { dbConnection->close(); } connectionInfo = connectionInfoFactory->create(wizard); storeConnectionInfo(connectionInfo); dbConnection = establishNewConnection(connectionInfo); saveConnectionInfos(); } } void MainWindow::openConnectionManagerWindow() { ConnectionManager manager(this, &connections); if (manager.exec()) { } } void MainWindow::createConnectionSubMenu() { ui->menuVerbinden->clear(); // QMapIterator<QString, QMap<QString, ConnectionInfo*> > typeIterator(connections); QMap<QString, QMap<QString, ConnectionInfo*>>::iterator typeIterator = connections.begin(); // while (typeIterator.hasNext()) { while(typeIterator != connections.end()) { // typeIterator.next(); QMenu* typeMenu = new QMenu(typeIterator.key()); QMapIterator<QString, ConnectionInfo*> connectionsIterator(typeIterator.value()); while(connectionsIterator.hasNext()) { connectionsIterator.next(); typeMenu->addAction(connectionsIterator.value()->getConnectionName()); } ui->menuVerbinden->addMenu(typeMenu); ++typeIterator; } if (0 < connections.size()) { ui->menuVerbinden->menuAction()->setVisible(true); } } void MainWindow::showResultTableContextMenu(const QPoint& point) { QMenu *menu=new QMenu(); // QAction copyAction(tr("copy"), this); QAction copyAction(QCoreApplication::tr("copy")); connect(&copyAction, SIGNAL(triggered()), dbConnection, SLOT(copyResultViewSelection())); menu->addAction(&copyAction); QAction deleteAction(tr("delete"), this); connect(&deleteAction, SIGNAL(triggered()), dbConnection, SLOT(deleteResultViewSelection())); menu->addAction(&deleteAction); QAction pasteAction(tr("paste"), this); connect(&pasteAction, SIGNAL(triggered()), dbConnection, SLOT(pasteToResultView())); menu->addAction(&pasteAction); QAction insertNullAction(tr("insert NULL")); connect(&insertNullAction, SIGNAL(triggered()), dbConnection, SLOT(insertNullToResultView())); menu->addAction(&insertNullAction); if (menu->exec(ui->queryResult->viewport()->mapToGlobal(point))) { // this->currentContextMenuItem = nullptr; } } void MainWindow::saveConnectionInfos() { QFile file("DBManager.xml"); file.open(QFile::ReadWrite); // delete all current content of file. file.resize(0); QXmlStreamWriter stream(&file); stream.setAutoFormatting(true); stream.writeStartDocument(); stream.writeStartElement("connections"); // QMapIterator<QString, QMap<QString, ConnectionInfo*> > typeIterator(connections); QMap<QString, QMap<QString, ConnectionInfo*>>::iterator typeIterator = connections.begin(); // while (typeIterator.hasNext()) { while(typeIterator != connections.end()) { // typeIterator.next(); QMapIterator<QString, ConnectionInfo*> connectionsIterator(typeIterator.value()); while(connectionsIterator.hasNext()) { connectionsIterator.next(); stream.writeStartElement("connection"); // stream.writeAttribute("href", "url"); if (!connectionsIterator.value()->getConnectionName().isEmpty() && !connectionsIterator.value()->isConnectionNameAutogenerated() ) { stream.writeTextElement("name", connectionsIterator.value()->getConnectionName()); } stream.writeTextElement("type", connectionsIterator.value()->getConnectionType()); if ("MYSQL" == connectionsIterator.value()->getConnectionType()) { if (!connectionsIterator.value()->getHost().isEmpty()) { stream.writeTextElement("host", connectionsIterator.value()->getHost()); } if (0 < connectionsIterator.value()->getPort()) { stream.writeTextElement("port", QString::number(connectionsIterator.value()->getPort())); } if (!connectionsIterator.value()->getUser().isEmpty()) { stream.writeTextElement("user", connectionsIterator.value()->getUser()); } if (!connectionsIterator.value()->getPassword().isEmpty()) { stream.writeTextElement("password", connectionsIterator.value()->getPassword()); } if (!connectionsIterator.value()->getDatabaseName().isEmpty()) { stream.writeTextElement("database", connectionsIterator.value()->getDatabaseName()); } } else if ("SQLITE" == connectionsIterator.value()->getConnectionType()) { stream.writeTextElement("databasePath", connectionsIterator.value()->getDatabasePath()); } stream.writeEndElement(); } ++typeIterator; } stream.writeEndElement(); stream.writeEndDocument(); file.close(); } void MainWindow::loadConnectionInfos() { QFile file("DBManager.xml"); if (!QFileInfo::exists("DBManager.xml")) { return; } file.open(QFile::ReadOnly | QFile::Text); QXmlStreamReader stream(&file); connections.clear(); while(!stream.atEnd() && !stream.hasError() ) { QXmlStreamReader::TokenType token = stream.readNext(); if (QXmlStreamReader::StartElement == token && "connection" == stream.name() ) { ConnectionInfo* connectionInfo = connectionInfoFactory->create(stream); connections.insert(connectionInfo); // connections[connectionInfo->getConnectionType()][connectionInfo->getConnectionName()] = connectionInfo; } } createConnectionSubMenu(); file.close(); emit connections.changed(); } void MainWindow::storeConnectionInfo(ConnectionInfo* connectionInfo) { connections.insert(connectionInfo); connectionsSaved = false; emit connections.changed(); } void MainWindow::onEstablishNewConnection(QAction *action) { QWidget* widget = action->parentWidget(); if (widget) { QMenu* menu = dynamic_cast<QMenu* >(widget); establishNewConnection(connections[menu->title()][action->text()]); } } Connection* MainWindow::establishNewConnection(ConnectionInfo* connectionInfo) { dbConnection = connectionFactory->create(connectionInfo); connect(dbConnection, SIGNAL(connectionError(QString)), this, SLOT(handleConnectionError(QString))); connect(ui->databaseList, SIGNAL(customContextMenuRequested(const QPoint&)), this->dbConnection, SLOT(showDatabaseContextMenu(const QPoint&))); ui->queryResult->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->queryResult, SIGNAL(customContextMenuRequested(QPoint)), this->dbConnection, SLOT(showResultTableContextMenu(QPoint))); connect(ui->btnAddNewRow, SIGNAL(clicked()), this->dbConnection, SLOT(addNewRow())); connect(ui->btnQueryResultSave, SIGNAL(clicked()), this->dbConnection, SLOT(saveQueryResultChanges())); connect(ui->btnQueryResultCancel, SIGNAL(clicked()), this->dbConnection, SLOT(cancelQueryResultChanges())); dbConnection->setDatabaseListView(ui->databaseList); dbConnection->setQueryResultView(ui->queryResult); // dbConnection->setQueryRequestView(qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex()))); dbConnection->setInformationView(ui->information); dbConnection->loadDatabaseList(); if (nullptr != dbConnection && nullptr != dbConnection->getKeywords() ) { TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(this->ui->tabWidget->currentIndex())); highlighter = new Highlighter(textEdit->document(), dbConnection->getKeywords()); textEdit->setConnection(dbConnection); } if ("SQLITE" == connectionInfo->getConnectionType()) { setWindowTitle(QString("%1 - %2").arg(connectionInfo->getDatabaseName()).arg("Database Manager")); } else { setWindowTitle(QString("%1@%2 - %3").arg(Defaults::Resolver::resolve("user", connectionInfo->getUser())).arg(connectionInfo->getHost()).arg("Database Manager")); } return dbConnection; } void MainWindow::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Return && event->modifiers() == Qt::ControlModifier) { this->onExecuteQueryClicked(); } } void MainWindow::handleConnectionError(QString errorMessage) { this->ui->information->append(errorMessage); } void MainWindow::onExecuteQueryClicked() { /* // qDebug() << "Current Tab Index von QTabWidget::currentIndex: " << ui->tabWidget->currentIndex(); TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(ui->tabWidget->currentIndex())); // qDebug() << "MainWindow::onExecuteQueryClicked textEdit: " << textEdit; QString queryString = textEdit->toPlainText(); // QString queryString = ui->queryRequest->toPlainText(); if (nullptr == dbConnection) { this->ui->information->append(tr("No Connection established!")); return; } QSqlQuery query = dbConnection->sendQuery(queryString); QStandardItemModel* queryResultModel = new QStandardItemModel; if (query.isActive()) { QSqlRecord localRecord = query.record(); // qDebug() << "Local Record: " << localRecord; for (int currentPos = 0; currentPos < localRecord.count(); ++currentPos) { QStandardItem* headerItem = new QStandardItem(localRecord.fieldName(currentPos)); queryResultModel->setHorizontalHeaderItem(currentPos, headerItem); } query.seek(-1); int currentRow = 0; while (query.next()) { QSqlRecord currentRecord = query.record(); for (int currentColumn = 0; currentColumn < currentRecord.count(); ++currentColumn) { QStandardItem* value = new QStandardItem(currentRecord.field(currentColumn).value().toString()); queryResultModel->setItem(currentRow, currentColumn, value); } ++currentRow; } } ui->queryResult->setModel(queryResultModel); ui->queryResult->resizeColumnsToContents(); statusBar()->showMessage(tr("connected!")); */ TextEdit* textEdit = qobject_cast<TextEdit*>(ui->tabWidget->widget(ui->tabWidget->currentIndex())); QString queryString = textEdit->toPlainText(); if (nullptr == dbConnection) { this->ui->information->append(tr("No Connection established!")); return; } QSqlQuery query = dbConnection->sendQuery(queryString); QSqlQueryModel* queryResultModel = new QSqlQueryModel; queryResultModel->setQuery(query); ui->queryResult->setVisible(false); ui->queryResult->setModel(queryResultModel); // ui->queryResult->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->queryResult->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); ui->queryResult->resizeColumnsToContents(); ui->queryResult->setVisible(true); } void MainWindow::onQueryResultHeaderClicked(QStandardItem* item) { } /** Public slot to get unsaved state for global application. * @brief MainWindow::markAsUnsaved * @param unsaved */ void MainWindow::markAsUnsaved(bool unsaved) { this->setUnsaved(unsaved); } bool MainWindow::isUnsaved() const { return unsaved; } void MainWindow::setUnsaved(const bool unsaved) { this->unsaved = unsaved; } void MainWindow::showAboutText() { QMessageBox messageBox(this); messageBox.setIcon(QMessageBox::Icon::Information); messageBox.setWindowTitle(tr("DBManager - about")); messageBox.setTextFormat(Qt::RichText); messageBox.setText(tr("DBManager in version %1.<br />This Program is Freeware and OpenSource.").arg(Application::BuildNo)); messageBox.setInformativeText(tr("Future information and Projects under <a href='https://www.byte-artist.de'>www.byte-artist.de</a><br /><br />Found issues can tracked here: <a href='https://bitbucket.org/mastercad/dbmanager/issues'>DBManager Issue Tracker</a>")); messageBox.exec(); } MainWindow::~MainWindow() { delete currentQueryRequests; delete updateManager; delete ui; }
36.17609
268
0.663556
mastercad
091b507b80ac9b8007e71b48db5493edfad67ce8
88
cpp
C++
esl/economics/markets/ticker.cpp
rht/ESL
f883155a167d3c48e5ecdca91c8302fefc901c22
[ "Apache-2.0" ]
37
2019-10-13T12:23:32.000Z
2022-03-19T10:40:29.000Z
esl/economics/markets/ticker.cpp
rht/ESL
f883155a167d3c48e5ecdca91c8302fefc901c22
[ "Apache-2.0" ]
3
2020-03-20T04:44:06.000Z
2021-01-12T06:18:33.000Z
esl/economics/markets/ticker.cpp
vishalbelsare/ESL
cea6feda1e588d5f441742dbb1e4c5479b47d357
[ "Apache-2.0" ]
10
2019-11-06T15:59:06.000Z
2021-08-09T17:28:24.000Z
// // Created by Maarten on 23/06/2020. // #include <esl/economics/markets/ticker.hpp>
14.666667
43
0.693182
rht
091c3aa3ffe44824646d95909d3fa62068d0ab2e
1,320
hxx
C++
client/default_colors.hxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
client/default_colors.hxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
client/default_colors.hxx
Drako/MPSnake
a22bd7156f79f9824ce689c54ac4a7ef085efd08
[ "MIT" ]
null
null
null
#pragma once #ifndef SNAKE_DEFAULT_COLORS_HXX #define SNAKE_DEFAULT_COLORS_HXX #include "sdl.hxx" namespace snake::client::colors { static SDL_Color const BLACK{0, 0, 0, 0xFF}; static SDL_Color const WHITE{0xFF, 0xFF, 0xFF, 0xFF}; enum class Channel : std::uint8_t { Red = 0, Green = 8, Blue = 16, Alpha = 32, }; constexpr std::uint8_t extractColorChannel(std::uint32_t color, Channel which) { return static_cast<std::uint8_t>(color >> static_cast<std::uint32_t>(which)); } constexpr std::uint32_t calculateColorChannel(std::uint32_t value, Channel which) { return static_cast<std::uint32_t>(value) << static_cast<std::uint32_t>(which); } constexpr std::uint32_t colorToRGBA(SDL_Color const & color) { return calculateColorChannel(color.r, Channel::Red) | calculateColorChannel(color.g, Channel::Green) | calculateColorChannel(color.b, Channel::Blue) | calculateColorChannel(color.a, Channel::Alpha); } constexpr SDL_Color rgbaToColor(std::uint32_t rgba) { return { extractColorChannel(rgba, Channel::Red), extractColorChannel(rgba, Channel::Green), extractColorChannel(rgba, Channel::Blue), extractColorChannel(rgba, Channel::Alpha), }; } } #endif // SNAKE_DEFAULT_COLORS_HXX
25.882353
83
0.689394
Drako
092003d9cf0ba3280ca15da351c51ef13a4248ff
6,742
cpp
C++
pomdog/experimental/gui/stack_panel.cpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
163
2015-03-16T08:42:32.000Z
2022-01-11T21:40:22.000Z
pomdog/experimental/gui/stack_panel.cpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
17
2015-04-12T20:57:50.000Z
2020-10-10T10:51:45.000Z
pomdog/experimental/gui/stack_panel.cpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
21
2015-04-12T20:45:11.000Z
2022-01-14T20:50:16.000Z
// Copyright mogemimi. Distributed under the MIT license. #include "pomdog/experimental/gui/stack_panel.hpp" #include "pomdog/experimental/gui/drawing_context.hpp" #include "pomdog/experimental/gui/pointer_point.hpp" #include "pomdog/experimental/gui/ui_event_dispatcher.hpp" #include "pomdog/experimental/gui/ui_helper.hpp" #include "pomdog/math/math.hpp" namespace pomdog::gui { StackPanel::StackPanel( const std::shared_ptr<UIEventDispatcher>& dispatcher, int widthIn, int heightIn) : Widget(dispatcher) , padding{12, 8, 10, 8} , barHeight(16) , needToUpdateLayout(true) { SetSize(widthIn, heightIn); verticalLayout = std::make_shared<VerticalLayout>(dispatcher, 140, 10); verticalLayout->SetStackedLayout(true); verticalLayout->SetLayoutSpacing(12); } void StackPanel::SetPosition(const Point2D& positionIn) { Widget::SetPosition(positionIn); POMDOG_ASSERT(verticalLayout != nullptr); verticalLayout->MarkParentTransformDirty(); } void StackPanel::SetPadding(const Thickness& paddingIn) { padding = paddingIn; needToUpdateLayout = true; } void StackPanel::MarkParentTransformDirty() { Widget::MarkParentTransformDirty(); POMDOG_ASSERT(verticalLayout); verticalLayout->MarkParentTransformDirty(); } void StackPanel::MarkContentLayoutDirty() { needToUpdateLayout = true; } bool StackPanel::GetSizeToFitContent() const noexcept { return false; } void StackPanel::OnEnter() { POMDOG_ASSERT(verticalLayout != nullptr); verticalLayout->MarkParentTransformDirty(); POMDOG_ASSERT(shared_from_this()); verticalLayout->SetParent(shared_from_this()); verticalLayout->OnEnter(); } void StackPanel::OnPointerPressed(const PointerPoint& pointerPoint) { if (pointerPoint.MouseEvent && (*pointerPoint.MouseEvent != PointerMouseEvent::LeftButtonPressed)) { return; } auto pointInView = UIHelper::ProjectToChildSpace(pointerPoint.Position, GetGlobalPosition()); const auto collisionHeight = barHeight + padding.Top; Rectangle captionBar{ 0, GetHeight() - collisionHeight, GetWidth(), collisionHeight}; if (captionBar.Contains(pointInView)) { startTouchPoint = math::ToVector2(pointInView); } } void StackPanel::OnPointerMoved(const PointerPoint& pointerPoint) { if (!startTouchPoint) { return; } auto pointInView = UIHelper::ProjectToChildSpace(pointerPoint.Position, GetGlobalPosition()); auto position = math::ToVector2(pointInView); auto tangent = position - *startTouchPoint; auto distanceSquared = math::LengthSquared(tangent); if (distanceSquared >= 1.4143f) { SetPosition(GetPosition() + math::ToPoint2D(tangent)); // NOTE: recalculate position in current coordinate system pointInView = UIHelper::ProjectToChildSpace(pointerPoint.Position, GetGlobalPosition()); position = math::ToVector2(pointInView); startTouchPoint = position; } } void StackPanel::OnPointerReleased([[maybe_unused]] const PointerPoint& pointerPoint) { if (!startTouchPoint) { return; } startTouchPoint = std::nullopt; } void StackPanel::AddChild(const std::shared_ptr<Widget>& widget) { POMDOG_ASSERT(verticalLayout); verticalLayout->AddChild(widget); needToUpdateLayout = true; } std::shared_ptr<Widget> StackPanel::GetChildAt(const Point2D& position) { POMDOG_ASSERT(verticalLayout != nullptr); auto bounds = verticalLayout->GetBounds(); if (bounds.Contains(position)) { return verticalLayout; } return nullptr; } void StackPanel::UpdateAnimation(const Duration& frameDuration) { POMDOG_ASSERT(verticalLayout != nullptr); verticalLayout->UpdateAnimation(frameDuration); } void StackPanel::UpdateLayout() { POMDOG_ASSERT(verticalLayout); verticalLayout->DoLayout(); if (!needToUpdateLayout) { return; } const auto requiredHeight = padding.Top + barHeight + verticalLayout->GetHeight() + padding.Bottom; if (requiredHeight != GetHeight()) { // NOTE: Keeping the original position const auto positionOffset = Point2D{0, GetHeight() - requiredHeight}; SetPosition(GetPosition() + positionOffset); // NOTE: Resizing this panel SetSize(GetWidth(), requiredHeight); auto parent = GetParent(); if (parent) { parent->MarkContentLayoutDirty(); } } // NOTE: Update layout for children { verticalLayout->SetPosition(Point2D{padding.Left, padding.Bottom}); switch (verticalLayout->GetHorizontalAlignment()) { case HorizontalAlignment::Stretch: { auto childWidth = GetWidth() - (padding.Left + padding.Right); verticalLayout->SetSize(childWidth, verticalLayout->GetHeight()); verticalLayout->MarkContentLayoutDirty(); break; } case HorizontalAlignment::Left: break; case HorizontalAlignment::Right: break; } } needToUpdateLayout = false; } void StackPanel::DoLayout() { UpdateLayout(); } void StackPanel::Draw(DrawingContext& drawingContext) { UpdateLayout(); POMDOG_ASSERT(!needToUpdateLayout); const auto* colorScheme = drawingContext.GetColorScheme(); POMDOG_ASSERT(colorScheme != nullptr); auto globalPos = UIHelper::ProjectToWorldSpace(GetPosition(), drawingContext.GetCurrentTransform()); auto primitiveBatch = drawingContext.GetPrimitiveBatch(); const auto w = static_cast<float>(GetWidth()); const auto h = static_cast<float>(GetHeight()); primitiveBatch->DrawRectangle( Rectangle{globalPos.X, globalPos.Y, GetWidth(), GetHeight()}, colorScheme->PanelBackgroundColor); primitiveBatch->DrawRectangle( Rectangle{globalPos.X, globalPos.Y + (GetHeight() - barHeight), GetWidth(), barHeight}, colorScheme->PanelTitleBarColor); const auto pos = math::ToVector2(globalPos); primitiveBatch->DrawLine(pos + Vector2{0.0f, 0.0f}, pos + Vector2{w, 0.0f}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->DrawLine(pos + Vector2{0.0f, 0.0f}, pos + Vector2{0.0f, h}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->DrawLine(pos + Vector2{0.0f, h}, pos + Vector2{w, h}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->DrawLine(pos + Vector2{w, 0.0f}, pos + Vector2{w, h}, colorScheme->PanelOutlineBorderColor, 1.0f); primitiveBatch->Flush(); drawingContext.PushTransform(globalPos); POMDOG_ASSERT(verticalLayout); verticalLayout->Draw(drawingContext); drawingContext.PopTransform(); } } // namespace pomdog::gui
29.060345
124
0.700979
mogemimi
09202c2533a6fc7dd34f1494ff33881ef3d60fa0
177,837
cpp
C++
External/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp
Sonicadvance1/FEX
d84b536c4a2f785870a714bd5ed9f914dff735a3
[ "MIT" ]
1
2020-05-24T22:00:46.000Z
2020-05-24T22:00:46.000Z
External/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp
Sonicadvance1/FEX
d84b536c4a2f785870a714bd5ed9f914dff735a3
[ "MIT" ]
null
null
null
External/FEXCore/Source/Interface/Core/OpcodeDispatcher.cpp
Sonicadvance1/FEX
d84b536c4a2f785870a714bd5ed9f914dff735a3
[ "MIT" ]
null
null
null
#include "Interface/Core/OpcodeDispatcher.h" #include <FEXCore/Core/CoreState.h> #include <climits> #include <cstddef> #include <cstdint> #include <FEXCore/Core/X86Enums.h> namespace FEXCore::IR { auto OpToIndex = [](uint8_t Op) constexpr -> uint8_t { switch (Op) { // Group 1 case 0x80: return 0; case 0x81: return 1; case 0x82: return 2; case 0x83: return 3; // Group 2 case 0xC0: return 0; case 0xC1: return 1; case 0xD0: return 2; case 0xD1: return 3; case 0xD2: return 4; case 0xD3: return 5; // Group 3 case 0xF6: return 0; case 0xF7: return 1; // Group 4 case 0xFE: return 0; // Group 5 case 0xFF: return 0; // Group 11 case 0xC6: return 0; case 0xC7: return 1; } return 0; }; #define OpcodeArgs [[maybe_unused]] FEXCore::X86Tables::DecodedOp Op void OpDispatchBuilder::SyscallOp(OpcodeArgs) { constexpr size_t SyscallArgs = 7; constexpr std::array<uint64_t, SyscallArgs> GPRIndexes = { FEXCore::X86State::REG_RAX, FEXCore::X86State::REG_RDI, FEXCore::X86State::REG_RSI, FEXCore::X86State::REG_RDX, FEXCore::X86State::REG_R10, FEXCore::X86State::REG_R8, FEXCore::X86State::REG_R9, }; auto NewRIP = _Constant(Op->PC); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); auto SyscallOp = _Syscall( _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[0] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[1] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[2] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[3] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[4] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[5] * 8, GPRClass), _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs) + GPRIndexes[6] * 8, GPRClass)); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), SyscallOp); } void OpDispatchBuilder::LEAOp(OpcodeArgs) { uint32_t DstSize = X86Tables::DecodeFlags::GetOpAddr(Op->Flags) == X86Tables::DecodeFlags::FLAG_OPERAND_SIZE_LAST ? 2 : X86Tables::DecodeFlags::GetOpAddr(Op->Flags) == X86Tables::DecodeFlags::FLAG_WIDENING_SIZE_LAST ? 8 : 4; uint32_t SrcSize = (Op->Flags & X86Tables::DecodeFlags::FLAG_ADDRESS_SIZE) ? 4 : 8; OrderedNode *Src = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], SrcSize, Op->Flags, -1, false); StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, DstSize, -1); } void OpDispatchBuilder::NOPOp(OpcodeArgs) { } void OpDispatchBuilder::RETOp(OpcodeArgs) { auto Constant = _Constant(8); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewRIP = _LoadMem(GPRClass, 8, OldSP, 8); OrderedNode *NewSP; if (Op->OP == 0xC2) { auto Offset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); NewSP = _Add(_Add(OldSP, Constant), Offset); } else { NewSP = _Add(OldSP, Constant); } // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); BlockSetRIP = true; } template<uint32_t SrcIndex> void OpDispatchBuilder::SecondaryALUOp(OpcodeArgs) { FEXCore::IR::IROps IROp; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 0): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 0): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 0): IROp = FEXCore::IR::IROps::OP_ADD; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 1): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 1): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 1): IROp = FEXCore::IR::IROps::OP_OR; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 4): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 4): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 4): IROp = FEXCore::IR::IROps::OP_AND; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 5): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 5): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 5): IROp = FEXCore::IR::IROps::OP_SUB; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 5): case OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 5): IROp = FEXCore::IR::IROps::OP_MUL; break; case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 6): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 6): case OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 6): IROp = FEXCore::IR::IROps::OP_XOR; break; default: IROp = FEXCore::IR::IROps::OP_LAST; LogMan::Msg::A("Unknown ALU Op: 0x%x", Op->OP); break; }; #undef OPD // X86 basic ALU ops just do the operation between the destination and a single source OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _Add(Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; StoreResult(GPRClass, Op, ALUOp, -1); // Flags set { auto Size = GetSrcSize(Op) * 8; switch (IROp) { case FEXCore::IR::IROps::OP_ADD: GenerateFlags_ADD(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_SUB: GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_MUL: GenerateFlags_MUL(Op, _Bfe(Size, 0, ALUOp), _MulH(Dest, Src)); break; case FEXCore::IR::IROps::OP_AND: case FEXCore::IR::IROps::OP_XOR: case FEXCore::IR::IROps::OP_OR: { GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; } default: break; } } } template<uint32_t SrcIndex> void OpDispatchBuilder::ADCOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto CF = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto ALUOp = _Add(_Add(Dest, Src), CF); StoreResult(GPRClass, Op, ALUOp, -1); GenerateFlags_ADC(Op, ALUOp, Dest, Src, CF); } template<uint32_t SrcIndex> void OpDispatchBuilder::SBBOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto CF = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto ALUOp = _Sub(_Sub(Dest, Src), CF); StoreResult(GPRClass, Op, ALUOp, -1); GenerateFlags_SBB(Op, ALUOp, Dest, Src, CF); } void OpDispatchBuilder::PUSHOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src; if (Op->OP == 0x68 || Op->OP == 0x6A) { // Immediate Push Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); } else { if (Op->OP == 0xFF && Size == 4) LogMan::Msg::A("Woops. Can't do 32bit for this PUSH op"); Src = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); } auto Constant = _Constant(Size); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewSP = _Sub(OldSP, Constant); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store our value to the new stack location _StoreMem(GPRClass, Size, NewSP, Src, Size); } void OpDispatchBuilder::POPOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); auto Constant = _Constant(Size); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewGPR = _LoadMem(GPRClass, Size, OldSP, Size); auto NewSP = _Add(OldSP, Constant); if (Op->OP == 0x8F && Size == 4) LogMan::Msg::A("Woops. Can't do 32bit for this POP op"); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store what we loaded from the stack StoreResult(GPRClass, Op, NewGPR, -1); } void OpDispatchBuilder::LEAVEOp(OpcodeArgs) { // First we move RBP in to RSP and then behave effectively like a pop uint8_t Size = GetSrcSize(Op); auto Constant = _Constant(Size); LogMan::Throw::A(Size == 8, "Can't handle a LEAVE op with size %d", Size); auto OldBP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RBP]), GPRClass); auto NewGPR = _LoadMem(GPRClass, Size, OldBP, Size); auto NewSP = _Add(OldBP, Constant); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); // Store what we loaded to RBP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RBP]), NewGPR); } void OpDispatchBuilder::CALLOp(OpcodeArgs) { BlockSetRIP = true; auto ConstantPC = _Constant(Op->PC + Op->InstSize); OrderedNode *JMPPCOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *NewRIP = _Add(JMPPCOffset, ConstantPC); auto ConstantPCReturn = _Constant(Op->PC + Op->InstSize); auto ConstantSize = _Constant(8); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewSP = _Sub(OldSP, ConstantSize); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); _StoreMem(GPRClass, 8, NewSP, ConstantPCReturn, 8); // Store the RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); // If we get here then leave the function now } void OpDispatchBuilder::CALLAbsoluteOp(OpcodeArgs) { BlockSetRIP = true; OrderedNode *JMPPCOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto ConstantPCReturn = _Constant(Op->PC + Op->InstSize); auto ConstantSize = _Constant(8); auto OldSP = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), GPRClass); auto NewSP = _Sub(OldSP, ConstantSize); // Store the new stack pointer _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSP]), NewSP); _StoreMem(GPRClass, 8, NewSP, ConstantPCReturn, 8); // Store the RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), JMPPCOffset); _ExitFunction(); // If we get here then leave the function now } void OpDispatchBuilder::CondJUMPOp(OpcodeArgs) { BlockSetRIP = true; auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); IRPair<IROp_Header> SrcCond; IRPair<IROp_Constant> TakeBranch; IRPair<IROp_Constant> DoNotTakeBranch; TakeBranch = _Constant(1); DoNotTakeBranch = _Constant(0); switch (Op->OP) { case 0x70: case 0x80: { // JO - Jump if OF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x71: case 0x81: { // JNO - Jump if OF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x72: case 0x82: { // JC - Jump if CF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x73: case 0x83: { // JNC - Jump if CF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x74: case 0x84: { // JE - Jump if ZF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x75: case 0x85: { // JNE - Jump if ZF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x76: case 0x86: { // JNA - Jump if CF == 1 || ZC == 1 auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto Check = _Or(Flag1, Flag2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, TakeBranch, DoNotTakeBranch); break; } case 0x77: case 0x87: { // JA - Jump if CF == 0 && ZF == 0 auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_CF_LOC); auto Check = _Or(Flag1, _Lshl(Flag2, _Constant(1))); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x78: case 0x88: { // JS - Jump if SF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x79: case 0x89: { // JNS - Jump if SF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x7A: case 0x8A: { // JP - Jump if PF == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_PF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x7B: case 0x8B: { // JNP - Jump if PF == 0 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_PF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag, ZeroConst, TakeBranch, DoNotTakeBranch); break; } case 0x7C: // SF <> OF case 0x8C: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag1, Flag2, TakeBranch, DoNotTakeBranch); break; } case 0x7D: // SF = OF case 0x8D: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag1, Flag2, TakeBranch, DoNotTakeBranch); break; } case 0x7E: // ZF = 1 || SF <> OF case 0x8E: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, OneConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_NEQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _Or(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, TakeBranch, DoNotTakeBranch); break; } case 0x7F: // ZF = 0 && SF = OF case 0x8F: { auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, ZeroConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_EQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _And(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, TakeBranch, DoNotTakeBranch); break; } default: LogMan::Msg::A("Unknown Jmp Op: 0x%x\n", Op->OP); return; } LogMan::Throw::A(Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Target = Op->PC + Op->InstSize + Op->Src[0].TypeLiteral.Literal; auto TrueBlock = JumpTargets.find(Target); auto FalseBlock = JumpTargets.find(Op->PC + Op->InstSize); // Fallback { auto CondJump = _CondJump(SrcCond); // Taking branch block if (TrueBlock != JumpTargets.end()) { SetTrueJumpTarget(CondJump, TrueBlock->second.BlockEntry); } else { // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); auto RIPOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto RIPTargetConst = _Constant(Op->PC + Op->InstSize); auto NewRIP = _Add(RIPOffset, RIPTargetConst); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); } // Failure to take branch if (FalseBlock != JumpTargets.end()) { SetFalseJumpTarget(CondJump, FalseBlock->second.BlockEntry); } else { // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); // Leave block auto RIPTargetConst = _Constant(Op->PC + Op->InstSize); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), RIPTargetConst); _ExitFunction(); } } } void OpDispatchBuilder::JUMPOp(OpcodeArgs) { BlockSetRIP = true; // This is just an unconditional relative literal jump // XXX: Reenable if (Multiblock) { LogMan::Throw::A(Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Target = Op->PC + Op->InstSize + Op->Src[0].TypeLiteral.Literal; auto JumpBlock = JumpTargets.find(Target); if (JumpBlock != JumpTargets.end()) { _Jump(GetNewJumpBlock(Target)); } else { // If the block isn't a jump target then we need to create an exit block auto Jump = _Jump(); auto JumpTarget = CreateNewCodeBlock(); SetJumpTarget(Jump, JumpTarget); SetCurrentCodeBlock(JumpTarget); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), _Constant(Target)); _ExitFunction(); } return; } // Fallback { // This source is a literal auto RIPOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto RIPTargetConst = _Constant(Op->PC + Op->InstSize); auto NewRIP = _Add(RIPOffset, RIPTargetConst); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); _ExitFunction(); } } void OpDispatchBuilder::JUMPAbsoluteOp(OpcodeArgs) { BlockSetRIP = true; // This is just an unconditional jump // This uses ModRM to determine its location // No way to use this effectively in multiblock auto RIPOffset = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Store the new RIP _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), RIPOffset); _ExitFunction(); } void OpDispatchBuilder::SETccOp(OpcodeArgs) { enum CompareType { COMPARE_ZERO, COMPARE_NOTZERO, COMPARE_EQUALMASK, COMPARE_OTHER, }; uint32_t FLAGMask; CompareType Type = COMPARE_OTHER; OrderedNode *SrcCond; auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); switch (Op->OP) { case 0x90: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_NOTZERO; break; case 0x91: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_ZERO; break; case 0x92: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_NOTZERO; break; case 0x93: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_ZERO; break; case 0x94: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_NOTZERO; break; case 0x95: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_ZERO; break; case 0x96: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_NOTZERO; break; case 0x97: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_ZERO; break; case 0x98: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_NOTZERO; break; case 0x99: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_ZERO; break; case 0x9A: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_NOTZERO; break; case 0x9B: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_ZERO; break; case 0x9D: { // SF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag1, Flag2, OneConst, ZeroConst); break; } case 0x9C: { // SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag1, Flag2, OneConst, ZeroConst); break; } case 0x9E: { // ZF = 1 || SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, OneConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_NEQ, Flag2, Flag3, OneConst, ZeroConst); SrcCond = _Or(Select1, Select2); break; } case 0x9F: { // ZF = 0 && SF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, ZeroConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_EQ, Flag2, Flag3, OneConst, ZeroConst); SrcCond = _And(Select1, Select2); break; } default: LogMan::Msg::A("Unhandled SetCC op: 0x%x", Op->OP); break; } if (Type != COMPARE_OTHER) { auto MaskConst = _Constant(FLAGMask); auto RFLAG = GetPackedRFLAG(false); auto AndOp = _And(RFLAG, MaskConst); switch (Type) { case COMPARE_ZERO: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, ZeroConst, OneConst, ZeroConst); break; } case COMPARE_NOTZERO: { SrcCond = _Select(FEXCore::IR::COND_NEQ, AndOp, ZeroConst, OneConst, ZeroConst); break; } case COMPARE_EQUALMASK: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, MaskConst, OneConst, ZeroConst); break; } case COMPARE_OTHER: break; } } StoreResult(GPRClass, Op, SrcCond, -1); } template<uint32_t SrcIndex> void OpDispatchBuilder::TESTOp(OpcodeArgs) { // TEST is an instruction that does an AND between the sources // Result isn't stored in result, only writes to flags OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _And(Dest, Src); auto Size = GetSrcSize(Op) * 8; GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::MOVSXDOp(OpcodeArgs) { // This instruction is a bit special // if SrcSize == 2 // Then lower 16 bits of destination is written without changing the upper 48 bits // else /* Size == 4 */ // if REX_WIDENING: // Sext(32, Src) // else // Zext(32, Src) // uint8_t Size = std::min(static_cast<uint8_t>(4), GetSrcSize(Op)); OrderedNode *Src = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], Size, Op->Flags, -1); if (Size == 2) { // This'll make sure to insert in to the lower 16bits without modifying upper bits StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, Size, -1); } else if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REX_WIDENING) { // With REX.W then Sext Src = _Sext(Size * 8, Src); StoreResult(GPRClass, Op, Src, -1); } else { // Without REX.W then Zext Src = _Zext(Size * 8, Src); StoreResult(GPRClass, Op, Src, -1); } } void OpDispatchBuilder::MOVSXOp(OpcodeArgs) { // This will ZExt the loaded size // We want to Sext it uint8_t Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _Sext(Size * 8, Src); StoreResult(GPRClass, Op, Op->Dest, Src, -1); } void OpDispatchBuilder::MOVZXOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Just make sure this is zero extended Src = _Zext(Size * 8, Src); StoreResult(GPRClass, Op, Src, -1); } template<uint32_t SrcIndex> void OpDispatchBuilder::CMPOp(OpcodeArgs) { // CMP is an instruction that does a SUB between the sources // Result isn't stored in result, only writes to flags OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op) * 8; auto ALUOp = _Sub(Dest, Src); GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::CQOOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto BfeOp = _Bfe(1, GetSrcSize(Op) * 8 - 1, Src); auto ZeroConst = _Constant(0); auto MaxConst = _Constant(~0ULL); auto SelectOp = _Select(FEXCore::IR::COND_EQ, BfeOp, ZeroConst, ZeroConst, MaxConst); StoreResult(GPRClass, Op, SelectOp, -1); } void OpDispatchBuilder::XCHGOp(OpcodeArgs) { // Load both the source and the destination if (Op->OP == 0x90 && GetSrcSize(Op) >= 4 && Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Src[0].TypeGPR.GPR == FEXCore::X86State::REG_RAX && Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Dest.TypeGPR.GPR == FEXCore::X86State::REG_RAX) { // This is one heck of a sucky special case // If we are the 0x90 XCHG opcode (Meaning source is GPR RAX) // and destination register is ALSO RAX // and in this very specific case we are 32bit or above // Then this is a no-op // This is because 0x90 without a prefix is technically `xchg eax, eax` // But this would result in a zext on 64bit, which would ruin the no-op nature of the instruction // So x86-64 spec mandates this special case that even though it is a 32bit instruction and // is supposed to zext the result, it is a true no-op return; } OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); if (DestIsLockedMem(Op)) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); auto Result = _AtomicSwap(Dest, Src, GetSrcSize(Op)); StoreResult(GPRClass, Op, Op->Src[0], Result, -1); } else { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); // Swap the contents // Order matters here since we don't want to swap context contents for one that effects the other StoreResult(GPRClass, Op, Op->Dest, Src, -1); StoreResult(GPRClass, Op, Op->Src[0], Dest, -1); } } void OpDispatchBuilder::CDQOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t SrcSize = GetSrcSize(Op); Src = _Sext(SrcSize * 4, Src); if (SrcSize == 4) { Src = _Zext(SrcSize * 8, Src); SrcSize *= 2; } StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, SrcSize * 8, -1); } void OpDispatchBuilder::SAHFOp(OpcodeArgs) { OrderedNode *Src = _LoadContext(1, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, GPRClass); // Clear bits that aren't supposed to be set Src = _And(Src, _Constant(~0b101000)); // Set the bit that is always set here Src = _Or(Src, _Constant(0b10)); // Store the lower 8 bits in to RFLAGS SetPackedRFLAG(true, Src); } void OpDispatchBuilder::LAHFOp(OpcodeArgs) { // Load the lower 8 bits of the Rflags register auto RFLAG = GetPackedRFLAG(true); // Store the lower 8 bits of the rflags register in to AH _StoreContext(GPRClass, 1, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, RFLAG); } void OpDispatchBuilder::FLAGControlOp(OpcodeArgs) { enum OpType { OP_CLEAR, OP_SET, OP_COMPLEMENT, }; OpType Type; uint64_t Flag; switch (Op->OP) { case 0xF5: // CMC Flag= FEXCore::X86State::RFLAG_CF_LOC; Type = OP_COMPLEMENT; break; case 0xF8: // CLC Flag= FEXCore::X86State::RFLAG_CF_LOC; Type = OP_CLEAR; break; case 0xF9: // STC Flag= FEXCore::X86State::RFLAG_CF_LOC; Type = OP_SET; break; case 0xFC: // CLD Flag= FEXCore::X86State::RFLAG_DF_LOC; Type = OP_CLEAR; break; case 0xFD: // STD Flag= FEXCore::X86State::RFLAG_DF_LOC; Type = OP_SET; break; } OrderedNode *Result{}; switch (Type) { case OP_CLEAR: { Result = _Constant(0); break; } case OP_SET: { Result = _Constant(1); break; } case OP_COMPLEMENT: { auto RFLAG = GetRFLAG(Flag); Result = _Xor(RFLAG, _Constant(1)); break; } } SetRFLAG(Result, Flag); } void OpDispatchBuilder::MOVSegOp(OpcodeArgs) { // In x86-64 mode the accesses to the segment registers end up being constant zero moves // Aside from FS/GS LogMan::Msg::A("Wanting reg: %d\n", Op->Src[0].TypeGPR.GPR); // StoreResult(Op, Src); } void OpDispatchBuilder::MOVOffsetOp(OpcodeArgs) { OrderedNode *Src; switch (Op->OP) { case 0xA0: case 0xA1: // Source is memory(literal) // Dest is GPR Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1, true, true); break; case 0xA2: case 0xA3: // Source is GPR // Dest is memory(literal) Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); break; } StoreResult(GPRClass, Op, Op->Dest, Src, -1); } void OpDispatchBuilder::CMOVOp(OpcodeArgs) { enum CompareType { COMPARE_ZERO, COMPARE_NOTZERO, COMPARE_EQUALMASK, COMPARE_OTHER, }; uint32_t FLAGMask; CompareType Type = COMPARE_OTHER; OrderedNode *SrcCond; auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); switch (Op->OP) { case 0x40: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_NOTZERO; break; case 0x41: FLAGMask = 1 << FEXCore::X86State::RFLAG_OF_LOC; Type = COMPARE_ZERO; break; case 0x42: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_NOTZERO; break; case 0x43: FLAGMask = 1 << FEXCore::X86State::RFLAG_CF_LOC; Type = COMPARE_ZERO; break; case 0x44: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_NOTZERO; break; case 0x45: FLAGMask = 1 << FEXCore::X86State::RFLAG_ZF_LOC; Type = COMPARE_ZERO; break; case 0x46: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_NOTZERO; break; case 0x47: FLAGMask = (1 << FEXCore::X86State::RFLAG_ZF_LOC) | (1 << FEXCore::X86State::RFLAG_CF_LOC); Type = COMPARE_ZERO; break; case 0x48: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_NOTZERO; break; case 0x49: FLAGMask = 1 << FEXCore::X86State::RFLAG_SF_LOC; Type = COMPARE_ZERO; break; case 0x4A: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_NOTZERO; break; case 0x4B: FLAGMask = 1 << FEXCore::X86State::RFLAG_PF_LOC; Type = COMPARE_ZERO; break; case 0x4C: { // SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_NEQ, Flag1, Flag2, Src, Dest); break; } case 0x4D: { // SF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); SrcCond = _Select(FEXCore::IR::COND_EQ, Flag1, Flag2, Src, Dest); break; } case 0x4E: { // ZF = 1 || SF <> OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, OneConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_NEQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _Or(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, Src, Dest); break; } case 0x4F: { // ZF = 0 && SSF = OF auto Flag1 = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); auto Flag2 = GetRFLAG(FEXCore::X86State::RFLAG_SF_LOC); auto Flag3 = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); auto Select1 = _Select(FEXCore::IR::COND_EQ, Flag1, ZeroConst, OneConst, ZeroConst); auto Select2 = _Select(FEXCore::IR::COND_EQ, Flag2, Flag3, OneConst, ZeroConst); auto Check = _And(Select1, Select2); SrcCond = _Select(FEXCore::IR::COND_EQ, Check, OneConst, Src, Dest); break; } default: LogMan::Msg::A("Unhandled CMOV op: 0x%x", Op->OP); break; } if (Type != COMPARE_OTHER) { auto MaskConst = _Constant(FLAGMask); auto RFLAG = GetPackedRFLAG(false); auto AndOp = _And(RFLAG, MaskConst); switch (Type) { case COMPARE_ZERO: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, ZeroConst, Src, Dest); break; } case COMPARE_NOTZERO: { SrcCond = _Select(FEXCore::IR::COND_NEQ, AndOp, ZeroConst, Src, Dest); break; } case COMPARE_EQUALMASK: { SrcCond = _Select(FEXCore::IR::COND_EQ, AndOp, MaskConst, Src, Dest); break; } case COMPARE_OTHER: break; } } StoreResult(GPRClass, Op, SrcCond, -1); } void OpDispatchBuilder::CPUIDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto Res = _CPUID(Src); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), _ExtractElement(Res, 0)); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RBX]), _ExtractElement(Res, 1)); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), _ExtractElement(Res, 2)); _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), _ExtractElement(Res, 3)); } template<bool SHL1Bit> void OpDispatchBuilder::SHLOp(OpcodeArgs) { OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); if (SHL1Bit) { Src = _Constant(1); } else { Src = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); } auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(0x3F)); else Src = _And(Src, _Constant(0x1F)); auto ALUOp = _Lshl(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This isn't correct // GenerateFlags_Shift(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } template<bool SHR1Bit> void OpDispatchBuilder::SHROp(OpcodeArgs) { OrderedNode *Src; auto Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); if (SHR1Bit) { Src = _Constant(1); } else { Src = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); } auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(0x3F)); else Src = _And(Src, _Constant(0x1F)); if (Size != 64) { Dest = _Bfe(Size, 0, Dest); } auto ALUOp = _Lshr(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This isn't correct GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (SHR1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } void OpDispatchBuilder::SHLDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Shift = LoadSource_WithOpSize(GPRClass, Op, Op->Src[1], 1, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Shift = _And(Shift, _Constant(0x3F)); else Shift = _And(Shift, _Constant(0x1F)); auto ShiftRight = _Sub(_Constant(Size), Shift); OrderedNode *Res{}; if (Size == 16) { LogMan::Msg::A("Unsupported Op"); } else { auto Tmp1 = _Lshl(Dest, Shift); auto Tmp2 = _Lshr(Src, ShiftRight); Res = _Or(Tmp1, Tmp2); } StoreResult(GPRClass, Op, Res, -1); // XXX: This isn't correct // GenerateFlags_Shift(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::SHRDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Shift{}; if (Op->OP == 0xAC) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); Shift = _Constant(Op->Src[1].TypeLiteral.Literal); } else Shift = _LoadContext(1, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); auto Size = GetSrcSize(Op) * 8; // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Shift = _And(Shift, _Constant(0x3F)); else Shift = _And(Shift, _Constant(0x1F)); auto ShiftRight = _Neg(Shift); OrderedNode *Res{}; if (Size == 16) { LogMan::Msg::A("Unsupported Op"); } else { auto Tmp1 = _Lshr(Dest, Shift); auto Tmp2 = _Lshl(Src, ShiftRight); Res = _Or(Tmp1, Tmp2); } StoreResult(GPRClass, Op, Res, -1); // XXX: This isn't correct // GenerateFlags_Shift(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } void OpDispatchBuilder::ASHROp(OpcodeArgs) { bool SHR1Bit = false; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 7): case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 7): SHR1Bit = true; break; } #undef OPD OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; if (SHR1Bit) { Src = _Constant(Size, 1); } else { Src = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); } // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(Size, 0x3F)); else Src = _And(Src, _Constant(Size, 0x1F)); auto ALUOp = _Ashr(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This isn't correct GenerateFlags_Logical(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (SHR1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } template<uint32_t SrcIndex> void OpDispatchBuilder::ROROp(OpcodeArgs) { bool Is1Bit = false; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 1): case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 1): Is1Bit = true; break; } #undef OPD OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; if (Is1Bit) { Src = _Constant(Size, 1); } else { Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); } // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(Size, 0x3F)); else Src = _And(Src, _Constant(Size, 0x1F)); auto ALUOp = _Ror(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This is incorrect GenerateFlags_Rotate(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (Is1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } template<uint32_t SrcIndex> void OpDispatchBuilder::ROLOp(OpcodeArgs) { bool Is1Bit = false; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) switch (Op->OP) { case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 0): case OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 0): Is1Bit = true; break; default: break; } #undef OPD OrderedNode *Src; OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op) * 8; if (Is1Bit) { Src = _Constant(Size, 1); } else { Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); } // x86 masks the shift by 0x3F or 0x1F depending on size of op if (Size == 64) Src = _And(Src, _Constant(Size, 0x3F)); else Src = _And(Src, _Constant(Size, 0x1F)); auto ALUOp = _Rol(Dest, Src); StoreResult(GPRClass, Op, ALUOp, -1); // XXX: This is incorrect GenerateFlags_Rotate(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); if (Is1Bit) { SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Bfe(1, Size - 1, Src)); } } template<uint32_t SrcIndex> void OpDispatchBuilder::BTOp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); Result = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Result, BitSelect); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } template<uint32_t SrcIndex> void OpDispatchBuilder::BTROp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); BitMask = _Neg(BitMask); Dest = _And(Dest, BitMask); StoreResult(GPRClass, Op, Dest, -1); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); OrderedNode *Value = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Value, BitSelect); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); BitMask = _Neg(BitMask); Value = _And(Value, BitMask); _StoreMem(GPRClass, Size, MemoryLocation, Value, Size); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } template<uint32_t SrcIndex> void OpDispatchBuilder::BTSOp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Dest = _Or(Dest, BitMask); StoreResult(GPRClass, Op, Dest, -1); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); OrderedNode *Value = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Value, BitSelect); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Value = _Or(Value, BitMask); _StoreMem(GPRClass, Size, MemoryLocation, Value, Size); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } template<uint32_t SrcIndex> void OpDispatchBuilder::BTCOp(OpcodeArgs) { OrderedNode *Result; OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Result = _Lshr(Dest, Src); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Dest = _Xor(Dest, BitMask); StoreResult(GPRClass, Op, Dest, -1); } else { // Load the address to the memory location OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); uint32_t Size = GetSrcSize(Op); uint32_t Mask = Size * 8 - 1; OrderedNode *SizeMask = _Constant(Mask); // Get the bit selection from the src OrderedNode *BitSelect = _And(Src, SizeMask); // Address is provided as bits we want BYTE offsets // Just shift by 3 to get the offset Src = _Lshr(Src, _Constant(3)); // Get the address offset by shifting out the size of the op (To shift out the bit selection) // Then use that to index in to the memory location by size of op // Now add the addresses together and load the memory OrderedNode *MemoryLocation = _Add(Dest, Src); OrderedNode *Value = _LoadMem(GPRClass, Size, MemoryLocation, Size); // Now shift in to the correct bit location Result = _Lshr(Value, BitSelect); OrderedNode *BitMask = _Lshl(_Constant(1), BitSelect); Value = _Xor(Value, BitMask); _StoreMem(GPRClass, Size, MemoryLocation, Value, Size); } SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(Result); } void OpDispatchBuilder::IMUL1SrcOp(OpcodeArgs) { OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto Dest = _Mul(Src1, Src2); StoreResult(GPRClass, Op, Dest, -1); GenerateFlags_MUL(Op, Dest, _MulH(Src1, Src2)); } void OpDispatchBuilder::IMUL2SrcOp(OpcodeArgs) { OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Src2 = LoadSource(GPRClass, Op, Op->Src[1], Op->Flags, -1); auto Dest = _Mul(Src1, Src2); StoreResult(GPRClass, Op, Dest, -1); GenerateFlags_MUL(Op, Dest, _MulH(Src1, Src2)); } void OpDispatchBuilder::IMULOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); if (Size != 8) { Src1 = _Sext(Size * 8, Src1); Src2 = _Sext(Size * 8, Src2); } OrderedNode *Result = _Mul(Src1, Src2); OrderedNode *ResultHigh{}; if (Size == 1) { // Result is stored in AX _StoreContext(GPRClass, 2, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(8, 8, Result); ResultHigh = _Sext(Size * 8, ResultHigh); } else if (Size == 2) { // 16bits stored in AX // 16bits stored in DX _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(16, 16, Result); ResultHigh = _Sext(Size * 8, ResultHigh); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 4) { // 32bits stored in EAX // 32bits stored in EDX // Make sure they get Zext correctly OrderedNode *ResultLow = _Bfe(32, 0, Result); ResultLow = _Zext(Size * 8, ResultLow); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), ResultLow); ResultHigh = _Bfe(32, 32, Result); ResultHigh = _Zext(Size * 8, ResultHigh); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 8) { // 64bits stored in RAX // 64bits stored in RDX ResultHigh = _MulH(Src1, Src2); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } GenerateFlags_MUL(Op, Result, ResultHigh); } void OpDispatchBuilder::MULOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); if (Size != 8) { Src1 = _Zext(Size * 8, Src1); Src2 = _Zext(Size * 8, Src2); } OrderedNode *Result = _UMul(Src1, Src2); OrderedNode *ResultHigh{}; if (Size == 1) { // Result is stored in AX _StoreContext(GPRClass, 2, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(8, 8, Result); } else if (Size == 2) { // 16bits stored in AX // 16bits stored in DX _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); ResultHigh = _Bfe(16, 16, Result); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 4) { // 32bits stored in EAX // 32bits stored in EDX // Make sure they get Zext correctly OrderedNode *ResultLow = _Bfe(32, 0, Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), ResultLow); ResultHigh = _Bfe(32, 32, Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } else if (Size == 8) { // 64bits stored in RAX // 64bits stored in RDX ResultHigh = _UMulH(Src1, Src2); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), Result); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), ResultHigh); } GenerateFlags_UMUL(Op, ResultHigh); } void OpDispatchBuilder::NOTOp(OpcodeArgs) { uint8_t Size = GetSrcSize(Op); OrderedNode *MaskConst{}; if (Size == 8) { MaskConst = _Constant(~0ULL); } else { MaskConst = _Constant((1ULL << (Size * 8)) - 1); } OrderedNode *Src = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Src = _Xor(Src, MaskConst); StoreResult(GPRClass, Op, Src, -1); } void OpDispatchBuilder::XADDOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // If this is a GPR then we can just do an Add and store auto Result = _Add(Dest, Src); StoreResult(GPRClass, Op, Result, -1); // Previous value in dest gets stored in src StoreResult(GPRClass, Op, Op->Src[0], Dest, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_ADD(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); } else { auto Before = _AtomicFetchAdd(Dest, Src, GetSrcSize(Op)); StoreResult(GPRClass, Op, Op->Src[0], Before, -1); } } void OpDispatchBuilder::PopcountOp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _Popcount(Src); StoreResult(GPRClass, Op, Src, -1); } void OpDispatchBuilder::RDTSCOp(OpcodeArgs) { auto Counter = _CycleCounter(); auto CounterLow = _Bfe(32, 0, Counter); auto CounterHigh = _Bfe(32, 32, Counter); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), CounterLow); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), CounterHigh); } void OpDispatchBuilder::INCOp(OpcodeArgs) { LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX), "Can't handle REP on this\n"); if (DestIsLockedMem(Op)) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); auto OneConst = _Constant(1); auto AtomicResult = _AtomicFetchAdd(Dest, OneConst, GetSrcSize(Op)); auto ALUOp = _Add(AtomicResult, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_ADD(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } else { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto OneConst = _Constant(1); auto ALUOp = _Add(Dest, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_ADD(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } } void OpDispatchBuilder::DECOp(OpcodeArgs) { LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX), "Can't handle REP on this\n"); if (DestIsLockedMem(Op)) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); auto OneConst = _Constant(1); auto AtomicResult = _AtomicFetchSub(Dest, OneConst, GetSrcSize(Op)); auto ALUOp = _Sub(AtomicResult, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } else { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto OneConst = _Constant(1); auto ALUOp = _Sub(Dest, OneConst); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, Dest), _Bfe(Size, 0, OneConst)); } } void OpDispatchBuilder::STOSOp(OpcodeArgs) { LogMan::Throw::A(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX, "Can't handle REP not existing on STOS\n"); auto Size = GetSrcSize(Op); // Create all our blocks auto LoopHead = CreateNewCodeBlock(); auto LoopTail = CreateNewCodeBlock(); auto LoopEnd = CreateNewCodeBlock(); // At the time this was written, our RA can't handle accessing nodes across blocks. // So we need to re-load and re-calculate essential values each iteration of the loop. // First thing we need to do is finish this block and jump to the start of the loop. _Jump(LoopHead); SetCurrentCodeBlock(LoopHead); { OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); auto ZeroConst = _Constant(0); // Can we end the block? auto CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, ZeroConst, _Constant(1), ZeroConst); _CondJump(CanLeaveCond, LoopEnd, LoopTail); } SetCurrentCodeBlock(LoopTail); { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); // Store to memory where RDI points _StoreMem(GPRClass, Size, Dest, Src, Size); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); OrderedNode *TailDest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); // Calculate direction. auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); // Offset the pointer TailDest = _Add(TailDest, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), TailDest); // Jump back to the start, we have more work to do _Jump(LoopHead); } // Make sure to start a new block after ending this one SetCurrentCodeBlock(LoopEnd); } void OpDispatchBuilder::MOVSOp(OpcodeArgs) { LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REPNE_PREFIX), "Can't handle REPNE on MOVS\n"); if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX) { auto Size = GetSrcSize(Op); // Create all our blocks auto LoopHead = CreateNewCodeBlock(); auto LoopTail = CreateNewCodeBlock(); auto LoopEnd = CreateNewCodeBlock(); // At the time this was written, our RA can't handle accessing nodes across blocks. // So we need to re-load and re-calculate essential values each iteration of the loop. // First thing we need to do is finish this block and jump to the start of the loop. _Jump(LoopHead); SetCurrentCodeBlock(LoopHead); { OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); auto ZeroConst = _Constant(0); // Can we end the block? auto CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, ZeroConst, _Constant(1), ZeroConst); _CondJump(CanLeaveCond, LoopEnd, LoopTail); } SetCurrentCodeBlock(LoopTail); { OrderedNode *Src = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); OrderedNode *Dest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); Src = _LoadMem(GPRClass, Size, Src, Size); // Store to memory where RDI points _StoreMem(GPRClass, Size, Dest, Src, Size); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); // Calculate direction. auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); // Offset the pointer OrderedNode *TailSrc = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); OrderedNode *TailDest = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); TailSrc = _Add(TailSrc, PtrDir); TailDest = _Add(TailDest, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), TailSrc); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), TailDest); // Jump back to the start, we have more work to do _Jump(LoopHead); } // Make sure to start a new block after ending this one SetCurrentCodeBlock(LoopEnd); } else { auto Size = GetSrcSize(Op); OrderedNode *RSI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); OrderedNode *RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); auto Src = _LoadMem(GPRClass, Size, RSI, Size); // Store to memory where RDI points _StoreMem(GPRClass, Size, RDI, Src, Size); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); // Calculate direction. auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); RSI = _Add(RSI, PtrDir); RDI = _Add(RDI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), RSI); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), RDI); } } void OpDispatchBuilder::CMPSOp(OpcodeArgs) { LogMan::Throw::A(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REP_PREFIX, "Can't only handle REP\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REPNE_PREFIX), "Can't only handle REP\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_ADDRESS_SIZE), "Can't handle adddress size\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX), "Can't handle FS\n"); LogMan::Throw::A(!(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX), "Can't handle GS\n"); auto Size = GetSrcSize(Op); auto JumpStart = _Jump(); // Make sure to start a new block after ending this one auto LoopStart = CreateNewCodeBlock(); SetJumpTarget(JumpStart, LoopStart); SetCurrentCodeBlock(LoopStart); OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Can we end the block? OrderedNode *CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, _Constant(0), _Constant(1), _Constant(0)); auto CondJump = _CondJump(CanLeaveCond); IRPair<IROp_CondJump> InternalCondJump; auto LoopTail = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, LoopTail); SetCurrentCodeBlock(LoopTail); // Working loop { OrderedNode *Dest_RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); OrderedNode *Dest_RSI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), GPRClass); auto Src1 = _LoadMem(GPRClass, Size, Dest_RDI, Size); auto Src2 = _LoadMem(GPRClass, Size, Dest_RSI, Size); auto ALUOp = _Sub(Src1, Src2); GenerateFlags_SUB(Op, _Bfe(Size * 8, 0, ALUOp), _Bfe(Size * 8, 0, Src1), _Bfe(Size * 8, 0, Src2)); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), _Constant(Size), _Constant(-Size)); // Offset the pointer Dest_RDI = _Add(Dest_RDI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), Dest_RDI); // Offset second pointer Dest_RSI = _Add(Dest_RSI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RSI]), Dest_RSI); OrderedNode *ZF = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); InternalCondJump = _CondJump(ZF); // Jump back to the start if we have more work to do SetTrueJumpTarget(InternalCondJump, LoopStart); } // Make sure to start a new block after ending this one auto LoopEnd = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, LoopEnd); SetFalseJumpTarget(InternalCondJump, LoopEnd); SetCurrentCodeBlock(LoopEnd); } void OpDispatchBuilder::SCASOp(OpcodeArgs) { LogMan::Throw::A(Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_REPNE_PREFIX, "Can only handle REPNE\n"); auto Size = GetSrcSize(Op); auto JumpStart = _Jump(); // Make sure to start a new block after ending this one auto LoopStart = CreateNewCodeBlock(); SetJumpTarget(JumpStart, LoopStart); SetCurrentCodeBlock(LoopStart); auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); OrderedNode *Counter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); // Can we end the block? OrderedNode *CanLeaveCond = _Select(FEXCore::IR::COND_EQ, Counter, ZeroConst, OneConst, ZeroConst); // We leave if RCX = 0 auto CondJump = _CondJump(CanLeaveCond); IRPair<IROp_CondJump> InternalCondJump; auto LoopTail = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, LoopTail); SetCurrentCodeBlock(LoopTail); // Working loop { OrderedNode *Dest_RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); auto Src1 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); auto Src2 = _LoadMem(GPRClass, Size, Dest_RDI, Size); auto ALUOp = _Sub(Src1, Src2); GenerateFlags_SUB(Op, ALUOp, Src1, Src2); OrderedNode *TailCounter = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), GPRClass); OrderedNode *TailDest_RDI = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), GPRClass); // Decrement counter TailCounter = _Sub(TailCounter, _Constant(1)); // Store the counter so we don't have to deal with PHI here _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RCX]), TailCounter); auto SizeConst = _Constant(Size); auto NegSizeConst = _Constant(-Size); auto DF = GetRFLAG(FEXCore::X86State::RFLAG_DF_LOC); auto PtrDir = _Select(FEXCore::IR::COND_EQ, DF, _Constant(0), SizeConst, NegSizeConst); // Offset the pointer TailDest_RDI = _Add(TailDest_RDI, PtrDir); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDI]), TailDest_RDI); OrderedNode *ZF = GetRFLAG(FEXCore::X86State::RFLAG_ZF_LOC); InternalCondJump = _CondJump(ZF); // Jump back to the start if we have more work to do SetFalseJumpTarget(InternalCondJump, LoopStart); } // Make sure to start a new block after ending this one auto LoopEnd = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, LoopEnd); SetTrueJumpTarget(InternalCondJump, LoopEnd); SetCurrentCodeBlock(LoopEnd); } void OpDispatchBuilder::BSWAPOp(OpcodeArgs) { OrderedNode *Dest; if (GetSrcSize(Op) == 2) { // BSWAP of 16bit is undef. ZEN+ causes the lower 16bits to get zero'd Dest = _Constant(0); } else { Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); Dest = _Rev(Dest); } StoreResult(GPRClass, Op, Dest, -1); } void OpDispatchBuilder::NEGOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ZeroConst = _Constant(0); auto ALUOp = _Sub(ZeroConst, Dest); StoreResult(GPRClass, Op, ALUOp, -1); auto Size = GetSrcSize(Op) * 8; GenerateFlags_SUB(Op, _Bfe(Size, 0, ALUOp), _Bfe(Size, 0, ZeroConst), _Bfe(Size, 0, Dest)); } void OpDispatchBuilder::DIVOp(OpcodeArgs) { // This loads the divisor OrderedNode *Divisor = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op); if (Size == 1) { OrderedNode *Src1 = _LoadContext(2, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); auto UDivOp = _UDiv(Src1, Divisor); auto URemOp = _URem(Src1, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, URemOp); } else if (Size == 2) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LUDiv(Src1, Src2, Divisor); auto URemOp = _LURem(Src1, Src2, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } else if (Size == 4) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LUDiv(Src1, Src2, Divisor); auto URemOp = _LURem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), _Zext(32, UDivOp)); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), _Zext(32, URemOp)); } else if (Size == 8) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LUDiv(Src1, Src2, Divisor); auto URemOp = _LURem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } } void OpDispatchBuilder::IDIVOp(OpcodeArgs) { // This loads the divisor OrderedNode *Divisor = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op); if (Size == 1) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); auto UDivOp = _Div(Src1, Divisor); auto URemOp = _Rem(Src1, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]) + 1, URemOp); } else if (Size == 2) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LDiv(Src1, Src2, Divisor); auto URemOp = _LRem(Src1, Src2, Divisor); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } else if (Size == 4) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LDiv(Src1, Src2, Divisor); auto URemOp = _LRem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), _Zext(32, UDivOp)); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), _Zext(32, URemOp)); } else if (Size == 8) { OrderedNode *Src1 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); OrderedNode *Src2 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), GPRClass); auto UDivOp = _LDiv(Src1, Src2, Divisor); auto URemOp = _LRem(Src1, Src2, Divisor); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), UDivOp); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RDX]), URemOp); } } void OpDispatchBuilder::BSFOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Find the LSB of this source auto Result = _FindLSB(Src); auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); // If Src was zero then the destination doesn't get modified auto SelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, Dest, Result); // ZF is set to 1 if the source was zero auto ZFSelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, OneConst, ZeroConst); StoreResult(GPRClass, Op, SelectOp, -1); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFSelectOp); } void OpDispatchBuilder::BSROp(OpcodeArgs) { OrderedNode *Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // Find the MSB of this source auto Result = _FindMSB(Src); auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); // If Src was zero then the destination doesn't get modified auto SelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, Dest, Result); // ZF is set to 1 if the source was zero auto ZFSelectOp = _Select(FEXCore::IR::COND_EQ, Src, ZeroConst, OneConst, ZeroConst); StoreResult(GPRClass, Op, SelectOp, -1); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFSelectOp); } void OpDispatchBuilder::MOVAPSOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); StoreResult(FPRClass, Op, Src, -1); } void OpDispatchBuilder::MOVUPSOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 1); StoreResult(FPRClass, Op, Src, 1); } void OpDispatchBuilder::MOVLHPSOp(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, 8); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 8); auto Result = _VInsElement(16, 8, 1, 0, Dest, Src); StoreResult(FPRClass, Op, Result, 8); } void OpDispatchBuilder::MOVHPDOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // This instruction is a bit special that if the destination is a register then it'll ZEXT the 64bit source to 128bit if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // If the destination is a GPR then the source is memory // xmm1[127:64] = src OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, 16, Op->Flags, -1); auto Result = _VInsElement(16, 8, 1, 0, Dest, Src); StoreResult(FPRClass, Op, Result, -1); } else { // In this case memory is the destination and the high bits of the XMM are source // Mem64 = xmm1[127:64] auto Result = _VExtractToGPR(16, 8, Src, 1); StoreResult(GPRClass, Op, Result, -1); } } void OpDispatchBuilder::MOVLPOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 8); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, 8, 16); auto Result = _VInsElement(16, 8, 0, 0, Dest, Src); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Result, 8, 16); } else { StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Src, 8, 8); } } void OpDispatchBuilder::MOVSSOp(OpcodeArgs) { if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // MOVSS xmm1, xmm2 OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, 16, Op->Flags, -1); OrderedNode *Src = LoadSource_WithOpSize(FPRClass, Op, Op->Src[0], 4, Op->Flags, -1); auto Result = _VInsElement(16, 4, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Result, -1); } else if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // MOVSS xmm1, mem32 // xmm1[127:0] <- zext(mem32) OrderedNode *Src = LoadSource_WithOpSize(FPRClass, Op, Op->Src[0], 4, Op->Flags, -1); Src = _Zext(32, Src); Src = _Zext(64, Src); StoreResult(FPRClass, Op, Src, -1); } else { // MOVSS mem32, xmm1 OrderedNode *Src = LoadSource_WithOpSize(FPRClass, Op, Op->Src[0], 4, Op->Flags, -1); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Src, 4, -1); } } void OpDispatchBuilder::MOVSDOp(OpcodeArgs) { if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Src[0].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // xmm1[63:0] <- xmm2[63:0] OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto Result = _VInsElement(16, 8, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Result, -1); } else if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // xmm1[127:0] <- zext(mem64) OrderedNode *Src = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], 8, Op->Flags, -1); Src = _Zext(64, Src); StoreResult(FPRClass, Op, Src, -1); } else { // In this case memory is the destination and the low bits of the XMM are source // Mem64 = xmm2[63:0] OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, Src, 8, -1); } } template<size_t ElementSize> void OpDispatchBuilder::PADDQOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VAdd(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSUBQOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VSub(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PMINUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VUMin(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PMAXUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VUMax(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } void OpDispatchBuilder::PMINSWOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VSMin(Size, 2, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<FEXCore::IR::IROps IROp, size_t ElementSize> void OpDispatchBuilder::VectorALUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VAdd(Size, ElementSize, Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; StoreResult(FPRClass, Op, ALUOp, -1); } template<FEXCore::IR::IROps IROp, size_t ElementSize> void OpDispatchBuilder::VectorScalarALUOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // If OpSize == ElementSize then it only does the lower scalar op auto ALUOp = _VAdd(ElementSize, ElementSize, Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; // Insert the lower bits auto Result = _VInsElement(Size, ElementSize, 0, 0, Dest, ALUOp); StoreResult(FPRClass, Op, Result, -1); } template<FEXCore::IR::IROps IROp, size_t ElementSize, bool Scalar> void OpDispatchBuilder::VectorUnaryOp(OpcodeArgs) { auto Size = GetSrcSize(Op); if (Scalar) { Size = ElementSize; } OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _VFSqrt(Size, ElementSize, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; if (Scalar) { // Insert the lower bits auto Result = _VInsElement(GetSrcSize(Op), ElementSize, 0, 0, Dest, ALUOp); StoreResult(FPRClass, Op, Result, -1); } else { StoreResult(FPRClass, Op, ALUOp, -1); } } void OpDispatchBuilder::MOVQOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // This instruction is a bit special that if the destination is a register then it'll ZEXT the 64bit source to 128bit if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { _StoreContext(FPRClass, 8, offsetof(FEXCore::Core::CPUState, xmm[Op->Dest.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][0]), Src); auto Const = _Constant(0); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, xmm[Op->Dest.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][1]), Const); } else { // This is simple, just store the result StoreResult(FPRClass, Op, Src, -1); } } template<size_t ElementSize> void OpDispatchBuilder::MOVMSKOp(OpcodeArgs) { auto Size = GetSrcSize(Op); uint8_t NumElements = Size / ElementSize; OrderedNode *CurrentVal = _Constant(0); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); for (unsigned i = 0; i < NumElements; ++i) { // Extract the top bit of the element OrderedNode *Tmp = _Bfe(1, ((i + 1) * (ElementSize * 8)) - 1, Src); // Shift it to the correct location Tmp = _Lshl(Tmp, _Constant(i)); // Or it with the current value CurrentVal = _Or(CurrentVal, Tmp); } StoreResult(GPRClass, Op, CurrentVal, -1); } template<size_t ElementSize> void OpDispatchBuilder::PUNPCKLOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto ALUOp = _VZip(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PUNPCKHOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); auto ALUOp = _VZip2(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize, bool Low> void OpDispatchBuilder::PSHUFDOp(OpcodeArgs) { LogMan::Throw::A(ElementSize != 0, "What. No element size?"); auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t Shuffle = Op->Src[1].TypeLiteral.Literal; uint8_t NumElements = Size / ElementSize; // 16bit is a bit special of a shuffle // It only ever operates on half the register // Then there is a high and low variant of the instruction to determine where the destination goes // and where the source comes from if (ElementSize == 2) { NumElements /= 2; } uint8_t BaseElement = Low ? 0 : NumElements; auto Dest = Src; for (uint8_t Element = 0; Element < NumElements; ++Element) { Dest = _VInsElement(Size, ElementSize, BaseElement + Element, BaseElement + (Shuffle & 0b11), Dest, Src); Shuffle >>= 2; } StoreResult(FPRClass, Op, Dest, -1); } template<size_t ElementSize> void OpDispatchBuilder::SHUFOp(OpcodeArgs) { LogMan::Throw::A(ElementSize != 0, "What. No element size?"); auto Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t Shuffle = Op->Src[1].TypeLiteral.Literal; uint8_t NumElements = Size / ElementSize; auto Dest = Src1; std::array<OrderedNode*, 4> Srcs = { }; for (int i = 0; i < (NumElements >> 1); ++i) { Srcs[i] = Src1; } for (int i = (NumElements >> 1); i < NumElements; ++i) { Srcs[i] = Src2; } // 32bit: // [31:0] = Src1[Selection] // [63:32] = Src1[Selection] // [95:64] = Src2[Selection] // [127:96] = Src2[Selection] // 64bit: // [63:0] = Src1[Selection] // [127:64] = Src2[Selection] uint8_t SelectionMask = NumElements - 1; uint8_t ShiftAmount = __builtin_popcount(SelectionMask); for (uint8_t Element = 0; Element < NumElements; ++Element) { Dest = _VInsElement(Size, ElementSize, Element, Shuffle & SelectionMask, Dest, Srcs[Element]); Shuffle >>= ShiftAmount; } StoreResult(FPRClass, Op, Dest, -1); } void OpDispatchBuilder::ANDNOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); // Dest = ~Src1 & Src2 Src1 = _VNot(Size, Size, Src1); auto Dest = _VAnd(Size, Size, Src1, Src2); StoreResult(FPRClass, Op, Dest, -1); } template<size_t ElementSize> void OpDispatchBuilder::PINSROp(OpcodeArgs) { auto Size = GetDstSize(Op); OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, GetDstSize(Op), Op->Flags, -1); LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Index = Op->Src[1].TypeLiteral.Literal; // This maps 1:1 to an AArch64 NEON Op auto ALUOp = _VInsGPR(Size, ElementSize, Dest, Src, Index); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PCMPEQOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); // This maps 1:1 to an AArch64 NEON Op auto ALUOp = _VCMPEQ(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } template<size_t ElementSize> void OpDispatchBuilder::PCMPGTOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); // This maps 1:1 to an AArch64 NEON Op auto ALUOp = _VCMPGT(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, ALUOp, -1); } void OpDispatchBuilder::MOVDOp(OpcodeArgs) { if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR && Op->Dest.TypeGPR.GPR >= FEXCore::X86State::REG_XMM_0) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); // When destination is XMM then it is zext to 128bit uint64_t SrcSize = GetSrcSize(Op) * 8; while (SrcSize != 128) { Src = _Zext(SrcSize, Src); SrcSize *= 2; } StoreResult(FPRClass, Op, Op->Dest, Src, -1); } else { // Destination is GPR or mem // Extract from XMM first uint8_t ElementSize = 4; if (Op->Flags & X86Tables::DecodeFlags::FLAG_REX_WIDENING) ElementSize = 8; OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0],Op->Flags, -1); Src = _VExtractToGPR(GetSrcSize(Op), ElementSize, Src, 0); StoreResult(GPRClass, Op, Op->Dest, Src, -1); } } void OpDispatchBuilder::CMPXCHGOp(OpcodeArgs) { // CMPXCHG ModRM, reg, {RAX} // MemData = *ModRM.dest // if (RAX == MemData) // modRM.dest = reg; // ZF = 1 // else // ZF = 0 // RAX = MemData // // CASL Xs, Xt, Xn // MemData = *Xn // if (MemData == Xs) // *Xn = Xt // Xs = MemData auto Size = GetSrcSize(Op); // If this is a memory location then we want the pointer to it OrderedNode *Src1 = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX) { Src1 = _Add(Src1, _LoadContext(8, offsetof(FEXCore::Core::CPUState, fs), GPRClass)); } else if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX) { Src1 = _Add(Src1, _LoadContext(8, offsetof(FEXCore::Core::CPUState, gs), GPRClass)); } // This is our source register OrderedNode *Src2 = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Src3 = _LoadContext(Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), GPRClass); // 0x80014000 // 0x80064000 // 0x80064000 auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); if (Op->Dest.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { // If our destination is a GPR then this behaves differently // RAX = RAX == Op1 ? RAX : Op1 // AKA if they match then don't touch RAX value // Otherwise set it to the rm operand OrderedNode *RAXResult = _Select(FEXCore::IR::COND_EQ, Src1, Src3, Src3, Src1); // Op1 = RAX == Op1 ? Op2 : Op1 // If they match then set the rm operand to the input // else don't set the rm operand OrderedNode *DestResult = _Select(FEXCore::IR::COND_EQ, Src1, Src3, Src2, Src1); // ZF = RAX == Op1 ? 1 : 0 // Result of compare OrderedNode *ZFResult = _Select(FEXCore::IR::COND_EQ, Src1, Src3, OneConst, ZeroConst); // Set ZF SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFResult); if (Size < 4) { _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), RAXResult); } else { if (Size == 4) { RAXResult = _Zext(32, RAXResult); } _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), RAXResult); } // Store in to GPR Dest // Have to make sure this is after the result store in RAX for when Dest == RAX StoreResult(GPRClass, Op, DestResult, -1); } else { // DataSrc = *Src1 // if (DataSrc == Src3) { *Src1 == Src2; } Src2 = DataSrc // This will write to memory! Careful! // Third operand must be a calculated guest memory address OrderedNode *CASResult = _CAS(Src3, Src2, Src1); // If our CASResult(OldMem value) is equal to our comparison // Then we managed to set the memory OrderedNode *ZFResult = _Select(FEXCore::IR::COND_EQ, CASResult, Src3, OneConst, ZeroConst); // RAX gets the result of the CAS op if (Size < 4) { _StoreContext(GPRClass, Size, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), CASResult); } else { if (Size == 4) { CASResult = _Zext(32, CASResult); } _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, gregs[FEXCore::X86State::REG_RAX]), CASResult); } // Set ZF SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(ZFResult); } } OpDispatchBuilder::IRPair<IROp_CodeBlock> OpDispatchBuilder::CreateNewCodeBlock() { auto OldCursor = GetWriteCursor(); SetWriteCursor(CodeBlocks.back()); auto CodeNode = CreateCodeNode(); auto NewNode = _Dummy(); SetCodeNodeBegin(CodeNode, NewNode); auto EndBlock = _EndBlock(0); SetCodeNodeLast(CodeNode, EndBlock); if (CurrentCodeBlock) { LinkCodeBlocks(CurrentCodeBlock, CodeNode); } SetWriteCursor(OldCursor); return CodeNode; } void OpDispatchBuilder::SetCurrentCodeBlock(OrderedNode *Node) { CurrentCodeBlock = Node; LogMan::Throw::A(Node->Op(Data.Begin())->Op == OP_CODEBLOCK, "Node wasn't codeblock. It was '%s'", std::string(IR::GetName(Node->Op(Data.Begin())->Op)).c_str()); SetWriteCursor(Node->Op(Data.Begin())->CW<IROp_CodeBlock>()->Begin.GetNode(ListData.Begin())); } void OpDispatchBuilder::CreateJumpBlocks(std::vector<FEXCore::Frontend::Decoder::DecodedBlocks> const *Blocks) { OrderedNode *PrevCodeBlock{}; for (auto &Target : *Blocks) { auto CodeNode = CreateCodeNode(); auto NewNode = _Dummy(); SetCodeNodeBegin(CodeNode, NewNode); auto EndBlock = _EndBlock(0); SetCodeNodeLast(CodeNode, EndBlock); JumpTargets.try_emplace(Target.Entry, JumpTargetInfo{CodeNode, false}); if (PrevCodeBlock) { LinkCodeBlocks(PrevCodeBlock, CodeNode); } PrevCodeBlock = CodeNode; } } void OpDispatchBuilder::BeginFunction(uint64_t RIP, std::vector<FEXCore::Frontend::Decoder::DecodedBlocks> const *Blocks) { Entry = RIP; auto IRHeader = _IRHeader(InvalidNode, RIP, 0); CreateJumpBlocks(Blocks); auto Block = GetNewJumpBlock(RIP); SetCurrentCodeBlock(Block); IRHeader.first->Blocks = Block->Wrapped(ListData.Begin()); } void OpDispatchBuilder::Finalize() { // Node 0 is invalid node OrderedNode *RealNode = reinterpret_cast<OrderedNode*>(GetNode(1)); FEXCore::IR::IROp_Header *IROp = RealNode->Op(Data.Begin()); LogMan::Throw::A(IROp->Op == OP_IRHEADER, "First op in function must be our header"); // Let's walk the jump blocks and see if we have handled every block target for (auto &Handler : JumpTargets) { if (Handler.second.HaveEmitted) continue; // We haven't emitted. Dump out to the dispatcher SetCurrentCodeBlock(Handler.second.BlockEntry); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), _Constant(Handler.first)); _ExitFunction(); } CodeBlocks.clear(); } void OpDispatchBuilder::ExitFunction() { _ExitFunction(); } uint8_t OpDispatchBuilder::GetDstSize(FEXCore::X86Tables::DecodedOp Op) { constexpr std::array<uint8_t, 8> Sizes = { 0, // Invalid DEF 1, 2, 4, 8, 16, 32, 0, // Invalid DEF }; uint32_t DstSizeFlag = FEXCore::X86Tables::DecodeFlags::GetSizeDstFlags(Op->Flags); uint8_t Size = Sizes[DstSizeFlag]; LogMan::Throw::A(Size != 0, "Invalid destination size for op"); return Size; } uint8_t OpDispatchBuilder::GetSrcSize(FEXCore::X86Tables::DecodedOp Op) { constexpr std::array<uint8_t, 8> Sizes = { 0, // Invalid DEF 1, 2, 4, 8, 16, 32, 0, // Invalid DEF }; uint32_t SrcSizeFlag = FEXCore::X86Tables::DecodeFlags::GetSizeSrcFlags(Op->Flags); uint8_t Size = Sizes[SrcSizeFlag]; LogMan::Throw::A(Size != 0, "Invalid destination size for op"); return Size; } OrderedNode *OpDispatchBuilder::LoadSource_WithOpSize(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp const& Op, FEXCore::X86Tables::DecodedOperand const& Operand, uint8_t OpSize, uint32_t Flags, int8_t Align, bool LoadData, bool ForceLoad) { LogMan::Throw::A(Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB , "Unsupported Src type"); OrderedNode *Src {nullptr}; bool LoadableType = false; if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL) { Src = _Constant(Operand.TypeLiteral.Size * 8, Operand.TypeLiteral.Literal); } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { if (Operand.TypeGPR.GPR >= FEXCore::X86State::REG_XMM_0) { Src = _LoadContext(OpSize, offsetof(FEXCore::Core::CPUState, xmm[Operand.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][Operand.TypeGPR.HighBits ? 1 : 0]), FPRClass); } else { Src = _LoadContext(OpSize, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]) + (Operand.TypeGPR.HighBits ? 1 : 0), GPRClass); } } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT) { Src = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]), GPRClass); LoadableType = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPRIndirect.GPR]), GPRClass); auto Constant = _Constant(Operand.TypeGPRIndirect.Displacement); Src = _Add(GPR, Constant); LoadableType = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE) { Src = _Constant(Operand.TypeRIPLiteral.Literal + Op->PC + Op->InstSize); LoadableType = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB) { OrderedNode *Tmp {}; if (Operand.TypeSIB.Index != FEXCore::X86State::REG_INVALID) { Tmp = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Index]), GPRClass); if (Operand.TypeSIB.Scale != 1) { auto Constant = _Constant(Operand.TypeSIB.Scale); Tmp = _Mul(Tmp, Constant); } } if (Operand.TypeSIB.Base != FEXCore::X86State::REG_INVALID) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Base]), GPRClass); if (Tmp != nullptr) { Tmp = _Add(Tmp, GPR); } else { Tmp = GPR; } } if (Operand.TypeSIB.Offset) { if (Tmp != nullptr) { Src = _Add(Tmp, _Constant(Operand.TypeSIB.Offset)); } else { Src = _Constant(Operand.TypeSIB.Offset); } } else { if (Tmp != nullptr) { Src = Tmp; } else { Src = _Constant(0); } } LoadableType = true; } else { LogMan::Msg::A("Unknown Src Type: %d\n", Operand.TypeNone.Type); } if ((LoadableType && LoadData) || ForceLoad) { if (Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX) { Src = _Add(Src, _LoadContext(8, offsetof(FEXCore::Core::CPUState, fs), GPRClass)); } else if (Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX) { Src = _Add(Src, _LoadContext(8, offsetof(FEXCore::Core::CPUState, gs), GPRClass)); } Src = _LoadMem(Class, OpSize, Src, Align == -1 ? OpSize : Align); } return Src; } OrderedNode *OpDispatchBuilder::LoadSource(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp const& Op, FEXCore::X86Tables::DecodedOperand const& Operand, uint32_t Flags, int8_t Align, bool LoadData, bool ForceLoad) { uint8_t OpSize = GetSrcSize(Op); return LoadSource_WithOpSize(Class, Op, Operand, OpSize, Flags, Align, LoadData, ForceLoad); } void OpDispatchBuilder::StoreResult_WithOpSize(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp Op, FEXCore::X86Tables::DecodedOperand const& Operand, OrderedNode *const Src, uint8_t OpSize, int8_t Align) { LogMan::Throw::A((Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE || Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB ), "Unsupported Dest type"); // 8Bit and 16bit destination types store their result without effecting the upper bits // 32bit ops ZEXT the result to 64bit OrderedNode *MemStoreDst {nullptr}; bool MemStore = false; if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL) { MemStoreDst = _Constant(Operand.TypeLiteral.Size * 8, Operand.TypeLiteral.Literal); MemStore = true; // Literals are ONLY hardcoded memory destinations } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR) { if (Operand.TypeGPR.GPR >= FEXCore::X86State::REG_XMM_0) { _StoreContext(Src, OpSize, offsetof(FEXCore::Core::CPUState, xmm[Operand.TypeGPR.GPR - FEXCore::X86State::REG_XMM_0][Operand.TypeGPR.HighBits ? 1 : 0]), Class); } else { if (OpSize == 4) { LogMan::Throw::A(!Operand.TypeGPR.HighBits, "Can't handle 32bit store to high 8bit register"); auto ZextOp = _Zext(Src, 32); _StoreContext(ZextOp, 8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]), Class); } else { _StoreContext(Src, std::min(static_cast<uint8_t>(8), OpSize), offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]) + (Operand.TypeGPR.HighBits ? 1 : 0), Class); } } } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_DIRECT) { MemStoreDst = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPR.GPR]), GPRClass); MemStore = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_GPR_INDIRECT) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeGPRIndirect.GPR]), GPRClass); auto Constant = _Constant(Operand.TypeGPRIndirect.Displacement); MemStoreDst = _Add(GPR, Constant); MemStore = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_RIP_RELATIVE) { MemStoreDst = _Constant(Operand.TypeRIPLiteral.Literal + Op->PC + Op->InstSize); MemStore = true; } else if (Operand.TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_SIB) { OrderedNode *Tmp {}; if (Operand.TypeSIB.Index != FEXCore::X86State::REG_INVALID) { Tmp = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Index]), GPRClass); if (Operand.TypeSIB.Scale != 1) { auto Constant = _Constant(Operand.TypeSIB.Scale); Tmp = _Mul(Tmp, Constant); } } if (Operand.TypeSIB.Base != FEXCore::X86State::REG_INVALID) { auto GPR = _LoadContext(8, offsetof(FEXCore::Core::CPUState, gregs[Operand.TypeSIB.Base]), GPRClass); if (Tmp != nullptr) { Tmp = _Add(Tmp, GPR); } else { Tmp = GPR; } } if (Operand.TypeSIB.Offset) { if (Tmp != nullptr) { MemStoreDst = _Add(Tmp, _Constant(Operand.TypeSIB.Offset)); } else { MemStoreDst = _Constant(Operand.TypeSIB.Offset); } } else { if (Tmp != nullptr) { MemStoreDst = Tmp; } else { MemStoreDst = _Constant(0); } } MemStore = true; } if (MemStore) { if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_FS_PREFIX) { MemStoreDst = _Add(MemStoreDst, _LoadContext(8, offsetof(FEXCore::Core::CPUState, fs), GPRClass)); } else if (Op->Flags & FEXCore::X86Tables::DecodeFlags::FLAG_GS_PREFIX) { MemStoreDst = _Add(MemStoreDst, _LoadContext(8, offsetof(FEXCore::Core::CPUState, gs), GPRClass)); } if (OpSize == 10) { // For X87 extended doubles, split before storing _StoreMem(FPRClass, 8, MemStoreDst, Src, Align); auto Upper = _VExtractToGPR(16, 8, Src, 1); auto DestAddr = _Add(MemStoreDst, _Constant(8)); _StoreMem(GPRClass, 2, DestAddr, Upper, std::min<uint8_t>(Align, 8)); } else { _StoreMem(Class, OpSize, MemStoreDst, Src, Align == -1 ? OpSize : Align); } } } void OpDispatchBuilder::StoreResult(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp Op, FEXCore::X86Tables::DecodedOperand const& Operand, OrderedNode *const Src, int8_t Align) { StoreResult_WithOpSize(Class, Op, Operand, Src, GetDstSize(Op), Align); } void OpDispatchBuilder::StoreResult(FEXCore::IR::RegisterClassType Class, FEXCore::X86Tables::DecodedOp Op, OrderedNode *const Src, int8_t Align) { StoreResult(Class, Op, Op->Dest, Src, Align); } OpDispatchBuilder::OpDispatchBuilder() : Data {8 * 1024 * 1024} , ListData {8 * 1024 * 1024} { ResetWorkingList(); } void OpDispatchBuilder::ResetWorkingList() { Data.Reset(); ListData.Reset(); CodeBlocks.clear(); JumpTargets.clear(); BlockSetRIP = false; CurrentWriteCursor = nullptr; // This is necessary since we do "null" pointer checks InvalidNode = reinterpret_cast<OrderedNode*>(ListData.Allocate(sizeof(OrderedNode))); DecodeFailure = false; ShouldDump = false; CurrentCodeBlock = nullptr; } template<unsigned BitOffset> void OpDispatchBuilder::SetRFLAG(OrderedNode *Value) { _StoreFlag(Value, BitOffset); } void OpDispatchBuilder::SetRFLAG(OrderedNode *Value, unsigned BitOffset) { _StoreFlag(Value, BitOffset); } OrderedNode *OpDispatchBuilder::GetRFLAG(unsigned BitOffset) { return _LoadFlag(BitOffset); } constexpr std::array<uint32_t, 17> FlagOffsets = { FEXCore::X86State::RFLAG_CF_LOC, FEXCore::X86State::RFLAG_PF_LOC, FEXCore::X86State::RFLAG_AF_LOC, FEXCore::X86State::RFLAG_ZF_LOC, FEXCore::X86State::RFLAG_SF_LOC, FEXCore::X86State::RFLAG_TF_LOC, FEXCore::X86State::RFLAG_IF_LOC, FEXCore::X86State::RFLAG_DF_LOC, FEXCore::X86State::RFLAG_OF_LOC, FEXCore::X86State::RFLAG_IOPL_LOC, FEXCore::X86State::RFLAG_NT_LOC, FEXCore::X86State::RFLAG_RF_LOC, FEXCore::X86State::RFLAG_VM_LOC, FEXCore::X86State::RFLAG_AC_LOC, FEXCore::X86State::RFLAG_VIF_LOC, FEXCore::X86State::RFLAG_VIP_LOC, FEXCore::X86State::RFLAG_ID_LOC, }; void OpDispatchBuilder::SetPackedRFLAG(bool Lower8, OrderedNode *Src) { uint8_t NumFlags = FlagOffsets.size(); if (Lower8) { NumFlags = 5; } auto OneConst = _Constant(1); for (int i = 0; i < NumFlags; ++i) { auto Tmp = _And(_Lshr(Src, _Constant(FlagOffsets[i])), OneConst); SetRFLAG(Tmp, FlagOffsets[i]); } } OrderedNode *OpDispatchBuilder::GetPackedRFLAG(bool Lower8) { OrderedNode *Original = _Constant(2); uint8_t NumFlags = FlagOffsets.size(); if (Lower8) { NumFlags = 5; } for (int i = 0; i < NumFlags; ++i) { OrderedNode *Flag = _LoadFlag(FlagOffsets[i]); Flag = _Zext(32, Flag); Flag = _Lshl(Flag, _Constant(FlagOffsets[i])); Original = _Or(Original, Flag); } return Original; } void OpDispatchBuilder::GenerateFlags_ADC(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2, OrderedNode *CF) { auto Size = GetSrcSize(Op) * 8; // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto PopCountOp = _Popcount(_And(Res, _Constant(0xFF))); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto Dst8 = _Bfe(Size, 0, Res); auto SelectOp = _Select(FEXCore::IR::COND_EQ, Dst8, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF // Unsigned { auto Dst8 = _Bfe(Size, 0, Res); auto Src8 = _Bfe(Size, 0, Src2); auto SelectOpLT = _Select(FEXCore::IR::COND_ULT, Dst8, Src8, _Constant(1), _Constant(0)); auto SelectOpLE = _Select(FEXCore::IR::COND_ULE, Dst8, Src8, _Constant(1), _Constant(0)); auto SelectCF = _Select(FEXCore::IR::COND_EQ, CF, _Constant(1), SelectOpLE, SelectOpLT); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectCF); } // OF // Signed { auto NegOne = _Constant(~0ULL); auto XorOp1 = _Xor(_Xor(Src1, Src2), NegOne); auto XorOp2 = _Xor(Res, Src1); OrderedNode *AndOp1 = _And(XorOp1, XorOp2); switch (Size) { case 8: AndOp1 = _Bfe(1, 7, AndOp1); break; case 16: AndOp1 = _Bfe(1, 15, AndOp1); break; case 32: AndOp1 = _Bfe(1, 31, AndOp1); break; case 64: AndOp1 = _Bfe(1, 63, AndOp1); break; default: LogMan::Msg::A("Unknown BFESize: %d", Size); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(AndOp1); } } void OpDispatchBuilder::GenerateFlags_SBB(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2, OrderedNode *CF) { // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto PopCountOp = _Popcount(_And(Res, _Constant(0xFF))); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF // Unsigned { auto Dst8 = _Bfe(GetSrcSize(Op) * 8, 0, Res); auto Src8_1 = _Bfe(GetSrcSize(Op) * 8, 0, Src1); auto SelectOpLT = _Select(FEXCore::IR::COND_UGT, Dst8, Src8_1, _Constant(1), _Constant(0)); auto SelectOpLE = _Select(FEXCore::IR::COND_UGE, Dst8, Src8_1, _Constant(1), _Constant(0)); auto SelectCF = _Select(FEXCore::IR::COND_EQ, CF, _Constant(1), SelectOpLE, SelectOpLT); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectCF); } // OF // Signed { auto XorOp1 = _Xor(Src1, Src2); auto XorOp2 = _Xor(Res, Src1); OrderedNode *AndOp1 = _And(XorOp1, XorOp2); switch (GetSrcSize(Op)) { case 1: AndOp1 = _Bfe(1, 7, AndOp1); break; case 2: AndOp1 = _Bfe(1, 15, AndOp1); break; case 4: AndOp1 = _Bfe(1, 31, AndOp1); break; case 8: AndOp1 = _Bfe(1, 63, AndOp1); break; default: LogMan::Msg::A("Unknown BFESize: %d", GetSrcSize(Op)); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(AndOp1); } } void OpDispatchBuilder::GenerateFlags_SUB(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); auto Bfe8 = _Bfe(GetSrcSize(Op) * 8, 0, Res); auto SelectOp = _Select(FEXCore::IR::COND_EQ, Bfe8, ZeroConst, OneConst, ZeroConst); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF { auto ZeroConst = _Constant(0); auto OneConst = _Constant(1); auto SelectOp = _Select(FEXCore::IR::COND_ULT, Src1, Src2, OneConst, ZeroConst); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); } // OF { auto XorOp1 = _Xor(Src1, Src2); auto XorOp2 = _Xor(Res, Src1); OrderedNode *FinalAnd = _And(XorOp1, XorOp2); switch (GetSrcSize(Op)) { case 1: FinalAnd = _Bfe(1, 7, FinalAnd); break; case 2: FinalAnd = _Bfe(1, 15, FinalAnd); break; case 4: FinalAnd = _Bfe(1, 31, FinalAnd); break; case 8: FinalAnd = _Bfe(1, 63, FinalAnd); break; default: LogMan::Msg::A("Unknown BFESize: %d", GetSrcSize(Op)); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(FinalAnd); } } void OpDispatchBuilder::GenerateFlags_ADD(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // AF { OrderedNode *AFRes = _Xor(_Xor(Src1, Src2), Res); AFRes = _Bfe(1, 4, AFRes); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(AFRes); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF { auto Dst8 = _Bfe(GetSrcSize(Op) * 8, 0, Res); auto Src8 = _Bfe(GetSrcSize(Op) * 8, 0, Src2); auto SelectOp = _Select(FEXCore::IR::COND_ULT, Dst8, Src8, _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); } // OF { auto NegOne = _Constant(~0ULL); auto XorOp1 = _Xor(_Xor(Src1, Src2), NegOne); auto XorOp2 = _Xor(Res, Src1); OrderedNode *AndOp1 = _And(XorOp1, XorOp2); switch (GetSrcSize(Op)) { case 1: AndOp1 = _Bfe(1, 7, AndOp1); break; case 2: AndOp1 = _Bfe(1, 15, AndOp1); break; case 4: AndOp1 = _Bfe(1, 31, AndOp1); break; case 8: AndOp1 = _Bfe(1, 63, AndOp1); break; default: LogMan::Msg::A("Unknown BFESize: %d", GetSrcSize(Op)); break; } SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(AndOp1); } } void OpDispatchBuilder::GenerateFlags_MUL(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *High) { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); // PF/AF/ZF/SF // Undefined { SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(_Constant(0)); } // CF/OF { // CF and OF are set if the result of the operation can't be fit in to the destination register // If the value can fit then the top bits will be zero auto SignBit = _Ashr(Res, SignBitConst); auto SelectOp = _Select(FEXCore::IR::COND_EQ, High, SignBit, _Constant(0), _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(SelectOp); } } void OpDispatchBuilder::GenerateFlags_UMUL(FEXCore::X86Tables::DecodedOp Op, OrderedNode *High) { // AF/SF/PF/ZF // Undefined { SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(_Constant(0)); } // CF/OF { // CF and OF are set if the result of the operation can't be fit in to the destination register // The result register will be all zero if it can't fit due to how multiplication behaves auto SelectOp = _Select(FEXCore::IR::COND_EQ, High, _Constant(0), _Constant(0), _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(SelectOp); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(SelectOp); } } void OpDispatchBuilder::GenerateFlags_Logical(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // AF { // Undefined // Set to zero anyway SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF/OF { SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Constant(0)); } } void OpDispatchBuilder::GenerateFlags_Shift(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { auto CmpResult = _Select(FEXCore::IR::COND_EQ, Src2, _Constant(0), _Constant(1), _Constant(0)); auto CondJump = _CondJump(CmpResult); // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); // AF { // Undefined // Set to zero anyway SetRFLAG<FEXCore::X86State::RFLAG_AF_LOC>(_Constant(0)); } // SF { auto SignBitConst = _Constant(GetSrcSize(Op) * 8 - 1); auto LshrOp = _Lshr(Res, SignBitConst); SetRFLAG<FEXCore::X86State::RFLAG_SF_LOC>(LshrOp); } // PF { auto EightBitMask = _Constant(0xFF); auto PopCountOp = _Popcount(_And(Res, EightBitMask)); auto XorOp = _Xor(PopCountOp, _Constant(1)); SetRFLAG<FEXCore::X86State::RFLAG_PF_LOC>(XorOp); } // ZF { auto SelectOp = _Select(FEXCore::IR::COND_EQ, Res, _Constant(0), _Constant(1), _Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_ZF_LOC>(SelectOp); } // CF/OF { SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Constant(0)); } auto Jump = _Jump(); auto NextJumpTarget = CreateNewCodeBlock(); SetJumpTarget(Jump, NextJumpTarget); SetTrueJumpTarget(CondJump, NextJumpTarget); SetCurrentCodeBlock(NextJumpTarget); } void OpDispatchBuilder::GenerateFlags_Rotate(FEXCore::X86Tables::DecodedOp Op, OrderedNode *Res, OrderedNode *Src1, OrderedNode *Src2) { // CF/OF // XXX: These are wrong { SetRFLAG<FEXCore::X86State::RFLAG_CF_LOC>(_Constant(0)); SetRFLAG<FEXCore::X86State::RFLAG_OF_LOC>(_Constant(0)); } } void OpDispatchBuilder::UnhandledOp(OpcodeArgs) { DecodeFailure = true; } template<uint32_t SrcIndex> void OpDispatchBuilder::MOVGPROp(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, 1); StoreResult(GPRClass, Op, Src, 1); } void OpDispatchBuilder::MOVVectorOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, 1); StoreResult(FPRClass, Op, Src, 1); } template<uint32_t SrcIndex> void OpDispatchBuilder::ALUOp(OpcodeArgs) { FEXCore::IR::IROps IROp; switch (Op->OP) { case 0x0: case 0x1: case 0x2: case 0x3: case 0x4: case 0x5: IROp = FEXCore::IR::IROps::OP_ADD; break; case 0x8: case 0x9: case 0xA: case 0xB: case 0xC: case 0xD: IROp = FEXCore::IR::IROps::OP_OR; break; case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: IROp = FEXCore::IR::IROps::OP_AND; break; case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: IROp = FEXCore::IR::IROps::OP_SUB; break; case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: IROp = FEXCore::IR::IROps::OP_XOR; break; default: IROp = FEXCore::IR::IROps::OP_LAST; LogMan::Msg::A("Unknown ALU Op: 0x%x", Op->OP); break; } // X86 basic ALU ops just do the operation between the destination and a single source OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Result{}; OrderedNode *Dest{}; if (DestIsLockedMem(Op)) { OrderedNode *DestMem = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); switch (IROp) { case FEXCore::IR::IROps::OP_ADD: { Dest = _AtomicFetchAdd(DestMem, Src, GetSrcSize(Op)); Result = _Add(Dest, Src); break; } case FEXCore::IR::IROps::OP_SUB: { Dest = _AtomicFetchSub(DestMem, Src, GetSrcSize(Op)); Result = _Sub(Dest, Src); break; } case FEXCore::IR::IROps::OP_OR: { Dest = _AtomicFetchOr(DestMem, Src, GetSrcSize(Op)); Result = _Or(Dest, Src); break; } case FEXCore::IR::IROps::OP_AND: { Dest = _AtomicFetchAnd(DestMem, Src, GetSrcSize(Op)); Result = _And(Dest, Src); break; } case FEXCore::IR::IROps::OP_XOR: { Dest = _AtomicFetchXor(DestMem, Src, GetSrcSize(Op)); Result = _Xor(Dest, Src); break; } default: LogMan::Msg::A("Unknown Atomic IR Op: %d", IROp); break; } } else { Dest = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1); auto ALUOp = _Add(Dest, Src); // Overwrite our IR's op type ALUOp.first->Header.Op = IROp; StoreResult(GPRClass, Op, ALUOp, -1); Result = ALUOp; } // Flags set { auto Size = GetSrcSize(Op) * 8; switch (IROp) { case FEXCore::IR::IROps::OP_ADD: GenerateFlags_ADD(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_SUB: GenerateFlags_SUB(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; case FEXCore::IR::IROps::OP_MUL: GenerateFlags_MUL(Op, _Bfe(Size, 0, Result), _MulH(Dest, Src)); break; case FEXCore::IR::IROps::OP_AND: case FEXCore::IR::IROps::OP_XOR: case FEXCore::IR::IROps::OP_OR: { GenerateFlags_Logical(Op, _Bfe(Size, 0, Result), _Bfe(Size, 0, Dest), _Bfe(Size, 0, Src)); break; } default: break; } } } void OpDispatchBuilder::INTOp(OpcodeArgs) { uint8_t Reason{}; uint8_t Literal{}; bool setRIP = false; switch (Op->OP) { case 0xCD: Reason = 1; Literal = Op->Src[0].TypeLiteral.Literal; break; case 0xCE: Reason = 2; break; case 0xF1: Reason = 3; break; case 0xF4: { Reason = 4; setRIP = true; break; } case 0x0B: Reason = 5; case 0xCC: Reason = 6; setRIP = true; break; break; } if (setRIP) { BlockSetRIP = setRIP; // We want to set RIP to the next instruction after HLT/INT3 auto NewRIP = _Constant(Op->PC + Op->InstSize); _StoreContext(GPRClass, 8, offsetof(FEXCore::Core::CPUState, rip), NewRIP); } if (Op->OP == 0xCE) { // Conditional to only break if Overflow == 1 auto Flag = GetRFLAG(FEXCore::X86State::RFLAG_OF_LOC); // If condition doesn't hold then keep going auto CondJump = _CondJump(_Xor(Flag, _Constant(1))); auto FalseBlock = CreateNewCodeBlock(); SetFalseJumpTarget(CondJump, FalseBlock); SetCurrentCodeBlock(FalseBlock); _Break(Reason, Literal); // Make sure to start a new block after ending this one auto JumpTarget = CreateNewCodeBlock(); SetTrueJumpTarget(CondJump, JumpTarget); SetCurrentCodeBlock(JumpTarget); } else { _Break(Reason, Literal); } } template<size_t ElementSize, uint32_t SrcIndex> void OpDispatchBuilder::PSRLD(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetSrcSize(Op); auto Shift = _VUShr(Size, ElementSize, Dest, Src); StoreResult(FPRClass, Op, Shift, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSRLI(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t ShiftConstant = Op->Src[1].TypeLiteral.Literal; auto Size = GetSrcSize(Op); auto Shift = _VUShrI(Size, ElementSize, Dest, ShiftConstant); StoreResult(FPRClass, Op, Shift, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSLLI(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t ShiftConstant = Op->Src[1].TypeLiteral.Literal; auto Size = GetSrcSize(Op); auto Shift = _VShlI(Size, ElementSize, Dest, ShiftConstant); StoreResult(FPRClass, Op, Shift, -1); } template<size_t ElementSize, bool Scalar, uint32_t SrcIndex> void OpDispatchBuilder::PSLL(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); OrderedNode *Result{}; if (Scalar) { Result = _VUShlS(Size, ElementSize, Dest, Src); } else { Result = _VUShl(Size, ElementSize, Dest, Src); } StoreResult(FPRClass, Op, Result, -1); } template<size_t ElementSize, bool Scalar, uint32_t SrcIndex> void OpDispatchBuilder::PSRAOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[SrcIndex], Op->Flags, -1); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); OrderedNode *Result{}; if (Scalar) { Result = _VSShrS(Size, ElementSize, Dest, Src); } else { Result = _VSShr(Size, ElementSize, Dest, Src); } StoreResult(FPRClass, Op, Result, -1); } void OpDispatchBuilder::PSRLDQ(OpcodeArgs) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Shift = Op->Src[1].TypeLiteral.Literal; OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); auto Result = _VSRI(Size, 16, Dest, Shift); StoreResult(FPRClass, Op, Result, -1); } void OpDispatchBuilder::PSLLDQ(OpcodeArgs) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Shift = Op->Src[1].TypeLiteral.Literal; OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); auto Result = _VSLI(Size, 16, Dest, Shift); StoreResult(FPRClass, Op, Result, -1); } template<size_t ElementSize> void OpDispatchBuilder::PSRAIOp(OpcodeArgs) { LogMan::Throw::A(Op->Src[1].TypeNone.Type == FEXCore::X86Tables::DecodedOperand::TYPE_LITERAL, "Src1 needs to be literal here"); uint64_t Shift = Op->Src[1].TypeLiteral.Literal; OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); auto Size = GetDstSize(Op); auto Result = _VSShrI(Size, ElementSize, Dest, Shift); StoreResult(FPRClass, Op, Result, -1); } void OpDispatchBuilder::MOVDDUPOp(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Res = _SplatVector2(Src); StoreResult(FPRClass, Op, Res, -1); } template<size_t DstElementSize, bool Signed> void OpDispatchBuilder::CVT(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); if (Op->Flags & X86Tables::DecodeFlags::FLAG_REX_WIDENING) { // Source is 64bit if (DstElementSize == 4) { Src = _Bfe(32, 0, Src); } } else { // Source is 32bit if (DstElementSize == 8) { if (Signed) Src = _Sext(32, Src); else Src = _Zext(32, Src); } } if (Signed) Src = _SCVTF(Src, DstElementSize); else Src = _UCVTF(Src, DstElementSize); OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, 16, Op->Flags, -1); Src = _VInsElement(16, DstElementSize, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Src, -1); } template<size_t SrcElementSize, bool Signed> void OpDispatchBuilder::FCVT(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); if (Signed) Src = _FCVTZS(Src, SrcElementSize); else Src = _FCVTZU(Src, SrcElementSize); StoreResult_WithOpSize(GPRClass, Op, Op->Dest, Src, SrcElementSize, -1); } template<size_t SrcElementSize, bool Signed, bool Widen> void OpDispatchBuilder::VFCVT(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); size_t ElementSize = SrcElementSize; size_t Size = GetDstSize(Op); if (Widen) { Src = _VSXTL(Src, Size, ElementSize); ElementSize <<= 1; } if (Signed) Src = _VSCVTF(Src, Size, ElementSize); else Src = _VUCVTF(Src, Size, ElementSize); StoreResult(FPRClass, Op, Src, -1); } template<size_t DstElementSize, size_t SrcElementSize> void OpDispatchBuilder::FCVTF(OpcodeArgs) { OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _FCVTF(Src, DstElementSize, SrcElementSize); Src = _VInsElement(16, DstElementSize, 0, 0, Dest, Src); StoreResult(FPRClass, Op, Src, -1); } template<size_t DstElementSize, size_t SrcElementSize> void OpDispatchBuilder::VFCVTF(OpcodeArgs) { OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); size_t Size = GetDstSize(Op); if (DstElementSize > SrcElementSize) { Src = _VFCVTL(Src, Size, SrcElementSize); } else { Src = _VFCVTN(Src, Size, SrcElementSize); } StoreResult(FPRClass, Op, Src, -1); } void OpDispatchBuilder::TZCNT(OpcodeArgs) { OrderedNode *Src = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); Src = _FindTrailingZeros(Src); StoreResult(GPRClass, Op, Src, -1); } template<size_t ElementSize, bool Scalar> void OpDispatchBuilder::VFCMPOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Dest = LoadSource_WithOpSize(FPRClass, Op, Op->Dest, GetDstSize(Op), Op->Flags, -1); uint8_t CompType = Op->Src[1].TypeLiteral.Literal; OrderedNode *Result{}; // This maps 1:1 to an AArch64 NEON Op //auto ALUOp = _VCMPGT(Size, ElementSize, Dest, Src); switch (CompType) { case 0x00: case 0x08: case 0x10: case 0x18: // EQ Result = _VFCMPEQ(Size, ElementSize, Dest, Src); break; case 0x01: case 0x09: case 0x11: case 0x19: // LT, GT(Swapped operand) Result = _VFCMPLT(Size, ElementSize, Dest, Src); break; case 0x02: case 0x0A: case 0x12: case 0x1A: // LE, GE(Swapped operand) Result = _VFCMPLE(Size, ElementSize, Dest, Src); break; case 0x04: case 0x0C: case 0x14: case 0x1C: // NEQ Result = _VFCMPNEQ(Size, ElementSize, Dest, Src); break; case 0x05: case 0x0D: case 0x15: case 0x1D: // NLT, NGT(Swapped operand) Result = _VFCMPLE(Size, ElementSize, Src, Dest); break; case 0x06: case 0x0E: case 0x16: case 0x1E: // NLE, NGE(Swapped operand) Result = _VFCMPLT(Size, ElementSize, Src, Dest); break; default: LogMan::Msg::A("Unknown Comparison type: %d", CompType); } if (Scalar) { // Insert the lower bits Result = _VInsElement(GetDstSize(Op), ElementSize, 0, 0, Dest, Result); } StoreResult(FPRClass, Op, Result, -1); } OrderedNode *OpDispatchBuilder::GetX87Top() { // Yes, we are storing 3 bits in a single flag register. // Deal with it return _LoadContext(1, offsetof(FEXCore::Core::CPUState, flags) + FEXCore::X86State::X87FLAG_TOP_LOC, GPRClass); } void OpDispatchBuilder::SetX87Top(OrderedNode *Value) { _StoreContext(Value, 1, offsetof(FEXCore::Core::CPUState, flags) + FEXCore::X86State::X87FLAG_TOP_LOC, GPRClass); } template<size_t width> void OpDispatchBuilder::FLD(OpcodeArgs) { // Update TOP auto orig_top = GetX87Top(); auto top = _And(_Sub(orig_top, _Constant(1)), _Constant(7)); SetX87Top(top); size_t read_width = (width == 80) ? 16 : width / 8; // Read from memory auto data = LoadSource_WithOpSize(GPRClass, Op, Op->Src[0], read_width, Op->Flags, -1); OrderedNode *converted; // Convert to 80bit float if (width == 32 || width == 64) { _Zext(32, data); if (width == 32) data = _Zext(32, data); constexpr size_t mantissa_bits = (width == 32) ? 23 : 52; constexpr size_t sign_bits = width - (mantissa_bits + 1); uint64_t sign_mask = (width == 32) ? 0x80000000 : 0x8000000000000000; uint64_t exponent_mask = (width == 32) ? 0x7F800000 : 0x7FE0000000000000; uint64_t lower_mask = (width == 32) ? 0x007FFFFF : 0x001FFFFFFFFFFFFF; auto sign = _Lshr(_And(data, _Constant(sign_mask)), _Constant(width - 16)); auto exponent = _Lshr(_And(data, _Constant(exponent_mask)), _Constant(mantissa_bits)); auto lower = _Lshl(_And(data, _Constant(lower_mask)), _Constant(63 - mantissa_bits)); // XXX: Need to handle NaN/Infinities constexpr size_t exponent_zero = (1 << (sign_bits-1)); auto adjusted_exponent = _Add(exponent, _Constant(0x4000 - exponent_zero)); auto upper = _Or(sign, adjusted_exponent); // XXX: Need to support decoding of denormals auto intergerBit = _Constant(1ULL << 63); converted = _VCastFromGPR(16, 8, _Or(intergerBit, lower)); converted = _VInsElement(16, 8, 1, 0, converted, _VCastFromGPR(16, 8, upper)); } else if (width == 80) { // TODO } // Write to ST[TOP] _StoreContextIndexed(converted, top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); //_StoreContext(converted, 16, offsetof(FEXCore::Core::CPUState, mm[7][0])); } template<size_t width, bool pop> void OpDispatchBuilder::FST(OpcodeArgs) { auto orig_top = GetX87Top(); if (width == 80) { auto data = _LoadContextIndexed(orig_top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); StoreResult_WithOpSize(FPRClass, Op, Op->Dest, data, 10, 1); } // TODO: Other widths if (pop) { auto top = _And(_Add(orig_top, _Constant(1)), _Constant(7)); SetX87Top(top); } } void OpDispatchBuilder::FADD(OpcodeArgs) { auto top = GetX87Top(); OrderedNode* arg; auto mask = _Constant(7); if (Op->Src[0].TypeNone.Type != 0) { // Memory arg arg = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1); } else { // Implicit arg auto offset = _Constant(Op->OP & 7); arg = _And(_Add(top, offset), mask); } auto a = _LoadContextIndexed(top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); auto b = _LoadContextIndexed(arg, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); // _StoreContext(a, 16, offsetof(FEXCore::Core::CPUState, mm[0][0])); // _StoreContext(b, 16, offsetof(FEXCore::Core::CPUState, mm[1][0])); auto ExponentMask = _Constant(0x7FFF); //auto result = _F80Add(a, b); // TODO: Handle sign and negative additions. // TODO: handle NANs (and other weird numbers?) auto a_Exponent = _And(_VExtractToGPR(16, 8, a, 1), ExponentMask); auto b_Exponent = _And(_VExtractToGPR(16, 8, b, 1), ExponentMask); auto shift = _Sub(a_Exponent, b_Exponent); auto zero = _Constant(0); auto ExponentLarger = _Select(COND_ULT, shift, zero, a_Exponent, b_Exponent); auto a_Mantissa = _VExtractToGPR(16, 8, a, 0); auto b_Mantissa = _VExtractToGPR(16, 8, b, 0); auto MantissaLarger = _Select(COND_ULT, shift, zero, a_Mantissa, b_Mantissa); auto MantissaSmaller = _Select(COND_ULT, shift, zero, b_Mantissa, a_Mantissa); auto invertedShift = _Select(COND_ULT, shift, zero, _Neg(shift), shift); auto MantissaSmallerShifted = _Lshr(MantissaSmaller, invertedShift); auto MantissaSummed = _Add(MantissaLarger, MantissaSmallerShifted); auto one = _Constant(1); // Hacky way to detect overflow and adjust auto ExponentAdjusted = _Select(COND_ULT, MantissaLarger, MantissaSummed, ExponentLarger, _Add(ExponentLarger, one)); auto MantissaShifted = _Or(_Constant(1ULL << 63), _Lshr(MantissaSummed, one)); auto MantissaAdjusted = _Select(COND_ULT, MantissaLarger, MantissaSummed, MantissaSummed, MantissaShifted); // TODO: Rounding, Infinities, exceptions, precision, tags? auto lower = _VCastFromGPR(16, 8, MantissaAdjusted); auto upper = _VCastFromGPR(16, 8, ExponentAdjusted); auto result = _VInsElement(16, 8, 1, 0, lower, upper); if ((Op->TableInfo->Flags & X86Tables::InstFlags::FLAGS_POP) != 0) { top = _And(_Add(top, one), mask); SetX87Top(top); } // Write to ST[TOP] _StoreContextIndexed(result, top, 16, offsetof(FEXCore::Core::CPUState, mm[0][0]), 16, FPRClass); } void OpDispatchBuilder::FXSaveOp(OpcodeArgs) { OrderedNode *Mem = LoadSource(GPRClass, Op, Op->Dest, Op->Flags, -1, false); // Saves 512bytes to the memory location provided // Header changes depending on if REX.W is set or not if (Op->Flags & X86Tables::DecodeFlags::FLAG_REX_WIDENING) { // BYTE | 0 1 | 2 3 | 4 | 5 | 6 7 | 8 9 | a b | c d | e f | // ------------------------------------------ // 00 | FCW | FSW | FTW | <R> | FOP | FIP | // 16 | FDP | MXCSR | MXCSR_MASK| } else { // BYTE | 0 1 | 2 3 | 4 | 5 | 6 7 | 8 9 | a b | c d | e f | // ------------------------------------------ // 00 | FCW | FSW | FTW | <R> | FOP | FIP[31:0] | FCS | <R> | // 16 | FDP[31:0] | FDS | <R> | MXCSR | MXCSR_MASK| } // BYTE | 0 1 | 2 3 | 4 | 5 | 6 7 | 8 9 | a b | c d | e f | // ------------------------------------------ // 32 | ST0/MM0 | <R> // 48 | ST1/MM1 | <R> // 64 | ST2/MM2 | <R> // 80 | ST3/MM3 | <R> // 96 | ST4/MM4 | <R> // 112 | ST5/MM5 | <R> // 128 | ST6/MM6 | <R> // 144 | ST7/MM7 | <R> // 160 | XMM0 // 173 | XMM1 // 192 | XMM2 // 208 | XMM3 // 224 | XMM4 // 240 | XMM5 // 256 | XMM6 // 272 | XMM7 // 288 | XMM8 // 304 | XMM9 // 320 | XMM10 // 336 | XMM11 // 352 | XMM12 // 368 | XMM13 // 384 | XMM14 // 400 | XMM15 // 416 | <R> // 432 | <R> // 448 | <R> // 464 | Available // 480 | Available // 496 | Available // FCW: x87 FPU control word // FSW: x87 FPU status word // FTW: x87 FPU Tag word (Abridged) // FOP: x87 FPU opcode. Lower 11 bits of the opcode // FIP: x87 FPU instructyion pointer offset // FCS: x87 FPU instruction pointer selector. If CPUID_0000_0007_0000_00000:EBX[bit 13] = 1 then this is deprecated and stores as 0 // FDP: x87 FPU instruction operand (data) pointer offset // FDS: x87 FPU instruction operand (data) pointer selector. Same deprecation as FCS // MXCSR: If OSFXSR bit in CR4 is not set then this may not be saved // MXCSR_MASK: Mask for writes to the MXCSR register // If OSFXSR bit in CR4 is not set than FXSAVE /may/ not save the XMM registers // This is implementation dependent for (unsigned i = 0; i < 8; ++i) { OrderedNode *MMReg = _LoadContext(16, offsetof(FEXCore::Core::CPUState, mm[i]), FPRClass); OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 32)); _StoreMem(FPRClass, 16, MemLocation, MMReg, 16); } for (unsigned i = 0; i < 16; ++i) { OrderedNode *XMMReg = _LoadContext(16, offsetof(FEXCore::Core::CPUState, xmm[i]), FPRClass); OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 160)); _StoreMem(FPRClass, 16, MemLocation, XMMReg, 16); } } void OpDispatchBuilder::FXRStoreOp(OpcodeArgs) { OrderedNode *Mem = LoadSource(GPRClass, Op, Op->Src[0], Op->Flags, -1, false); for (unsigned i = 0; i < 8; ++i) { OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 32)); auto MMReg = _LoadMem(FPRClass, 16, MemLocation, 16); _StoreContext(FPRClass, 16, offsetof(FEXCore::Core::CPUState, mm[i]), MMReg); } for (unsigned i = 0; i < 16; ++i) { OrderedNode *MemLocation = _Add(Mem, _Constant(i * 16 + 160)); auto XMMReg = _LoadMem(FPRClass, 16, MemLocation, 16); _StoreContext(FPRClass, 16, offsetof(FEXCore::Core::CPUState, xmm[i]), XMMReg); } } void OpDispatchBuilder::PAlignrOp(OpcodeArgs) { OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); uint8_t Index = Op->Src[1].TypeLiteral.Literal; OrderedNode *Res = _VExtr(GetDstSize(Op), 1, Src1, Src2, Index); StoreResult(FPRClass, Op, Res, -1); } void OpDispatchBuilder::LDMXCSR(OpcodeArgs) { } void OpDispatchBuilder::STMXCSR(OpcodeArgs) { // Default MXCSR StoreResult(GPRClass, Op, _Constant(0x1F80), -1); } template<size_t ElementSize> void OpDispatchBuilder::PACKUSOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Dest = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode *Res = _VSQXTUN(Size, ElementSize, Dest); Res = _VSQXTUN2(Size, ElementSize, Res, Src); StoreResult(FPRClass, Op, Res, -1); } template<size_t ElementSize, bool Signed> void OpDispatchBuilder::PMULOp(OpcodeArgs) { auto Size = GetSrcSize(Op); OrderedNode *Src1 = LoadSource(FPRClass, Op, Op->Dest, Op->Flags, -1); OrderedNode *Src2 = LoadSource(FPRClass, Op, Op->Src[0], Op->Flags, -1); OrderedNode* Srcs1[2]{}; OrderedNode* Srcs2[2]{}; Srcs1[0] = _VExtr(Size, ElementSize, Src1, Src1, 0); Srcs1[1] = _VExtr(Size, ElementSize, Src1, Src1, 2); Srcs2[0] = _VExtr(Size, ElementSize, Src2, Src2, 0); Srcs2[1] = _VExtr(Size, ElementSize, Src2, Src2, 2); Src1 = _VInsElement(Size, ElementSize, 1, 0, Srcs1[0], Srcs1[1]); Src2 = _VInsElement(Size, ElementSize, 1, 0, Srcs2[0], Srcs2[1]); OrderedNode *Res{}; if (Signed) { Res = _VSMull(Size, ElementSize, Src1, Src2); } else { Res = _VUMull(Size, ElementSize, Src1, Src2); } StoreResult(FPRClass, Op, Res, -1); } void OpDispatchBuilder::UnimplementedOp(OpcodeArgs) { // We don't actually support this instruction // Multiblock may hit it though _Break(0, 0); } #undef OpcodeArgs void OpDispatchBuilder::ReplaceAllUsesWithInclusive(OrderedNode *Node, OrderedNode *NewNode, IR::NodeWrapperIterator After, IR::NodeWrapperIterator End) { uintptr_t ListBegin = ListData.Begin(); uintptr_t DataBegin = Data.Begin(); while (After != End) { OrderedNodeWrapper *WrapperOp = After(); OrderedNode *RealNode = WrapperOp->GetNode(ListBegin); FEXCore::IR::IROp_Header *IROp = RealNode->Op(DataBegin); uint8_t NumArgs = IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { if (IROp->Args[i].ID() == Node->Wrapped(ListBegin).ID()) { Node->RemoveUse(); NewNode->AddUse(); IROp->Args[i].NodeOffset = NewNode->Wrapped(ListBegin).NodeOffset; } } ++After; } } void OpDispatchBuilder::RemoveArgUses(OrderedNode *Node) { uintptr_t ListBegin = ListData.Begin(); uintptr_t DataBegin = Data.Begin(); FEXCore::IR::IROp_Header *IROp = Node->Op(DataBegin); uint8_t NumArgs = IR::GetArgs(IROp->Op); for (uint8_t i = 0; i < NumArgs; ++i) { auto ArgNode = IROp->Args[i].GetNode(ListBegin); ArgNode->RemoveUse(); } } void OpDispatchBuilder::Remove(OrderedNode *Node) { RemoveArgUses(Node); Node->Unlink(ListData.Begin()); } void InstallOpcodeHandlers() { const std::vector<std::tuple<uint8_t, uint8_t, X86Tables::OpDispatchPtr>> BaseOpTable = { // Instructions {0x00, 1, &OpDispatchBuilder::ALUOp<0>}, {0x01, 1, &OpDispatchBuilder::ALUOp<0>}, {0x02, 1, &OpDispatchBuilder::ALUOp<0>}, {0x03, 1, &OpDispatchBuilder::ALUOp<0>}, {0x04, 1, &OpDispatchBuilder::ALUOp<0>}, {0x05, 1, &OpDispatchBuilder::ALUOp<0>}, {0x08, 1, &OpDispatchBuilder::ALUOp<0>}, {0x09, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0A, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0B, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0C, 1, &OpDispatchBuilder::ALUOp<0>}, {0x0D, 1, &OpDispatchBuilder::ALUOp<0>}, {0x10, 1, &OpDispatchBuilder::ADCOp<0>}, {0x11, 1, &OpDispatchBuilder::ADCOp<0>}, {0x12, 1, &OpDispatchBuilder::ADCOp<0>}, {0x13, 1, &OpDispatchBuilder::ADCOp<0>}, {0x14, 1, &OpDispatchBuilder::ADCOp<0>}, {0x15, 1, &OpDispatchBuilder::ADCOp<0>}, {0x18, 1, &OpDispatchBuilder::SBBOp<0>}, {0x19, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1A, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1B, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1C, 1, &OpDispatchBuilder::SBBOp<0>}, {0x1D, 1, &OpDispatchBuilder::SBBOp<0>}, {0x20, 1, &OpDispatchBuilder::ALUOp<0>}, {0x21, 1, &OpDispatchBuilder::ALUOp<0>}, {0x22, 1, &OpDispatchBuilder::ALUOp<0>}, {0x23, 1, &OpDispatchBuilder::ALUOp<0>}, {0x24, 1, &OpDispatchBuilder::ALUOp<0>}, {0x25, 1, &OpDispatchBuilder::ALUOp<0>}, {0x28, 1, &OpDispatchBuilder::ALUOp<0>}, {0x29, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2A, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2B, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2C, 1, &OpDispatchBuilder::ALUOp<0>}, {0x2D, 1, &OpDispatchBuilder::ALUOp<0>}, {0x30, 1, &OpDispatchBuilder::ALUOp<0>}, {0x31, 1, &OpDispatchBuilder::ALUOp<0>}, {0x32, 1, &OpDispatchBuilder::ALUOp<0>}, {0x33, 1, &OpDispatchBuilder::ALUOp<0>}, {0x34, 1, &OpDispatchBuilder::ALUOp<0>}, {0x35, 1, &OpDispatchBuilder::ALUOp<0>}, {0x38, 6, &OpDispatchBuilder::CMPOp<0>}, {0x50, 8, &OpDispatchBuilder::PUSHOp}, {0x58, 8, &OpDispatchBuilder::POPOp}, {0x63, 1, &OpDispatchBuilder::MOVSXDOp}, {0x68, 1, &OpDispatchBuilder::PUSHOp}, {0x69, 1, &OpDispatchBuilder::IMUL2SrcOp}, {0x6A, 1, &OpDispatchBuilder::PUSHOp}, {0x6B, 1, &OpDispatchBuilder::IMUL2SrcOp}, {0x70, 16, &OpDispatchBuilder::CondJUMPOp}, {0x84, 2, &OpDispatchBuilder::TESTOp<0>}, {0x86, 2, &OpDispatchBuilder::XCHGOp}, {0x88, 4, &OpDispatchBuilder::MOVGPROp<0>}, {0x8D, 1, &OpDispatchBuilder::LEAOp}, {0x90, 8, &OpDispatchBuilder::XCHGOp}, {0x98, 1, &OpDispatchBuilder::CDQOp}, {0x99, 1, &OpDispatchBuilder::CQOOp}, {0x9E, 1, &OpDispatchBuilder::SAHFOp}, {0x9F, 1, &OpDispatchBuilder::LAHFOp}, {0xA0, 4, &OpDispatchBuilder::MOVOffsetOp}, {0xA4, 2, &OpDispatchBuilder::MOVSOp}, {0xA6, 2, &OpDispatchBuilder::CMPSOp}, {0xA8, 2, &OpDispatchBuilder::TESTOp<0>}, {0xAA, 2, &OpDispatchBuilder::STOSOp}, {0xAE, 2, &OpDispatchBuilder::SCASOp}, {0xB0, 16, &OpDispatchBuilder::MOVGPROp<0>}, {0xC2, 2, &OpDispatchBuilder::RETOp}, {0xC9, 1, &OpDispatchBuilder::LEAVEOp}, {0xCC, 2, &OpDispatchBuilder::INTOp}, {0xE8, 1, &OpDispatchBuilder::CALLOp}, {0xE9, 1, &OpDispatchBuilder::JUMPOp}, {0xEB, 1, &OpDispatchBuilder::JUMPOp}, {0xF1, 1, &OpDispatchBuilder::INTOp}, {0xF4, 1, &OpDispatchBuilder::INTOp}, {0xF5, 1, &OpDispatchBuilder::FLAGControlOp}, {0xF8, 2, &OpDispatchBuilder::FLAGControlOp}, {0xFC, 2, &OpDispatchBuilder::FLAGControlOp}, }; const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> TwoByteOpTable = { // Instructions {0x00, 1, nullptr}, // GROUP 6 {0x01, 1, nullptr}, // GROUP 7 {0x05, 1, &OpDispatchBuilder::SyscallOp}, {0x0B, 1, &OpDispatchBuilder::INTOp}, {0x0D, 1, nullptr}, // GROUP P {0x18, 1, nullptr}, // GROUP 16 {0x19, 7, &OpDispatchBuilder::NOPOp}, // NOP with ModRM {0x31, 1, &OpDispatchBuilder::RDTSCOp}, {0x40, 16, &OpDispatchBuilder::CMOVOp}, {0x6E, 1, &OpDispatchBuilder::UnhandledOp}, // MOVD {0x7E, 1, &OpDispatchBuilder::UnhandledOp}, // MOVD {0x80, 16, &OpDispatchBuilder::CondJUMPOp}, // XXX: Fails to fixup some jumps {0x90, 16, &OpDispatchBuilder::SETccOp}, // XXX: Causes some unit tests to fail due to flags being incorrect {0xA2, 1, &OpDispatchBuilder::CPUIDOp}, {0xA3, 1, &OpDispatchBuilder::BTOp<0>}, // BT {0xA4, 2, &OpDispatchBuilder::SHLDOp}, {0xAB, 1, &OpDispatchBuilder::BTSOp<0>}, {0xAC, 2, &OpDispatchBuilder::SHRDOp}, {0xAF, 1, &OpDispatchBuilder::IMUL1SrcOp}, // XXX: Causes issues with LLVM JIT {0xB0, 2, &OpDispatchBuilder::CMPXCHGOp}, // CMPXCHG {0xB3, 1, &OpDispatchBuilder::BTROp<0>}, {0xB6, 2, &OpDispatchBuilder::MOVZXOp}, {0xBB, 1, &OpDispatchBuilder::BTCOp<0>}, {0xBC, 1, &OpDispatchBuilder::BSFOp}, // BSF {0xBD, 1, &OpDispatchBuilder::BSROp}, // BSF {0xBE, 2, &OpDispatchBuilder::MOVSXOp}, {0xC0, 2, &OpDispatchBuilder::XADDOp}, {0xC8, 8, &OpDispatchBuilder::BSWAPOp}, // SSE // XXX: Broken on LLVM? {0x10, 2, &OpDispatchBuilder::MOVUPSOp}, {0x12, 2, &OpDispatchBuilder::MOVLPOp}, {0x14, 1, &OpDispatchBuilder::PUNPCKLOp<4>}, {0x15, 1, &OpDispatchBuilder::PUNPCKHOp<4>}, {0x16, 1, &OpDispatchBuilder::MOVLHPSOp}, {0x17, 1, &OpDispatchBuilder::MOVUPSOp}, {0x28, 2, &OpDispatchBuilder::MOVUPSOp}, {0x50, 1, &OpDispatchBuilder::MOVMSKOp<4>}, {0x54, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VAND, 16>}, {0x55, 1, &OpDispatchBuilder::ANDNOp}, {0x56, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VOR, 16>}, {0x57, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VXOR, 16>}, {0x58, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFADD, 4>}, {0x59, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMUL, 4>}, {0x5A, 1, &OpDispatchBuilder::VFCVTF<8, 4>}, {0x5B, 1, &OpDispatchBuilder::FCVT<4, true>}, {0x5C, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFSUB, 4>}, {0x5D, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMIN, 4>}, {0x5E, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFDIV, 4>}, {0x5F, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMAX, 4>}, {0x71, 1, nullptr}, // GROUP 12 {0x72, 1, nullptr}, // GROUP 13 {0x73, 1, nullptr}, // GROUP 14 {0xAE, 1, nullptr}, // GROUP 15 {0xB9, 1, nullptr}, // GROUP 10 {0xBA, 1, nullptr}, // GROUP 8 {0xC2, 1, &OpDispatchBuilder::VFCMPOp<4, false>}, {0xC6, 1, &OpDispatchBuilder::SHUFOp<4>}, {0xC7, 1, nullptr}, // GROUP 9 }; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_1) << 6) | (prefix) << 3 | (Reg)) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> PrimaryGroupOpTable = { // GROUP 1 // XXX: Something in this group causing bad syscall when commented out {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 0), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 1), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 2), 1, &OpDispatchBuilder::ADCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 3), 1, &OpDispatchBuilder::SBBOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 4), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 5), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 6), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x80), 7), 1, &OpDispatchBuilder::CMPOp<1>}, // CMP {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 0), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 1), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 2), 1, &OpDispatchBuilder::ADCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 3), 1, &OpDispatchBuilder::SBBOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 4), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 5), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 6), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x81), 7), 1, &OpDispatchBuilder::CMPOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 0), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 1), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 2), 1, &OpDispatchBuilder::ADCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 3), 1, &OpDispatchBuilder::SBBOp<1>}, // Unit tests find this setting flags incorrectly {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 4), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 5), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 6), 1, &OpDispatchBuilder::SecondaryALUOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_1, OpToIndex(0x83), 7), 1, &OpDispatchBuilder::CMPOp<1>}, // GROUP 2 {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 5), 1, &OpDispatchBuilder::SHROp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC0), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 5), 1, &OpDispatchBuilder::SHROp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xC1), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 4), 1, &OpDispatchBuilder::SHLOp<true>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 5), 1, &OpDispatchBuilder::SHROp<true>}, // 1Bit SHR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD0), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 4), 1, &OpDispatchBuilder::SHLOp<true>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 5), 1, &OpDispatchBuilder::SHROp<true>}, // 1Bit SHR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD1), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 5), 1, &OpDispatchBuilder::SHROp<false>}, // SHR by CL {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD2), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 0), 1, &OpDispatchBuilder::ROLOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 1), 1, &OpDispatchBuilder::ROROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 4), 1, &OpDispatchBuilder::SHLOp<false>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 5), 1, &OpDispatchBuilder::SHROp<false>}, // SHR by CL {OPD(FEXCore::X86Tables::TYPE_GROUP_2, OpToIndex(0xD3), 7), 1, &OpDispatchBuilder::ASHROp}, // SAR // GROUP 3 {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 0), 1, &OpDispatchBuilder::TESTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 2), 1, &OpDispatchBuilder::NOTOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 3), 1, &OpDispatchBuilder::NEGOp}, // NEG {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 4), 1, &OpDispatchBuilder::MULOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 5), 1, &OpDispatchBuilder::IMULOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 6), 1, &OpDispatchBuilder::DIVOp}, // DIV {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF6), 7), 1, &OpDispatchBuilder::IDIVOp}, // IDIV {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 0), 1, &OpDispatchBuilder::TESTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 2), 1, &OpDispatchBuilder::NOTOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 3), 1, &OpDispatchBuilder::NEGOp}, // NEG {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 4), 1, &OpDispatchBuilder::MULOp}, // MUL {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 5), 1, &OpDispatchBuilder::IMULOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 6), 1, &OpDispatchBuilder::DIVOp}, // DIV {OPD(FEXCore::X86Tables::TYPE_GROUP_3, OpToIndex(0xF7), 7), 1, &OpDispatchBuilder::IDIVOp}, // IDIV // GROUP 4 {OPD(FEXCore::X86Tables::TYPE_GROUP_4, OpToIndex(0xFE), 0), 1, &OpDispatchBuilder::INCOp}, // INC {OPD(FEXCore::X86Tables::TYPE_GROUP_4, OpToIndex(0xFE), 1), 1, &OpDispatchBuilder::DECOp}, // DEC // GROUP 5 {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 0), 1, &OpDispatchBuilder::INCOp}, // INC {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 1), 1, &OpDispatchBuilder::DECOp}, // DEC {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 2), 1, &OpDispatchBuilder::CALLAbsoluteOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 4), 1, &OpDispatchBuilder::JUMPAbsoluteOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_5, OpToIndex(0xFF), 6), 1, &OpDispatchBuilder::PUSHOp}, // GROUP 11 {OPD(FEXCore::X86Tables::TYPE_GROUP_11, OpToIndex(0xC6), 0), 1, &OpDispatchBuilder::MOVGPROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_11, OpToIndex(0xC7), 0), 1, &OpDispatchBuilder::MOVGPROp<1>}, }; #undef OPD const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> RepModOpTable = { {0x10, 2, &OpDispatchBuilder::MOVSSOp}, {0x19, 7, &OpDispatchBuilder::NOPOp}, {0x2A, 1, &OpDispatchBuilder::CVT<4, true>}, {0x2C, 1, &OpDispatchBuilder::FCVT<4, true>}, {0x51, 1, &OpDispatchBuilder::VectorUnaryOp<IR::OP_VFSQRT, 4, true>}, {0x52, 1, &OpDispatchBuilder::VectorUnaryOp<IR::OP_VFRSQRT, 4, true>}, {0x58, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFADD, 4>}, {0x59, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMUL, 4>}, {0x5A, 1, &OpDispatchBuilder::FCVTF<8, 4>}, {0x5C, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFSUB, 4>}, {0x5D, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMIN, 4>}, {0x5E, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFDIV, 4>}, {0x5F, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMAX, 4>}, {0x6F, 1, &OpDispatchBuilder::MOVUPSOp}, {0x70, 1, &OpDispatchBuilder::PSHUFDOp<2, false>}, {0x7E, 1, &OpDispatchBuilder::MOVQOp}, {0x7F, 1, &OpDispatchBuilder::MOVUPSOp}, {0xB8, 1, &OpDispatchBuilder::PopcountOp}, {0xBC, 2, &OpDispatchBuilder::TZCNT}, {0xC2, 1, &OpDispatchBuilder::VFCMPOp<4, true>}, {0xE6, 1, &OpDispatchBuilder::VFCVT<4, true, true>}, }; const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> RepNEModOpTable = { {0x10, 2, &OpDispatchBuilder::MOVSDOp}, {0x12, 1, &OpDispatchBuilder::MOVDDUPOp}, {0x19, 7, &OpDispatchBuilder::NOPOp}, {0x2A, 1, &OpDispatchBuilder::CVT<8, true>}, {0x2C, 1, &OpDispatchBuilder::FCVT<8, true>}, {0x51, 1, &OpDispatchBuilder::VectorUnaryOp<IR::OP_VFSQRT, 8, true>}, //x52 = Invalid {0x58, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFADD, 8>}, {0x59, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMUL, 8>}, {0x5A, 1, &OpDispatchBuilder::FCVTF<4, 8>}, {0x5C, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFSUB, 8>}, {0x5D, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMIN, 8>}, {0x5E, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFDIV, 8>}, {0x5F, 1, &OpDispatchBuilder::VectorScalarALUOp<IR::OP_VFMAX, 8>}, {0x70, 1, &OpDispatchBuilder::PSHUFDOp<2, true>}, {0xC2, 1, &OpDispatchBuilder::VFCMPOp<8, true>}, {0xF0, 1, &OpDispatchBuilder::MOVVectorOp}, }; const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> OpSizeModOpTable = { {0x10, 2, &OpDispatchBuilder::MOVVectorOp}, {0x12, 2, &OpDispatchBuilder::MOVLPOp}, {0x14, 1, &OpDispatchBuilder::PUNPCKLOp<8>}, {0x15, 1, &OpDispatchBuilder::PUNPCKHOp<8>}, {0x16, 2, &OpDispatchBuilder::MOVHPDOp}, {0x19, 7, &OpDispatchBuilder::NOPOp}, {0x28, 2, &OpDispatchBuilder::MOVAPSOp}, {0x40, 16, &OpDispatchBuilder::CMOVOp}, {0x50, 1, &OpDispatchBuilder::MOVMSKOp<8>}, {0x54, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VAND, 16>}, {0x55, 1, &OpDispatchBuilder::ANDNOp}, {0x56, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VOR, 16>}, {0x57, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VXOR, 16>}, {0x58, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFADD, 8>}, {0x59, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMUL, 8>}, {0x5A, 1, &OpDispatchBuilder::VFCVTF<4, 8>}, {0x5C, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFSUB, 8>}, {0x5D, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMIN, 8>}, {0x5E, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFDIV, 8>}, {0x5F, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VFMAX, 8>}, {0x60, 1, &OpDispatchBuilder::PUNPCKLOp<1>}, {0x61, 1, &OpDispatchBuilder::PUNPCKLOp<2>}, {0x62, 1, &OpDispatchBuilder::PUNPCKLOp<4>}, {0x64, 1, &OpDispatchBuilder::PCMPGTOp<1>}, {0x65, 1, &OpDispatchBuilder::PCMPGTOp<2>}, {0x66, 1, &OpDispatchBuilder::PCMPGTOp<4>}, {0x67, 1, &OpDispatchBuilder::PACKUSOp<2>}, {0x68, 1, &OpDispatchBuilder::PUNPCKHOp<1>}, {0x69, 1, &OpDispatchBuilder::PUNPCKHOp<2>}, {0x6A, 1, &OpDispatchBuilder::PUNPCKHOp<4>}, {0x6C, 1, &OpDispatchBuilder::PUNPCKLOp<8>}, {0x6D, 1, &OpDispatchBuilder::PUNPCKHOp<8>}, {0x6E, 1, &OpDispatchBuilder::MOVDOp}, {0x6F, 1, &OpDispatchBuilder::MOVUPSOp}, {0x70, 1, &OpDispatchBuilder::PSHUFDOp<4, true>}, // XXX: Causing IR interpreter some problems {0x74, 1, &OpDispatchBuilder::PCMPEQOp<1>}, {0x75, 1, &OpDispatchBuilder::PCMPEQOp<2>}, {0x76, 1, &OpDispatchBuilder::PCMPEQOp<4>}, {0x78, 1, nullptr}, // GROUP 17 {0x7E, 1, &OpDispatchBuilder::MOVDOp}, {0x7F, 1, &OpDispatchBuilder::MOVUPSOp}, {0xC2, 1, &OpDispatchBuilder::VFCMPOp<8, false>}, {0xC4, 1, &OpDispatchBuilder::PINSROp<2>}, {0xC6, 1, &OpDispatchBuilder::SHUFOp<8>}, {0xD4, 1, &OpDispatchBuilder::PADDQOp<8>}, // XXX: Causes LLVM to crash if commented out? {0xD6, 1, &OpDispatchBuilder::MOVQOp}, {0xD7, 1, &OpDispatchBuilder::MOVMSKOp<1>}, // PMOVMSKB // XXX: Untested {0xDA, 1, &OpDispatchBuilder::PMINUOp<1>}, {0xDB, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VAND, 16>}, {0xDE, 1, &OpDispatchBuilder::PMAXUOp<1>}, {0xDF, 1, &OpDispatchBuilder::ANDNOp}, {0xE1, 1, &OpDispatchBuilder::PSRAOp<2, true, 0>}, {0xE2, 1, &OpDispatchBuilder::PSRAOp<4, true, 0>}, {0xE7, 1, &OpDispatchBuilder::MOVVectorOp}, {0xEA, 1, &OpDispatchBuilder::PMINSWOp}, {0xEB, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VOR, 16>}, {0xEC, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VSQADD, 1>}, {0xED, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VSQADD, 2>}, {0xEE, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VSMAX, 2>}, {0xEF, 1, &OpDispatchBuilder::VectorALUOp<IR::OP_VXOR, 16>}, {0xF2, 1, &OpDispatchBuilder::PSLL<4, true, 0>}, {0xF3, 1, &OpDispatchBuilder::PSLL<8, true, 0>}, {0xF4, 1, &OpDispatchBuilder::PMULOp<4, false>}, {0xF8, 1, &OpDispatchBuilder::PSUBQOp<1>}, {0xF9, 1, &OpDispatchBuilder::PSUBQOp<2>}, {0xFA, 1, &OpDispatchBuilder::PSUBQOp<4>}, {0xFB, 1, &OpDispatchBuilder::PSUBQOp<8>}, {0xFD, 1, &OpDispatchBuilder::PADDQOp<2>}, {0xFE, 1, &OpDispatchBuilder::PADDQOp<4>}, }; constexpr uint16_t PF_NONE = 0; constexpr uint16_t PF_F3 = 1; constexpr uint16_t PF_66 = 2; constexpr uint16_t PF_F2 = 3; #define OPD(group, prefix, Reg) (((group - FEXCore::X86Tables::TYPE_GROUP_6) << 5) | (prefix) << 3 | (Reg)) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> SecondaryExtensionOpTable = { // GROUP 8 {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 4), 1, &OpDispatchBuilder::BTOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 5), 1, &OpDispatchBuilder::BTSOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 6), 1, &OpDispatchBuilder::BTROp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_NONE, 7), 1, &OpDispatchBuilder::BTCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F3, 7), 1, &OpDispatchBuilder::BTCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_66, 7), 1, &OpDispatchBuilder::BTCOp<1>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_8, PF_F2, 7), 1, &OpDispatchBuilder::BTCOp<1>}, // GROUP 12 {OPD(FEXCore::X86Tables::TYPE_GROUP_12, PF_66, 2), 1, &OpDispatchBuilder::PSRLI<2>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_12, PF_66, 4), 1, &OpDispatchBuilder::PSRAIOp<2>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_12, PF_66, 6), 1, &OpDispatchBuilder::PSLLI<2>}, // GROUP 13 {OPD(FEXCore::X86Tables::TYPE_GROUP_13, PF_66, 2), 1, &OpDispatchBuilder::PSRLI<4>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_13, PF_66, 4), 1, &OpDispatchBuilder::PSRAIOp<4>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_13, PF_66, 6), 1, &OpDispatchBuilder::PSLLI<4>}, // GROUP 14 {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 2), 1, &OpDispatchBuilder::PSRLI<8>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 3), 1, &OpDispatchBuilder::PSRLDQ}, {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 6), 1, &OpDispatchBuilder::PSLLI<8>}, {OPD(FEXCore::X86Tables::TYPE_GROUP_14, PF_66, 7), 1, &OpDispatchBuilder::PSLLDQ}, // GROUP 15 {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 0), 1, &OpDispatchBuilder::FXSaveOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 1), 1, &OpDispatchBuilder::FXRStoreOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 2), 1, &OpDispatchBuilder::LDMXCSR}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 3), 1, &OpDispatchBuilder::STMXCSR}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 5), 1, &OpDispatchBuilder::NOPOp}, //LFENCE {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 6), 1, &OpDispatchBuilder::NOPOp}, //MFENCE {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_NONE, 7), 1, &OpDispatchBuilder::NOPOp}, //SFENCE {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_F3, 5), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_15, PF_F3, 6), 1, &OpDispatchBuilder::UnimplementedOp}, // GROUP 16 {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_NONE, 0), 8, &OpDispatchBuilder::NOPOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_F3, 0), 8, &OpDispatchBuilder::NOPOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_66, 0), 8, &OpDispatchBuilder::NOPOp}, {OPD(FEXCore::X86Tables::TYPE_GROUP_16, PF_F2, 0), 8, &OpDispatchBuilder::NOPOp}, }; #undef OPD const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> SecondaryModRMExtensionOpTable = { // REG /2 {((1 << 3) | 0), 1, &OpDispatchBuilder::UnimplementedOp}, }; #define OPDReg(op, reg) (((op - 0xD8) << 8) | (reg << 3)) #define OPD(op, modrmop) (((op - 0xD8) << 8) | modrmop) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> X87OpTable = { {OPDReg(0xD9, 0) | 0x00, 8, &OpDispatchBuilder::FLD<32>}, {OPDReg(0xD9, 0) | 0x40, 8, &OpDispatchBuilder::FLD<32>}, {OPDReg(0xD9, 0) | 0x80, 8, &OpDispatchBuilder::FLD<32>}, {OPDReg(0xD9, 5) | 0x00, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FLDCW {OPDReg(0xD9, 5) | 0x40, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FLDCW {OPDReg(0xD9, 5) | 0x80, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FLDCW {OPDReg(0xD9, 7) | 0x00, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FNSTCW {OPDReg(0xD9, 7) | 0x40, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FNSTCW {OPDReg(0xD9, 7) | 0x80, 8, &OpDispatchBuilder::NOPOp}, // XXX: stubbed FNSTCW {OPDReg(0xDB, 7) | 0x00, 8, &OpDispatchBuilder::FST<80, true>}, {OPDReg(0xDB, 7) | 0x40, 8, &OpDispatchBuilder::FST<80, true>}, {OPDReg(0xDB, 7) | 0x80, 8, &OpDispatchBuilder::FST<80, true>}, {OPDReg(0xDD, 0) | 0x00, 8, &OpDispatchBuilder::FLD<64>}, {OPDReg(0xDD, 0) | 0x40, 8, &OpDispatchBuilder::FLD<64>}, {OPDReg(0xDD, 0) | 0x80, 8, &OpDispatchBuilder::FLD<64>}, {OPD(0xDE, 0xC0), 8, &OpDispatchBuilder::FADD}, }; #undef OPD #undef OPDReg #define OPD(prefix, opcode) ((prefix << 8) | opcode) constexpr uint16_t PF_38_NONE = 0; constexpr uint16_t PF_38_66 = 1; constexpr uint16_t PF_38_F2 = 2; const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> H0F38Table = { {OPD(PF_38_66, 0x00), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(PF_38_66, 0x3B), 1, &OpDispatchBuilder::UnimplementedOp}, }; #undef OPD #define OPD(REX, prefix, opcode) ((REX << 9) | (prefix << 8) | opcode) #define PF_3A_NONE 0 #define PF_3A_66 1 const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> H0F3ATable = { {OPD(0, PF_3A_66, 0x0F), 1, &OpDispatchBuilder::PAlignrOp}, {OPD(1, PF_3A_66, 0x0F), 1, &OpDispatchBuilder::PAlignrOp}, }; #undef PF_3A_NONE #undef PF_3A_66 #undef OPD #define OPD(map_select, pp, opcode) (((map_select - 1) << 10) | (pp << 8) | (opcode)) const std::vector<std::tuple<uint16_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> VEXTable = { {OPD(1, 0b01, 0x6E), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x6F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b10, 0x6F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x74), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x75), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x76), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b00, 0x77), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x7E), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0x7F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b10, 0x7F), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0xD7), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0xEB), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(1, 0b01, 0xEF), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x3B), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x58), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x59), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x5A), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x78), 1, &OpDispatchBuilder::UnimplementedOp}, {OPD(2, 0b01, 0x79), 1, &OpDispatchBuilder::UnimplementedOp}, }; #undef OPD const std::vector<std::tuple<uint8_t, uint8_t, FEXCore::X86Tables::OpDispatchPtr>> EVEXTable = { {0x10, 1, &OpDispatchBuilder::UnimplementedOp}, {0x11, 1, &OpDispatchBuilder::UnimplementedOp}, {0x59, 1, &OpDispatchBuilder::UnimplementedOp}, {0x7F, 1, &OpDispatchBuilder::UnimplementedOp}, }; uint64_t NumInsts{}; auto InstallToTable = [&NumInsts](auto& FinalTable, auto& LocalTable) { for (auto Op : LocalTable) { auto OpNum = std::get<0>(Op); auto Dispatcher = std::get<2>(Op); for (uint8_t i = 0; i < std::get<1>(Op); ++i) { LogMan::Throw::A(FinalTable[OpNum + i].OpcodeDispatcher == nullptr, "Duplicate Entry"); FinalTable[OpNum + i].OpcodeDispatcher = Dispatcher; if (Dispatcher) ++NumInsts; } } }; [[maybe_unused]] auto CheckTable = [](auto& FinalTable) { for (size_t i = 0; i < FinalTable.size(); ++i) { auto const &Op = FinalTable.at(i); if (Op.Type != X86Tables::TYPE_INST) continue; // Invalid op, we don't care if (Op.OpcodeDispatcher == nullptr) { LogMan::Msg::D("Op: 0x%lx %s didn't have an OpDispatcher", i, Op.Name); } } }; InstallToTable(FEXCore::X86Tables::BaseOps, BaseOpTable); InstallToTable(FEXCore::X86Tables::SecondBaseOps, TwoByteOpTable); InstallToTable(FEXCore::X86Tables::PrimaryInstGroupOps, PrimaryGroupOpTable); InstallToTable(FEXCore::X86Tables::RepModOps, RepModOpTable); InstallToTable(FEXCore::X86Tables::RepNEModOps, RepNEModOpTable); InstallToTable(FEXCore::X86Tables::OpSizeModOps, OpSizeModOpTable); InstallToTable(FEXCore::X86Tables::SecondInstGroupOps, SecondaryExtensionOpTable); InstallToTable(FEXCore::X86Tables::SecondModRMTableOps, SecondaryModRMExtensionOpTable); InstallToTable(FEXCore::X86Tables::X87Ops, X87OpTable); InstallToTable(FEXCore::X86Tables::H0F38TableOps, H0F38Table); InstallToTable(FEXCore::X86Tables::H0F3ATableOps, H0F3ATable); InstallToTable(FEXCore::X86Tables::VEXTableOps, VEXTable); InstallToTable(FEXCore::X86Tables::EVEXTableOps, EVEXTable); // Useful for debugging // CheckTable(FEXCore::X86Tables::BaseOps); printf("We installed %ld instructions to the tables\n", NumInsts); } }
35.868697
262
0.668764
Sonicadvance1
09270f9b813223c4241a18d16d62e89f40aa4004
225
cpp
C++
Lists/ArrayList/main.cpp
coolzoa/Data-Structures
623d0390ad4f5545f1456c3c4b441e37953b95c5
[ "MIT" ]
null
null
null
Lists/ArrayList/main.cpp
coolzoa/Data-Structures
623d0390ad4f5545f1456c3c4b441e37953b95c5
[ "MIT" ]
null
null
null
Lists/ArrayList/main.cpp
coolzoa/Data-Structures
623d0390ad4f5545f1456c3c4b441e37953b95c5
[ "MIT" ]
null
null
null
#include "array.h" int main() { ArrayList<int> list1(10); list1.append(5); list1.insert(7); list1.goToStart(); list1.insert(8); list1.next(); int a = list1.remove(); cout << a; return 0; }
17.307692
29
0.555556
coolzoa
09277a46ea76f561b20269c505d93cdcdc85a7a7
6,443
cc
C++
src/openclx/program.cc
igankevich/openclx
5063635392619eef84e536f24f8252ea41a5ffe6
[ "Unlicense" ]
null
null
null
src/openclx/program.cc
igankevich/openclx
5063635392619eef84e536f24f8252ea41a5ffe6
[ "Unlicense" ]
null
null
null
src/openclx/program.cc
igankevich/openclx
5063635392619eef84e536f24f8252ea41a5ffe6
[ "Unlicense" ]
null
null
null
#include <memory> #include <openclx/array_view> #include <openclx/binary> #include <openclx/bits/macros> #include <openclx/build_status> #include <openclx/context> #include <openclx/device> #include <openclx/downcast> #include <openclx/kernel> #include <openclx/program> void clx::program::build(const std::string& options, const device_array& devices) { CLX_CHECK(::clBuildProgram( this->_ptr, devices.size(), downcast(devices.data()), options.data(), nullptr, nullptr )); } clx::build_status clx::program::build_status(const device& dev) const { CLX_BODY_SCALAR( ::clGetProgramBuildInfo, ::clx::build_status, dev.get(), CL_PROGRAM_BUILD_STATUS ) } #if CL_TARGET_VERSION >= 120 clx::binary_types clx::program::binary_type(const device& dev) const { CLX_BODY_SCALAR( ::clGetProgramBuildInfo, ::clx::binary_types, dev.get(), CL_PROGRAM_BINARY_TYPE ) } #endif #if CL_TARGET_VERSION >= 200 size_t clx::program::size_of_global_variables(const device& dev) const { CLX_BODY_SCALAR( ::clGetProgramBuildInfo, size_t, dev.get(), CL_PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE ) } #endif std::string clx::program::options(const device& dev) const { std::string value(4096, ' '); int_type ret; bool success = false; size_t actual_size = 0; while (!success) { ret = ::clGetProgramBuildInfo( this->_ptr, dev.get(), CL_PROGRAM_BUILD_OPTIONS, sizeof(value), &value, nullptr ); value.resize(actual_size); if (errc(ret) != errc::invalid_value && actual_size <= value.size()) { CLX_CHECK(ret); success = true; } } return value; } std::string clx::program::build_log(const device& dev) const { std::string value(4096, ' '); int_type ret; size_t actual_size = 0; ret = ::clGetProgramBuildInfo( this->_ptr, dev.get(), CL_PROGRAM_BUILD_LOG, 0, nullptr, &actual_size ); CLX_CHECK(ret); value.resize(actual_size); ret = ::clGetProgramBuildInfo( this->_ptr, dev.get(), CL_PROGRAM_BUILD_LOG, value.size(), &value[0], nullptr ); CLX_CHECK(ret); return value; } std::vector<clx::binary> clx::program::binaries() const { unsigned_int_type ndevices = this->num_devices(); std::vector<size_t> sizes(ndevices); CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_BINARY_SIZES, sizes.size()*sizeof(size_t), sizes.data(), nullptr )); static_assert( sizeof(std::unique_ptr<unsigned char>) == sizeof(unsigned char*), "bad size" ); std::vector<std::unique_ptr<unsigned char[]>> binaries; binaries.reserve(ndevices); for (const auto& s : sizes) { binaries.emplace_back(new unsigned char[s]); } CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_BINARIES, binaries.size()*sizeof(unsigned char*), binaries.data(), nullptr )); std::vector<binary> result; result.reserve(ndevices); for (unsigned_int_type i=0; i<ndevices; ++i) { result.emplace_back(binaries[i].get(), sizes[i]); } return result; } #if CL_TARGET_VERSION >= 120 && defined(CLX_HAVE_clCompileProgram) void clx::program::compile( const std::string& options, const header_array& headers, const device_array& devices ) { std::vector<program_type> programs; programs.reserve(headers.size()); std::vector<const char*> names; names.reserve(headers.size()); for (const auto& h : headers) { programs.emplace_back(h.program.get()); names.emplace_back(h.name.data()); } CLX_CHECK(::clCompileProgram( this->_ptr, devices.size(), downcast(devices.data()), options.data(), headers.size(), programs.data(), names.data(), nullptr, nullptr )); } #endif std::vector<clx::kernel> clx::program::kernels() const { std::vector<::clx::kernel> result(4096 / sizeof(::clx::kernel)); int_type ret = 0; bool success = false; unsigned_int_type actual_size = 0; while (!success) { ret = ::clCreateKernelsInProgram( this->_ptr, result.size(), downcast(result.data()), &actual_size ); result.resize(actual_size); if (errc(ret) != errc::invalid_value && actual_size <= result.size()) { CLX_CHECK(ret); success = true; } } return result; } clx::kernel clx::program::kernel(const char* name) const { int_type ret = 0; auto krnl = ::clCreateKernel(this->_ptr, name, &ret); CLX_CHECK(ret); return static_cast<::clx::kernel>(krnl); } CLX_METHOD_SCALAR(clx::program::context, ::clGetProgramInfo, ::clx::context, CL_PROGRAM_CONTEXT) CLX_METHOD_SCALAR(clx::program::num_references, ::clGetProgramInfo, unsigned_int_type, CL_PROGRAM_REFERENCE_COUNT) CLX_METHOD_SCALAR(clx::program::num_devices, ::clGetProgramInfo, unsigned_int_type, CL_PROGRAM_NUM_DEVICES) CLX_METHOD_ARRAY(clx::program::devices, ::clGetProgramInfo, CL_PROGRAM_DEVICES, device) CLX_METHOD_STRING(clx::program::source, ::clGetProgramInfo, CL_PROGRAM_SOURCE) #if CL_TARGET_VERSION >= 210 clx::intermediate_language clx::program::intermediate_language() const { size_t actual_size = 0; CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_IL, 0, nullptr, &actual_size )); ::clx::intermediate_language il(actual_size); CLX_CHECK(::clGetProgramInfo( this->_ptr, CL_PROGRAM_IL, actual_size, il.data(), nullptr )); return il; } #endif #if CL_TARGET_VERSION >= 120 && defined(CLX_HAVE_clLinkProgram) clx::program clx::link( const array_view<program>& programs, const std::string& options, const array_view<device>& devices ) { if (programs.empty()) { throw std::invalid_argument("empty programs"); } int_type ret = 0; auto prog = ::clLinkProgram( programs.front().context().get(), devices.size(), downcast(devices.data()), options.data(), programs.size(), downcast(programs.data()), nullptr, nullptr, &ret ); CLX_CHECK(ret); return static_cast<program>(prog); } #endif
27.185654
114
0.630141
igankevich
092902ce69874dd1af5f469fe42105021bd2cee6
104
hpp
C++
src/io/json.hpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
9
2018-07-12T17:06:33.000Z
2021-11-20T23:13:26.000Z
src/io/json.hpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
119
2016-06-22T07:36:04.000Z
2019-03-10T19:38:12.000Z
src/io/json.hpp
dbeurle/neon
63cd2929a6eaaa0e1654c729cd35a9a52a706962
[ "MIT" ]
9
2017-10-08T16:51:38.000Z
2021-03-15T08:08:04.000Z
#pragma once /// @file #include "nlohmann/json.hpp" namespace neon { using json = nlohmann::json; }
8.666667
28
0.673077
dbeurle
092955dfd86ac62bd508fac2ae6bf3ffa3a3403f
16,091
cpp
C++
QuantumGateLib/Network/Ping.cpp
kareldonk/QuantumGate
c6563b156c628ca0d32534680aa001d4eb820b73
[ "MIT" ]
87
2018-09-01T05:29:22.000Z
2022-03-13T17:44:00.000Z
QuantumGateLib/Network/Ping.cpp
kareldonk/QuantumGate
c6563b156c628ca0d32534680aa001d4eb820b73
[ "MIT" ]
6
2019-01-30T14:48:17.000Z
2022-03-14T21:10:56.000Z
QuantumGateLib/Network/Ping.cpp
kareldonk/QuantumGate
c6563b156c628ca0d32534680aa001d4eb820b73
[ "MIT" ]
16
2018-11-25T23:09:47.000Z
2022-02-01T22:14:11.000Z
// This file is part of the QuantumGate project. For copyright and // licensing information refer to the license file(s) in the project root. #include "pch.h" #include "Ping.h" #include "..\Common\Random.h" #include "..\Common\ScopeGuard.h" #include <Iphlpapi.h> #include <Ipexport.h> #include <icmpapi.h> #include <winternl.h> // for IO_STATUS_BLOCK namespace QuantumGate::Implementation::Network { bool Ping::Execute(const bool use_os_api) noexcept { Reset(); switch (m_DestinationIPAddress.AddressFamily) { case BinaryIPAddress::Family::IPv4: case BinaryIPAddress::Family::IPv6: if (use_os_api) return ExecuteOS(); else return ExecuteRAW(); default: assert(false); break; } LogErr(L"Ping failed due to invalid IP address family"); m_Status = Status::Failed; return false; } bool Ping::ExecuteOS() noexcept { String error; try { LogDbg(L"Pinging %s (Buffer: %u bytes, TTL: %llus, Timeout: %llums)", IPAddress(m_DestinationIPAddress).GetString().c_str(), m_BufferSize, m_TTL.count(), m_Timeout.count()); IPAddr dest_addr4{ 0 }; sockaddr_in6 src_addr6{ 0 }; sockaddr_in6 dest_addr6{ 0 }; Size reply_size{ 0 }; HANDLE icmp_handle{ INVALID_HANDLE_VALUE }; if (m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4) { dest_addr4 = m_DestinationIPAddress.UInt32s[0]; reply_size = sizeof(ICMP_ECHO_REPLY) + m_BufferSize + 8 + sizeof(IO_STATUS_BLOCK); icmp_handle = IcmpCreateFile(); } else { src_addr6.sin6_family = AF_INET6; dest_addr6.sin6_family = AF_INET6; static_assert(sizeof(BinaryIPAddress::Bytes) == sizeof(IPV6_ADDRESS_EX::sin6_addr), "Should be same size"); std::memcpy(&dest_addr6.sin6_addr, &m_DestinationIPAddress.Bytes, sizeof(in6_addr)); reply_size = sizeof(ICMPV6_ECHO_REPLY) + m_BufferSize + 8 + sizeof(IO_STATUS_BLOCK); icmp_handle = Icmp6CreateFile(); } if (icmp_handle != INVALID_HANDLE_VALUE) { // Cleanup when we leave auto sg = MakeScopeGuard([&]() noexcept { IcmpCloseHandle(icmp_handle); }); IP_OPTION_INFORMATION ip_opts{ 0 }; ip_opts.Ttl = static_cast<UCHAR>(m_TTL.count()); auto icmp_data = Random::GetPseudoRandomBytes(m_BufferSize); Buffer reply_buffer(reply_size); const auto num_replies = std::invoke([&]() { if (m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4) { return IcmpSendEcho2( icmp_handle, nullptr, nullptr, nullptr, dest_addr4, icmp_data.GetBytes(), static_cast<WORD>(icmp_data.GetSize()), &ip_opts, reply_buffer.GetBytes(), static_cast<DWORD>(reply_buffer.GetSize()), static_cast<DWORD>(m_Timeout.count())); } else { return Icmp6SendEcho2( icmp_handle, nullptr, nullptr, nullptr, &src_addr6, &dest_addr6, icmp_data.GetBytes(), static_cast<WORD>(icmp_data.GetSize()), &ip_opts, reply_buffer.GetBytes(), static_cast<DWORD>(reply_buffer.GetSize()), static_cast<DWORD>(m_Timeout.count())); } }); if (num_replies != 0) { ULONG status{ 0 }; BinaryIPAddress rip; ULONG rtt{ 0 }; std::optional<ULONG> ttl; if (m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4) { const auto echo_reply = reinterpret_cast<ICMP_ECHO_REPLY*>(reply_buffer.GetBytes()); status = echo_reply->Status; rtt = echo_reply->RoundTripTime; ttl = echo_reply->Options.Ttl; rip.AddressFamily = BinaryIPAddress::Family::IPv4; rip.UInt32s[0] = echo_reply->Address; } else { if (Icmp6ParseReplies(reply_buffer.GetBytes(), static_cast<DWORD>(reply_buffer.GetSize())) == 1) { const auto echo_reply = reinterpret_cast<ICMPV6_ECHO_REPLY*>(reply_buffer.GetBytes()); status = echo_reply->Status; rtt = echo_reply->RoundTripTime; rip.AddressFamily = BinaryIPAddress::Family::IPv6; static_assert(sizeof(BinaryIPAddress::Bytes) == sizeof(IPV6_ADDRESS_EX::sin6_addr), "Should be same size"); std::memcpy(&rip.Bytes, &dest_addr6.sin6_addr, sizeof(IPV6_ADDRESS_EX::sin6_addr)); } else error = L"failed to parse ICMP6 reply"; } switch (status) { case IP_SUCCESS: m_Status = Status::Succeeded; break; case IP_TTL_EXPIRED_TRANSIT: m_Status = Status::TimeToLiveExceeded; break; case IP_DEST_NET_UNREACHABLE: case IP_DEST_HOST_UNREACHABLE: case IP_BAD_DESTINATION: m_Status = Status::DestinationUnreachable; break; case IP_REQ_TIMED_OUT: m_Status = Status::Timedout; default: break; } switch (m_Status) { case Status::Succeeded: case Status::DestinationUnreachable: case Status::TimeToLiveExceeded: if (ttl.has_value()) m_ResponseTTL = std::chrono::seconds(*ttl); m_RespondingIPAddress = rip; m_RoundTripTime = std::chrono::milliseconds(rtt); return true; case Status::Timedout: return true; default: break; } } else { if (GetLastError() == IP_REQ_TIMED_OUT) { m_Status = Status::Timedout; return true; } error = Util::FormatString(L"failed to send ICMP echo request (%s)", GetLastSocketErrorString().c_str()); } } else error = Util::FormatString(L"failed to create ICMP file handle (%s)", GetLastSocketErrorString().c_str()); } catch (...) { error = L"an exception was thrown"; } LogErr(L"Pinging IP address %s failed - %s", IPAddress(m_DestinationIPAddress).GetString().c_str(), error.c_str()); m_Status = Status::Failed; return false; } bool Ping::ExecuteRAW() noexcept { // Currently only supports IPv4. On Windows this does not fully work for // because the OS does not notify the socket of Time Exceeded ICMP // messages. assert(m_DestinationIPAddress.AddressFamily == BinaryIPAddress::Family::IPv4); String error; try { LogDbg(L"Pinging %s (Buffer: %u bytes, TTL: %llus, Timeout: %llums)", IPAddress(m_DestinationIPAddress).GetString().c_str(), m_BufferSize, m_TTL.count(), m_Timeout.count()); ICMP::EchoMessage icmp_hdr; icmp_hdr.Header.Type = static_cast<UInt8>(ICMP::MessageType::Echo); icmp_hdr.Header.Code = 0; icmp_hdr.Header.Checksum = 0; const UInt64 num = Random::GetPseudoRandomNumber(); icmp_hdr.Identifier = static_cast<UInt16>(num); icmp_hdr.SequenceNumber = static_cast<UInt16>(num >> 32); const auto icmp_data = Random::GetPseudoRandomBytes(m_BufferSize); Buffer icmp_msg(reinterpret_cast<Byte*>(&icmp_hdr), sizeof(icmp_hdr)); icmp_msg += icmp_data; reinterpret_cast<ICMP::EchoMessage*>(icmp_msg.GetBytes())->Header.Checksum = ICMP::CalculateChecksum(icmp_msg); Socket socket(IP::AddressFamily::IPv4, Socket::Type::RAW, IP::Protocol::ICMP); if (!socket.SetIPTimeToLive(m_TTL)) return false; if (socket.SendTo(IPEndpoint(m_DestinationIPAddress, 0), icmp_msg) && icmp_msg.IsEmpty()) { const auto snd_steady_time = Util::GetCurrentSteadyTime(); if (socket.UpdateIOStatus(m_Timeout)) { const auto rcv_steady_time = Util::GetCurrentSteadyTime(); if (socket.GetIOStatus().CanRead()) { IPEndpoint endpoint; Buffer data; if (socket.ReceiveFrom(endpoint, data)) { if (data.GetSize() >= sizeof(IP::Header)) { const auto ip_hdr = reinterpret_cast<const IP::Header*>(data.GetBytes()); if (ip_hdr->Protocol == static_cast<UInt8>(IP::Protocol::ICMP)) { const auto ttl = ip_hdr->TTL; const auto msg_type = ProcessICMPReply(data, icmp_hdr.Identifier, icmp_hdr.SequenceNumber, icmp_data); if (msg_type.has_value()) { switch (*msg_type) { case ICMP::MessageType::EchoReply: m_Status = Status::Succeeded; break; case ICMP::MessageType::DestinationUnreachable: m_Status = Status::DestinationUnreachable; break; case ICMP::MessageType::TimeExceeded: m_Status = Status::TimeToLiveExceeded; break; default: assert(false); break; } if (m_Status != Status::Unknown) { m_ResponseTTL = std::chrono::seconds(ttl); m_RespondingIPAddress = endpoint.GetIPAddress().GetBinary(); m_RoundTripTime = std::chrono::duration_cast<std::chrono::milliseconds>(rcv_steady_time - snd_steady_time); return true; } } } error = L"received unrecognized ICMP reply"; } else error = L"not enough data received for IP header"; } else error = L"failed to receive from socket"; } else if (socket.GetIOStatus().HasException()) { error = L"exception on socket (" + GetSysErrorString(socket.GetIOStatus().GetErrorCode()) + L")"; } else { m_Status = Status::Timedout; return true; } } else error = L"failed to update socket state"; } else error = L"failed to send ICMP packet"; } catch (...) { error = L"an exception was thrown"; } LogErr(L"Pinging IP address %s failed - %s", IPAddress(m_DestinationIPAddress).GetString().c_str(), error.c_str()); m_Status = Status::Failed; return false; } std::optional<ICMP::MessageType> Ping::ProcessICMPReply(BufferView buffer, const UInt16 expected_id, const UInt16 expected_sequence_number, const BufferView expected_data) const noexcept { if (buffer.GetSize() >= sizeof(IP::Header) + sizeof(ICMP::Header)) { // Remove IP header buffer.RemoveFirst(sizeof(IP::Header)); auto icmp_hdr = *reinterpret_cast<const ICMP::Header*>(buffer.GetBytes()); switch (static_cast<ICMP::MessageType>(icmp_hdr.Type)) { case ICMP::MessageType::DestinationUnreachable: if (buffer.GetSize() >= (sizeof(ICMP::DestinationUnreachableMessage) + sizeof(IP::Header) + sizeof(ICMP::EchoMessage))) { if (VerifyICMPMessageChecksum(buffer)) { auto du_msg = *reinterpret_cast<const ICMP::DestinationUnreachableMessage*>(buffer.GetBytes()); if (du_msg.Unused == 0) { buffer.RemoveFirst(sizeof(ICMP::DestinationUnreachableMessage)); buffer.RemoveFirst(sizeof(IP::Header)); if (VerifyICMPEchoMessage(buffer, expected_id, expected_sequence_number, expected_data)) { return ICMP::MessageType::DestinationUnreachable; } else LogErr(L"Received ICMP destination unreachable message with invalid original echo message data"); } } } else LogErr(L"Received ICMP destination unreachable message with unexpected size of %zu bytes", buffer.GetSize()); break; case ICMP::MessageType::TimeExceeded: if (buffer.GetSize() >= (sizeof(ICMP::TimeExceededMessage) + sizeof(IP::Header) + sizeof(ICMP::EchoMessage))) { if (VerifyICMPMessageChecksum(buffer)) { auto te_msg = *reinterpret_cast<const ICMP::TimeExceededMessage*>(buffer.GetBytes()); if (te_msg.Unused == 0) { buffer.RemoveFirst(sizeof(ICMP::TimeExceededMessage)); buffer.RemoveFirst(sizeof(IP::Header)); if (VerifyICMPEchoMessage(buffer, expected_id, expected_sequence_number, expected_data)) { return ICMP::MessageType::TimeExceeded; } else LogErr(L"Received ICMP time exceeded message with invalid original echo message data"); } } } else LogErr(L"Received ICMP time exceeded message with unexpected size of %zu bytes", buffer.GetSize()); break; case ICMP::MessageType::EchoReply: if (buffer.GetSize() >= sizeof(ICMP::EchoMessage)) { if (VerifyICMPMessageChecksum(buffer)) { auto echo_msg = *reinterpret_cast<const ICMP::EchoMessage*>(buffer.GetBytes()); if (echo_msg.Header.Code == 0 && echo_msg.Identifier == expected_id && echo_msg.SequenceNumber == expected_sequence_number) { buffer.RemoveFirst(sizeof(ICMP::EchoMessage)); if (buffer == expected_data) { return ICMP::MessageType::EchoReply; } } else LogErr(L"Received ICMP echo reply message with unexpected code, ID or sequence number"); } } else LogErr(L"Received ICMP echo reply message with unexpected size of %zu bytes", buffer.GetSize()); break; default: LogErr(L"Received unrecognized ICMP message type %u", icmp_hdr.Type); break; } } return std::nullopt; } bool Ping::VerifyICMPEchoMessage(BufferView buffer, const UInt16 expected_id, const UInt16 expected_sequence_number, const BufferView expected_data) const noexcept { if (buffer.GetSize() >= sizeof(ICMP::EchoMessage)) { auto echo_msg = *reinterpret_cast<const ICMP::EchoMessage*>(buffer.GetBytes()); if (echo_msg.Identifier == expected_id && echo_msg.SequenceNumber == expected_sequence_number) { buffer.RemoveFirst(sizeof(ICMP::EchoMessage)); auto cmp_size = expected_data.GetSize(); // We'll compare at most the first 64 bits // which are required according to RFC 792 if (cmp_size > 8) cmp_size = 8; if (buffer.GetSize() >= cmp_size) { return (buffer.GetFirst(cmp_size) == expected_data.GetFirst(cmp_size)); } } } return false; } bool Ping::VerifyICMPMessageChecksum(BufferView buffer) const noexcept { try { // We should require at least the basic ICMP header if (buffer.GetSize() >= sizeof(ICMP::Header)) { Buffer chksum_buf{ buffer }; // Reset checksum to zeros before calculating reinterpret_cast<ICMP::Header*>(chksum_buf.GetBytes())->Checksum = 0; if (reinterpret_cast<const ICMP::Header*>(buffer.GetBytes())->Checksum == ICMP::CalculateChecksum(chksum_buf)) return true; LogErr(L"ICMP message checksum failed verification"); } } catch (...) { LogErr(L"Failed to verify ICMP message checksum due to exception"); } return false; } String Ping::GetString() const noexcept { try { String str = Util::FormatString(L"Destination [IP: %s, Timeout: %llums, Buffer size: %u bytes, TTL: %llus]", IPAddress(m_DestinationIPAddress).GetString().c_str(), m_Timeout.count(), m_BufferSize, m_TTL.count()); String rttl_str; if (m_ResponseTTL.has_value()) { rttl_str += Util::FormatString(L", Response TTL: %llus", m_ResponseTTL->count()); } switch (m_Status) { case Status::Succeeded: str += Util::FormatString(L" / Result [Succeeded, Responding IP: %s, Response time: %llums%s]", IPAddress(*m_RespondingIPAddress).GetString().c_str(), m_RoundTripTime->count(), rttl_str.c_str()); break; case Status::TimeToLiveExceeded: str += Util::FormatString(L" / Result [TTL Exceeded, Responding IP: %s, Response time: %llums%s]", IPAddress(*m_RespondingIPAddress).GetString().c_str(), m_RoundTripTime->count(), rttl_str.c_str()); break; case Status::DestinationUnreachable: str += Util::FormatString(L" / Result [Destination unreachable, Responding IP: %s, Response time: %llums%s]", IPAddress(*m_RespondingIPAddress).GetString().c_str(), m_RoundTripTime->count(), rttl_str.c_str()); break; case Status::Timedout: str += L" / Result [Timed out]"; break; case Status::Failed: str += L" / Result [Failed]"; break; default: str += L" / Result [None]"; break; } return str; } catch (...) {} return {}; } std::ostream& operator<<(std::ostream& stream, const Ping& ping) { stream << Util::ToStringA(ping.GetString()); return stream; } std::wostream& operator<<(std::wostream& stream, const Ping& ping) { stream << ping.GetString(); return stream; } }
30.76673
119
0.651544
kareldonk
093679c0163ca70b4454aa3d90b2c27d2225a990
7,384
cpp
C++
FuegoUniversalComponent/fuego/smartgame/SgBoardConst.cpp
GSMgeeth/gameofgo
51563fea15fbdca797afb7cf9a29773a313e5697
[ "Apache-2.0" ]
13
2016-09-09T13:45:42.000Z
2021-12-17T08:42:28.000Z
FuegoUniversalComponent/fuego/smartgame/SgBoardConst.cpp
GSMgeeth/gameofgo
51563fea15fbdca797afb7cf9a29773a313e5697
[ "Apache-2.0" ]
1
2016-06-18T05:19:58.000Z
2016-09-15T18:21:54.000Z
FuegoUniversalComponent/fuego/smartgame/SgBoardConst.cpp
cbordeman/gameofgo
51563fea15fbdca797afb7cf9a29773a313e5697
[ "Apache-2.0" ]
5
2016-11-19T03:05:12.000Z
2022-01-31T12:20:40.000Z
//---------------------------------------------------------------------------- /** @file SgBoardConst.cpp See SgBoardConst.h */ //---------------------------------------------------------------------------- #include "SgSystem.h" #include "SgBoardConst.h" #include <algorithm> #include "SgInit.h" #include "SgStack.h" using namespace std; using SgPointUtil::Pt; //---------------------------------------------------------------------------- SgBoardConst::BoardConstImpl::BoardConstImpl(SgGrid size) : m_size(size), m_firstBoardPoint(Pt(1, 1)), m_lastBoardPoint(Pt(size, size)) { m_gridToLine.Fill(0); m_gridToPos.Fill(0); m_up.Fill(0); for (SgGrid line = 0; line <= SG_MAX_SIZE / 2; ++line) m_line[line].Clear(); // Set up values for points on the board. m_boardIterEnd = m_boardIter; SgGrid halfSize = (m_size + 1) / 2; for (SgGrid row = 1; row <= m_size; ++row) { for (SgGrid col = 1; col <= m_size; ++col) { SgPoint p = Pt(col, row); SgGrid lineRow = row > halfSize ? m_size + 1 - row : row; SgGrid lineCol = col > halfSize ? m_size + 1 - col : col; SgGrid line = min(lineRow, lineCol); SgGrid pos = max(lineRow, lineCol); m_gridToLine[p] = line; m_gridToPos[p] = pos; m_line[line - 1].Include(p); const int MAX_EDGE = m_size > 11 ? 4 : 3; if (line <= MAX_EDGE) { if (pos <= MAX_EDGE + 1) m_corners.Include(p); else m_edges.Include(p); } else m_centers.Include(p); int nuNb = 0; if (row > 1) m_neighbors[p][nuNb++] = Pt(col, row - 1); if (col > 1) m_neighbors[p][nuNb++] = Pt(col - 1, row); if (col < m_size) m_neighbors[p][nuNb++] = Pt(col + 1, row); if (row < m_size) m_neighbors[p][nuNb++] = Pt(col, row + 1); m_neighbors[p][nuNb] = SG_ENDPOINT; *(m_boardIterEnd++) = p; } } // Set up direction to point on line above. for (SgPoint p = 0; p < SG_MAXPOINT; ++p) { if (m_gridToLine[p] != 0) { SgGrid line = m_gridToLine[p]; if (m_gridToLine[p - SG_NS] == line + 1) m_up[p] = -SG_NS; if (m_gridToLine[p - SG_WE] == line + 1) m_up[p] = -SG_WE; if (m_gridToLine[p + SG_WE] == line + 1) m_up[p] = SG_WE; if (m_gridToLine[p + SG_NS] == line + 1) m_up[p] = SG_NS; // If no line above vertically or horizontally, try diagonally. if (m_up[p] == 0) { if (m_gridToLine[p - SG_NS - SG_WE] == line + 1) m_up[p] = -SG_NS - SG_WE; if (m_gridToLine[p - SG_NS + SG_WE] == line + 1) m_up[p] = -SG_NS + SG_WE; if (m_gridToLine[p + SG_NS - SG_WE] == line + 1) m_up[p] = SG_NS - SG_WE; if (m_gridToLine[p + SG_NS + SG_WE] == line + 1) m_up[p] = SG_NS + SG_WE; } } } // Set up direction to the sides, based on Up. Always list clockwise // direction first. { for (int i = 0; i <= 2 * (SG_NS + SG_WE); ++i) { m_side[0][i] = 0; m_side[1][i] = 0; } // When Up is towards center, sides are orthogonal to Up. m_side[0][-SG_NS + (SG_NS + SG_WE)] = -SG_WE; m_side[1][-SG_NS + (SG_NS + SG_WE)] = +SG_WE; m_side[0][-SG_WE + (SG_NS + SG_WE)] = +SG_NS; m_side[1][-SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[0][+SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[1][+SG_WE + (SG_NS + SG_WE)] = +SG_NS; m_side[0][+SG_NS + (SG_NS + SG_WE)] = +SG_WE; m_side[1][+SG_NS + (SG_NS + SG_WE)] = -SG_WE; // When Up is diagonal, sides are along different sides of board. m_side[0][-SG_NS - SG_WE + (SG_NS + SG_WE)] = -SG_WE; m_side[1][-SG_NS - SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[0][-SG_NS + SG_WE + (SG_NS + SG_WE)] = -SG_NS; m_side[1][-SG_NS + SG_WE + (SG_NS + SG_WE)] = +SG_WE; m_side[0][+SG_NS - SG_WE + (SG_NS + SG_WE)] = +SG_NS; m_side[1][+SG_NS - SG_WE + (SG_NS + SG_WE)] = -SG_WE; m_side[0][+SG_NS + SG_WE + (SG_NS + SG_WE)] = +SG_WE; m_side[1][+SG_NS + SG_WE + (SG_NS + SG_WE)] = +SG_NS; } // Terminate board iterator. *m_boardIterEnd = SG_ENDPOINT; // Set up line iterators. { int lineIndex = 0; for (SgGrid line = 1; line <= (SG_MAX_SIZE / 2) + 1; ++line) { m_lineIterAddress[line - 1] = &m_lineIter[lineIndex]; for (SgPoint p = m_firstBoardPoint; p <= m_lastBoardPoint; ++p) { if (m_gridToLine[p] == line) m_lineIter[lineIndex++] = p; } m_lineIter[lineIndex++] = SG_ENDPOINT; ////SG_ASSERT(lineIndex //<= SG_MAX_SIZE * SG_MAX_SIZE + (SG_MAX_SIZE / 2) + 1); } ////SG_ASSERT(lineIndex == m_size * m_size + (SG_MAX_SIZE / 2) + 1); } // Set up corner iterator. m_cornerIter[0] = Pt(1, 1); m_cornerIter[1] = Pt(m_size, 1); m_cornerIter[2] = Pt(1, m_size); m_cornerIter[3] = Pt(m_size, m_size); m_cornerIter[4] = SG_ENDPOINT; m_sideExtensions = m_line[2 - 1] | m_line[3 - 1] | m_line[4 - 1]; // LineSet(line) == m_line[line - 1], see .h // exclude diagonals, so that different sides from corner are in different // sets. m_sideExtensions.Exclude(Pt(2, 2)); m_sideExtensions.Exclude(Pt(2, m_size + 1 - 2)); m_sideExtensions.Exclude(Pt(m_size + 1 - 2, 2)); m_sideExtensions.Exclude(Pt(m_size + 1 - 2, m_size + 1 - 2)); if (m_size > 2) { m_sideExtensions.Exclude(Pt(3, 3)); m_sideExtensions.Exclude(Pt(3, m_size + 1 - 3)); m_sideExtensions.Exclude(Pt(m_size + 1 - 3, 3)); m_sideExtensions.Exclude(Pt(m_size + 1 - 3, m_size + 1 - 3)); if (m_size > 3) { m_sideExtensions.Exclude(Pt(4, 4)); m_sideExtensions.Exclude(Pt(4, m_size + 1 - 4)); m_sideExtensions.Exclude(Pt(m_size + 1 - 4, 4)); m_sideExtensions.Exclude(Pt(m_size + 1 - 4, m_size + 1 - 4)); } } } //---------------------------------------------------------------------------- SgBoardConst::BoardConstImplArray SgBoardConst::s_const; void SgBoardConst::Create(SgGrid size) { //SG_ASSERT_GRIDRANGE(size); if (! s_const[size]) s_const[size] = boost::shared_ptr<BoardConstImpl>(new BoardConstImpl(size)); m_const = s_const[size]; ////SG_ASSERT(m_const); } SgBoardConst::SgBoardConst(SgGrid size) { //SG_ASSERT_GRIDRANGE(size); SgInitCheck(); Create(size); } void SgBoardConst::ChangeSize(SgGrid newSize) { //SG_ASSERT_GRIDRANGE(newSize); ////SG_ASSERT(m_const); // Don't do anything if called with same size. SgGrid oldSize = m_const->m_size; if (newSize != oldSize) Create(newSize); } //----------------------------------------------------------------------------
34.666667
78
0.49052
GSMgeeth
093814bc4494041809d6e82965519e38a8997f49
5,551
cc
C++
tensorflow/contrib/lite/kernels/transpose.cc
tsesarrizqi/tflite2
f48c1868e5f64f5fcdd1939a54cfad28a84be2b0
[ "Apache-2.0" ]
24
2018-02-01T15:49:22.000Z
2021-01-11T16:31:18.000Z
tensorflow/contrib/lite/kernels/transpose.cc
tsesarrizqi/tflite2
f48c1868e5f64f5fcdd1939a54cfad28a84be2b0
[ "Apache-2.0" ]
2
2018-09-09T07:29:07.000Z
2019-03-11T07:14:45.000Z
tensorflow/contrib/lite/kernels/transpose.cc
tsesarrizqi/tflite2
f48c1868e5f64f5fcdd1939a54cfad28a84be2b0
[ "Apache-2.0" ]
4
2018-10-29T18:43:22.000Z
2020-09-28T07:19:52.000Z
/* Copyright 2017 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 <string.h> #include <vector> #include "tensorflow/contrib/lite/builtin_op_data.h" #include "tensorflow/contrib/lite/context.h" #include "tensorflow/contrib/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/contrib/lite/kernels/internal/tensor.h" #include "tensorflow/contrib/lite/kernels/kernel_util.h" #include "tensorflow/contrib/lite/kernels/op_macros.h" namespace tflite { namespace ops { namespace builtin { namespace transpose { // This file has two implementations of Transpose. enum KernelType { kReference, }; struct TransposeContext { TransposeContext(TfLiteContext* context, TfLiteNode* node) { input = GetInput(context, node, 0); perm = GetInput(context, node, 1); output = GetOutput(context, node, 0); } TfLiteTensor* input; TfLiteTensor* perm; TfLiteTensor* output; }; TfLiteStatus ResizeOutputTensor(TfLiteContext* context, TransposeContext* op_context) { int dims = NumDimensions(op_context->input); const int* perm_data = GetTensorData<int32_t>(op_context->perm); // Ensure validity of the permutations tensor as a 1D tensor. TF_LITE_ENSURE_EQ(context, NumDimensions(op_context->perm), 1); TF_LITE_ENSURE_EQ(context, op_context->perm->dims->data[0], dims); for (int idx = 0; idx < dims; ++idx) { TF_LITE_ENSURE_MSG(context, (perm_data[idx] >= 0 && perm_data[idx] < dims), "Transpose op permutations array is out of bounds."); } // Determine size of output tensor. TfLiteIntArray* input_size = op_context->input->dims; TfLiteIntArray* output_size = TfLiteIntArrayCopy(input_size); for (int idx = 0; idx < dims; ++idx) { output_size->data[idx] = input_size->data[perm_data[idx]]; } return context->ResizeTensor(context, op_context->output, output_size); } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TransposeContext op_context(context, node); // Ensure validity of input tensor. TF_LITE_ENSURE_MSG(context, NumDimensions(op_context.input) <= 4, "Transpose op only supports 1D-4D input arrays."); TF_LITE_ENSURE_EQ(context, op_context.input->type, op_context.output->type); if (!IsConstantTensor(op_context.perm)) { SetTensorToDynamic(op_context.output); return kTfLiteOk; } return ResizeOutputTensor(context, &op_context); } template <KernelType kernel_type> TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { TransposeContext op_context(context, node); // Resize the output tensor if the output tensor is dynamic. if (IsDynamicTensor(op_context.output)) { TF_LITE_ENSURE_OK(context, ResizeOutputTensor(context, &op_context)); TfLiteTensorRealloc(op_context.output->bytes, op_context.output); } // Reverse the permuted axes and convert to 4D due to the way Dims are // constructed in GetTensorDims. const int* perm_data = GetTensorData<int32_t>(op_context.perm); const int size = op_context.perm->dims->data[0]; const int kOutputDimensionNum = 4; int reversed_perm[kOutputDimensionNum]; for (int output_k = 0, input_k = size - 1; output_k < size; ++output_k, --input_k) { reversed_perm[output_k] = size - perm_data[input_k] - 1; } for (int k = size; k < kOutputDimensionNum; ++k) { reversed_perm[k] = k; } #define TF_LITE_TRANSPOSE(type, scalar) \ type::Transpose(GetTensorData<scalar>(op_context.input), \ GetTensorDims(op_context.input), \ GetTensorData<scalar>(op_context.output), \ GetTensorDims(op_context.output), reversed_perm) switch (op_context.input->type) { case kTfLiteFloat32: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, float); } break; case kTfLiteUInt8: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, uint8_t); } break; case kTfLiteInt32: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, int32_t); } break; case kTfLiteInt64: if (kernel_type == kReference) { TF_LITE_TRANSPOSE(reference_ops, int64_t); } break; default: context->ReportError(context, "Type is currently not supported by Transpose."); return kTfLiteError; } #undef TF_LITE_TRANSPOSE return kTfLiteOk; } } // namespace transpose TfLiteRegistration* Register_TRANSPOSE_REF() { static TfLiteRegistration r = {nullptr, nullptr, transpose::Prepare, transpose::Eval<transpose::kReference>}; return &r; } TfLiteRegistration* Register_TRANSPOSE() { return Register_TRANSPOSE_REF(); } } // namespace builtin } // namespace ops } // namespace tflite
34.478261
80
0.693749
tsesarrizqi
093a8113eada610132a5d1abe25441eaac183cf0
891
cpp
C++
Codeforces/1093B - Letters Rearranging.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1093B - Letters Rearranging.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1093B - Letters Rearranging.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> using namespace std; bool is_palindrome(string s) { string temp = s; reverse(s.begin(), s.end()); if (temp == s) return true; else return false; } int main() { int t; cin >> t; while(t--) { string s; cin >> s; if ( is_palindrome(s) ) { bool found = false; [&](){ for (int j = 0; j < s.length() - 1; ++j) { char temp = s[j]; s[j] = s[j + 1]; s[j + 1] = temp; if ( !is_palindrome(s) ) { found = true; return; } } }(); if (found) cout << s << endl; else cout << -1 << endl; } else cout << s << endl; } return 0; }
21.731707
58
0.367003
naimulcsx
093c540701ca29415d0edf36b480f5f1b6e5952f
1,764
cpp
C++
src/system.cpp
SusannaMaria/CppND-System-Monitor-Project-Updated
a07c51465107c38c51fb7ee12122b87068d9c7e0
[ "MIT" ]
null
null
null
src/system.cpp
SusannaMaria/CppND-System-Monitor-Project-Updated
a07c51465107c38c51fb7ee12122b87068d9c7e0
[ "MIT" ]
null
null
null
src/system.cpp
SusannaMaria/CppND-System-Monitor-Project-Updated
a07c51465107c38c51fb7ee12122b87068d9c7e0
[ "MIT" ]
null
null
null
/** * @file system.cpp * @author Susanna Maria, David Silver * @brief system handling impletionments * @version 1.0 * @date 2020-06-21 * * @copyright MIT License * */ #include "system.h" #include <unistd.h> #include <cstddef> #include <iostream> #include <set> #include <string> #include <vector> #include "linux_parser.h" #include "process.h" #include "process_container.h" #include "processor.h" using LinuxParser::ProcessStates; using std::set; using std::size_t; using std::string; using std::vector; /** * Return the system's CPU * * @return Processor& */ Processor& System::Cpu() { return cpu_; } /** * Return a container composed of the system's processes * * @return vector<Process>& */ vector<Process>& System::Processes() { return process_container_.Processes(); } /** * Return the system's kernel identifier (string) * * @return std::string */ std::string System::Kernel() const { return LinuxParser::Kernel(); } /** * Return the system's memory utilization * * @return float */ float System::MemoryUtilization() const { return LinuxParser::MemoryUtilization(); } /** * Return the operating system name * * @return std::string */ std::string System::OperatingSystem() const { return LinuxParser::OperatingSystem(); } /** * Return the number of processes actively running on the system * * @return int */ int System::RunningProcesses() const { return LinuxParser::RunningProcesses(); } /** * Return the total number of processes on the system * * @return int */ int System::TotalProcesses() const { return LinuxParser::TotalProcesses(); } /** * Return the number of seconds since the system started running * * @return long int */ long int System::UpTime() const { return LinuxParser::UpTime(); }
19.384615
80
0.693311
SusannaMaria
093e9ad8fcb60d97b9eca2301ed0150467597ca7
6,579
hpp
C++
lib/stub/s2sFunction.hpp
youelebr/assist
9ccf862bf3350009fe9e42fbe45eecc7858a49dc
[ "BSD-2-Clause" ]
1
2019-05-23T08:57:09.000Z
2019-05-23T08:57:09.000Z
lib/stub/s2sFunction.hpp
youelebr/assist
9ccf862bf3350009fe9e42fbe45eecc7858a49dc
[ "BSD-2-Clause" ]
null
null
null
lib/stub/s2sFunction.hpp
youelebr/assist
9ccf862bf3350009fe9e42fbe45eecc7858a49dc
[ "BSD-2-Clause" ]
null
null
null
#ifndef S2SFUNC #define S2SFUNC #include "rose.h" #include "s2sDefines.hpp" #include "api.hpp" #include <sstream> #include <string> #include <iostream> #include <vector> //int MAQAO_DEBUG_LEVEL=0; static int identifierFunctions=0; class ASTFunction; class Function; struct variable_spe; /** * ASTFunction class : * Represent the top of the tree * A tree root is the global scope of a file and all nodes are functions definitions */ class ASTFunction { protected: // size_t id; // to match with maqao id function // std::string name; // Name of the function SgGlobal* root; // Represent a node above the subtree of functions (it should be a SgNode*) std::vector<Function*> internalFunctionsList; // Vector which contain list of all functions of the file public: //Constructor ASTFunction(SgSourceFile*); ASTFunction(SgBasicBlock*); ASTFunction(SgGlobal* root); //Destructor ~ASTFunction(); //Accessors std::vector<Function*> get_internalFunctionsList(); void set_internalFunctionsList(std::vector<Function*> ); //Miscellaneous /** * Print functions which are marks as not found * Essentially use to compare which functions match with binary loops */ void printASTLines(); /** * Print functions which marks as not found * Essentially use to compare which functions match with binary functions */ void print_function_not_found(); /** * Print information about all functions of the subtree, * only print information about all functions in the file. */ void print(); /** * Print all functions names of the file where they're comme from. */ void print_names(); /** * Search into the global tree a function near of the start/end lines * * @param start - Line where the function start * @param end - Line where the function end * @return - Pointer on a Function which correspond to the lines */ Function* get_function_from_line(int start,int end=-1); /** * Search into the global tree a function with the name name * * @param name - The name of the function * @return - Pointer on a Function which correspond to the name */ Function* get_func_from_name(std::string name); /** * Search into the global tree which function contains a maqao directive and apply it */ void apply_directive(); /** * Return true if the gloabl tree is empty * @return - Return true if the gloabl scope doesn't have any function definition */ bool empty(); }; /** * Function class: * represent a function definition with its body and original body (before any transformation), its pointer on the Rose representation of the Function definition, the type of the function and its id. * */ class Function { public: enum functionType_ { SUBROUTINE, FUNCTION, UNKNOWN }; // Enum to represent the function type protected: size_t id; // Used to match with maqao id function, by default functions' id are set from 1 to n to the order of reading the source code SgFunctionDefinition * function; // Rose function SgBasicBlock * body_without_trans; functionType_ typeOfFunction; // The function type bool is_matching; // Only for internal used public: //CONSTRUCTOR Function(SgFunctionDefinition* f); ~Function(); //ACCESSORS SgFunctionDefinition* get_function(); SgFunctionDefinition* get_function() const; void set_function(SgFunctionDefinition* f); size_t get_id(); size_t get_id() const; void set_id(size_t ID); std::string get_name() const; std::string get_file_name() const; functionType_ get_functionType(); functionType_ get_functionType() const; void set_functionType(Function::functionType_); void set_functionType(std::string functionKeyword); int get_line_start(); int get_line_end(); /** * Return true or false if the function was already meets the binary function conrresponding or not. * @return Return true if the function was already meets the binary function conrresponding */ bool is_matching_with_bin_loop(); void set_matching_with_bin_loop(bool); //Prints /** * Print the type of the function (Fortran do; C/C++ "for" ; while ; etc) */ std::string print_functionType(); void print_statement_class(); /** * Print the function begining and ending lines. */ void printLines(); /** * Print information about the function */ void print(); /** * Print functions which marks as not found * Essentially use to compare which functions match with binary functions */ void print_function_not_found(); //miscellaneous /** * Attach a directive to the function * * @param s - string containing the directive line without the "!DIR$" */ void add_directive(std::string s); /** * Look for all maqao directive, * then apply transformations requested. */ bool apply_directive(); bool apply_directive(std::string dirctive); // void apply_directive2(); /** * Sepcialize a function for a special value, * this value can be specified explicitly than equals to a fix value. * Or it's possible to indicate what it's its limits, * for example, it's possible to indicate than a variable is < to 3 or is between {2,10} * * This function will analyze vectors of variable_spe and will create special function with there indications */ void specialize(std::vector<variable_spe*> var, bool create_call); // /!\ Deprecated void specialize_v2(std::vector<variable_spe*> var, bool create_call); /** * Add the call to the function of our library to modify prefect guided by a configuration define in the string s. * String s : The configuration name for prefetch. */ bool modify_prefetch(std::string s); }; /** * Build a conditionnal of a if stmt */ SgExprStatement* build_if_cond(variable_spe* var, SgSymbol* v_symbol, SgScopeStatement* function); /** * Continue to build the conditionnal of the if stmt */ SgExprStatement* build_if_cond_from_ifcond(variable_spe* var, SgSymbol* v_symbol, SgScopeStatement* function, SgExprStatement* ifcond); /** * Return a pointer on function corresponding to the function at line lstart */ Function* get_function_from_line(ASTFunction* ast, int lstart, int lend = -1, int delta=0); #endif
32.25
164
0.680955
youelebr
0945bb1a48c0fdb819800dd3801d9e3b8a1453c8
1,159
cc
C++
complejo/src/complejo.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97
d1dbcfb1ea8e478b869c10ae718cada45155a8ae
[ "MIT" ]
null
null
null
complejo/src/complejo.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97
d1dbcfb1ea8e478b869c10ae718cada45155a8ae
[ "MIT" ]
null
null
null
complejo/src/complejo.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Marcant97
d1dbcfb1ea8e478b869c10ae718cada45155a8ae
[ "MIT" ]
null
null
null
#include <iostream> #include "complejo.h" complejo::complejo(double real, double imaginario){ //Constructor por defecto parte_real = real; parte_imaginaria = imaginario; } void complejo::print(){ //Función print complejo std::cout<<"Su número complejo es: "<<parte_real<<"+"<<parte_imaginaria<<"i"<<std::endl; } double complejo::suma(double real, double imaginario, double real1, double imaginario1){ //Función suma de 2 complejos parte_real = (real+real1); parte_imaginaria = (imaginario+imaginario1); std::cout<<"La suma de sus 2 números complejos es: "<<parte_real<<"+"<<parte_imaginaria<<"i"<<std::endl; } double complejo::resta(double real, double imaginario, double real1, double imaginario1){ //Función resta de 2 complejos parte_real = (real-real1); parte_imaginaria = (imaginario-imaginario1); if (parte_imaginaria >= 0){ std::cout<<"La resta de sus 2 números complejos es: "<<parte_real<<"+"<<parte_imaginaria<<"i"<<std::endl; } if (parte_imaginaria < 0){ std::cout<<"La resta de sus 2 números complejos es: "<<parte_real<<"+("<<parte_imaginaria<<")i"<<std::endl; } }
42.925926
122
0.679034
ULL-ESIT-IB-2020-2021
094974e1b7d804aa5eddef344cbe678d854ef481
890
hpp
C++
include/tex/dds_reader.hpp
magicmoremagic/bengine-texi
e7a6f476ccb85262db8958e39674bc9570956bbe
[ "MIT" ]
null
null
null
include/tex/dds_reader.hpp
magicmoremagic/bengine-texi
e7a6f476ccb85262db8958e39674bc9570956bbe
[ "MIT" ]
null
null
null
include/tex/dds_reader.hpp
magicmoremagic/bengine-texi
e7a6f476ccb85262db8958e39674bc9570956bbe
[ "MIT" ]
1
2022-02-19T08:08:21.000Z
2022-02-19T08:08:21.000Z
#pragma once #ifndef BE_GFX_TEX_DDS_READER_HPP_ #define BE_GFX_TEX_DDS_READER_HPP_ #include "default_texture_reader.hpp" #include "betx_payload_compression_mode.hpp" #include <be/core/logging.hpp> namespace be::gfx::tex { /////////////////////////////////////////////////////////////////////////////// bool is_dds(const Buf<const UC>& buf) noexcept; /////////////////////////////////////////////////////////////////////////////// class DdsReader final : public detail::DefaultTextureReader { public: DdsReader(bool strict = false, Log& log = default_log()); private: TextureFileFormat format_impl_() noexcept final; TextureFileInfo info_impl_(std::error_code& ec) noexcept final; Texture texture_(std::error_code& ec) noexcept final; Image image_(std::error_code& ec, std::size_t layer, std::size_t face, std::size_t level) noexcept final; }; } // be::gfx::tex #endif
30.689655
108
0.625843
magicmoremagic
094b339ddf9ab1ed589f5f6a731f557c9f64f6c9
2,834
cpp
C++
projects/lab3/code/lab3.cpp
MTBorg/D7045E
f4db7e066335facffbdc70efa9a47461792354b9
[ "MIT" ]
null
null
null
projects/lab3/code/lab3.cpp
MTBorg/D7045E
f4db7e066335facffbdc70efa9a47461792354b9
[ "MIT" ]
null
null
null
projects/lab3/code/lab3.cpp
MTBorg/D7045E
f4db7e066335facffbdc70efa9a47461792354b9
[ "MIT" ]
null
null
null
#include "lab3.h" #include "config.h" #include "cube.h" #include "graphics_node.h" #include "mesh.h" #include "monochrome_material.h" #include "types.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <iostream> using namespace Display; Lab3::Lab3() {} Lab3::~Lab3() {} const float32 movingDistance = 0.05f; const float32 rotationAngle = 5.0f; unsigned int currentObject = 0; bool Lab3::Open() { App::Open(); this->window = new Display::Window; window->SetKeyPressFunction([this](int32 keyCode, int32, int32 action, int32) { switch (keyCode) { case GLFW_KEY_1: case GLFW_KEY_2: case GLFW_KEY_3: currentObject = keyCode - GLFW_KEY_1; break; case GLFW_KEY_W: this->objects[currentObject].translate(glm::vec3(0, 0, -movingDistance)); break; case GLFW_KEY_A: this->objects[currentObject].translate(glm::vec3(-movingDistance, 0, 0)); break; case GLFW_KEY_S: this->objects[currentObject].translate(glm::vec3(0, 0, movingDistance)); break; case GLFW_KEY_D: this->objects[currentObject].translate(glm::vec3(movingDistance, 0, 0)); break; case GLFW_KEY_E: this->objects[currentObject].translate(glm::vec3(0, movingDistance, 0)); break; case GLFW_KEY_Q: this->objects[currentObject].translate(glm::vec3(0, -movingDistance, 0)); break; case GLFW_KEY_I: this->objects[currentObject].rotate(-rotationAngle, glm::vec3(1, 0, 0)); break; case GLFW_KEY_J: this->objects[currentObject].rotate(-rotationAngle, glm::vec3(0, 1, 0)); break; case GLFW_KEY_K: this->objects[currentObject].rotate(rotationAngle, glm::vec3(1, 0, 0)); break; case GLFW_KEY_L: this->objects[currentObject].rotate(rotationAngle, glm::vec3(0, 1, 0)); break; case GLFW_KEY_U: this->objects[currentObject].rotate(rotationAngle, glm::vec3(0, 0, 1)); break; case GLFW_KEY_O: this->objects[currentObject].rotate(-rotationAngle, glm::vec3(0, 0, 1)); break; case GLFW_KEY_ESCAPE: this->window->Close(); default: break; } }); if (this->window->Open()) { // set clear color to gray glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glEnable(GL_DEPTH_TEST); this->objects = std::vector<GraphicsNode>{ createCube(glm::vec3(0), RGBA(1, 0, 0, 1)), createCube(glm::vec3(1.0f, -1.0f, -2.0f), RGBA(0, 1, 0, 1)), createCube(glm::vec3(-4.0f, 2.0f, -8.0f), RGBA(0, 0, 1, 1))}; return true; } return false; } void Lab3::Run() { while (this->window->IsOpen()) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); this->window->Update(); for (const auto &object : objects) { object.draw(); } this->window->SwapBuffers(); } }
27.25
79
0.628088
MTBorg
094bb1a34a8c78c867686a7674324aef4ffe0caa
13,564
cpp
C++
test/MainWindow.cpp
benjamin-fukdawurld/FDQUI
95ecc0ebd1ca2ba38865974035bbe7fd1486e16f
[ "Apache-2.0" ]
null
null
null
test/MainWindow.cpp
benjamin-fukdawurld/FDQUI
95ecc0ebd1ca2ba38865974035bbe7fd1486e16f
[ "Apache-2.0" ]
null
null
null
test/MainWindow.cpp
benjamin-fukdawurld/FDQUI
95ecc0ebd1ca2ba38865974035bbe7fd1486e16f
[ "Apache-2.0" ]
null
null
null
#include <MainWindow.h> #include <FDCore/FileUtils.h> #include <FDQUI/GUI/OpenGLApplication.h> #include <FDQUI/GUI/View/TransformDelegate.h> #include <FDQUI/GUI/Widget/VectorWidget.h> #include <FDQUI/Model/TransformModel.h> #include <QOpenGLTexture> #include <QDockWidget> #include <QTimer> #include <QTreeView> #include <QVBoxLayout> #include <QHBoxLayout> #include <qlogging.h> /* void FDQUI::OpenGLWidget::paintGL() { m_timeMgr.start(); m_program = createShaderProgram(); m_tex = loadTexture("../../FDGL/test/resources/wall.jpg"); m_program.bind(); FD3D::Projection &proj = m_cam.projection; proj.setFov(glm::radians(45.0f)); proj.setWidth(getWidth()); proj.setHeight(getHeight()); proj.setNear(0.1f); proj.setFar(100.0f); proj.setType(FD3D::ProjectionType::Perspective); glClear(getClearMask()); if(m_renderStrategy) m_renderStrategy(*this); FD3D::Transform m_transform; std::vector<FD3D::Mesh*> meshes = m_scene.getComponentsAs<FD3D::Mesh>(); FD3D::Projection &proj = m_cam.projection; // bind textures on corresponding texture units m_tex.activateTexture(0); m_tex.bind(FDGL::TextureTarget::Texture2D); double t2 = 0; float radius = 10.0f; float camX = sin(t2) * radius; float camZ = cos(t2) * radius; m_cam.setPosition(glm::vec3(camX, 0.0f, camZ)); m_cam.setRotation(glm::vec3(0.0f, t2, 0.0f)); // activate shader m_program.bind(); m_program.setUniform("texture", 0); m_program.setUniform(1, m_cam.getMatrix()); m_program.setUniform(2, proj.getMatrix()); m_program.setUniform(0, m_transform.getMatrix()); m_vao.bind(); FDGL::drawElements<uint32_t>(FDGL::DrawMode::Triangles, meshes[0]->getNumberOfIndices(), nullptr); if (!qApp->loadOpenGLFunctions(qApp->getProcAddressFunc())) { qFatal("failed to load OpenGl functions"); qApp->exit(-1); } qApp->enableDepth(); qApp->enableFaceCulling(); qApp->enable(GL_DEBUG_OUTPUT); glDebugMessageCallback(MessageCallback, nullptr); setClearColor(glm::vec4(0.2f, 0.3f, 0.3f, 1.0f)); setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_timeMgr.start(); FD3D::SceneLoader loader; loader.setTextureLoader([](const std::string &path){ return loadTexture(path); }); loader.setEmbeddedTextureLoader([](const aiTexture *texture){ return loadTexture(texture); }); assert(loader.loadScene(m_scene, "../../FDGL/test/resources/crate/CrateModel.obj", aiProcess_Triangulate )); std::vector<FD3D::Mesh*> meshes = m_scene.getComponentsAs<FD3D::Mesh>(); std::vector<FD3D::Material*> mat = m_scene.getComponentsAs<FD3D::Material>(); m_program = createShaderProgram(); m_tex = loadTexture("../../FDGL/test/resources/wall.jpg"); m_vbo.create(); m_vbo.bind(FDGL::BufferTarget::VertexAttribute); m_vbo.allocate(sizeof(float) * meshes[0]->getNumberOfVertices() * meshes[0]->getVertexSize(), FDGL::BufferUsage::StaticDraw, meshes[0]->getVertices()); m_ebo.create(); m_ebo.bind(FDGL::BufferTarget::VertexIndex); m_ebo.allocate(sizeof(uint32_t) * meshes[0]->getNumberOfIndices(), FDGL::BufferUsage::StaticDraw, meshes[0]->getIndices()); m_vao.create(); m_vao.setFunction([](FDGL::OpenGLBuffer &vbo, FDGL::OpenGLBuffer &ebo, FD3D::AbstractMesh &m) { vbo.bind(FDGL::BufferTarget::VertexAttribute); ebo.bind(FDGL::BufferTarget::VertexIndex); size_t s = m.getStride() * sizeof(float); FDGL::setAttribFromBuffer<GL_FLOAT, 3, false>(0, s, static_cast<size_t>(m.getComponentOffset(FD3D::VertexComponentType::Position)) * sizeof(float)); FDGL::enableAttrib(0); FDGL::setAttribFromBuffer<GL_FLOAT, 3, false>(1, s, static_cast<size_t>(m.getComponentOffset(FD3D::VertexComponentType::Normal)) * sizeof(float)); FDGL::enableAttrib(1); FDGL::setAttribFromBuffer<GL_FLOAT, 2, false>(2, s, static_cast<size_t>(m.getComponentOffset(FD3D::VertexComponentType::Texture)) * sizeof(float)); FDGL::enableAttrib(2); }, std::ref(m_vbo), std::ref(m_ebo), std::ref(*meshes.front())); m_program.bind(); FD3D::Projection &proj = m_cam.projection; proj.setFov(glm::radians(45.0f)); proj.setWidth(getWidth()); proj.setHeight(getHeight()); proj.setNear(0.1f); proj.setFar(100.0f); proj.setType(FD3D::ProjectionType::Perspective); }*/ using namespace std; /*static FDGL::OpenGLShaderProgramWrapper createShaderProgram() { FDGL::OpenGLShaderProgramWrapper program; FDGL::OpenGLShader v_shad; v_shad.create(FDGL::ShaderType::Vertex); v_shad.setSource(std::string(FDCore::readFile("../../FDGL/test/resources/vertex.vert").get())); if(!v_shad.compile()) { std::string msg = "Cannot compile vertex shader: "; msg += v_shad.getCompileErrors(); cerr << msg << endl; return FDGL::OpenGLShaderProgramWrapper(); } FDGL::OpenGLShader f_shad; f_shad.create(FDGL::ShaderType::Fragment); f_shad.setSource(std::string(FDCore::readFile("../../FDGL/test/resources/frag.frag").get())); if(!f_shad.compile()) { std::string msg = "Cannot compile fragment shader: "; msg += f_shad.getCompileErrors(); cerr << msg << endl; return FDGL::OpenGLShaderProgramWrapper(); } // link shaders program.create(); program.attach(v_shad); program.attach(f_shad); if(!program.link()) { std::string msg = "Cannot link shader program: "; msg += program.getLinkErrors(); cerr << msg << endl; return FDGL::OpenGLShaderProgramWrapper(); } return program; }*/ class Renderer { protected: FD3D::Camera m_cam; QTimer m_rendertimer; QOpenGLTexture *m_tex; FD3D::Scene m_scene; FDGL::OpenGLBuffer m_vbo; FDGL::OpenGLBuffer m_ebo; FDGL::OpenGLVertexArray m_vao; public: Renderer(); void onInit(FDGL::BaseOpenGLWindow &w); void onQuit(FDGL::BaseOpenGLWindow &w); void onRender(FDGL::BaseOpenGLWindow &w); void onResize(FDGL::BaseOpenGLWindow &w, int width, int height); void onError(FDGL::ErrorSoure source, FDGL::ErrorType type, uint32_t id, FDGL::ErrorSeverity level, const std::string &msg) const; private: static void debugCallbackHelper(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); }; static Renderer renderer; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { prepareGLWidget(); prepareLeftDock(); } MainWindow::~MainWindow() { } void MainWindow::prepareGLWidget() { m_glWindow = new FDQUI::OpenGLWidget(); if(!m_glWindow->create(800, 600, "Test window")) { qFatal("failed to create window"); qApp->exit(-1); } setCentralWidget(m_glWindow); /*m_glWindow->setInitializeStrategy(&Renderer::onInit, &renderer); m_glWindow->setQuitStrategy(&Renderer::onQuit, &renderer); m_glWindow->setRenderStrategy(&Renderer::onRender, &renderer); m_glWindow->setResizeStrategy(&Renderer::onResize, &renderer);*/ } void MainWindow::prepareLeftDock() { QDockWidget *leftDock = new QDockWidget(); QWidget *wid = new QWidget(); QVBoxLayout *vlay = new QVBoxLayout(); QTreeView *view = new QTreeView(); FDQUI::VectorWidget *vectorWid = new FDQUI::VectorWidget(); FDQUI::TransformModel *model = new FDQUI::TransformModel(view); model->setTranfsorm(&m_transform); vectorWid->setVector(m_transform.getPosition()); view->setHeaderHidden(true); view->setModel(model); view->setItemDelegate(new FDQUI::TransformDelegate(view)); vlay->addWidget(view); vlay->addWidget(vectorWid); wid->setLayout(vlay); leftDock->setWidget(wid); addDockWidget(Qt::LeftDockWidgetArea, leftDock); } Renderer::Renderer() : m_tex(nullptr) { FD3D::Projection &proj = m_cam.projection; proj.setFov(glm::radians(45.0f)); proj.setNear(0.1f); proj.setFar(100.0f); proj.setType(FD3D::ProjectionType::Perspective); } void Renderer::onInit(FDGL::BaseOpenGLWindow &w) { if (!qApp->loadOpenGLFunctions(qApp->getProcAddressFunc())) { qFatal("failed to load OpenGl functions"); qApp->exit(-1); } w.setClearColor(glm::vec4(0.2f, 0.3f, 0.3f, 1.0f)); w.setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); m_rendertimer.connect(&m_rendertimer, &QTimer::timeout, static_cast<FDQUI::OpenGLWidget*>(&w), QOverload<>::of(&FDQUI::OpenGLWidget::update)); qApp->enableDepth(); qApp->enableFaceCulling(); qApp->enable(GL_DEBUG_OUTPUT); glDebugMessageCallback(&Renderer::debugCallbackHelper, this); m_rendertimer.start(1000/60); m_tex = new QOpenGLTexture(QOpenGLTexture::Target2D); m_tex->create(); m_tex->setData(QImage("../../FDGL/test/resources/wall.jpg").mirrored()); FD3D::SceneLoader loader; loader.setTextureLoader([](const std::string &path){ return QOpenGLTexture(QImage(path.c_str()).mirrored()).textureId(); }); loader.setEmbeddedTextureLoader([](const aiTexture *texture){ QImage img; QOpenGLTexture tex(QOpenGLTexture::Target2D); if(texture->mHeight == 0) { if(!img.loadFromData(reinterpret_cast<uint8_t*>(texture->pcData), static_cast<int>(texture->mWidth), QString(texture->achFormatHint).toUpper().toStdString().c_str())) return 0u; tex.setData(img); } else { /*QOpenGLTexture::PixelType type = QOpenGLTexture::NoPixelType; if(QString(texture->achFormatHint) == "rgba8888" || QString(texture->achFormatHint) == "argb8888") type = QOpenGLTexture::UInt32_RGBA8; else if(QString(texture->achFormatHint) == "rgba5650") type = QOpenGLTexture::UInt16_R5G6B5; else qCritical("Unsupported texture format: %s for texture %s", texture->achFormatHint, texture->mFilename.C_Str());*/ //tex.setData(0, 0, QOpenGLTexture::RGBA, type, reinterpret_cast<void*>(texture->pcData)); } return tex.textureId(); }); assert(loader.loadScene(m_scene, "../../FDGL/test/resources/crate/CrateModel.obj", aiProcess_Triangulate )); } void Renderer::onQuit(FDGL::BaseOpenGLWindow &) { delete m_tex; } void Renderer::onRender(FDGL::BaseOpenGLWindow &w) { w.clear(); } void Renderer::onResize(FDGL::BaseOpenGLWindow &, int width, int height) { m_cam.projection.setWidth(width); m_cam.projection.setHeight(height); } void Renderer::onError(FDGL::ErrorSoure source, FDGL::ErrorType type, uint32_t id, FDGL::ErrorSeverity level, const std::string &msg) const { constexpr const char *format = "GL_DEBUG_MESSAGE:" "\n{" "\n source: %s," "\n type: %s," "\n severity: %s," "\n id: %u" "\n message: %s" "\n}"; switch(level) { case FDGL::ErrorSeverity::Low: qWarning(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; case FDGL::ErrorSeverity::Medium: qCritical(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; case FDGL::ErrorSeverity::High: qFatal(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; default: qDebug(format, FDGL::errorSourceToString(source).c_str(), FDGL::errorTypeToString(type).c_str(), FDGL::errorSeverityToString(level).c_str(), id, msg.data()); break; } } void Renderer::debugCallbackHelper(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) { const Renderer *r = reinterpret_cast<const Renderer *>(userParam); r->onError(static_cast<FDGL::ErrorSoure>(source), static_cast<FDGL::ErrorType>(type), id, static_cast<FDGL::ErrorSeverity>(severity), std::string(message, static_cast<size_t>(length))); }
30.897494
108
0.610071
benjamin-fukdawurld
09502ca06e3792157dc7eea4aa784a6a649b07fd
3,619
cpp
C++
exmathlib/exmathlib/exmath.cpp
IWeidl/ExMath-Library
ff809f4040c37003170f94bdb15f4edbf5bed1dd
[ "MIT" ]
1
2016-04-07T18:20:42.000Z
2016-04-07T18:20:42.000Z
exmathlib/exmathlib/exmath.cpp
Dasttann777/ExMath-Library
ff809f4040c37003170f94bdb15f4edbf5bed1dd
[ "MIT" ]
4
2016-04-07T07:47:56.000Z
2016-04-10T11:19:22.000Z
exmathlib/exmathlib/exmath.cpp
IWeidl/ExMath-Library
ff809f4040c37003170f94bdb15f4edbf5bed1dd
[ "MIT" ]
null
null
null
#pragma once #include "exmath.h" #include "exfrac.h" int RoundToINT(double e) { return (int)(e + 0.5); } double Math::Multiply(std::initializer_list<double> e) { double a = 1; std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a *= *it; } return a; } double Math::add_Array(double e[]) { double a = 0; for (int i = 0; i != sizeof(e); i++) { a += e[i]; } return a; } double Math::minus_Array(double e[]) { double a = 0; for (int i = 0; i != sizeof(e); i++) { a -= e[i]; } return a; } double Math::Add(std::initializer_list<double> e) { double a = 0; std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a += *it; } return a; } Fraction Math::Add(std::initializer_list<Fraction> e) { Fraction a(0, 0); std::initializer_list<Fraction>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a = a.Add(*it); } return a; } Fraction Math::Add(Fraction fx, Fraction fy) { fx = fx.Add(fy); return fx; } double Math::Minus(std::initializer_list<double> e) { double a = 0; std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { a -= *it; } return a; } void Math::Restart() { _x.clear(); } void Math::Append(std::initializer_list<double> e) { std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { _x.push_back(*it); } } Math::Math(std::initializer_list<double> e) { std::initializer_list<double>::iterator it; for (it = e.begin(); it != e.end(); ++it) { _x.push_back(*it); } } Math::Math(std::vector<double> e) { _x = e; } Math& operator+=(Math &obj, double p) { obj._x.push_back(p); return obj; } std::vector<double> Math::anti_diff(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { (*i) /= s; (*i) *= s; s--; } return e; } double Math::diff(double x1, double c) { return x1; } std::vector<double> Math::diff(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { (*i) /= s; s--; } return e; } std::vector<double> Math::diff(double x2, double x1, double c) { std::vector<double> a(0); a.push_back(x2 / 2); a.push_back(x1 / 1); return a; } std::vector<double> Math::diff(double x3, double x2, double x1, double c) { std::vector<double> a(0); a.push_back(x3 / 3); a.push_back(x2 / 2); a.push_back(x1 / 1); return a; } template<typename T> std::ostream& operator<< (std::ostream& out, const std::vector<T>& v) { out << "["; size_t last = v.size() - 1; for (size_t i = 0; i < v.size(); ++i) { out << v[i]; if (i != last) out << ", "; } out << "]"; return out; } std::vector<double> sqrt_all(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { *i = sqrt(*i); } return e; } double square(double e) { return e*e; } std::vector<double> square_all(std::vector<double> e) { double s = e.size() - 1; for (std::vector<double>::iterator i = e.begin(); i != e.end(); ++i) { (*i) *= (*i); } return e; } double cubert(double e) { return pow(e, 1 / 3.); } double xroot(double e, double n) { return pow(e, 1 / n); } Fraction cubert(Fraction a) { return Fraction(cubert(a.numerator), cubert(a.denominator)); } Fraction xroot(Fraction e, double n) { return Fraction(xroot(e.numerator, n), xroot(e.denominator, n)); }
20.919075
74
0.567284
IWeidl
095144bb72b0e7cbb18a532f52a9f0f5af4597a6
12,688
cpp
C++
src/cpu.cpp
aimktech/chip8
40f278e2638eb95abb2f7b979a4d8bfa69d2400b
[ "Apache-2.0" ]
3
2021-01-20T21:26:30.000Z
2021-12-17T10:09:54.000Z
src/cpu.cpp
aimktech/chip8
40f278e2638eb95abb2f7b979a4d8bfa69d2400b
[ "Apache-2.0" ]
null
null
null
src/cpu.cpp
aimktech/chip8
40f278e2638eb95abb2f7b979a4d8bfa69d2400b
[ "Apache-2.0" ]
null
null
null
/* * cpu.cpp * CPU Management Unit implementation */ // includes #include <cstring> #include <cstdlib> #include <ctime> #include "constants.h" #include "except.h" #include "cpu.h" // constants constexpr int NUM_REGISTERS = 16; enum Register { V0 = 0x00, VF = 0x0F }; // class structure struct CPU::OpaqueData { MMU *pMMU {nullptr}; // screen data byte_t *pScreen {nullptr}; word_t screenWidth {0}; // CPU registers byte_t V[NUM_REGISTERS] {}; word_t I {}; word_t PC {}; word_t SP {}; void create(); void destroy(); void reset(); bool putPixel(int x, int y); void clearScreen(); }; // Initialize the structure void CPU::OpaqueData::create() { // set the screen pointer pScreen = pMMU->getPointer(MemoryZone::SCREEN_BEGIN); screenWidth = pMMU->readW(MemoryRegister::SCREEN_WIDTH); // reset the CPU reset(); } // De-initialize the structure void CPU::OpaqueData::destroy() { } // Reset the CPU void CPU::OpaqueData::reset() { I = MemoryZone::ROM_BEGIN; PC = MemoryZone::CODE_BEGIN; SP = MemoryZone::STACK_END; ::memset(&V[0], 0x00, NUM_REGISTERS); ::srand(::time(NULL)); } /* Draw a pixel on the screen * Returns: * True if a collision occurred */ bool CPU::OpaqueData::putPixel(int x, int y) { int offset = y * screenWidth + x; bool isCollision {false}; if( pScreen[offset] == 1 ) isCollision = true; pScreen[offset] ^= 1; return isCollision; } // Clear the screen memory void CPU::OpaqueData::clearScreen() { ::memset(pScreen, 0x00, MemoryZone::SCREEN_SIZE); } /* Constructor * Args: * pMMU: the pointer to the MMU * pDisplay: the pointer to the Display */ CPU::CPU(MMU *pMMU) : data_(new (std::nothrow) OpaqueData) { if( data_ == nullptr ) { throw CPUError("Unable to allocate CPU data."); } data_->pMMU = pMMU; data_->create(); } // Destructor CPU::~CPU() { data_->destroy(); } // Reset the CPU to it's initial state void CPU::reset() { data_->reset(); data_->clearScreen(); } // Performs a Fetch/Decode/Execute cycle bool CPU::update() { // read the next instruction auto opcode = data_->pMMU->readW(data_->PC); // retrieve values from the opcode auto addr = (opcode & 0x0FFF); auto x = (opcode & 0x0F00) >> 8; auto y = (opcode & 0x00F0) >> 4; auto value = (opcode & 0x00FF); // incrememt PC to next instruction data_->PC += 2; switch(opcode & 0xF000) { case 0x0000: switch(opcode) { case 0x00E0: // CLS data_->clearScreen(); break; case 0x00EE: // RET data_->PC = data_->pMMU->readW(data_->SP); data_->SP += 2; break; } break; case 0x1000: // JP addr data_->PC = addr; break; case 0x2000: // CALL addr data_->SP -= 2; data_->pMMU->writeW(data_->SP, data_->PC); data_->PC = addr; break; case 0x3000: // SE Vx, byte if( data_->V[x] == value) data_->PC += 2; break; case 0x4000: // SNE Vx, byte if( data_->V[x] != value) data_->PC += 2; break; case 0x5000: // SE Vx, Vy if( data_->V[x] == data_->V[y] ) data_->PC += 2; break; case 0x6000: // LD Vx, byte data_->V[x] = value; break; case 0x7000: // ADD Vx, byte data_->V[x] += value; break; case 0x8000: switch(opcode & 0x000F) { case 0x0000: // LD Vx, Vy data_->V[x] = data_->V[y]; break; case 0x0001: // OR Vx, Vy data_->V[x] |= data_->V[y]; break; case 0x0002: // AND Vx, Vy data_->V[x] &= data_->V[y]; break; case 0x0003: // XOR Vx, Vy data_->V[x] ^= data_->V[y]; break; case 0x0004: // ADC Vx, Vy { int sum = data_->V[x] + data_->V[y]; data_->V[Register::VF] = (sum > 0x00FF) ? 1 : 0; data_->V[x] = (sum & 0xFF); } break; case 0x0005: // SBC Vx, Vy data_->V[Register::VF] = (data_->V[x] > data_->V[y]) ? 1 : 0; data_->V[x] -= data_->V[y]; break; case 0x0006: // SHR Vx, 1 data_->V[Register::VF] = (data_->V[x] & 0x01); data_->V[x] >>= 1; break; case 0x0007: // SUBN Vx, Vy data_->V[Register::VF] = (data_->V[y] > data_->V[x]) ? 1 : 0; data_->V[x] = data_->V[y] - data_->V[x]; break; case 0x000E: // SHL Vx, 1 data_->V[Register::VF] = (data_->V[x] & 0x80) ? 1 : 0; data_->V[x] <<= 1; break; } break; case 0x9000: // SNE Vx, Vy if( data_->V[x] != data_->V[y] ) data_->PC += 2; break; case 0xA000: // LD I, addr data_->I = addr; break; case 0xB000: // JP V0, addr data_->PC = addr + data_->V[Register::V0]; break; case 0xC000: // RND Vx, byte data_->V[x] = (::rand() % (0xFF + 1)) & value; break; case 0xD000: // DRW Vx, Vy, n { byte_t height = opcode & 0x000F; data_->V[Register::VF] = 0; for (int row = 0; row < height; row++) { byte_t sprite = data_->pMMU->readB(data_->I + row); for(int col = 0; col < Constants::SPRITE_WIDTH; col++) { // check the upper bit only if( (sprite & 0x80) > 0 ) { // if this is true then a collision occurred if( data_->putPixel(data_->V[x] + col, data_->V[y] + row) ) data_->V[Register::VF] = 1; } // next bit sprite <<= 1; } } } break; case 0xE000: switch(opcode & 0x00FF) { case 0x009E: // SKP Vx { int key = (int)data_->pMMU->readW(MemoryRegister::KEYBOARD_STATUS); int vx = 1 << data_->V[x]; if( (key & vx) == vx ) data_->PC += 2; } break; case 0x00A1: // SKNP Vx { int key = (int)data_->pMMU->readW(MemoryRegister::KEYBOARD_STATUS); int vx = 1 << data_->V[x]; if( (key & vx) != vx ) data_->PC += 2; } break; } break; case 0xF000: switch(opcode & 0x00FF) { case 0x0007: // LD Vx, DT data_->V[x] = data_->pMMU->readB(MemoryRegister::DELAY_TIMER); break; case 0x000A: // LD Vx, K { int key = (data_->pMMU->readW(MemoryRegister::KEYBOARD_STATUS)); if( key == 0 ) data_->PC -= 2; else { int vx = 1; int mask = vx; while( (key & mask) != mask) { vx += 1; mask = 1 << vx; } data_->V[x] = vx; } } break; case 0x0015: // LD DT, Vx data_->pMMU->writeB(MemoryRegister::DELAY_TIMER, data_->V[x]); break; case 0x0018: // LD ST, Vx data_->pMMU->writeB(MemoryRegister::SOUND_TIMER, data_->V[x]); break; case 0x001E: // ADD I, VX data_->V[Register::VF] = ( (data_->I + data_->V[x]) > 0x0FFF ) ? 1 : 0; data_->I += data_->V[x]; break; case 0x0029: // LD F, Vx data_->I = MemoryZone::ROM_BEGIN + (int)(data_->V[x]) * Constants::FONT_SIZE; break; case 0x0033: // LD B, Vx data_->pMMU->writeB(data_->I, (data_->V[x] / 100)); data_->pMMU->writeB(data_->I + 1, (data_->V[x] / 10) % 10); data_->pMMU->writeB(data_->I + 2, (data_->V[x] % 10)); break; case 0x0055: // LD [I], Vx switch(x) { case 0x0F: data_->pMMU->writeB(data_->I + 0x0F, data_->V[0x0F]); case 0x0E: data_->pMMU->writeB(data_->I + 0x0E, data_->V[0x0E]); case 0x0D: data_->pMMU->writeB(data_->I + 0x0D, data_->V[0x0D]); case 0x0C: data_->pMMU->writeB(data_->I + 0x0C, data_->V[0x0C]); case 0x0B: data_->pMMU->writeB(data_->I + 0x0B, data_->V[0x0B]); case 0x0A: data_->pMMU->writeB(data_->I + 0x0A, data_->V[0x0A]); case 0x09: data_->pMMU->writeB(data_->I + 0x09, data_->V[0x09]); case 0x08: data_->pMMU->writeB(data_->I + 0x08, data_->V[0x08]); case 0x07: data_->pMMU->writeB(data_->I + 0x07, data_->V[0x07]); case 0x06: data_->pMMU->writeB(data_->I + 0x06, data_->V[0x06]); case 0x05: data_->pMMU->writeB(data_->I + 0x05, data_->V[0x05]); case 0x04: data_->pMMU->writeB(data_->I + 0x04, data_->V[0x04]); case 0x03: data_->pMMU->writeB(data_->I + 0x03, data_->V[0x03]); case 0x02: data_->pMMU->writeB(data_->I + 0x02, data_->V[0x02]); case 0x01: data_->pMMU->writeB(data_->I + 0x01, data_->V[0x01]); case 0x00: data_->pMMU->writeB(data_->I + 0x00, data_->V[0x00]); } data_->I += x + 1; break; case 0x0065: // LD Vx, [I] switch(x) { case 0x0F: data_->V[0x0F] = data_->pMMU->readB(data_->I + 0x0F); case 0x0E: data_->V[0x0E] = data_->pMMU->readB(data_->I + 0x0E); case 0x0D: data_->V[0x0D] = data_->pMMU->readB(data_->I + 0x0D); case 0x0C: data_->V[0x0C] = data_->pMMU->readB(data_->I + 0x0C); case 0x0B: data_->V[0x0B] = data_->pMMU->readB(data_->I + 0x0B); case 0x0A: data_->V[0x0A] = data_->pMMU->readB(data_->I + 0x0A); case 0x09: data_->V[0x09] = data_->pMMU->readB(data_->I + 0x09); case 0x08: data_->V[0x08] = data_->pMMU->readB(data_->I + 0x08); case 0x07: data_->V[0x07] = data_->pMMU->readB(data_->I + 0x07); case 0x06: data_->V[0x06] = data_->pMMU->readB(data_->I + 0x06); case 0x05: data_->V[0x05] = data_->pMMU->readB(data_->I + 0x05); case 0x04: data_->V[0x04] = data_->pMMU->readB(data_->I + 0x04); case 0x03: data_->V[0x03] = data_->pMMU->readB(data_->I + 0x03); case 0x02: data_->V[0x02] = data_->pMMU->readB(data_->I + 0x02); case 0x01: data_->V[0x01] = data_->pMMU->readB(data_->I + 0x01); case 0x00: data_->V[0x00] = data_->pMMU->readB(data_->I + 0x00); } data_->I += x + 1; break; } break; } return true; }
31.562189
97
0.415747
aimktech
0953e163adba8e1dcc2205bcad313d08cf2c0b47
8,106
cpp
C++
src/command/FbxWriter.cpp
chadmv/dem-bones
bb4ea9f391c4be9abe4f85a407c2c47979bad959
[ "BSD-3-Clause" ]
584
2019-10-08T20:21:01.000Z
2022-03-31T14:29:50.000Z
src/command/FbxWriter.cpp
chadmv/dem-bones
bb4ea9f391c4be9abe4f85a407c2c47979bad959
[ "BSD-3-Clause" ]
18
2019-12-13T22:19:08.000Z
2021-09-18T07:09:50.000Z
src/command/FbxWriter.cpp
chadmv/dem-bones
bb4ea9f391c4be9abe4f85a407c2c47979bad959
[ "BSD-3-Clause" ]
112
2019-10-08T20:41:20.000Z
2022-03-29T04:12:18.000Z
/////////////////////////////////////////////////////////////////////////////// // Dem Bones - Skinning Decomposition Library // // Copyright (c) 2019, Electronic Arts. All rights reserved. // /////////////////////////////////////////////////////////////////////////////// #include "FbxWriter.h" #include "FbxShared.h" #include "LogMsg.h" #include <sstream> #include <Eigen/Dense> #include <DemBones/MatBlocks.h> #include <set> using namespace std; using namespace Eigen; #define err(msgStr) {msg(1, msgStr); return false;} class FbxSceneExporter: public FbxSceneShared { public: FbxSceneExporter(bool embedMedia=true): FbxSceneShared(false) { (*(lSdkManager->GetIOSettings())).SetBoolProp(EXP_FBX_EMBEDDED, embedMedia); } //https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref__export_scene01_2main_8cxx_example_html //https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref__switch_binding_2main_8cxx_example_html bool save(const string& fileName) { // Create an exporter. FbxExporter* lExporter=FbxExporter::Create(lSdkManager, ""); // Get the appropriate file format. int lFileFormat=lSdkManager->GetIOPluginRegistry()->GetNativeWriterFormat(); // Initialize the exporter. if (!lExporter->Initialize(fileName.c_str(), lFileFormat, lSdkManager->GetIOSettings())) err("Call to FbxExporter::Initialize() failed.\n"); // Export the scene to the file. lExporter->Export(lScene); lExporter->Destroy(); return true; } void createJoints(const vector<string>& name, const ArrayXi& parent, double radius) { FbxNode* lRoot=NULL; for (int j=0; j!=name.size(); j++) if (parent(j)==-1) { FbxSkeleton* lSkeletonAttribute=FbxSkeleton::Create(lScene, name[j].c_str()); lSkeletonAttribute->SetSkeletonType(((parent==j).count()>0)?FbxSkeleton::eRoot:FbxSkeleton::eLimb); lSkeletonAttribute->Size.Set(radius); FbxNode* lSkeleton=FbxNode::Create(lScene, name[j].c_str()); lSkeleton->SetNodeAttribute(lSkeletonAttribute); lSkeleton->SetRotationOrder(FbxNode::eSourcePivot, eEulerXYZ); lScene->GetRootNode()->AddChild(lSkeleton); lRoot=lSkeleton; } for (int j=0; j!=name.size(); j++) if (parent(j)!=-1) { FbxSkeleton* lSkeletonAttribute=FbxSkeleton::Create(lScene, name[j].c_str()); lSkeletonAttribute->SetSkeletonType(FbxSkeleton::eLimb); lSkeletonAttribute->Size.Set(radius); FbxNode* lSkeleton=FbxNode::Create(lScene, name[j].c_str()); lSkeleton->SetNodeAttribute(lSkeletonAttribute); lSkeleton->SetRotationOrder(FbxNode::eSourcePivot, eEulerXYZ); lRoot->AddChild(lSkeleton); } } void addToCurve(const VectorXd& val, const VectorXd& fTime, FbxAnimCurve* lCurve) { lCurve->KeyModifyBegin(); int idx=0; int nFr=(int)fTime.size(); FbxTime lTime; for (int k=0; k<nFr; k++) { lTime.SetSecondDouble(fTime(k)); idx=lCurve->KeyAdd(lTime); lCurve->KeySetValue(idx, (float)val(k)); lCurve->KeySetInterpolation(idx, FbxAnimCurveDef::eInterpolationCubic); lCurve->KeySetTangentMode(idx, FbxAnimCurveDef::eTangentAuto); } lCurve->KeyModifyEnd(); } void setJoints(const vector<string>& name, const VectorXd& fTime, const MatrixXd& lr, const MatrixXd& lt, const MatrixXd& lbr, const MatrixXd& lbt) { // Animation stack & layer. FbxString lAnimStackName="demBones"; FbxAnimStack* lAnimStack=FbxAnimStack::Create(lScene, lAnimStackName); FbxAnimLayer* lAnimLayer=FbxAnimLayer::Create(lScene, "Base Layer"); lAnimStack->AddMember(lAnimLayer); VectorXd val; for (int j=0; j!=name.size(); j++) { FbxNode* lSkeleton=lScene->FindNodeByName(FbxString(name[j].c_str())); lSkeleton->LclRotation.Set(FbxDouble3(lbr(0, j), lbr(1, j), lbr(2, j))); lSkeleton->LclTranslation.Set(FbxDouble3(lbt(0, j), lbt(1, j), lbt(2, j))); val=lr.col(j); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data(), val.size()/3), fTime, lSkeleton->LclRotation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+1, val.size()/3), fTime, lSkeleton->LclRotation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+2, val.size()/3), fTime, lSkeleton->LclRotation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, true)); val=lt.col(j); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data(), val.size()/3), fTime, lSkeleton->LclTranslation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_X, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+1, val.size()/3), fTime, lSkeleton->LclTranslation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Y, true)); addToCurve(Map<VectorXd, 0, InnerStride<3>>(val.data()+2, val.size()/3), fTime, lSkeleton->LclTranslation.GetCurve(lAnimLayer, FBXSDK_CURVENODE_COMPONENT_Z, true)); } } void setSkinCluster(const vector<string>& name, const SparseMatrix<double>& w, const MatrixXd& gb) { FbxMesh* lMesh=firstMesh(lScene->GetRootNode()); FbxSkin* lSkin=firstSkin(lMesh); if (lSkin==NULL) { lSkin=FbxSkin::Create(lScene, "demSkinCluster"); lMesh->AddDeformer(lSkin); lSkin->SetSkinningType(FbxSkin::eLinear); } //Clear all clusters while (lSkin->GetClusterCount()) { FbxCluster* lCluster=lSkin->GetCluster(lSkin->GetClusterCount()-1); lSkin->RemoveCluster(lCluster); } //Clear all poses while (lScene->GetPoseCount()) lScene->RemovePose(lScene->GetPoseCount()-1); //Create a new bind pose FbxPose* lPose=FbxPose::Create(lScene, "demBindPose"); lPose->SetIsBindPose(true); FbxAMatrix gMat=lMesh->GetNode()->EvaluateGlobalTransform(); lPose->Add(lMesh->GetNode(), gMat); SparseMatrix<double> wT=w.transpose(); int nB=(int)name.size(); set<FbxNode*> added; for (int j=0; j<nB; j++) { ostringstream s; s<<"demCluster"<<j; FbxCluster* lCluster=FbxCluster::Create(lScene, s.str().c_str()); FbxNode* lNode=lScene->FindNodeByName(FbxString(name[j].c_str())); lCluster->SetLink(lNode); lCluster->SetLinkMode(FbxCluster::eTotalOne); for (SparseMatrix<double>::InnerIterator it(wT, j); it; ++it) lCluster->AddControlPointIndex((int)it.row(), it.value()); lCluster->SetTransformMatrix(gMat); //Equaivalent to jointMat=lJoint->EvaluateGlobalTransform(), but with better accuracy FbxAMatrix jointMat; Map<Matrix4d> mm(&jointMat.mData[0][0], 4, 4); mm=gb.blk4(0, j); lCluster->SetTransformLinkMatrix(jointMat); lSkin->AddCluster(lCluster); //Add to bind pose while ((lNode)&&(added.find(lNode)==added.end())) { added.insert(lNode); lPose->Add(lNode, lNode->EvaluateGlobalTransform()); lNode=lNode->GetParent(); } } lScene->AddPose(lPose); } }; bool writeFBXs(const vector<string>& fileNames, const vector<string>& inputFileNames, DemBonesExt<double, float>& model, bool embedMedia) { msg(1, "Writing outputs:\n"); if ((int)fileNames.size()!=model.nS) err("Wrong number of FBX files.\n"); FbxSceneExporter exporter(embedMedia); bool needCreateJoints=(model.boneName.size()==0); double radius; if (needCreateJoints) { model.boneName.resize(model.nB); for (int j=0; j<model.nB; j++) { ostringstream s; s<<"joint"<<j; model.boneName[j]=s.str(); } radius=sqrt((model.u-(model.u.rowwise().sum()/model.nV).replicate(1, model.nV)).cwiseAbs().rowwise().maxCoeff().squaredNorm()/model.nS); } for (int s=0; s<model.nS; s++) { msg(1, " \""<<inputFileNames[s]<<"\" "); if (!exporter.open(inputFileNames[s])) err("Error on opening file.\n"); msg(1, "--> \""<<fileNames[s]<<"\" "); MatrixXd lr, lt, gb, lbr, lbt; model.computeRTB(s, lr, lt, gb, lbr, lbt); if (needCreateJoints) exporter.createJoints(model.boneName, model.parent, radius); exporter.setJoints(model.boneName, model.fTime.segment(model.fStart(s), model.fStart(s+1)-model.fStart(s)), lr, lt, lbr, lbt); exporter.setSkinCluster(model.boneName, model.w, gb); if (!exporter.save(fileNames[s])) err("Error on exporting file.\n"); msg(1, "("<<model.fStart(s+1)-model.fStart(s)<<" frames)\n"); } return true; }
38.417062
167
0.690846
chadmv
0956e2a4bab6585323216d41ada3347d3581f846
3,895
cc
C++
omaha/base/thread_pool.cc
Gunanekza/omaha
e73cb9edffaba24bb3b7515f5b48376f922b697e
[ "Apache-2.0" ]
34
2019-11-01T04:26:40.000Z
2022-03-29T03:00:40.000Z
omaha/base/thread_pool.cc
Wicked2303/omaha
1b18ab3989b8cf503d5e46a351c44c9d2754caed
[ "Apache-2.0" ]
1
2020-11-19T18:11:20.000Z
2020-11-19T18:11:20.000Z
omaha/base/thread_pool.cc
Wicked2303/omaha
1b18ab3989b8cf503d5e46a351c44c9d2754caed
[ "Apache-2.0" ]
8
2019-11-01T04:27:53.000Z
2022-03-16T22:17:12.000Z
// Copyright 2004-2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== #include "omaha/base/thread_pool.h" #include <memory> #include "omaha/base/debug.h" #include "omaha/base/error.h" #include "omaha/base/logging.h" #include "omaha/base/utils.h" namespace omaha { namespace { // Context keeps track the information necessary to execute a work item // inside a thread pool thread. class Context { public: Context(ThreadPool* pool, UserWorkItem* work_item, DWORD coinit_flags) : pool_(pool), work_item_(work_item), coinit_flags_(coinit_flags) { ASSERT1(pool); ASSERT1(work_item); } ThreadPool* pool() const { return pool_; } UserWorkItem* work_item() const { return work_item_; } DWORD coinit_flags() const { return coinit_flags_; } private: ThreadPool* pool_; UserWorkItem* work_item_; const DWORD coinit_flags_; DISALLOW_COPY_AND_ASSIGN(Context); }; } // namespace DWORD WINAPI ThreadPool::ThreadProc(void* param) { UTIL_LOG(L4, (_T("[ThreadPool::ThreadProc]"))); ASSERT1(param); Context* context = static_cast<Context*>(param); scoped_co_init init_com_apt(context->coinit_flags()); ASSERT1(SUCCEEDED(init_com_apt.hresult())); context->pool()->ProcessWorkItem(context->work_item()); delete context; return 0; } ThreadPool::ThreadPool() : work_item_count_(0), shutdown_delay_(0) { UTIL_LOG(L2, (_T("[ThreadPool::ThreadPool]"))); } ThreadPool::~ThreadPool() { UTIL_LOG(L2, (_T("[ThreadPool::~ThreadPool]"))); if (!shutdown_event_) { return; } DWORD baseline_tick_count = ::GetTickCount(); if (::SetEvent(get(shutdown_event_))) { while (work_item_count_ != 0) { ::Sleep(1); if (TimeHasElapsed(baseline_tick_count, shutdown_delay_)) { UTIL_LOG(LE, (_T("[ThreadPool::~ThreadPool][timeout elapsed]"))); // Exiting a thread pool that has active work items can result in a // race condition and undefined behavior during shutdown. ::RaiseException(EXCEPTION_ACCESS_VIOLATION, EXCEPTION_NONCONTINUABLE, 0, NULL); break; } } } } HRESULT ThreadPool::Initialize(int shutdown_delay) { shutdown_delay_ = shutdown_delay; reset(shutdown_event_, ::CreateEvent(NULL, true, false, NULL)); return shutdown_event_ ? S_OK : HRESULTFromLastError(); } void ThreadPool::ProcessWorkItem(UserWorkItem* work_item) { ASSERT1(work_item); work_item->Process(); delete work_item; ::InterlockedDecrement(&work_item_count_); } HRESULT ThreadPool::QueueUserWorkItem(UserWorkItem* work_item, DWORD coinit_flags, uint32 flags) { UTIL_LOG(L4, (_T("[ThreadPool::QueueUserWorkItem]"))); ASSERT1(work_item); auto context = std::make_unique<Context>(this, work_item, coinit_flags); work_item->set_shutdown_event(get(shutdown_event_)); ::InterlockedIncrement(&work_item_count_); if (!::QueueUserWorkItem(&ThreadPool::ThreadProc, context.get(), flags)) { ::InterlockedDecrement(&work_item_count_); return HRESULTFromLastError(); } // The thread pool has the ownership of the work item thereon. context.release(); return S_OK; } } // namespace omaha
28.639706
76
0.671374
Gunanekza
095740e3a488d46f7e5ec3601cd10175f17185cc
843
cpp
C++
huffman_decode/main.cpp
8alery/algorithms
67cf12724f61cdae7eff1788062c1b7c26f98ca4
[ "Apache-2.0" ]
null
null
null
huffman_decode/main.cpp
8alery/algorithms
67cf12724f61cdae7eff1788062c1b7c26f98ca4
[ "Apache-2.0" ]
null
null
null
huffman_decode/main.cpp
8alery/algorithms
67cf12724f61cdae7eff1788062c1b7c26f98ca4
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <unordered_map> #include <stdio.h> int main() { int letters_count, code_length; std::cin >> letters_count >> code_length; std::unordered_map<std::string,char> letters_map; std::string character; std::string code; for (int i = 0; i < letters_count; i++){ std::cin >> character >> code; letters_map[code] = character[0]; } std::string codedString; std::cin >> codedString; int i = 0; std::string current = ""; std::string decodedString = ""; while (i < codedString.length()){ current += codedString[i]; auto found = letters_map.find(current); if (found != letters_map.end()){ decodedString += found->second; current = ""; } i++; } std::cout << decodedString; return 0; }
26.34375
53
0.572954
8alery
095bf50d18ec9f3d72f735d509f483569ef4336a
4,456
hpp
C++
include/latte_core_hook.hpp
iwatakeshi/latte
ec0c31092af3d9b42e757a6bb375d817ff522376
[ "MIT" ]
1
2019-03-05T02:24:32.000Z
2019-03-05T02:24:32.000Z
include/latte_core_hook.hpp
iwatakeshi/latte
ec0c31092af3d9b42e757a6bb375d817ff522376
[ "MIT" ]
null
null
null
include/latte_core_hook.hpp
iwatakeshi/latte
ec0c31092af3d9b42e757a6bb375d817ff522376
[ "MIT" ]
null
null
null
#ifndef LATTE_CORE_HOOK_H #define LATTE_CORE_HOOK_H #include "latte_core_state.hpp" #include "latte_type.hpp" #include <iostream> #include <string> #include <unordered_map> #include <vector> namespace latte { namespace core { // Base class for before(), after(), before_each(), and after_each() struct latte_test_hook { latte_test_hook(): latte_test_hook("latte_test_hook") {} latte_test_hook(const std::string& name) { name_ = name; } protected: virtual void operator()(const std::string& description, const type::latte_callback& hook) { description_ = description; this->operator()(hook); } virtual void operator()(const type::latte_callback& hook) { // Find the hook's call stack associated with the current describe() auto current_call_stack = call_stack.find(parent_depth()); // We found the stack if (current_call_stack != call_stack.end()) { auto stack = current_call_stack->second; // Add the hook to the local stack stack.push_back(hook); // Update the local stack call_stack[parent_depth()] = stack; } else { // Create the local stack std::vector<type::latte_callback> stack { hook }; // Add the local stack call_stack[parent_depth()] = stack; } }; virtual void operator() (int depth) { auto current_call_stack = call_stack.find(depth); if (current_call_stack != call_stack.end()) { std::vector<type::latte_callback> stack = current_call_stack->second; try { if (!stack.empty()) { // The function call is located at the end. auto function = stack.back(); function(); } } catch(const std::exception& e) { // debug("[latte error::core::hook]: " + std::string(e.what())); } } else { // debug("---: couldn't find hook: " + name_); } } void clear(int depth) { auto current_call_stack = call_stack.find(depth); if (current_call_stack != call_stack.end()) { // Remove the function from the call stack if (!current_call_stack->second.empty()) { current_call_stack->second.pop_back(); } } } std::string name_ = ""; std::string description_ = ""; private: std::unordered_map<int, std::vector<type::latte_callback>> call_stack; int parent_depth () { return _latte_state.depth(); } }; struct latte_before : public latte_test_hook { latte_before(): latte_test_hook("before()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; struct latte_before_each : public latte_test_hook { latte_before_each(): latte_test_hook("before_each()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; struct latte_after : public latte_test_hook { latte_after(): latte_test_hook("after()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; struct latte_after_each: public latte_test_hook { latte_after_each(): latte_test_hook("after_each()") {}; virtual void operator()(const std::string& description, type::latte_callback&& hook) { latte_test_hook::operator()(description, hook); } virtual void operator()(type::latte_callback&& hook) { latte_test_hook::operator()(hook); }; private: friend struct latte_describe; friend struct latte_it; virtual void operator() (int depth) { latte_test_hook::operator()(depth); } }; } // core } // latte #endif
26.52381
93
0.665171
iwatakeshi
82368801a5da131d0f1f214fc9506ea345c34e48
1,224
cpp
C++
lib/Util/Printing.cpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
7
2018-06-25T12:06:13.000Z
2022-01-18T09:20:13.000Z
lib/Util/Printing.cpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
20
2016-12-01T23:46:12.000Z
2019-08-11T02:41:04.000Z
lib/Util/Printing.cpp
seec-team/seec
4b92456011e86b70f9d88833a95c1f655a21cf1a
[ "MIT" ]
1
2020-10-19T03:20:05.000Z
2020-10-19T03:20:05.000Z
//===- lib/Util/Printing.cpp ----------------------------------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #include "seec/Util/Fallthrough.hpp" #include "seec/Util/Printing.hpp" #include "llvm/Support/DataTypes.h" #include "llvm/Support/raw_ostream.h" namespace seec { namespace util { void writeJSONStringLiteral(llvm::StringRef S, llvm::raw_ostream &Out) { Out.write('"'); auto const End = S.data() + S.size(); for (auto It = S.data(); It != End; ++It) { switch (*It) { case '"': Out << "\\\""; break; case '\\': Out << "\\\\"; break; case '/': Out << "\\/"; break; case '\b': Out << "\\b"; break; case '\f': Out << "\\f"; break; case '\n': Out << "\\n"; break; case '\r': Out << "\\r"; break; case '\t': Out << "\\t"; break; default: Out.write(*It); break; } } Out.write('"'); } } // namespace util } // namespace seec
23.09434
80
0.41585
seec-team
823daeb71466bb7e38cdcb396fa91e5491d4cd73
13,685
cpp
C++
src/upcore/test/random.cpp
upcaste/upcaste
8174a2f40e7fde022806f8d1565bb4a415ecb210
[ "MIT" ]
1
2018-09-17T20:50:14.000Z
2018-09-17T20:50:14.000Z
src/upcore/test/random.cpp
jwtowner/upcaste
8174a2f40e7fde022806f8d1565bb4a415ecb210
[ "MIT" ]
null
null
null
src/upcore/test/random.cpp
jwtowner/upcaste
8174a2f40e7fde022806f8d1565bb4a415ecb210
[ "MIT" ]
null
null
null
// // Upcaste Performance Libraries // Copyright (C) 2012-2013 Jesse W. Towner // // 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 <up/cinttypes.hpp> #include <up/cmath.hpp> #include <up/log.hpp> #include <up/random.hpp> #include <up/test.hpp> namespace prng { UP_TEST_CASE(generate_canonical) { up::xorshift64_engine<uint_least32_t, 13, 7, 17> engine32; up::xorshift64_engine<uint_least64_t, 13, 7, 17> engine64; long double sum; double d; float f; size_t i; for (sum = 0.0l, i = 1; i <= 32768; sum += f, ++i) { f = ::up::generate_canonical<float, FLT_MANT_DIG>(engine32); require((0.0f <= f) && (f < 1.0f)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); for (sum = 0.0l, i = 1; i <= 32768; sum += f, ++i) { f = ::up::generate_canonical<float, FLT_MANT_DIG>(engine64); require((0.0f <= f) && (f < 1.0f)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); for (sum = 0.0l, i = 1; i <= 32768; sum += d, ++i) { d = ::up::generate_canonical<double, DBL_MANT_DIG>(engine32); require((0.0 <= d) && (d < 1.0)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); for (sum = 0.0l, i = 1; i <= 32768; sum += d, ++i) { d = ::up::generate_canonical<float, DBL_MANT_DIG>(engine64); require((0.0 <= d) && (d < 1.0)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); } UP_TEST_CASE(generate_random_seed) { uint_least32_t seed; uint_least32_t seq[4]; seed = 0; up::generate_random_seed(seq, 4, &seed, 1); require(seq[0] == 0xb0a842fd); require(seq[1] == 0x04290315); require(seq[2] == 0x75a0adfa); require(seq[3] == 0x1fb83b0f); seed = 1; up::generate_random_seed(seq, 4, &seed, 1); require(seq[0] == 0x4dc239dd); require(seq[1] == 0x529c8ec8); require(seq[2] == 0x60e79bf6); require(seq[3] == 0x624f7451); seed = 521288629; up::generate_random_seed(seq, 4, &seed, 1); require(seq[0] == 0xb887f987); require(seq[1] == 0x6e42c737); require(seq[2] == 0xd6c4c175); require(seq[3] == 0xf71737b9); } UP_TEST_CASE(xorshift64_engine) { up::default_xorshift64_engine engine; require(engine.min() == ((UINT_FAST32_MAX > 0xFFFFFFFF) ? 1 : 0)) require(engine.max() == UINT_FAST32_MAX); #ifdef UP_DEBUG up::log_event(up::log_level_info, "First 128 values...\n\n"); for (size_t i = 1; i <= 128; ++i) { up::log_eventf(up::log_level_info, "%#.8" PRIxFAST32 " ", static_cast<uintmax_t>(engine())); if ((i % 4) == 0) { up::log_event(up::log_level_info, "\n"); } } #else engine.discard(128); #endif #if UINT_FAST32_MAX == 0xFFFFFFFF require(engine() == 0xfb699180); #else require(engine() == 0xda8b4c09021984c3ull); #endif } UP_TEST_CASE(xorshift128_engine) { up::default_xorshift128_engine engine; require(engine.min() == 0) require(engine.max() == UINT_FAST32_MAX); #ifdef UP_DEBUG up::log_event(up::log_level_info, "First 128 values...\n\n"); for (size_t i = 1; i <= 128; ++i) { up::log_eventf(up::log_level_info, "%#.8" PRIxFAST32 " ", static_cast<uintmax_t>(engine())); if ((i % 4) == 0) { up::log_event(up::log_level_info, "\n"); } } #else engine.discard(128); #endif #if UINT_FAST32_MAX == 0xFFFFFFFF require(engine() == 0xc72a4e0a); #else require(engine() == 0x60f38d031f5c90b1); #endif } UP_TEST_CASE(uniform_int_distribution) { up::default_random_engine engine; long double sum; size_t i; int x; static_assert(up::is_same<int, up::uniform_int_distribution<int>::result_type>::value, "unexpected type"); up::uniform_int_distribution<int> dist0(0, 0); require((dist0.a() == 0) && (dist0.b() == 0)); require((dist0.min() == 0) && (dist0.max() == 0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_int_distribution<int> dist1(0, 10); require((dist1.a() == 0) && (dist1.b() == 10)); require((dist1.min() == 0) && (dist1.max() == 10)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist1(engine); require((x >= 0) && (x <= 10)); } require_approx(sum / 16384.0l, 5.0l, 0.05l); up::uniform_int_distribution<int> dist2(-10, 0); require((dist2.a() == -10) && (dist2.b() == 0)); require((dist2.min() == -10) && (dist2.max() == 0)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist2(engine); require((x >= -10) && (x <= 0)); } require_approx(sum / 16384.0l, -5.0l, 0.05l); up::uniform_int_distribution<int> dist3(-10, 10); require((dist3.a() == -10) && (dist3.b() == 10)); require((dist3.min() == -10) && (dist3.max() == 10)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist3(engine); require((x >= -10) && (x <= 10)); } require_approx(sum / 16384.0l, 0.0l, 0.05l); up::uniform_int_distribution<int> dist4; require((dist4.a() == 0) && (dist4.b() == INT_MAX)); require((dist4.min() == 0) && (dist4.max() == INT_MAX)); for (sum = 0.0l, i = 1; i <= (INT_MAX / 8); sum += x, ++i) { x = dist4(engine); require((x >= 0) && (x <= INT_MAX)); } require_approx(sum / (INT_MAX / 8.0l), (INT_MAX / 2.0l), 50000.0l); } UP_TEST_CASE(uniform_llong_distribution) { typedef long long llong; up::default_random_engine engine; long double sum; llong x; size_t i; static_assert(up::is_same<llong, up::uniform_int_distribution<llong>::result_type>::value, "unexpected type"); up::uniform_int_distribution<llong> dist0(0, 0); require((dist0.a() == 0) && (dist0.b() == 0)); require((dist0.min() == 0) && (dist0.max() == 0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_int_distribution<llong> dist1(-100, 100); require((dist1.a() == -100) && (dist1.b() == 100)); require((dist1.min() == -100) && (dist1.max() == 100)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist1(engine); require((x >= -100) && (x <= 100)); } require_approx(sum / 16384.0l, 0.0l, 1.0l); up::uniform_int_distribution<llong> dist2; require((dist2.a() == 0) && (dist2.b() == LLONG_MAX)); require((dist2.min() == 0) && (dist2.max() == LLONG_MAX)); for (sum = 0.0l, i = 1; i <= (INT_MAX / 8); sum += x, ++i) { x = dist2(engine); require((x >= 0) && (x <= LLONG_MAX)); } require_approx(sum / (INT_MAX / 8.0l), (LLONG_MAX / 2.0l), 4.0e+14); } UP_TEST_CASE(uniform_ullong_distribution) { typedef unsigned long long ullong; up::default_random_engine engine; long double sum; ullong x; size_t i; static_assert(up::is_same<ullong, up::uniform_int_distribution<ullong>::result_type>::value, "unexpected type"); up::uniform_int_distribution<ullong> dist0(0, 0); require((dist0.a() == 0) && (dist0.b() == 0)); require((dist0.min() == 0) && (dist0.max() == 0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_int_distribution<ullong> dist1(0, 100); require((dist1.a() == 0) && (dist1.b() == 100)); require((dist1.min() == 0) && (dist1.max() == 100)); for (sum = 0.0l, i = 1; i <= 16384; sum += x, ++i) { x = dist1(engine); require(x <= 100); } require_approx(sum / 16384.0l, 50.0l, 1.0l); up::uniform_int_distribution<ullong> dist2; require((dist2.a() == 0) && (dist2.b() == ULLONG_MAX)); require((dist2.min() == 0) && (dist2.max() == ULLONG_MAX)); for (sum = 0.0l, i = 1; i <= (INT_MAX / 8); sum += x, ++i) { x = dist2(engine); require(x <= ULLONG_MAX); } require_approx(sum / (INT_MAX / 8.0l), (ULLONG_MAX / 2.0l), 4.0e+14); } UP_TEST_CASE(uniform_float_distribution) { up::default_random_engine engine; long double sum; float x; size_t i; static_assert(up::is_same<float, up::uniform_real_distribution<float>::result_type>::value, "unexpected type"); up::uniform_real_distribution<float> dist0(0.0f, 0.0f); require((dist0.a() == 0.0f) && (dist0.b() == 0.0f)); require((dist0.min() == 0.0f) && (dist0.max() == 0.0f)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0.0f); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_real_distribution<float> dist1; require((dist1.a() == 0.0f) && (dist1.b() == 1.0f)); require((dist1.min() == 0.0f) && (dist1.max() == 1.0f)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist1(engine); require((0.0f <= x) && (x < 1.0f)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); up::uniform_real_distribution<float> dist2(-128.0f, 128.0f); require((dist2.a() == -128.0f) && (dist2.b() == 128.0f)); require((dist2.min() == -128.0f) && (dist2.max() == 128.0f)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist2(engine); require((-128.0f <= x) && (x < 128.0f)); } require_approx(sum / 32768.0l, 0.0l, 1.0l); } UP_TEST_CASE(uniform_double_distribution) { up::default_random_engine engine; long double sum; double x; size_t i; static_assert(up::is_same<double, up::uniform_real_distribution<double>::result_type>::value, "unexpected type"); up::uniform_real_distribution<double> dist0(0.0, 0.0); require((dist0.a() == 0.0) && (dist0.b() == 0.0)); require((dist0.min() == 0.0) && (dist0.max() == 0.0)); for (sum = 0.0l, i = 1; i <= 1024; sum += x, ++i) { x = dist0(engine); require(x == 0.0); } require_approx(sum / 1024.0l, 0.0l, LDBL_EPSILON); up::uniform_real_distribution<double> dist1; require((dist1.a() == 0.0) && (dist1.b() == 1.0)); require((dist1.min() == 0.0) && (dist1.max() == 1.0)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist1(engine); require((0.0 <= x) && (x < 1.0)); } require_approx(sum / 32768.0l, 0.5l, 0.01l); up::uniform_real_distribution<double> dist2(-128.0, 128.0); require((dist2.a() == -128.0) && (dist2.b() == 128.0)); require((dist2.min() == -128.0) && (dist2.max() == 128.0)); for (sum = 0.0l, i = 1; i <= 32768; sum += x, ++i) { x = dist2(engine); require((-128.0 <= x) && (x < 128.0)); } require_approx(sum / 32768.0l, 0.0l, 1.0l); up::uniform_real_distribution<double> dist3(-FLT_MAX, FLT_MAX); require((dist3.a() == -FLT_MAX) && (dist3.b() == FLT_MAX)); require((dist3.min() == -FLT_MAX) && (dist3.max() == FLT_MAX)); for (sum = 0.0l, i = 1; i <= INT_MAX; sum += x, ++i) { x = dist3(engine); require((-FLT_MAX <= x) && (x < FLT_MAX)); } require_approx(sum / INT_MAX, 0.0l, FLT_MAX); } }
35.179949
122
0.51129
upcaste
823ec2c4c7a57c4d5b51e558af1530eb875b1c97
390
cpp
C++
assets/docs/samples/events.cpp
mariusvn/turbo-engine
63cc2b76bc1aff7de9655916553a03bd768f5879
[ "MIT" ]
2
2021-02-12T13:05:02.000Z
2021-02-22T14:25:00.000Z
assets/docs/samples/events.cpp
mariusvn/turbo-engine
63cc2b76bc1aff7de9655916553a03bd768f5879
[ "MIT" ]
null
null
null
assets/docs/samples/events.cpp
mariusvn/turbo-engine
63cc2b76bc1aff7de9655916553a03bd768f5879
[ "MIT" ]
null
null
null
#include <iostream> #include <turbo/Engine.hpp> int main() { turbo::EventHandler<unsigned int, float> event_handler([](unsigned int i, float j) { std::cout << "i: " << i << ", j: " << j << std::endl; }); turbo::Event<unsigned int, float> testEvent; testEvent += event_handler; testEvent(4, -4.84); testEvent(8, 17.5); testEvent(19, 0.1); return 0; }
27.857143
88
0.584615
mariusvn
824489ea9f7b731c51e7e6e4a7fa2031863d45eb
406
hpp
C++
include/Regiment.hpp
a276me/MilSim
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
[ "MIT" ]
null
null
null
include/Regiment.hpp
a276me/MilSim
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
[ "MIT" ]
null
null
null
include/Regiment.hpp
a276me/MilSim
b3ba8ef8cc46b6ae9cc7befece6cd00b016038ea
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <vector> #define MECH_INF 0 #define ARMOR 1 #define ARTILLARY 2 #define SF 3 #define INF 4 class Regiment{ public: int type; int battalions; double BBV; double BDV; double BS; double BBD; double BSP; void addBattalion(); int getStrength(); double getBV(); double getDV(); double getBD(); double getSpeed(); Regiment(int t, int b); };
11.6
24
0.679803
a276me
82453b175b65a5b303fe610c2be21f920d323376
889
cpp
C++
test.cpp
ReflectMun/DataStructureQuizArchive
6805179e17391e854d7495ef8f3db2d3acb84dfb
[ "MIT" ]
null
null
null
test.cpp
ReflectMun/DataStructureQuizArchive
6805179e17391e854d7495ef8f3db2d3acb84dfb
[ "MIT" ]
null
null
null
test.cpp
ReflectMun/DataStructureQuizArchive
6805179e17391e854d7495ef8f3db2d3acb84dfb
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; typedef struct node{ int n; struct node * left; struct node * right; }node; node * make_tree(){ node * n5 = new node; n5->n = 5; n5->left = nullptr; n5->right = nullptr; node * n4 = new node; n4->n = 4; n4->left = nullptr; n4->right = nullptr; node * n3 = new node; n3->n = 3; n3->left = nullptr; n3->right = nullptr; node * n2 = new node; n2->n = 2; n2->left = n4; n2->right = n5; node * root = new node; root->n = 1; root->left = n2; root->right = n3; return root; } int main(){ ifstream reader("a.txt"); string str1, str2, str3, str4; reader >> str1 >> str2 >> str3 >> str4; if(str1 == "") cout << "1" << endl; if(str2 == "") cout << "2" << endl; if(str3 == "") cout << "3" << endl; if(str4 == "") cout << "4" << endl; reader.close(); return 0; }
25.4
77
0.537683
ReflectMun
8249ca08605691ed6332c02640b45b30eb87b79c
1,584
hpp
C++
VSDataReduction/VSSimCoordTransform.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
1
2018-04-17T14:03:36.000Z
2018-04-17T14:03:36.000Z
VSDataReduction/VSSimCoordTransform.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
VSDataReduction/VSSimCoordTransform.hpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
//-*-mode:c++; mode:font-lock;-*- /*! \file VSSimCoordTransform.hpp Perform coordinate transforms on simulation events. \author Matthew Wood \n UCLA \n [email protected] \n \version 1.0 \date 09/11/2008 $Id: VSSimCoordTransform.hpp,v 3.1 2008/09/24 20:01:16 matthew Exp $ */ #ifndef VSSIMCOORDTRANSFORM_HPP #define VSSIMCOORDTRANSFORM_HPP #include <SphericalCoords.h> #include <VSOptions.hpp> namespace VERITAS { class VSSimCoordTransform { public: VSSimCoordTransform(const std::pair<double,double>& src_radec = s_default_src_radec, double wobble_phi_deg = s_default_wobble_phi_deg); virtual ~VSSimCoordTransform(); virtual void transform(SEphem::SphericalCoords& radec, unsigned corsika_particle_id, const SEphem::SphericalCoords& azzn, const SEphem::SphericalCoords& obs_azzn); virtual void setObsRADec(const SEphem::SphericalCoords& obs_radec) { m_obs_radec = obs_radec; } static void configure(VSOptions& options, const std::string& profile="", const std::string& opt_prefix=""); private: SEphem::SphericalCoords m_src_radec; SEphem::SphericalCoords m_obs_radec; double m_wobble_phi_rad; // Default options -------------------------------------------------------- static std::pair< double, double > s_default_src_radec; static double s_default_wobble_phi_deg; }; } // namespace VERITAS #endif // VSSIMCOORDTRANSFORM_HPP
25.548387
79
0.640152
sfegan
824e717c4a58d13ad2d91ed111fac33a3307c6de
5,526
hpp
C++
source/NanairoCore/Material/SurfaceModel/Surface/microfacet-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
30
2015-09-06T03:14:29.000Z
2021-06-18T11:00:19.000Z
source/NanairoCore/Material/SurfaceModel/Surface/microfacet-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
31
2016-01-14T14:50:34.000Z
2018-06-25T13:21:48.000Z
source/NanairoCore/Material/SurfaceModel/Surface/microfacet-inl.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
6
2017-04-09T13:07:47.000Z
2021-05-29T21:17:34.000Z
/*! \file microfacet-inl.hpp \author Sho Ikeda Copyright (c) 2015-2018 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef NANAIRO_MICROFACET_INL_HPP #define NANAIRO_MICROFACET_INL_HPP #include "microfacet.hpp" // Standard C++ library #include <utility> // Zisc #include "zisc/error.hpp" #include "zisc/math.hpp" #include "zisc/utility.hpp" // Nanairo #include "fresnel.hpp" #include "NanairoCore/nanairo_core_config.hpp" #include "NanairoCore/Geometry/vector.hpp" #include "NanairoCore/Sampling/sampled_direction.hpp" namespace nanairo { /*! */ template <> inline Float Microfacet::SmithMicrosurface::evalG1( const Float roughness_x, const Float roughness_y, const Vector3& v, const Vector3& m_normal) noexcept { Float g1 = 0.0; const Float cos_nv = v[2]; const Float cos_mv = zisc::dot(m_normal, v); if (((0.0 <= cos_nv) && (0.0 <= cos_mv)) || ((cos_nv < 0.0) && (cos_mv < 0.0))) { const Float r2t2 = Microfacet::calcRoughness2Tan2(roughness_x, roughness_y, v); g1 = 2.0 / (1.0 + zisc::sqrt(1.0 + r2t2)); } ZISC_ASSERT(zisc::isInClosedBounds(g1, 0.0, 1.0), "GGX G1 isn't [0, 1]."); return g1; } /*! */ template <> inline Float Microfacet::SmithMicrosurface::evalG2( const Float roughness_x, const Float roughness_y, const Vector3& vin, const Vector3& vout, const Vector3& m_normal) noexcept { const Float g2 = evalG1(roughness_x, roughness_y, vin, m_normal) * evalG1(roughness_x, roughness_y, vout, m_normal); ZISC_ASSERT(zisc::isInClosedBounds(g2, 0.0, 1.0), "GGX G2 isn't [0, 1]."); return g2; } /*! \details No detailed. */ inline SampledDirection Microfacet::calcReflectionDirection( const Vector3& vin, const SampledDirection& sampled_m_normal) noexcept { ZISC_ASSERT(0.0 <= sampled_m_normal.inversePdf(), "The microfacet normal is negative."); // Calculate the reflection direction const auto& m_normal = sampled_m_normal.direction(); const auto vout = Fresnel::calcReflectionDirection(vin, m_normal); // Calculate the pdf of the direction const Float cos_mi = zisc::dot(m_normal, vin); const Float inverse_jacobian = calcReflectionInverseJacobian(cos_mi); ZISC_ASSERT(0.0 < inverse_jacobian, "The jacobian isn't negative."); const Float inverse_pdf = inverse_jacobian * sampled_m_normal.inversePdf(); return SampledDirection{vout, inverse_pdf}; } /*! \details No detailed. */ inline Vector3 Microfacet::calcReflectionHalfVector(const Vector3& vin, const Vector3& vout) noexcept { const auto half_vector = vin + vout; return half_vector.normalized(); } /*! \details No detailed. */ inline Float Microfacet::calcReflectionInverseJacobian(const Float cos_mi) noexcept { const Float inverse_jacobian = 4.0 * zisc::abs(cos_mi); ZISC_ASSERT(0.0 < inverse_jacobian, "Jacobian isn't positive."); return inverse_jacobian; } /*! \details n = n_transmission_side / n_incident_side */ inline SampledDirection Microfacet::calcRefractionDirection( const Vector3& vin, const SampledDirection& sampled_m_normal, const Float n, const Float g) noexcept { // Calculate the refraction direction const auto& m_normal = sampled_m_normal.direction(); const auto vout = Fresnel::calcRefractionDirection(vin, m_normal, n, g); // Calculate the pdf of the direction const Float cos_mi = zisc::dot(m_normal, vin); const Float cos_mo = zisc::dot(m_normal, vout); ZISC_ASSERT(zisc::isInBounds(-cos_mo, 0.0, 1.0), "cos_mo isn't [0, 1]."); const Float inverse_jacobian = calcRefractionInverseJacobian(cos_mi, cos_mo, n); const Float inverse_pdf = inverse_jacobian * sampled_m_normal.inversePdf(); ZISC_ASSERT(0.0 < inverse_pdf, "PDF isn't positive."); return SampledDirection{vout, inverse_pdf}; } /*! \details n = n_transmission_side / n_incident_side */ inline Vector3 Microfacet::calcRefractionHalfVector(const Vector3& vin, const Vector3& vout, const Float n) noexcept { ZISC_ASSERT(n != 1.0, "The relative index of refraction is 1."); const auto half = (1.0 < n) ? -(vin + n * vout) : (vin + n * vout); return half.normalized(); } /*! \details n = n_transmission_side / n_incident_side */ inline Float Microfacet::calcRefractionInverseJacobian(const Float cos_mi, const Float cos_mo, const Float n) noexcept { const Float tmp = cos_mi + n * cos_mo; const Float inverse_jacobian = zisc::power<2>(tmp) / (zisc::power<2>(n) * zisc::abs(cos_mo)); ZISC_ASSERT(0.0 < inverse_jacobian, "Jacobian isn't positive."); return inverse_jacobian; } /*! */ inline Float Microfacet::calcRoughness2Tan2(const Float roughness_x, const Float roughness_y, const Vector3& v) noexcept { ZISC_ASSERT(v[2] != 0.0, "The v[2] is zero."); const Float r2 = (zisc::power<2>(v[0]) * zisc::power<2>(roughness_x) + zisc::power<2>(v[1]) * zisc::power<2>(roughness_y)) / zisc::power<2>(v[2]); return r2; } } // namespace nanairo #endif // NANAIRO_MICROFACET_INL_HPP
30.196721
83
0.647666
byzin
824f2874943ec9626a9f9dfba120884bc862effc
6,104
cpp
C++
external/OpenGP/apps/glfwviewer_raw/main.cpp
MessCoder/CSC-305
71d64472dcac1eac6402a2650ec37e15b5643312
[ "MIT" ]
null
null
null
external/OpenGP/apps/glfwviewer_raw/main.cpp
MessCoder/CSC-305
71d64472dcac1eac6402a2650ec37e15b5643312
[ "MIT" ]
null
null
null
external/OpenGP/apps/glfwviewer_raw/main.cpp
MessCoder/CSC-305
71d64472dcac1eac6402a2650ec37e15b5643312
[ "MIT" ]
null
null
null
#include <OpenGP/SurfaceMesh/SurfaceMesh.h> #include <OpenGP/SurfaceMesh/bounding_box.h> #include <OpenGP/GL/glfw_helpers.h> #include <OpenGP/GL/glfw_trackball.h> #include <OpenGP/GL/Eigen.h> #include <OpenGP/MLogger.h> using namespace OpenGP; using namespace std; /// Viewer global status SurfaceMesh mesh; std::vector<unsigned int> triangles; /// @todo Find a better place where to put it GLuint programID; /// Matrix stack Eigen::Matrix4f projection; Eigen::Matrix4f model; Eigen::Matrix4f view; void set_uniform_vector(GLuint programID, const char* NAME, const Eigen::Vector3f& vector){ GLuint matrix_id = glGetUniformLocation(programID, NAME); glUniform3fv(matrix_id, 1, vector.data()); } void set_uniform_matrix(GLuint programID, const char* NAME, const Eigen::Matrix4f& matrix){ GLuint matrix_id = glGetUniformLocation(programID, NAME); glUniformMatrix4fv(matrix_id, 1, GL_FALSE, matrix.data()); } void update_projection_matrix() { /// Define projection matrix (FOV, aspect, near, far) projection = OpenGP::perspective(45.0f, static_cast<float>(_width)/static_cast<float>(_height), 0.1f, 10.f); // cout << projection << endl; } /// OpenGL initialization void init(){ ///----------------------- DATA ---------------------------- auto vpoints = mesh.get_vertex_property<Vec3>("v:point"); auto vnormals = mesh.get_vertex_property<Vec3>("v:normal"); assert(vpoints); assert(vnormals); ///---------------------- TRIANGLES ------------------------ triangles.clear(); for(auto f: mesh.faces()) for(auto v: mesh.vertices(f)) triangles.push_back(v.idx()); ///---------------------- OPENGL GLOBALS-------------------- glClearColor(1.0f, 1.0f, 1.0f, 0.0f); ///< background glEnable(GL_DEPTH_TEST); // Enable depth test // glDisable(GL_CULL_FACE); // Cull back-facing /// Compile the shaders programID = load_shaders("vshader.glsl", "fshader.glsl"); if(!programID) exit(EXIT_FAILURE); glUseProgram( programID ); ///---------------------- CAMERA ---------------------------- { typedef Eigen::Vector3f vec3; typedef Eigen::Matrix4f mat4; update_projection_matrix(); /// Define the view matrix (camera extrinsics) vec3 cam_pos(0,0,5); vec3 cam_look(0,0,-1); /// Remember: GL swaps viewdir vec3 cam_up(0,1,0); view = OpenGP::lookAt(cam_pos, cam_look, cam_up); // cout << view << endl; /// Define the modelview matrix model = mat4::Identity(); // cout << model << endl; /// Set initial matrices set_uniform_matrix(programID,"M",model); ///< to get world coordinates set_uniform_matrix(programID,"MV",view*model); ///< to get camera coordinates set_uniform_matrix(programID,"MVP",projection*view*model); ///< to get clip coordinates } ///---------------------- LIGHT ----------------------------- { Vec3 light_dir(0,0,1); set_uniform_vector(programID,"LDIR",light_dir); ///< to get camera coordinates } ///---------------------- VARRAY ---------------------------- { GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); } ///---------------------- BUFFERS ---------------------------- GLuint vertexbuffer, normalbuffer, trianglebuffer; { /// Load mesh vertices glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, mesh.n_vertices() * sizeof(Vec3), vpoints.data(), GL_STATIC_DRAW); /// Load mesh normals glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, mesh.n_vertices() * sizeof(Vec3), vnormals.data(), GL_STATIC_DRAW); /// Triangle indexes buffer glGenBuffers(1, &trianglebuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, trianglebuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, triangles.size() * sizeof(unsigned int), &triangles[0], GL_STATIC_DRAW); } ///---------------------- SHADER ATTRIBUTES ---------------------------- { /// Vertex positions in shader variable "vposition" GLuint vposition = glGetAttribLocation(programID, "vposition"); glEnableVertexAttribArray(vposition); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(vposition, 3, GL_FLOAT, DONT_NORMALIZE, ZERO_STRIDE, ZERO_BUFFER_OFFSET); /// Vertex normals in in shader variable "vnormal" GLuint vnormal = glGetAttribLocation(programID, "vnormal"); glEnableVertexAttribArray(vnormal); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer(vnormal, 3, GL_FLOAT, DONT_NORMALIZE, ZERO_STRIDE, ZERO_BUFFER_OFFSET); } } /// void update_matrices(Eigen::Matrix4f model){ set_uniform_matrix(programID,"M",model); set_uniform_matrix(programID,"MV",view*model); set_uniform_matrix(programID,"MVP",projection*view*model); } /// OpenGL render loop void display(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawElements(GL_TRIANGLES, triangles.size(), GL_UNSIGNED_INT, ZERO_BUFFER_OFFSET); } /// Entry point int main(int argc, char** argv){ if(argc!=2) mFatal("usage: glfwviewer bunny.obj"); int success = mesh.read(argv[1]); if(!success) mFatal() << "File not found"; mesh.triangulate(); mesh.update_vertex_normals(); cout << "input: '" << argv[1] << "' num vertices " << mesh.vertices_size() << endl; cout << "BBOX: " << bounding_box(mesh) << endl; glfwInitWindowSize(_width, _height); if (glfwMakeWindow(__FILE__) == EXIT_FAILURE) return EXIT_FAILURE; glfwDisplayFunc(display); glfwTrackball(update_matrices, update_projection_matrix); init(); glfwMainLoop(); return EXIT_SUCCESS; }
36.118343
118
0.615826
MessCoder
825111ac05fe2fe1f38ced0580c139aed27cd0c2
2,224
cpp
C++
aws-cpp-sdk-chime-sdk-identity/source/model/EndpointStatusReason.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-chime-sdk-identity/source/model/EndpointStatusReason.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-chime-sdk-identity/source/model/EndpointStatusReason.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/chime-sdk-identity/model/EndpointStatusReason.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ChimeSDKIdentity { namespace Model { namespace EndpointStatusReasonMapper { static const int INVALID_DEVICE_TOKEN_HASH = HashingUtils::HashString("INVALID_DEVICE_TOKEN"); static const int INVALID_PINPOINT_ARN_HASH = HashingUtils::HashString("INVALID_PINPOINT_ARN"); EndpointStatusReason GetEndpointStatusReasonForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == INVALID_DEVICE_TOKEN_HASH) { return EndpointStatusReason::INVALID_DEVICE_TOKEN; } else if (hashCode == INVALID_PINPOINT_ARN_HASH) { return EndpointStatusReason::INVALID_PINPOINT_ARN; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<EndpointStatusReason>(hashCode); } return EndpointStatusReason::NOT_SET; } Aws::String GetNameForEndpointStatusReason(EndpointStatusReason enumValue) { switch(enumValue) { case EndpointStatusReason::INVALID_DEVICE_TOKEN: return "INVALID_DEVICE_TOKEN"; case EndpointStatusReason::INVALID_PINPOINT_ARN: return "INVALID_PINPOINT_ARN"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace EndpointStatusReasonMapper } // namespace Model } // namespace ChimeSDKIdentity } // namespace Aws
31.323944
102
0.657374
perfectrecall
8253a14e6837b10f7fa743f21a28f328d071080e
11,233
cpp
C++
crashfix_service/libdumper/PdbCompilandStream.cpp
jsonzilla/crashfix
278a0dfb94f815709067bef61e64f1b290f17fa0
[ "BSD-3-Clause" ]
3
2019-01-07T20:55:30.000Z
2019-04-10T10:04:16.000Z
crashfix_service/libdumper/PdbCompilandStream.cpp
0um/crashfix
f283498b92efbaf150f6f09251d4bd69d8335a6b
[ "BSD-3-Clause" ]
9
2020-04-04T13:33:00.000Z
2020-04-04T13:33:18.000Z
crashfix_service/libdumper/PdbCompilandStream.cpp
jsonzilla/crashfix
278a0dfb94f815709067bef61e64f1b290f17fa0
[ "BSD-3-Clause" ]
1
2021-04-25T14:26:27.000Z
2021-04-25T14:26:27.000Z
//! \file PdbCompilandStream.cpp //! \brief PDB compiland stream. //! \author Oleg Krivtsov //! \date 2011 #include "stdafx.h" #include "PdbCompilandStream.h" #include "PdbDebugInfoStream.h" #include "Buffer.h" #include "strconv.h" #include "PdbStreamStruct.h" #include "PdbReader.h" CPdbCompilandStream::CPdbCompilandStream() : CPdbSymbolStream() { m_bInitialized = FALSE; m_nModuleIndex = -1; m_dwCompilandType = 0; } CPdbCompilandStream::CPdbCompilandStream(CPdbReader* pPdbReader, CMsfStream* pStream, DBI_ModuleInfo* pModuleInfo, BOOL* pbResult) { *pbResult = Init(pPdbReader, pStream, pModuleInfo); } CPdbCompilandStream::~CPdbCompilandStream() { Destroy(); } BOOL CPdbCompilandStream::Init(CPdbReader* pPdbReader, CMsfStream* pStream, DBI_ModuleInfo* pModuleInfo) { //! PDB compiland stream (stream number >=10) //! The stream has the following structure: //! 1. Header including compiland name (variable length). //! 2. Subheader followed by array of zero-terminated string pairs. //! The first string in a pair defines property name, the second one defines property value. //! 3. Symbol section follows (array of symbol records, as in stream #8). The size of this section can be determined from appropriate DBI stream's MODI record. //! 4. C13 Line numbers section follows. Size of this section can be determined from MODI record. //! 4.1. DWORD - maybe count or signature, or segment? //! 4.2. [DWORD - 16 byte] sequences (DWORD+16 byte checksum) //! 5. Some section follows. Leading 4 bytes is the size (size doesn't include 4 bytes). BOOL bResult=FALSE; DWORD dwOffs = 0; std::string str; std::string sParamName; int nCount = -1; DWORD dwLen = 0; DWORD dwLineSectionStart = 0; BOOL bBlocks = TRUE; // Reset stream pos pStream->SetStreamPos(0); // Allocate buffer for the entire stream DWORD dwStreamLen = pStream->GetStreamLen(); CBuffer buf(dwStreamLen); DWORD dwBytesRead = 0; BOOL bRead = pStream->ReadData(buf, dwStreamLen, &dwBytesRead, FALSE); if(!bRead || dwBytesRead!=dwStreamLen) goto cleanup; // Save module index m_nModuleIndex = pModuleInfo->m_nModuleIndex; // Read compiland type m_dwCompilandType = *(LPDWORD)buf.GetPtr(); if(m_dwCompilandType == CT_RESFILE) { // Resource file bResult = true; goto cleanup; } else if(m_dwCompilandType != CT_OBJMODULE) { // Invalid compiland type goto cleanup; } // // Read symbols following the header. // if((LONG)dwOffs<pModuleInfo->m_Info.cbSymbols) { if(!CPdbSymbolStream::Init(pPdbReader, pStream, 4, pModuleInfo->m_Info.cbSymbols-4, &dwOffs)) goto cleanup; } // // Read source file checksums and line numbers // // Read source checksum header //dwOffs = pModuleInfo->m_Info.cbSymbols; pStream->SetStreamPos(dwOffs); while(bBlocks) { BLOCK_HEADER_32 BlockHeader; bRead = pStream->ReadData((LPBYTE)&BlockHeader, sizeof(BLOCK_HEADER_32), &dwBytesRead, FALSE); if(!bRead || dwBytesRead!=sizeof(BLOCK_HEADER_32)) { // End of file reached bResult = true; goto cleanup; } switch(BlockHeader.dwBlockType) { case 0xF4: // Source file checksums { dwLineSectionStart = pStream->GetStreamPos(); BLOCK_HEADER_32 SrcChecksumHeader; bRead = pStream->ReadData((LPBYTE)&SrcChecksumHeader, sizeof(BLOCK_HEADER_32), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(BLOCK_HEADER_32)) { // It seems there is no source checsums bResult = true; goto cleanup; } assert(SrcChecksumHeader.dwBlockType==0xF4); dwOffs = 0; // Read source file checksums int i; for(i=0; dwOffs<SrcChecksumHeader.dwLength; i++) { SOURCE_CHECKSUM sc; bRead = pStream->ReadData((LPBYTE)&sc, sizeof(SOURCE_CHECKSUM), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(SOURCE_CHECKSUM)) { goto cleanup; } DWORD dwChecksumOffs = dwOffs; dwOffs += sizeof(SOURCE_CHECKSUM); SrcChecksum src_checksum; src_checksum.m_Info = sc; if(sc.wCheckSumType==CHECKSUM_MD5) { src_checksum.m_CheckSum.Allocate(16); bRead = pStream->ReadData((LPBYTE)src_checksum.m_CheckSum, 16, &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=16) goto cleanup; LPBYTE pCheckSum = src_checksum.m_CheckSum.GetPtr(); char szCheckSum[128] = ""; #ifdef _WIN32 sprintf_s( szCheckSum, 128, "0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x", pCheckSum[0], pCheckSum[1], pCheckSum[2], pCheckSum[3], pCheckSum[4], pCheckSum[5], pCheckSum[6], pCheckSum[7], pCheckSum[8], pCheckSum[9], pCheckSum[10], pCheckSum[11], pCheckSum[12], pCheckSum[13], pCheckSum[14], pCheckSum[15]); #else sprintf( szCheckSum, "0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x", pCheckSum[0], pCheckSum[1], pCheckSum[2], pCheckSum[3], pCheckSum[4], pCheckSum[5], pCheckSum[6], pCheckSum[7], pCheckSum[8], pCheckSum[9], pCheckSum[10], pCheckSum[11], pCheckSum[12], pCheckSum[13], pCheckSum[14], pCheckSum[15]); #endif src_checksum.m_sCheckSum = szCheckSum; dwOffs += 16; } dwOffs += 2; // skip padding bytes pStream->SetStreamPosRel(2); m_aSrcChecksums.push_back(src_checksum); m_aSrcChecksumOffsets[dwChecksumOffs] = m_aSrcChecksums.size()-1; } } break; case 0xF2: // Line numbers { SymbolLines SymLines; // Read symbol lines header SYMBOL_LINES sl; bRead = pStream->ReadData((LPBYTE)&sl, sizeof(SYMBOL_LINES), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(SYMBOL_LINES)) goto cleanup; SymLines.m_Header = sl; dwOffs = sizeof(SYMBOL_LINES)-8; // Read line addresses following the header for(;dwOffs<sl.Header.dwLength;) { LINE_ADDRESS la; bRead = pStream->ReadData((LPBYTE)&la, sizeof(LINE_ADDRESS), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(LINE_ADDRESS)) goto cleanup; SymLines.m_Lines.push_back(la); dwOffs += sizeof(LINE_ADDRESS); } m_aSrcLines.push_back(SymLines); } break; default: bBlocks = FALSE; break; } } // Read the last strange section (possibly relocations or OMAP) // Read section length DWORD bRead = pStream->ReadData((LPBYTE)&dwLen, sizeof(DWORD), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(DWORD)) goto cleanup; // Read DWORDs following the header nCount = dwLen/sizeof(DWORD); int i; for(i=0; i<nCount; i++) { DWORD dwNumber = 0; bRead = pStream->ReadData((LPBYTE)&dwNumber, sizeof(DWORD), &dwBytesRead, TRUE); if(!bRead || dwBytesRead!=sizeof(DWORD)) goto cleanup; m_aNumbers.push_back(dwNumber); } bResult=TRUE; cleanup: m_bInitialized = bResult; return bResult; } void CPdbCompilandStream::Destroy() { // Destroy parent CPdbSymbolStream::Destroy(); m_aNumbers.clear(); m_aSrcLines.clear(); m_aSrcChecksumOffsets.clear(); m_aSrcChecksums.clear(); } DWORD CPdbCompilandStream::GetCompilandType() { return m_dwCompilandType; } int CPdbCompilandStream::GetSrcFileCheckSumCount() { return (int)m_aSrcChecksums.size(); } SrcChecksum* CPdbCompilandStream::GetSrcFileCheckSum(int nIndex) { if(nIndex<0 || nIndex>=(int)m_aSrcChecksums.size()) return NULL; return &m_aSrcChecksums[nIndex]; } int CPdbCompilandStream::GetSrcFileCheckSumIndexByOffs(DWORD dwOffs) { std::map<DWORD, size_t>::iterator it = m_aSrcChecksumOffsets.find(dwOffs); if(it==m_aSrcChecksumOffsets.end()) return -1; // Not found such offset return (int)it->second; } int CPdbCompilandStream::GetSymbolLineCount() { return (int)m_aSrcLines.size(); } SymbolLines* CPdbCompilandStream::GetSymbolLines(int nIndex) { return &m_aSrcLines[nIndex]; } bool CPdbCompilandStream::FindSrcFileAndLineByAddr(DWORD64 dwAddr, std::wstring& sFileName, int& nLineNumber, DWORD& dwOffsInLine) { sFileName = L""; nLineNumber = -1; CPdbDebugInfoStream* pDBI = m_pPdbReader->GetDebugInfoStream(); CPdbSectionMapStream* pSectionMap = m_pPdbReader->GetSectionMapStream(); size_t i; for(i=0; i<m_aSrcLines.size(); i++) { // Get section start address SymbolLines& lines = m_aSrcLines[i]; IMAGE_SECTION_HEADER* pSecHdr = pSectionMap->GetSection(lines.m_Header.dwSegment-1); if(!pSecHdr) continue; // Get RVA and size of this section contribution DWORD dwStart = pSecHdr->VirtualAddress + lines.m_Header.dwOffset; DWORD dwSize = lines.m_Header.dwSectionContribLen; // Check if user-provided address belongs to this section contribution if(dwStart<=dwAddr && dwAddr<dwStart+dwSize) { int nCheckSumIndex = GetSrcFileCheckSumIndexByOffs(lines.m_Header.dwSrcCheckSumOffs); SrcChecksum* pChecksum = GetSrcFileCheckSum(nCheckSumIndex); assert(pChecksum); int nFileNameIndex = pDBI->FindSrcFileNameByModule(m_nModuleIndex, nCheckSumIndex); if(nFileNameIndex>=0) { sFileName = pDBI->GetSrcFileName(nFileNameIndex); } // Get line number DWORD dwOffs = (DWORD)dwAddr-dwStart; int j; for(j=(int)lines.m_Lines.size()-1; j>=0; j--) { LINE_ADDRESS& line = lines.m_Lines[j]; if(dwOffs<line.dwOffset) continue; nLineNumber = line.wNumber; dwOffsInLine = dwOffs-line.dwOffset; break; } return true; } } // No source file information found return false; }
32.002849
166
0.589958
jsonzilla
8254fd24e943bbb2aa0ae99803b2fe1807b2215c
71
cpp
C++
src/playground.cpp
salonmor/blog
1c51d1c6143d3688c30dda907df55dd6ba955a55
[ "0BSD" ]
null
null
null
src/playground.cpp
salonmor/blog
1c51d1c6143d3688c30dda907df55dd6ba955a55
[ "0BSD" ]
null
null
null
src/playground.cpp
salonmor/blog
1c51d1c6143d3688c30dda907df55dd6ba955a55
[ "0BSD" ]
null
null
null
#include "I.hpp" #include "T.hpp" using namespace std; int main() { }
8.875
20
0.647887
salonmor
82555430a96d157fb09eec653fcfc5723aa3e57a
17
cpp
C++
PokittoLibraryPrototype/FileSystems/File.cpp
Pharap/PokittoLibraryPrototype
f8efcbc693090d7cf3fe364272f6c9c2d3e30c1f
[ "BSD-3-Clause" ]
23
2018-12-30T21:04:47.000Z
2022-01-30T05:12:26.000Z
PokittoLibraryPrototype/FileSystems/File.cpp
Pharap/PokittoLibraryPrototype
f8efcbc693090d7cf3fe364272f6c9c2d3e30c1f
[ "BSD-3-Clause" ]
4
2019-01-01T21:30:56.000Z
2022-02-24T17:44:37.000Z
PokittoLibraryPrototype/FileSystems/File.cpp
Pharap/PokittoLibraryPrototype
f8efcbc693090d7cf3fe364272f6c9c2d3e30c1f
[ "BSD-3-Clause" ]
3
2019-06-12T19:25:53.000Z
2022-01-11T23:46:34.000Z
#include "File.h"
17
17
0.705882
Pharap
825610ec33ec066781f205bab30bf7cd74934b13
656
cpp
C++
FroggerObjects/Utilities/ResetableObject.cpp
RicardoEPRodrigues/FroggerOpenGL
dc02437dfe14203e9bdb39f160e4877b44363c42
[ "MIT" ]
null
null
null
FroggerObjects/Utilities/ResetableObject.cpp
RicardoEPRodrigues/FroggerOpenGL
dc02437dfe14203e9bdb39f160e4877b44363c42
[ "MIT" ]
1
2016-12-31T15:43:29.000Z
2016-12-31T15:43:29.000Z
FroggerObjects/Utilities/ResetableObject.cpp
RicardoEPRodrigues/FroggerOpenGL
dc02437dfe14203e9bdb39f160e4877b44363c42
[ "MIT" ]
null
null
null
/* * ResetableObject.cpp * * Created on: Oct 29, 2014 * Author: ricardo */ #include "ResetableObject.h" ResetableObject::ResetableObject() : DynamicObject() { this->setAlive(false); this->_resetTime = rand() % 10; } ResetableObject::~ResetableObject() { } void ResetableObject::resetPosition() { this->setPosition(this->_resetPosition); } void ResetableObject::die() { this->resetPosition(); this->setAlive(false); this->_resetTime = rand() % 10; } void ResetableObject::respawn() { this->resetPosition(); this->setAlive(true); } void ResetableObject::updateResetTime() { this->_resetTime--; }
17.72973
44
0.655488
RicardoEPRodrigues
825774a51d730677917f6c9321ad7fc6dc533b2d
2,767
cpp
C++
source/tests.cpp
saJonMR/programmiersprachen-raytracer-1
6f2345a9f1b255e0c02b2b11a4d33247f78d8fe7
[ "MIT" ]
null
null
null
source/tests.cpp
saJonMR/programmiersprachen-raytracer-1
6f2345a9f1b255e0c02b2b11a4d33247f78d8fe7
[ "MIT" ]
null
null
null
source/tests.cpp
saJonMR/programmiersprachen-raytracer-1
6f2345a9f1b255e0c02b2b11a4d33247f78d8fe7
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "shape.hpp" #include <glm/vec3.hpp> #include "box.hpp" #include "sphere.hpp" #include "color.hpp" #include "scene.hpp" #include "scene.cpp" #include <string> #include <sstream> TEST_CASE ("rec", "[rec]"){ glm::vec3 origin {0.f, 0.f, 0.f}; glm::vec3 corner1 {2.f, 2.f, 2.f}; Color color{0.f, 0.f, 0.f}; float z = 2; Material m1 = {"Holz", color, 0.f, 0.f, 0.f, 2}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Box b1 {origin,corner1,"KASTEN",c1}; REQUIRE(b1.area()==16); REQUIRE(b1.volume()==8); std::cout<<b1; } TEST_CASE ("sph", "[sph]"){ glm::vec3 origin {0.f, 0.f, 0.f}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Sphere s1 {origin, 4.f,"KREIS", c1}; REQUIRE(round(s1.area())==201); REQUIRE(round(s1.volume())==268); std::cout<<s1; } #include <glm/glm.hpp> #include <glm/gtx/intersect.hpp> TEST_CASE ("intersect_ray_sphere", "[intersect]") { // Ray glm::vec3 ray_origin {0.0f, 0.0f, 0.0f}; // ray direction has to be normalized ! // you can use : //v = glm::normalize (some_vector) glm::vec3 ray_direction{0.0f ,0.0f, 1.0f}; // Sphere glm::vec3 sphere_center{0.0f, 0.0f, 5.0f}; float sphere_radius {1.0f}; float distance = 0.0f; auto result = glm::intersectRaySphere( ray_origin, ray_direction , sphere_center , sphere_radius * sphere_radius , // squared radius !!! distance); REQUIRE(distance == Approx(4.0f)); glm::vec3 origin {8.f, 0.f, 0.f}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Sphere s1 {origin, 5.f,"KREIS", c1}; glm::vec3 rayo{0.0f, 0.0f, 0.0f}; glm::vec3 rayd{1.f, 0.f, 0.f}; Ray testray{rayo, rayd}; float t = 2; } TEST_CASE ("delete", "[delete]") { glm::vec3 origin {8.f, 0.f, 0.f}; std::shared_ptr<Material> red = std::make_shared<Material>(Material{}); Sphere* s1 =new Sphere{origin, 5.f,"sphere0", red}; Shape* s2 =new Sphere{origin, 5.f,"sphere1", red}; delete s1; delete s2; } TEST_CASE ("squareint", "[intersect]"){ glm::vec3 origin {1.f, 1.f, 1.f}; glm::vec3 corner1 {4.f, 4.f, 4.f}; std::shared_ptr<Material> c1 = std::make_shared<Material>(Material{}); Box b1 {origin,corner1,"BOX",c1}; glm::vec3 rayo{0.0f, 0.0f, 0.0f}; glm::vec3 rayd{1.f, 1.f, 1.f}; glm::vec3 rayc{1.f, 0.f, 1.f}; Ray testray2{rayo, rayc}; Ray testray{rayo, rayd}; float t = 1; REQUIRE(b1.intersect(testray, t).cut_); REQUIRE(!b1.intersect(testray2, t).cut_); } TEST_CASE ("tostruc", "[tostruc]"){ std::string path = "/home/vincent/Dokumente/programmiersprachen-raytracer/source/material.sdf"; Scene S {createscene(path)}; } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); }
28.525773
97
0.642212
saJonMR
825f3c3890893b99d7be27d32a2fd7c80670dbb8
1,655
cpp
C++
tests/src/count.cpp
pinam45/dynamic_bitset
6d19b2da9b69b8c77d7b86b453c757cd5fa8711f
[ "MIT" ]
98
2019-03-31T20:18:58.000Z
2022-03-15T12:58:19.000Z
tests/src/count.cpp
pinam45/dynamic_bitset
6d19b2da9b69b8c77d7b86b453c757cd5fa8711f
[ "MIT" ]
7
2019-07-09T15:16:53.000Z
2021-05-30T17:38:42.000Z
tests/src/count.cpp
pinam45/dynamic_bitset
6d19b2da9b69b8c77d7b86b453c757cd5fa8711f
[ "MIT" ]
12
2019-05-20T13:57:15.000Z
2022-02-06T09:43:13.000Z
// // Copyright (c) 2019 Maxime Pinard // // Distributed under the MIT license // See accompanying file LICENSE or copy at // https://opensource.org/licenses/MIT // #include "config.hpp" #include "utils.hpp" #include "RandomDynamicBitsetGenerator.hpp" #include <catch2/catch.hpp> #include <sul/dynamic_bitset.hpp> #include <cstdint> #if DYNAMIC_BITSET_CAN_USE_LIBPOPCNT # define COUNT_TESTED_IMPL "libpopcnt" #elif DYNAMIC_BITSET_CAN_USE_STD_BITOPS # define COUNT_TESTED_IMPL "C++20 binary operations" #elif DYNAMIC_BITSET_CAN_USE_GCC_BUILTIN # define COUNT_TESTED_IMPL "gcc builtins" #elif DYNAMIC_BITSET_CAN_USE_CLANG_BUILTIN_POPCOUNT # define COUNT_TESTED_IMPL "clang builtins" #else # define COUNT_TESTED_IMPL "base" #endif TEMPLATE_TEST_CASE("count (" COUNT_TESTED_IMPL ")", "[dynamic_bitset][libpopcnt][builtin][c++20]", uint16_t, uint32_t, uint64_t) { CAPTURE(SEED); SECTION("empty bitset") { sul::dynamic_bitset<TestType> bitset; REQUIRE(bitset.count() == 0); } SECTION("non-empty bitset") { sul::dynamic_bitset<TestType> bitset = GENERATE(take(RANDOM_VECTORS_TO_TEST, randomDynamicBitset<TestType>(SEED))); CAPTURE(bitset); size_t count = 0; for(size_t i = 0; i < bitset.size(); ++i) { count += static_cast<size_t>(bitset[i]); } SECTION("general") { REQUIRE(bitset.count() == count); } SECTION("first block empty") { bitset.append(0); bitset <<= bits_number<TestType>; REQUIRE(bitset.count() == count); } SECTION("last block empty") { bitset.append(0); REQUIRE(bitset.count() == count); } } }
22.066667
80
0.685196
pinam45
8266ef0c94bb05f329179d851d2a834cd51e899b
4,577
cpp
C++
src/state_machine.cpp
mairas/sailor-hat-firmware
48390bbc3226b046b294d804ca5c266797b5cb2e
[ "BSD-3-Clause" ]
null
null
null
src/state_machine.cpp
mairas/sailor-hat-firmware
48390bbc3226b046b294d804ca5c266797b5cb2e
[ "BSD-3-Clause" ]
null
null
null
src/state_machine.cpp
mairas/sailor-hat-firmware
48390bbc3226b046b294d804ca5c266797b5cb2e
[ "BSD-3-Clause" ]
1
2021-04-21T08:38:27.000Z
2021-04-21T08:38:27.000Z
#include "state_machine.h" #include "digital_io.h" #include "globals.h" // take care to have all enum values of StateType present void (*state_machine[])(void) = { sm_state_BEGIN, sm_state_WAIT_VIN_ON, sm_state_ENT_CHARGING, sm_state_CHARGING, sm_state_ENT_ON, sm_state_ON, sm_state_ENT_DEPLETING, sm_state_DEPLETING, sm_state_ENT_SHUTDOWN, sm_state_SHUTDOWN, sm_state_ENT_WATCHDOG_REBOOT, sm_state_WATCHDOG_REBOOT, sm_state_ENT_OFF, sm_state_OFF, }; StateType sm_state = BEGIN; StateType get_sm_state() { return sm_state; } // PATTERN: *___________________ int off_pattern[] = {50, 950, -1}; void sm_state_BEGIN() { set_en5v_pin(false); i2c_register = 0xff; watchdog_limit = 0; gpio_poweroff_elapsed = 0; status_blinker.set_pattern(off_pattern); sm_state = WAIT_VIN_ON; } void sm_state_WAIT_VIN_ON() { // never start if DC input voltage is not present if (v_in >= int(VIN_OFF / VIN_MAX * VIN_SCALE)) { sm_state = ENT_CHARGING; } } // PATTERN: *************_*_*_*_ int charging_pattern[] = {650, 50, 50, 50, 50, 50, 50, 50, -1}; void sm_state_ENT_CHARGING() { status_blinker.set_pattern(charging_pattern); sm_state = CHARGING; } void sm_state_CHARGING() { if (v_supercap > power_on_vcap_voltage) { sm_state = ENT_ON; } else if (v_in < int(VIN_OFF / VIN_MAX * VIN_SCALE)) { // if power is cut before supercap is charged, // kill power immediately sm_state = ENT_OFF; } } // PATTERN: ******************** int solid_on_pattern[] = {1000, 0, -1}; void sm_state_ENT_ON() { set_en5v_pin(true); status_blinker.set_pattern(solid_on_pattern); sm_state = ON; } // PATTERN: *******************_ int watchdog_enabled_pattern[] = {950, 50, -1}; void sm_state_ON() { if (watchdog_value_changed) { if (watchdog_limit) { status_blinker.set_pattern(watchdog_enabled_pattern); } else { status_blinker.set_pattern(solid_on_pattern); } watchdog_value_changed = false; } if (watchdog_limit && (watchdog_elapsed > watchdog_limit)) { sm_state = ENT_WATCHDOG_REBOOT; return; } // kill the power if the host has been powered off for more than a second if (gpio_poweroff_elapsed > GPIO_OFF_TIME_LIMIT) { sm_state = ENT_OFF; return; } if (v_in < int(VIN_OFF / VIN_MAX * VIN_SCALE)) { sm_state = ENT_DEPLETING; } } // PATTERN: *_*_*_*_____________ int draining_pattern[] = {50, 50, 50, 50, 50, 50, 50, 650, -1}; void sm_state_ENT_DEPLETING() { status_blinker.set_pattern(draining_pattern); sm_state = DEPLETING; } void sm_state_DEPLETING() { if (watchdog_limit && (watchdog_elapsed > watchdog_limit)) { sm_state = ENT_WATCHDOG_REBOOT; return; } if (shutdown_requested) { shutdown_requested = false; sm_state = ENT_SHUTDOWN; return; } else if (v_in > int(VIN_OFF / VIN_MAX * VIN_SCALE)) { sm_state = ENT_ON; return; } else if (v_supercap < power_off_vcap_voltage) { sm_state = ENT_OFF; return; } // kill the power if the host has been powered off for more than a second if (gpio_poweroff_elapsed > GPIO_OFF_TIME_LIMIT) { sm_state = ENT_OFF; return; } } elapsedMillis elapsed_shutdown; // PATTERN: ****____ int shutdown_pattern[] = {200, 200, -1}; void sm_state_ENT_SHUTDOWN() { status_blinker.set_pattern(shutdown_pattern); // ignore watchdog watchdog_limit = 0; elapsed_shutdown = 0; sm_state = SHUTDOWN; } void sm_state_SHUTDOWN() { if ((gpio_poweroff_elapsed > GPIO_OFF_TIME_LIMIT) || (elapsed_shutdown > SHUTDOWN_WAIT_DURATION)) { sm_state = ENT_OFF; } } elapsedMillis elapsed_off; void sm_state_ENT_OFF() { set_en5v_pin(false); // in case we're not dead, set a blink pattern status_blinker.set_pattern(off_pattern); sm_state = OFF; } void sm_state_OFF() { if (elapsed_off > OFF_STATE_DURATION) { // if we're still alive, jump back to begin sm_state = BEGIN; } } elapsedMillis elapsed_reboot; // PATTERN: *_ int watchdog_pattern[] = {50, 50, -1}; void sm_state_ENT_WATCHDOG_REBOOT() { elapsed_reboot = 0; watchdog_limit = 0; set_en5v_pin(false); status_blinker.set_pattern(watchdog_pattern); sm_state = WATCHDOG_REBOOT; } void sm_state_WATCHDOG_REBOOT() { if (elapsed_reboot > WATCHDOG_REBOOT_DURATION) { sm_state = BEGIN; } } // function to run the state machine void sm_run() { if (sm_state < NUM_STATES) { // call the function for the state (*state_machine[sm_state])(); } else { sm_state = BEGIN; // FIXME: should we restart instead? } }
22.546798
75
0.687787
mairas
826db133c6e83f060c8f139633347a860f1f3fee
554
cpp
C++
Opium/src/Renderer/UniformBuffer.cpp
yatiyr/Opium
ed6e7a08ee23bc353bcc6b943fa3e1a13b2f2d41
[ "MIT" ]
null
null
null
Opium/src/Renderer/UniformBuffer.cpp
yatiyr/Opium
ed6e7a08ee23bc353bcc6b943fa3e1a13b2f2d41
[ "MIT" ]
null
null
null
Opium/src/Renderer/UniformBuffer.cpp
yatiyr/Opium
ed6e7a08ee23bc353bcc6b943fa3e1a13b2f2d41
[ "MIT" ]
null
null
null
#include <Precomp.h> #include <Renderer/UniformBuffer.h> #include <Renderer/Renderer.h> #include <Platform/OpenGL/OpenGLUniformBuffer.h> namespace OP { Ref<UniformBuffer> UniformBuffer::Create(uint32_t size, uint32_t binding) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: OP_ENGINE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; case RendererAPI::API::OpenGL: return CreateRef<OpenGLUniformBuffer>(size, binding); } OP_ENGINE_ASSERT(false, "Unknown RendererAPI!"); return nullptr; } }
27.7
121
0.752708
yatiyr
82710ab65cb15b0991a59e7971e3967c9f4a80b0
10,923
cpp
C++
Source/TitaniumKit/src/Media/AudioPlayer.cpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
20
2015-04-02T06:55:30.000Z
2022-03-29T04:27:30.000Z
Source/TitaniumKit/src/Media/AudioPlayer.cpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
692
2015-04-01T21:05:49.000Z
2020-03-10T10:11:57.000Z
Source/TitaniumKit/src/Media/AudioPlayer.cpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
22
2015-04-01T20:57:51.000Z
2022-01-18T17:33:15.000Z
/** * TitaniumKit Titanium.Media.AudioPlayer * * Copyright (c) 2015 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License. * Please see the LICENSE included with this distribution for details. */ #include "Titanium/Media/AudioPlayer.hpp" #include "Titanium/detail/TiImpl.hpp" namespace Titanium { namespace Media { AudioPlayer::AudioPlayer(const JSContext& js_context) TITANIUM_NOEXCEPT : Module(js_context, "Ti.Media.AudioPlayer") , state_buffering__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Buffering))) , state_initialized__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Initialized))) , state_paused__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Paused))) , state_playing__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Playing))) , state_starting__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Starting))) , state_stopped__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Stopped))) , state_stopping__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::Stopping))) , state_waiting_for_data__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::WaitingForData))) , state_waiting_for_queue__(js_context.CreateNumber(static_cast<std::uint32_t>(AudioState::WaitingForQueue))) , allowBackground__(false) , autoplay__(false) , bitRate__(0) , idle__(false) , paused__(false) , playing__(false) , state__(AudioState::Stopped) , url__("") , volume__(0) , waiting__(false) , bufferSize__(0) { } TITANIUM_PROPERTY_READWRITE(AudioPlayer, bool, allowBackground) TITANIUM_PROPERTY_READWRITE(AudioPlayer, bool, autoplay) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::uint32_t, bitRate) TITANIUM_PROPERTY_READ(AudioPlayer, std::chrono::milliseconds, duration) TITANIUM_PROPERTY_READ(AudioPlayer, bool, idle) TITANIUM_PROPERTY_READWRITE(AudioPlayer, bool, paused) TITANIUM_PROPERTY_READ(AudioPlayer, bool, playing) TITANIUM_PROPERTY_READ(AudioPlayer, std::chrono::milliseconds, progress) TITANIUM_PROPERTY_READ(AudioPlayer, AudioState, state) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::string, url) TITANIUM_PROPERTY_READWRITE(AudioPlayer, double, volume) TITANIUM_PROPERTY_READ(AudioPlayer, bool, waiting) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::uint32_t, bufferSize) TITANIUM_PROPERTY_READWRITE(AudioPlayer, std::chrono::milliseconds, time) bool AudioPlayer::isPaused() TITANIUM_NOEXCEPT { return (get_state() == AudioState::Paused); } bool AudioPlayer::isPlaying() TITANIUM_NOEXCEPT { return (get_state() == AudioState::Playing); } void AudioPlayer::pause() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::pause: Unimplemented"); } void AudioPlayer::play() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::play: Unimplemented"); } void AudioPlayer::release() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::release: Unimplemented"); } void AudioPlayer::start() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::start: Unimplemented"); } std::string AudioPlayer::stateDescription(const AudioState& state) TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::stateDescription: Unimplemented"); return ""; } void AudioPlayer::stop() TITANIUM_NOEXCEPT { TITANIUM_LOG_WARN("AudioPlayer::stop: Unimplemented"); } void AudioPlayer::JSExportInitialize() { JSExport<AudioPlayer>::SetClassVersion(1); JSExport<AudioPlayer>::SetParent(JSExport<Module>::Class()); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_BUFFERING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_INITIALIZED); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_PAUSED); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_PLAYING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_STARTING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_STOPPED); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_STOPPING); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_WAITING_FOR_DATA); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, STATE_WAITING_FOR_QUEUE); TITANIUM_ADD_PROPERTY(AudioPlayer, allowBackground); TITANIUM_ADD_PROPERTY(AudioPlayer, autoplay); TITANIUM_ADD_PROPERTY(AudioPlayer, bitRate); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, duration); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, idle); TITANIUM_ADD_PROPERTY(AudioPlayer, paused); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, playing); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, progress); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, state); TITANIUM_ADD_PROPERTY(AudioPlayer, url); TITANIUM_ADD_PROPERTY(AudioPlayer, volume); TITANIUM_ADD_PROPERTY_READONLY(AudioPlayer, waiting); TITANIUM_ADD_PROPERTY(AudioPlayer, bufferSize); TITANIUM_ADD_PROPERTY(AudioPlayer, time); TITANIUM_ADD_FUNCTION(AudioPlayer, isPaused); TITANIUM_ADD_FUNCTION(AudioPlayer, isPlaying); TITANIUM_ADD_FUNCTION(AudioPlayer, pause); TITANIUM_ADD_FUNCTION(AudioPlayer, play); TITANIUM_ADD_FUNCTION(AudioPlayer, release); TITANIUM_ADD_FUNCTION(AudioPlayer, start); TITANIUM_ADD_FUNCTION(AudioPlayer, stateDescription); TITANIUM_ADD_FUNCTION(AudioPlayer, stop); TITANIUM_ADD_FUNCTION(AudioPlayer, getAllowBackground); TITANIUM_ADD_FUNCTION(AudioPlayer, setAllowBackground); TITANIUM_ADD_FUNCTION(AudioPlayer, getAutoplay); TITANIUM_ADD_FUNCTION(AudioPlayer, setAutoplay); TITANIUM_ADD_FUNCTION(AudioPlayer, getBitRate); TITANIUM_ADD_FUNCTION(AudioPlayer, setBitRate); TITANIUM_ADD_FUNCTION(AudioPlayer, getDuration); TITANIUM_ADD_FUNCTION(AudioPlayer, getIdle); TITANIUM_ADD_FUNCTION(AudioPlayer, getPaused); TITANIUM_ADD_FUNCTION(AudioPlayer, setPaused); TITANIUM_ADD_FUNCTION(AudioPlayer, getPlaying); TITANIUM_ADD_FUNCTION(AudioPlayer, getProgress); TITANIUM_ADD_FUNCTION(AudioPlayer, getState); TITANIUM_ADD_FUNCTION(AudioPlayer, getUrl); TITANIUM_ADD_FUNCTION(AudioPlayer, setUrl); TITANIUM_ADD_FUNCTION(AudioPlayer, getVolume); TITANIUM_ADD_FUNCTION(AudioPlayer, setVolume); TITANIUM_ADD_FUNCTION(AudioPlayer, getWaiting); TITANIUM_ADD_FUNCTION(AudioPlayer, getBufferSize); TITANIUM_ADD_FUNCTION(AudioPlayer, setBufferSize); TITANIUM_ADD_FUNCTION(AudioPlayer, getTime); TITANIUM_ADD_FUNCTION(AudioPlayer, setTime); } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_BUFFERING) { return state_buffering__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_INITIALIZED) { return state_initialized__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_PAUSED) { return state_paused__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_PLAYING) { return state_playing__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_STARTING) { return state_starting__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_STOPPED) { return state_stopped__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_STOPPING) { return state_stopping__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_WAITING_FOR_DATA) { return state_waiting_for_data__; } TITANIUM_PROPERTY_GETTER(AudioPlayer, STATE_WAITING_FOR_QUEUE) { return state_waiting_for_queue__; } TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, allowBackground) TITANIUM_PROPERTY_SETTER_BOOL(AudioPlayer, allowBackground) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, autoplay) TITANIUM_PROPERTY_SETTER_BOOL(AudioPlayer, autoplay) TITANIUM_PROPERTY_GETTER_UINT(AudioPlayer, bitRate) TITANIUM_PROPERTY_SETTER_UINT(AudioPlayer, bitRate) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, idle) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, paused) TITANIUM_PROPERTY_SETTER_BOOL(AudioPlayer, paused) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, playing) TITANIUM_PROPERTY_GETTER_STRING(AudioPlayer, url) TITANIUM_PROPERTY_SETTER_STRING(AudioPlayer, url) TITANIUM_PROPERTY_GETTER_DOUBLE(AudioPlayer, volume) TITANIUM_PROPERTY_SETTER_DOUBLE(AudioPlayer, volume) TITANIUM_PROPERTY_GETTER_BOOL(AudioPlayer, waiting) TITANIUM_PROPERTY_GETTER_UINT(AudioPlayer, bufferSize) TITANIUM_PROPERTY_SETTER_UINT(AudioPlayer, bufferSize) TITANIUM_PROPERTY_GETTER_TIME(AudioPlayer, time) TITANIUM_PROPERTY_SETTER_TIME(AudioPlayer, time) TITANIUM_PROPERTY_GETTER_ENUM(AudioPlayer, state) TITANIUM_PROPERTY_GETTER_TIME(AudioPlayer, duration) TITANIUM_PROPERTY_GETTER_TIME(AudioPlayer, progress) TITANIUM_FUNCTION(AudioPlayer, isPaused) { return get_context().CreateBoolean(isPaused()); } TITANIUM_FUNCTION(AudioPlayer, isPlaying) { return get_context().CreateBoolean(isPlaying()); } TITANIUM_FUNCTION(AudioPlayer, pause) { pause(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, play) { play(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, release) { release(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, start) { start(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION(AudioPlayer, stateDescription) { ENSURE_UINT_AT_INDEX(state, 0); return get_context().CreateString(stateDescription(static_cast<AudioState>(state))); } TITANIUM_FUNCTION(AudioPlayer, stop) { stop(); return get_context().CreateUndefined(); } TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getAllowBackground, allowBackground) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setAllowBackground, allowBackground) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getAutoplay, autoplay) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setAutoplay, autoplay) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getBitRate, bitRate) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setBitRate, bitRate) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getDuration, duration) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getIdle, idle) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getPaused, paused) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setPaused, paused) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getPlaying, playing) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getProgress, progress) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getState, state) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getUrl, url) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setUrl, url) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getVolume, volume) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setVolume, volume) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getWaiting, waiting) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getBufferSize, bufferSize) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setBufferSize, bufferSize) TITANIUM_FUNCTION_AS_GETTER(AudioPlayer, getTime, time) TITANIUM_FUNCTION_AS_SETTER(AudioPlayer, setTime, time) } // namespace Media } // namespace Titanium
36.654362
112
0.802161
garymathews
82716f4273626effe6da40ce822d1deef0f771df
853
cpp
C++
cf/Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1) /b.cpp
emengdeath/acmcode
cc1b0e067464e754d125856004a991d6eb92a2cd
[ "MIT" ]
null
null
null
cf/Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1) /b.cpp
emengdeath/acmcode
cc1b0e067464e754d125856004a991d6eb92a2cd
[ "MIT" ]
null
null
null
cf/Codeforces Round #470 (rated, Div. 2, based on VK Cup 2018 Round 1) /b.cpp
emengdeath/acmcode
cc1b0e067464e754d125856004a991d6eb92a2cd
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<algorithm> #define N 2000002 using namespace std; long long bz[N][3]; int d[100]; int n; void work(int x){ for (int i=2;(long long)i*i<=x;i++) if (x%i==0){ d[++d[0]]=i; while (!(x%i))x/=i; } if (x!=1)d[++d[0]]=x; } int main(){ scanf("%d",&n); bz[n][2]=1,bz[n-1][2]=-1; for (int i=n;i>=1;i--){ bz[i][0]+=bz[i+1][0],bz[i][1]+=bz[i+1][1],bz[i][2]+=bz[i+1][2]; if (bz[i][0]||bz[i][1]||bz[i][2]){ d[0]=0; work(i); if (d[1]==i){ bz[i][0]++; bz[i-1][0]--; continue; } for (int j=1;j<=d[0];j++){ int l=max(i-d[j],d[j]),r=i-1; if (l>r)continue; if (bz[i][2]) bz[l][1]--,bz[r][1]++; if (bz[i][1]) bz[l][0]--,bz[r][0]++; } } } for (int i=1;i<=n;i++) if (bz[i][0]){ printf("%d\n",i); return 0; } printf("%d\n",n); return 0; }
17.770833
67
0.444314
emengdeath
8276695a0e71d627f1ec862c350340047bcd766b
49,066
cpp
C++
mergeBathy/grid.cpp
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
9996f5ee40e40e892ce5eb77dc4bb67930af4005
[ "CC0-1.0" ]
4
2017-05-04T15:50:48.000Z
2020-07-30T03:52:07.000Z
mergeBathy/grid.cpp
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
9996f5ee40e40e892ce5eb77dc4bb67930af4005
[ "CC0-1.0" ]
null
null
null
mergeBathy/grid.cpp
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
9996f5ee40e40e892ce5eb77dc4bb67930af4005
[ "CC0-1.0" ]
2
2017-01-11T09:53:26.000Z
2020-07-30T03:52:09.000Z
/********************************************************************** * CC0 License ********************************************************************** * MergeBathy - Tool to combine one or more bathymetric data files onto a single input grid. * Modified in 2015 by Samantha J.Zambo([email protected]) while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Todd Holland while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Nathaniel Plant while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Kevin Duvieilh while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Paul Elmore while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Will Avera while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by Brian Bourgeois while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by A.Louise Perkins while employed by the U.S.Naval Research Laboratory. * Modified in 2015 by David Lalejini while employed by the U.S.Naval Research Laboratory. * To the extent possible under law, the author(s) and the U.S.Naval Research Laboratory have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide.This software is distributed without any warranty. * You should have received a copy of the CC0 Public Domain Dedication along with this software.If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. **********************************************************************/ //============================================================================ // Grid.C // Downloaded from http:\\oldmill.uchicago.edu/~wilder/Code/grid/ << broken // Working site as of 3 Mar 2018: https://sites.google.com/site/jivsoft/Home #include "grid.h" using namespace std; //============================================================================ // SPECIALIZATIONS FOR UCGRID template<> ostream& operator<<(ostream& os, const ucgrid& g) { for (uint i = 0; i < g.rows(); ++i) { for (uint j = 0; j < g.cols(); ++j) os << setw(4) << (int) g(i, j) << " "; os << "\n"; } return os; } //============================================================================ // SPECIALIZATIONS FOR DGRID #ifdef USE_LAPACK const int izero = 0, ione = 1; const double dzero = 0, done = 1; const cplx zzero = 0.0, zone = 1.0; const char notrans = 'N'; extern "C" { //============================================================================ // Blas 1 routine to compute y = a * x + y // Note: dcopy/zcopy and dscal/zscal are not included here as they are // typically not much, if any, faster than non-Blas routines. void daxpy_(const int*, const double*, const double*, const int*, double*, const int*); void zaxpy_(const int*, const cplx*, const cplx*, const int*, cplx*, const int*); void drot_(const int*, double*, const int*, double*, const int*, const double*, const double*); void zrot_(const int*, cplx*, const int*, cplx*, const int*, const double*, const cplx*); void dlartg_(const double*, const double*, double*, double*, double*); void zlartg_(const cplx*, const cplx*, double*, cplx*, cplx*); //============================================================================ // Blas 3 routines to compute the matrix multiplication product of matrices. void dtrmm_(const char* side, const char* uplo, const char* tra, const char* diag, const int* m, const int* n, const double* alpha, const double* a, const int* lda, double* b, const int* ldb); void ztrmm_(const char* side, const char* uplo, const char* tra, const char* diag, const int* m, const int* n, const cplx* alpha, const cplx* a, const int* lda, cplx* b, const int* ldb); void dgemm_(const char*, const char*, const int*, const int*, const int*, const double*, const double*, const int*, const double*, const int*, const double*, double*, const int*); void zgemm_(const char*, const char*, const int*, const int*, const int*, const cplx*, const cplx*, const int*, const cplx*, const int*, const cplx*, cplx*, const int*); //============================================================================ // Blas 3 routines to solve a AX=B where A is triangular. // These are similar to the Lapack trtrs routines, but they also // allow for solving XA=B. void dtrsm_(const char*, const char*, const char*, const char*, const int*, const int*, const double*, const double*, const int*, const double*, const int*); void ztrsm_(const char*, const char*, const char*, const char*, const int*, const int*, const cplx*, const cplx*, const int*, const cplx*, const int*); //============================================================================ // Lapack routines to solve overdetermined or underdetermined systems. // using a QR or LQ factorization. void dgels_(const char* trans, const int* m, const int* n, const int* nrhs, double* a, const int* lda, double* b, const int* ldb, double* work, const int* lwork, int* info); void zgels_(const char* trans, const int* m, const int* n, const int* nrhs, cplx* a, const int* lda, cplx* b, const int* ldb, cplx* work, const int* lwork, int* info); //============================================================================ // Lapack routines to solve AX=B for square matrices A. void dgesv_(const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, int* info); void zgesv_(const int* n, const int* nrhs, cplx* a, const int* lda, int* ipiv, cplx* b, const int* ldb, int* info); void dsysv_(const char* uplo, const int* n, const int* nrhs, double* a, const int* lda, int* ipiv, double* b, const int* ldb, double* work, const int* lwork, int* info); void zsysv_(const char* uplo, const int* n, const int* nrhs, cplx* a, const int* lda, int* ipiv, cplx* b, const int* ldb, cplx* work, const int* lwork, int* info); void zhesv_(const char* uplo, const int* n, const int* nrhs, cplx* a, const int* lda, int* ipiv, cplx* b, const int* ldb, cplx* work, const int* lwork, int* info); void dposv_(const char* uplo, const int* n, const int* nrhs, double* a, const int* lda, double* b, const int* ldb, int* info); void zposv_(const char* uplo, const int* n, const int* nrhs, cplx* a, const int* lda, cplx* b, const int* ldb, int* info); //============================================================================ // Lapack routines to compute the eigenvalues and (optionally) the // eigenvectors of a matrix. void dgeev_(const char* jobvl, const char* jobvr, const int* n, double* a, const int* lda, double* wr, double* wi, double* vl, const int* ldvl, double* vr, const int* ldvr, double* work, const int* lwork, int* info); void zgeev_(const char* jobvl, const char* jobvr, const int* n, cplx* a, const int* lda, cplx* w, cplx* vl, const int* ldvl, cplx* vr, const int* ldvr, cplx* work, const int* lwork, double* rwork, int* info); void dsyev_(const char* jobz, const char* uplo, const int* n, double* a, const int* lda, double* w, double* work, const int* lwork, int* info); void zheev_(const char* jobz, const char* uplo, const int* n, void* a, const int* lda, void* w, void* work, const int* lwork, const void* work2, int* info); //============================================================================ // Lapack routines to compute the singular values and singular vectors // of a general matrix. void dgesvd(const char* jobu, const char* jobvt, const int* m, const int* n, double* a, const int* lda, double* s, double* u, const int* ldu, double* vt, const int* ldvt, double* work, const int* lwork, int* info); void zgesvd(const char* jobu, const char* jobvt, const int* m, const int* n, cplx* a, const int* lda, double* s, cplx* u, const int* ldu, cplx* vt, const int* ldvt, cplx* work, const int* lwork, int* info); //============================================================================ // Lapack routines to compute the LU/Cholesky Factorization of a matrix // None are needed for triangular matrices... void dgetrf_(const int* m, const int* n, double* a, const int* lda, int* ipiv, int* info); void dsytrf_(const char* uplo, const int* n, double* a, const int* lda, int* ipiv, double* work, const int* lwork, int* info); void dpotrf_(const char* uplo, const int* n, double* a, const int* lda, int* info); void zgetrf_(const int* m, const int* n, cplx* a, const int* lda, int* ipiv, int* info); void zsytrf_(const char* uplo, const int* n, cplx* a, const int* lda, int* ipiv, cplx* work, const int* lwork, int* info); void zpotrf_(const char* uplo, const int* n, cplx* a, const int* lda, int* info); //============================================================================ // Lapack routines to solve a linear system using the // LU/Cholesky Factorization of a matrix void dgetrs_(const char* trans, const int* n, const int* nrhs, const double* a, const int* lda, const int* ipiv, double* b, const int* ldb, int* info); void dsytrs_(const char* uplo, const int* n, const int* nrhs, const double* a, const int* lda, const int* ipiv, double* b, const int* ldb, 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 dtrtrs_(const char* uplo, const char* trans, const char* diag, const int* n, const int* nrhs, const double* a, const int* lda, double* b, const int* ldb, int* info); void zgetrs_(const char* trans, const int* n, const int* nrhs, const cplx* a, const int* lda, const int* ipiv, cplx* b, const int* ldb, int* info); void zsytrs_(const char* uplo, const int* n, const int* nrhs, const cplx* a, const int* lda, const int* ipiv, cplx* b, const int* ldb, int* info); void zpotrs_(const char* uplo, const int* n, const int* nrhs, const cplx* a, const int* lda, cplx* b, const int* ldb, int* info); void ztrtrs_(const char* uplo, const char* trans, const char* diag, const int* n, const int* nrhs, const cplx* a, const int* lda, cplx* b, const int* ldb, int* info); //============================================================================ // Lapack routines to compute the inverse of a matrix void dgetri_(const int* n, double* a, const int* lda, const int* ipiv, double* work, const int* lwork, int* info); void dsytri_(const char* uplo, const int* n, double* a, const int* lda, const int* ipiv, double* work, int* info); void dpotri_(const char* uplo, const int* n, double* a, const int* lda, int* info); void dtrtri_(const char* uplo, const char* diag, const int* n, double* a, const int* lda, int* info); void zgetri_(const int* n, cplx* a, const int* lda, const int* ipiv, cplx* work, const int* lwork, int* info); void zsytri_(const char* uplo, const int* n, cplx* a, const int* lda, const int* ipiv, cplx* work, int* info); void zpotri_(const char* uplo, const int* n, cplx* a, const int* lda, int* info); void ztrtri_(const char* uplo, const char* diag, const int* n, cplx* a, const int* lda, int* info); } //============================================================================ // Compute the matrix product c = a %*% b of two grids/vectors: // More efficient: matmult(a, b, c); Less efficient: c = matmult(a, b); // If &c == &a or &c = &b, then 'a' or 'b' will get overwritten. template<> dgrid& matmult(const dgrid& a, const dgrid& b, dgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == &b) { dgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zgrid& matmult(const zgrid& a, const zgrid& b, zgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == &b) { zgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dgrid& matmult(const dgrid& a, const dvector& b, dgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || (const dvector*)&c == &b) { dgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zgrid& matmult(const zgrid& a, const zvector& b, zgrid& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || (const zvector*)&c == &b) { zgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dgrid& matmult(const dvector& a, const dgrid& b, dgrid& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if ((const dvector*)&c == &a || &c == &b) { dgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zgrid& matmult(const zvector& a, const zgrid& b, zgrid& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if ((const zvector*)&c == &a || &c == &b) { zgrid tmp(m, n); c << matmult(a, b, tmp, ta, tb); } else { c.resize(m, n); c.fill(0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dvector& matmult(const dgrid& a, const dvector& b, dvector& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == (const dvector*)&a || &c == &b) { dvector tmp(m); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(m); fill(c.begin(), c.end(), 0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zvector& matmult(const zgrid& a, const zvector& b, zvector& c, char ta, char tb) { const int ar = a.rows(), ac = a.cols(), br = b.size(), bc = 1; int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == (const zvector*)&a || &c == &b) { zvector tmp(m); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(m); fill(c.begin(), c.end(), 0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } template<> dvector& matmult(const dvector& a, const dgrid& b, dvector& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw dgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == (const dvector*)&b) { dvector tmp(n); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(n); fill(c.begin(), c.end(), 0); dgemm_(&ta, &tb, &m, &n, &k, &done, &a[0], &ar, &b[0], &br, &dzero, &c[0], &m); } return c; } template<> zvector& matmult(const zvector& a, const zgrid& b, zvector& c, char ta, char tb) { const int ar = a.size(), ac = 1, br = b.rows(), bc = b.cols(); int m, n, k, k2; if (ta == 'n' || ta == 'N') { m = ar; k = ac; } else { k = ar; m = ac; } if (tb == 'n' || tb == 'N') { k2 = br; n = bc; } else { n = br; k2 = bc; } if (k != k2) throw zgrid::grid_error("matmult: Grids are not comformable"); if (&c == &a || &c == (const zvector*)&b) { zvector tmp(n); c.swap(matmult(a, b, tmp, ta, tb)); } else { c.resize(n); fill(c.begin(), c.end(), 0); zgemm_(&ta, &tb, &m, &n, &k, &zone, &a[0], &ar, &b[0], &br, &zzero, &c[0], &m); } return c; } //============================================================================ // Compute the eigenvalues, or the magnitudes of the eigenvalues, of a // square matrix 'a'. // These routines reasonably handle the case when either the 'evec' // or 'eval' matrices are the same matrix as 'a' or each other. template<> int eigenvalues(const dgrid& a, dgrid& eval, int gridtype, char ul) { int info = 0; if (&eval == &a) { dgrid tmp; info = eigenvalues(a, tmp, gridtype, ul); eval << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { dgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 8 * a.rows(); int info = 0; eval.resize(n); dgrid evali(n); dvector work(lwork); dgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &eval[0], &evali[0], 0, &n, 0, &n, &work[0], &lwork, &info); if (info == 0) { for (uint i = 0; i < (uint)n; ++i) eval[i] = std::sqrt(eval[i] * eval[i] + evali[i] * evali[i]); eval.sort(); } } else if (gridtype == symgrid) { dgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); eval.resize(n); dvector work(lwork); dsyev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &info); } else throw dgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvalues(const zgrid& a, dgrid& eval, int gridtype, char ul) { int info = 0; if (a.rows() != a.cols()) throw zgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { zgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); int info = 0; eval.resize(n); zvector work(lwork); dgrid rwork(2*n); zgrid evalz(n); zgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &evalz[0], 0, &n, 0, &n, &work[0], &lwork, &rwork[0], &info); for (uint i = 0; i < (uint)n; ++i) eval[i] = std::sqrt(std::abs(evalz[i]*evalz[i])); eval.sort(); } else if (gridtype == symgrid) { // Need evec, not 'a', since it is destroyed by dheev_ zgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); zvector work(lwork), work2(3 * n - 2); eval.resize(n); zheev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &work2[0], &info); } else throw zgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvalues(const dgrid& a, zgrid& eval, int gridtype, char ul) { int info = 0; if (a.rows() != a.cols()) throw dgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { dgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 8 * a.rows(); int info = 0; eval.resize(n); dgrid evalr(n), evali(n); dvector work(lwork); dgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &evalr[0], &evali[0], 0, &n, 0, &n, &work[0], &lwork, &info); if (info == 0) for (uint i = 0; i < (uint)n; ++i) eval[i] = cplx(evalr[i], evali[i]); } else if (gridtype == symgrid) { dgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); dgrid evald(n); dvector work(lwork); dsyev_(&jobz, &ul, &n, &evec[0], &n, &evald[0], &work[0], &lwork, &info); if (info == 0) eval = evald; } else throw dgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvalues(const zgrid& a, zgrid& eval, int gridtype, char ul) { int info = 0; if (&eval == &a) { zgrid tmp; info = eigenvalues(a, tmp, gridtype, ul); eval << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("eigenvalues: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } if (gridtype == gengrid) { zgrid evec = a; char jobvl = 'N', jobvr = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); int info = 0; eval.resize(n); zvector work(lwork); dgrid rwork(2*n); zgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &eval[0], 0, &n, 0, &n, &work[0], &lwork, &rwork[0], &info); } else if (gridtype == symgrid) { // Need 'evec', not 'a', since it is destroyed by dheev_ zgrid evec = a; char jobz = 'N'; const int n = a.rows(), lwork = 4 * a.rows(); zvector work(lwork), work2(3 * n - 2); dgrid evald(n); zheev_(&jobz, &ul, &n, &evec[0], &n, &evald[0], &work[0], &lwork, &work2[0], &info); eval = evald; } else throw zgrid::grid_error("eigenvalues: Unknown grid type"); return info; } // Compute the eigenvalues and eigenvectors of a symmetric or hermetian matrix. template<> int eigenvectors(const dgrid& a, dgrid& evec, dgrid& eval, int gridtype, char ul) { int info = 0; if (&eval == &evec) throw dgrid::grid_error("eigenvectors: evec and eval are the same matrix"); if (&eval == &a) { dgrid tmp; info = eigenvectors(a, evec, tmp, gridtype, ul); eval << tmp; } else if (gridtype == gengrid) { throw dgrid::grid_error("eigenvectors: Not implemented for general grids"); dgrid evec = a; char jobvl = 'N', jobvr = 'V'; const int n = a.rows(), lwork = 8 * a.rows(); int info = 0; eval.resize(n); dgrid evali = eval; dvector work(lwork); dgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &eval[0], &evali[0], 0, &n, 0, &n, &work[0], &lwork, &info); } else if (gridtype == symgrid) { evec = a; if (a.rows() != a.cols()) throw dgrid::grid_error("eigenvectors: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } char jobz = 'V'; const int n = a.rows(), lwork = 4 * a.rows(); eval.resize(n); dvector work(lwork); dsyev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &info); } else throw dgrid::grid_error("eigenvalues: Unknown grid type"); return info; } template<> int eigenvectors(const zgrid& a, zgrid& evec, dgrid& eval, int gridtype, char ul) { int info = 0; if (gridtype == gengrid) { throw zgrid::grid_error("eigenvectors: Not implemented for general grids"); zgrid evec = a; char jobvl = 'N', jobvr = 'V'; const int n = a.rows(), lwork = 4 * a.rows(); int info = 0; eval.resize(n); zvector work(lwork); dgrid rwork(2*n); zgrid evalz(n); zgeev_(&jobvl, &jobvr, &n, &evec[0], &n, &evalz[0], 0, &n, 0, &n, &work[0], &lwork, &rwork[0], &info); for (uint i = 0; i < (uint)n; ++i) eval[i] = std::sqrt(std::abs(evalz[i]*evalz[i])); } else if (gridtype == symgrid) { evec = a; if (a.rows() != a.cols()) throw zgrid::grid_error("eigenvectors: Grid is not square"); if (a.rows() == 0 || a.cols() == 0) { eval.clear(); return(0); } char jobz = 'V'; const int n = a.rows(), lwork = 4 * a.rows(); zvector work(lwork), work2(3 * n - 2); eval.resize(n); zheev_(&jobz, &ul, &n, &evec[0], &n, &eval[0], &work[0], &lwork, &work2[0], &info); } else throw zgrid::grid_error("eigenvalues: Unknown grid type"); return info; } //============================================================================ // Compute the singular values of a symmetric or hermetian matrix // These routines reasonably handle the case when either the 'evec' // or 'eval' matrices are the same matrix as 'a' or each other. template<> int singularvalues(const dgrid& a, dgrid& sval) { int info = 0; throw dgrid::grid_error("singularvalues: Function not yet implemented"); return info; } template<> int singularvalues(const zgrid& a, dgrid& sval) { int info = 0; throw zgrid::grid_error("singularvalues: Function not yet implemented"); return info; } template<> int singularvectors(const dgrid& a, dgrid& svec, dgrid& sval) { int info = 0; throw dgrid::grid_error("singularvalues: Function not yet implemented"); return info; } template<> int singularvectors(const zgrid& a, zgrid& svec, dgrid& sval) { int info = 0; throw zgrid::grid_error("singularvalues: Function not yet implemented"); return info; } //============================================================================ // Use Lapack routines to compute the LU decomposition of a // grid using a LU decomposition appropriate for the type of grid. // For general and symmetric grids there will be be pivots. // If the grid type is positive definite, then the LU decomposition // is the Cholesky decomposition, and the parameter 'ul' is used // to indicate whether the 'U'pper (default) or 'L'ower Cholesky // factor is computed. For triangular matrices, the LU decomposition // is the original matrix. template<> int LU(const dgrid& a, dgrid& g, ivector& pivots, int gridtype, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("LU: Grid is not square"); const int n = a.rows(); int info = 0; if (gridtype == gengrid) { g = a; pivots.resize(n); dgetrf_(&n, &n, &g[0], &n, &pivots[0], &info); } else if (gridtype == symgrid) { g = a; pivots.resize(n); dgrid work(n); dsytrf_(&ul, &n, &g[0], &n, &pivots[0], &work[0], &n, &info); } else if (gridtype == posgrid) info = chol(a, g, ul); else if (gridtype == trigrid) g = a; else throw dgrid::grid_error("LU: Unknown grid type"); return info; } template<> int LU(const zgrid& a, zgrid& g, ivector& pivots, int gridtype, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("LU: Grid is not square"); const int n = a.rows(); int info = 0; if (gridtype == gengrid) { g = a; pivots.resize(n); zgetrf_(&n, &n, &g[0], &n, &pivots[0], &info); } else if (gridtype == symgrid) { g = a; pivots.resize(n); zgrid work(n); zsytrf_(&ul, &n, &g[0], &n, &pivots[0], &work[0], &n, &info); } else if (gridtype == posgrid) info = chol(a, g, ul); else if (gridtype == trigrid) g = a; else throw zgrid::grid_error("LU: Unknown grid type"); return info; } // For positive definite grids, compute the Cholesky Factorization. template<> int chol(const dgrid& a, dgrid& g, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("chol: Grid is not square"); g = a; const int n = (int) a.rows(); int info = 0; if (ul == 'U') for (int i = 0; i < n - 1; ++i) memset(&g[0] + i * n + i + 1, 0, sizeof(double) * (n - i - 1)); else for (int i = 1; i < n; ++i) memset(&g[0] + i * n, 0, sizeof(double) * i); dpotrf_(&ul, &n, &g[0], &n, &info); return info; } template<> int chol(const zgrid& a, zgrid& g, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("chol: Grid is not square"); g = a; const int n = (int) a.rows(); int info = 0; if (ul == 'U') for (int i = 0; i < n - 1; ++i) memset(&g[0] + i * n + i + 1, 0, sizeof(cplx) * (n - i - 1)); else for (int i = 1; i < n; ++i) memset(&g[0] + i * n, 0, sizeof(cplx) * i); zpotrf_(&ul, &n, &g[0], &n, &info); return info; } //============================================================================ // Solve the linear system a * x = b for square 'a' and arbitrary 'b' // assuming that 'a' contains a previously computed LU decomposition // of 'a'. The pivots matrix is ignored in the cases it is not needed. // Works fine if 'a' or 'b' are the same matrix as 'sol', in which case // 'a' or 'b' get overwritten with the solution. template<> int LUsolve(const dgrid& a, const dgrid& b, dgrid& sol, const ivector& pivots, int gridtype, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; dgrid tmp = b; info = LUsolve(a, b, tmp, pivots, gridtype, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("LUsolve: Grid is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("LUsolve: Grids are not comformable"); sol = b; const int n = a.rows(), bc = b.cols(); int info = 0; if (gridtype == gengrid) dgetrs_(&tr, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == symgrid) dsytrs_(&ul, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == posgrid) dpotrs_(&ul, &n, &bc, &a[0], &n, &sol[0], &n, &info); else if (gridtype == trigrid) dtrtrs_(&ul, &tr, &dg, &n, &bc, &a[0], &n, &sol[0], &n, &info); else throw dgrid::grid_error("LUsolve: Unknown grid type"); return info; } template<> int LUsolve(const zgrid& a, const zgrid& b, zgrid& sol, const ivector& pivots, int gridtype, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; zgrid tmp = b; info = LUsolve(a, b, tmp, pivots, gridtype, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("LUsolve: Grid is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("LUsolve: Grids are not comformable"); sol = b; const int n = a.rows(), bc = b.cols(); int info = 0; if (gridtype == gengrid) zgetrs_(&tr, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == symgrid) zsytrs_(&ul, &n, &bc, &a[0], &n, &pivots[0], &sol[0], &n, &info); else if (gridtype == posgrid) zpotrs_(&ul, &n, &bc, &a[0], &n, &sol[0], &n, &info); else if (gridtype == trigrid) ztrtrs_(&ul, &tr, &dg, &n, &bc, &a[0], &n, &sol[0], &n, &info); else throw zgrid::grid_error("LUsolve: Unknown grid type"); return info; } template<> int cholupdate(dgrid& a, dvector& x) { double ci, si, temp; const int n = a.rows(); for (int i = 0; i < n - 1; ++i) { dlartg_(&a[i * (1 + n)], &x[i], &ci, &si, &temp); a[i * (1 + n)] = temp; int j = n - i - 1; drot_(&j, &a[i + (i + 1) * n], &n, &x[i + 1], &ione, &ci, &si); } dlartg_(&a[n * n - 1], &x[n - 1], &ci, &si, &temp); a[n * n - 1] = temp; return 0; } template<> int cholupdate(zgrid& a, zvector& x) { double ci; cplx si, temp; const int n = a.rows(); for (int i = 0; i < n - 1; ++i) { zlartg_(&a[i * (1 + n)], &x[i], &ci, &si, &temp); a[i * (1 + n)] = temp; int j = n - i - 1; zrot_(&j, &a[i + (i + 1) * n], &n, &x[i + 1], &ione, &ci, &si); } zlartg_(&a[n * n - 1], &x[n - 1], &ci, &si, &temp); a[n * n - 1] = temp; return 0; } template<> int cholsolve(const dgrid& a, const dgrid& b, dgrid& sol, char ul) { if (&sol == &a) { int info = 0; dgrid tmp = b; info = cholsolve(a, b, tmp, ul); sol << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("cholsolve: Grid is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("cholsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; dpotrs_(&ul, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } template<> int cholsolve(const zgrid& a, const zgrid& b, zgrid& sol, char ul) { if (&sol == &a) { int info = 0; zgrid tmp = b; info = cholsolve(a, b, tmp, ul); sol << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("cholsolve: Grid is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("cholsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; zpotrs_(&ul, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } template<> int trsolve(const dgrid& a, const dgrid& b, dgrid& sol, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; dgrid tmp = b; info = trsolve(a, b, tmp, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw dgrid::grid_error("trsolve: Grid is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("trsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; dtrtrs_(&ul, &tr, &dg, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } template<> int trsolve(const zgrid& a, const zgrid& b, zgrid& sol, char ul, char tr, char dg) { if (&sol == &a) { int info = 0; zgrid tmp = b; info = trsolve(a, b, tmp, ul, tr, dg); sol << tmp; return info; } if (a.rows() != a.cols()) throw zgrid::grid_error("trsolve: Grid is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("trsolve: Grids are not comformable"); sol = b; const int ar = a.rows(), bc = b.cols(); int info = 0; ztrtrs_(&ul, &tr, &dg, &ar, &bc, &a[0], &ar, &sol[0], &ar, &info); return info; } //============================================================================ // Use Lapack routines to compute the inverse of a grid using a LU // factorization appropriate for the type of grid. // The paramter 'ul' is used for symmetric and triangular grids and // indicates whether the 'U'pper (default) or 'L'ower triangle of the // grid should be used in the computations. For these matrices, if the // parameter 'fill' is true (default), then the entire inverse will be // computed. Otherwise, only the corresponding upper or lower half will // be computed, and the other half will essentially be garbage. // For triangular matrices, 'dg' can be 'N' (default) to indicate the // diagonal entries will be used, or 'U' to indicate they will be // assumed to be 1 and ignored. // Syntax 1: inv(a, ainv) template<> int inv(const dgrid& a, dgrid& g, int gridtype, char ul, bool fill, char dg) { if (a.rows() != a.cols()) throw dgrid::grid_error("inv: Grid is not square"); g = a; int n = g.rows(); int info = 0; if (gridtype == gengrid) { ivector ipiv(n); dvector work(n); dgetrf_(&n, &n, &g[0], &n, &ipiv[0], &info); if (info == 0) dgetri_(&n, &g[0], &n, &ipiv[0], &work[0], &n, &info); } else if (gridtype == symgrid) { ivector ipiv(n); dvector work(n); dsytrf_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &n, &info); if (info == 0) dsytri_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &info); } else if (gridtype == posgrid) { dpotrf_(&ul, &n, &g[0], &n, &info); if (info == 0) dpotri_(&ul, &n, &g[0], &n, &info); } else if (gridtype == trigrid) { dtrtri_(&ul, &dg, &n, &g[0], &n, &info); } if (info == 0 && fill && (gridtype == posgrid || gridtype == symgrid)) if (ul == 'U') for (int i = 1; i < n; ++i) for (int j = 0; j < i; ++j) g(i, j) = g(j, i); else for (int i = 0; i < n - 1; ++i) for (int j = i + 1; j < n; ++j) g(i, j) = g(j, i); return info; } // Syntax 2: ainv = inv(a) template<> dgrid inv(const dgrid& a, int gridtype, char ul, bool fill, char dg) { dgrid tmp; inv(a, tmp, gridtype, ul, fill, dg); return tmp; } // Syntax 1: inv(a, ainv) template<> int inv(const zgrid& a, zgrid& g, int gridtype, char ul, bool fill, char dg) { if (a.rows() != a.cols()) throw dgrid::grid_error("inv: Grid is not square"); g = a; const int n = g.rows(); int info = 0; if (gridtype == gengrid) { ivector ipiv(n); zvector work(n); zgetrf_(&n, &n, &g[0], &n, &ipiv[0], &info); if (info == 0) zgetri_(&n, &g[0], &n, &ipiv[0], &work[0], &n, &info); } else if (gridtype == posgrid) { zpotrf_(&ul, &n, &g[0], &n, &info); if (info == 0) zpotri_(&ul, &n, &g[0], &n, &info); } else if (gridtype == symgrid) { ivector ipiv(n); zvector work(n); zsytrf_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &n, &info); if (info == 0) zsytri_(&ul, &n, &g[0], &n, &ipiv[0], &work[0], &info); } else if (gridtype == trigrid) { ztrtri_(&ul, &dg, &n, &g[0], &n, &info); } if (info == 0 && fill && (gridtype == posgrid || gridtype == symgrid)) if (ul == 'U') for (int i = 1; i < n; ++i) for (int j = 0; j < i; ++j) g(i, j) = g(j, i); else for (int i = 0; i < n - 1; ++i) for (int j = i + 1; j < n; ++j) g(i, j) = g(j, i); return info; } // Syntax 2: ainv = a.inv() template<> zgrid inv(const zgrid& a, int gridtype, char ul, bool fill, char dg) { zgrid tmp; inv(a, tmp, gridtype, ul, fill, dg); return tmp; } //============================================================================ // Compute y = alpha * x + y dgrid& axpy(const dgrid& x, double alpha, dgrid& y) { if (x.size() != y.size()) throw dgrid::grid_error("axpy: Grids are not comformable"); const int as = x.size(); if (as != 0) daxpy_(&as, &alpha, &x[0], &ione, &y[0], &ione); return y; } zgrid& axpy(const zgrid& x, cplx alpha, zgrid& y) { if (x.size() != y.size()) throw zgrid::grid_error("axpy: Grids are not comformable"); const int as = x.size(); if (as != 0) zaxpy_(&as, &alpha, &x[0], &ione, &y[0], &ione); return y; } //============================================================================ // Compute c = alpha * a * b + beta * c dgrid& trmm(const dgrid& a, dgrid& b, double alpha, const char side, const char uplo, const char tra, const char diag) { if (a.cols() != b.rows()) throw dgrid::grid_error("trmm: Grids are not comformable"); if (&a == &b) throw dgrid::grid_error("trmm: The two grid arguments are the same grid"); if (a.size() != 0 && b.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); dtrmm_(&side, &uplo, &tra, &diag, &ac, &bc, &alpha, &a[0], &ar, &b[0], &ac); } return b; } zgrid& trmm(const zgrid& a, zgrid& b, const cplx& alpha, const char side, const char uplo, const char tra, const char diag) { if (a.cols() != b.rows()) throw zgrid::grid_error("trmm: Grids are not comformable"); if (&a == &b) throw zgrid::grid_error("trmm: The two grid arguments are the same grid"); if (a.size() != 0 && b.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); ztrmm_(&side, &uplo, &tra, &diag, &ac, &bc, &alpha, &a[0], &ar, &b[0], &ac); } return b; } dgrid& gemm(const dgrid& a, const dgrid& b, dgrid& c, double alpha, double beta, char tra, char trb) { if (a.cols() != b.rows() || a.rows() != c.rows() || b.cols() != c.cols()) throw dgrid::grid_error("gemm: Grids are not comformable"); if (&a == &c || &b == &c) throw dgrid::grid_error("gemm: Result grid is the same as one of the multipliers"); if (a.cols() != 0 && c.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); dgemm_(&tra, &trb, &ar, &bc, &ac, &alpha, &a[0], &ar, &b[0], &ac, &beta, &c[0], &ar); } return c; } zgrid& gemm(const zgrid& a, const zgrid& b, zgrid& c, const cplx& alpha, const cplx& beta, char tra, char trb) { if (a.cols() != b.rows() || a.rows() != c.rows() || b.cols() != c.cols()) throw zgrid::grid_error("gemm: Grids are not comformable"); if (&a == &c || &b == &c) throw zgrid::grid_error("gemm: Result grid is the same as one of the multipliers"); if (a.cols() != 0 && c.size() != 0) { const int ar = a.rows(), ac = a.cols(), bc = b.cols(); zgemm_(&tra, &trb, &ar, &bc, &ac, &alpha, &a[0], &ar, &b[0], &ac, &beta, &c[0], &ar); } return c; } //============================================================================ // Solve the over/under-determined linear system a * x = b for arbitary // 'a' and 'b' using a QR or LQ factorization. On exit, 'a' contains // its QR or LQ factorization, while the columns of 'b' contain the // solution 'x'. int gels(dgrid& a, dgrid& b, char trans) { if (a.rows() != b.rows()) throw dgrid::grid_error("gels: Grids are not comformable"); const int m = a.rows(), n = a.cols(), nrhs = b.cols(); int info = 0; const int lwork = 10 * (m + n + nrhs); dvector work(lwork); dgels_(&trans, &m, &n, &nrhs, &a[0], &m, &b[0], &m, &work[0], &lwork, &info); return info; } int gels(zgrid& a, zgrid& b, char trans) { if (a.rows() != b.rows()) throw zgrid::grid_error("gels: Grids are not comformable"); const int m = a.rows(), n = a.cols(), nrhs = b.cols(); int info = 0; const int lwork = 10 * (m + n + nrhs); zvector work(lwork); zgels_(&trans, &m, &n, &nrhs, &a[0], &m, &b[0], &m, &work[0], &lwork, &info); return info; } //============================================================================ // Solve the linear system a * x = b for square 'a' and arbitrary 'b'. // On exit, if 'a' and 'b' are not the same matrix, 'a' contains an LU or // Cholesky decomposition, and 'b' contains the solution 'x'. If 'a' and // 'b' are the same matrix, then they will contain the identity solution. // General square 'a' int gesv(dgrid& a, dgrid& b, ivector& pivots) { if (a.rows() != a.cols()) throw dgrid::grid_error("gesv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("gesv: Grids are not comformable"); if (&a == &b) { b = dgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); dgesv_(&n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &info); return info; } int gesv(zgrid& a, zgrid& b, ivector& pivots) { if (a.rows() != a.cols()) throw zgrid::grid_error("gesv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("gesv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); zgesv_(&n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &info); return info; } // Symmetric square 'a' int sysv(dgrid& a, dgrid& b, ivector& pivots, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("sysv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("sysv: Grids are not comformable"); if (&a == &b) { b = dgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); const int lwork = 2 * n; dgrid work(lwork); dsysv_(&ul, &n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &work[0], &lwork, &info); return info; } int sysv(zgrid& a, zgrid& b, ivector& pivots, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("sysv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("sysv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); const int lwork = 2 * n; zgrid work(lwork); zsysv_(&ul, &n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &work[0], &lwork, &info); return info; } // Hermetian square 'a' int hesv(zgrid& a, zgrid& b, ivector& pivots, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("hesv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("hesv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; pivots.resize(n); const int lwork = 2 * n; zgrid work(lwork); zhesv_(&ul, &n, &nrhs, &a[0], &n, &pivots[0], &b[0], &n, &work[0], &lwork, &info); return info; } // Positive Definite square 'a' int posv(dgrid& a, dgrid& b, char ul) { if (a.rows() != a.cols()) throw dgrid::grid_error("posv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw dgrid::grid_error("posv: Grids are not comformable"); if (&a == &b) { b = dgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; dposv_(&ul, &n, &nrhs, &a[0], &n, &b[0], &n, &info); return info; } int posv(zgrid& a, zgrid& b, char ul) { if (a.rows() != a.cols()) throw zgrid::grid_error("posv: Grid 'A' is not square"); if (a.rows() != b.rows()) throw zgrid::grid_error("posv: Grids are not comformable"); if (&a == &b) { b = zgrid("I", a.cols()); return 0; } const int n = a.rows(), nrhs = b.cols(); int info = 0; zposv_(&ul, &n, &nrhs, &a[0], &n, &b[0], &n, &info); return info; } //============================================================================ // Solve a triangular system (*this) * x = b for x using either // back or forward substitution. template<> dgrid& backsolve(const dgrid& a, const dgrid& b, dgrid& x, char ul) { x = b; if (ul == 'U') trsm(a, b, x, 1.0, 'L', 'U', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'L', 'T', 'N'); return x; } template<> zgrid& backsolve(const zgrid& a, const zgrid& b, zgrid& x, char ul) { x = b; if (ul == 'U') trsm(a, b, x, 1.0, 'L', 'U', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'L', 'T', 'N'); return x; } template<> dgrid& forwardsolve(const dgrid& a, const dgrid& b, dgrid& x, char ul) { x = b; if (ul == 'L') trsm(a, b, x, 1.0, 'L', 'L', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'U', 'T', 'N'); return x; } template<> zgrid& forwardsolve(const zgrid& a, const zgrid& b, zgrid& x, char ul) { x = b; if (ul == 'L') trsm(a, b, x, 1.0, 'L', 'L', 'N', 'N'); else trsm(a, b, x, 1.0, 'L', 'U', 'T', 'N'); return x; } //============================================================================ // Solve prod(op(a), x) = alpha * b, where 'a' is a triangular matrix. // If 'sd' == 'L', prod(a,b) = a %*% b, otherwise, prod(a,b) = b %*% a. // If 'ul' == 'U', use upper half of 'a', otherwise use lower half. // If 'tr' == 'N', op(a) = a, otherwise op(a) = t(a). // If 'dg' != 'U', assume diagonal entries of 'a' are 1. // If x and b are equal, b will be overwritten with the solution x. dgrid& trsm(const dgrid& a, const dgrid& b, dgrid& x, double alpha, char sd, char ul, char tr, char dg) { if (sd != 'l' && sd != 'L') sd = 'R'; if (ul != 'u' && ul != 'U') ul = 'L'; if (tr != 'n' && tr != 'N') tr = 'T'; if (dg != 'n' && dg != 'N') dg = 'U'; x = b; const int br = b.rows(), bc = b.cols(), ar = a.rows(); dtrsm_(&sd, &ul, &tr, &dg, &br, &bc, &alpha, &a[0], &ar, &x[0], &br); return x; } zgrid& trsm(const zgrid& a, const zgrid& b, zgrid& x, const cplx& alpha, char sd, char ul, char tr, char dg) { if (sd != 'l' && sd != 'L') sd = 'R'; if (ul != 'u' && ul != 'U') ul = 'L'; if (tr != 'n' && tr != 'N') tr = 'T'; if (dg != 'n' && dg != 'N') dg = 'U'; x = b; const int br = b.rows(), bc = b.cols(), ar = a.rows(); ztrsm_(&sd, &ul, &tr, &dg, &br, &bc, &alpha, &a[0], &ar, &x[0], &br); return x; } //============================================================================ // grid.C #endif
39.98859
250
0.541149
Sammie-Jo
8278100f1e02979ae43e62c28dac6e1b4078e5ba
1,224
cpp
C++
src/object/mgr.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/object/mgr.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
src/object/mgr.cpp
degarashi/revenant
9e671320a5c8790f6bdd1b14934f81c37819f7b3
[ "MIT" ]
null
null
null
#include "mgr.hpp" #include "if.hpp" namespace rev { ObjMgr::~ObjMgr() { constexpr int N_RETRY = 8; for(int i=0 ; i<N_RETRY ; i++) { // オブジェクトが無くなるまで繰り返しdestroy auto tmp = base_t::getResourceSet(); if(tmp->set.empty()) break; for(auto& obj : tmp->set) { try { if(auto sp = obj.weak.lock()) sp->destroy(); } catch(...) {} } } } void ObjMgr::setLua(const Lua_SP& ls) { _lua = ls; } const Lua_SP& ObjMgr::getLua() const noexcept { return _lua; } } #include "lua.hpp" namespace rev { // -------------------- ObjectT_LuaBase -------------------- bool detail::ObjectT_LuaBase::CallRecvMsg(const Lua_SP& ls, const HObj& hObj, LCValue& dst, const GMessageStr& msg, const LCValue& arg) { ls->push(hObj); LValueS lv(ls->getLS()); dst = lv.callMethodNRet(luaNS::RecvMsg, msg, arg); auto& tbl = *boost::get<LCTable_SP>(dst); if(tbl[1]) { const int sz = tbl.size(); for(int i=1 ; i<=sz ; i++) tbl[i] = std::move(tbl[i+1]); tbl.erase(tbl.find(sz)); return true; } return false; } // -------------------- U_ObjectUpd -------------------- struct U_ObjectUpd::St_None : StateT<St_None> {}; U_ObjectUpd::U_ObjectUpd() { setStateNew<St_None>(); } }
24.48
138
0.573529
degarashi
8278d3ab731c5a2aecfa7e879d12431b0e0b3e59
4,874
hpp
C++
modules/core/include/glpp/core/render/renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
16
2019-12-10T19:44:17.000Z
2022-01-04T03:16:19.000Z
modules/core/include/glpp/core/render/renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
null
null
null
modules/core/include/glpp/core/render/renderer.hpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
3
2021-06-04T21:56:55.000Z
2022-03-03T06:47:56.000Z
#pragma once #include <string> #include <unordered_map> #include <glpp/core/object/texture_atlas.hpp> #include <glpp/core/object/shader.hpp> namespace glpp::core::render { namespace detail { struct none_t {}; template <class T, class Y> constexpr ptrdiff_t get_offset(Y T::* ptr) { return reinterpret_cast<char*>(&(reinterpret_cast<T*>(0)->*ptr))-reinterpret_cast<char*>(0); } } template <class uniform_description_t = detail::none_t> class renderer_t { public: template <class... shader_t> renderer_t( const shader_t&... shaders ); template <class view_t> void render(const view_t& view); template <class view_t> void render_instanced(const view_t& view, size_t count); template <class T> void set_uniform_name(T uniform_description_t::* uniform, std::string name); template <class T> void set_uniform(T uniform_description_t::* uniform, const T& value); template <class T> void set_uniform_array(T uniform_description_t::* uniform, const T* value, const size_t size); void set_texture(const char* name, const object::texture_slot_t& texture_slot); void set_texture(const char* name, object::texture_slot_t&& texture_slot); template <class texture_slot_iterator> void set_texture_array(const char* name, texture_slot_iterator begin, texture_slot_iterator end); template <class Container> void set_texture_array(const char* name, const Container& container); template <class AllocPolicy> void set_texture_atlas(const char* name, const object::texture_atlas_slot_t<AllocPolicy>& texture_atlas); private: glpp::core::object::shader_program_t m_shader; std::unordered_map<size_t, GLint> m_uniform_map; std::unordered_map<std::string, object::texture_slot_t> m_texture_slots; }; /** * Implementation */ template <class uniform_description_t> template <class... shader_t> renderer_t<uniform_description_t>::renderer_t( const shader_t&... shaders ) : m_shader(shaders...) { } template <class uniform_description_t> template <class view_t> void renderer_t<uniform_description_t>::render(const view_t& view) { m_shader.use(); view.draw(); } template <class uniform_description_t> template <class view_t> void renderer_t<uniform_description_t>::render_instanced(const view_t& view, size_t count) { m_shader.use(); view.draw_instanced(count); } template <class uniform_description_t> template <class T> void renderer_t<uniform_description_t>::set_uniform_name(T uniform_description_t::* uniform, std::string name) { m_uniform_map[detail::get_offset(uniform)] = m_shader.uniform_location(name.c_str()); } template <class uniform_description_t> template <class T> void renderer_t<uniform_description_t>::set_uniform(T uniform_description_t::* uniform, const T& value) { const auto location_it = m_uniform_map.find(detail::get_offset(uniform)); if(location_it == m_uniform_map.end()) { throw std::runtime_error("Could find uniform name for this uniform. Add a call renderer_t::set_uniform_name before renderer_t::set_uniform."); } const auto location = location_it->second; m_shader.set_uniform(location, value); } template <class uniform_description_t> template <class T> void renderer_t<uniform_description_t>::set_uniform_array(T uniform_description_t::* uniform, const T* value, const size_t size) { const auto location_it = m_uniform_map.find(detail::get_offset(uniform)); if(location_it == m_uniform_map.end()) { throw std::runtime_error("Could find uniform name for this uniform. Add a call renderer_t::set_uniform_name before renderer_t::set_uniform."); } const auto location = location_it->second; m_shader.set_uniform_array(location, value, size); } template <class uniform_description_t> void renderer_t<uniform_description_t>::set_texture(const char* name, const object::texture_slot_t& texture_slot) { m_shader.set_texture(name, texture_slot); } template <class uniform_description_t> void renderer_t<uniform_description_t>::set_texture(const char* name, object::texture_slot_t&& texture_slot) { m_shader.set_texture(name, texture_slot); m_texture_slots[name]=std::move(texture_slot); } template <class uniform_description_t> template <class texture_slot_iterator> void renderer_t<uniform_description_t>::set_texture_array(const char* name, texture_slot_iterator begin, texture_slot_iterator end) { m_shader.set_texture_array(name, begin, end); } template <class uniform_description_t> template <class Container> void renderer_t<uniform_description_t>::set_texture_array(const char* name, const Container& container) { set_texture_array(name, container.begin(), container.end()); } template <class uniform_description_t> template <class AllocPolicy> void renderer_t<uniform_description_t>::set_texture_atlas(const char* name, const object::texture_atlas_slot_t<AllocPolicy>& texture_atlas_slots) { set_texture_array(name, texture_atlas_slots.begin(), texture_atlas_slots.end()); } }
33.156463
147
0.787033
lenamueller
827a12a4901f3eb22852e3a264c7980242ee0197
966
cpp
C++
N64 Sound Tool/N64SoundListToolUpdated/N64SoundLibrary/DecompressClayfighter.cpp
Raspberryfloof/N64-Tools
96738d434ce3922dec0168cdd42f8e7ca131d0c5
[ "Unlicense" ]
1
2022-02-21T03:01:00.000Z
2022-02-21T03:01:00.000Z
N64 Sound Tool/N64SoundListToolUpdated/N64SoundLibrary/DecompressClayfighter.cpp
Raspberryfloof/N64-Tools
96738d434ce3922dec0168cdd42f8e7ca131d0c5
[ "Unlicense" ]
null
null
null
N64 Sound Tool/N64SoundListToolUpdated/N64SoundLibrary/DecompressClayfighter.cpp
Raspberryfloof/N64-Tools
96738d434ce3922dec0168cdd42f8e7ca131d0c5
[ "Unlicense" ]
null
null
null
#include "StdAfx.h" #include "DecompressClayfighter.h" #include "SharedFunctions.h" CDecompressClayfighter::CDecompressClayfighter(void) { } CDecompressClayfighter::~CDecompressClayfighter(void) { } int CDecompressClayfighter::Decompress(byte *output, byte *input) { bool bVar1; byte bVar2; byte bVar3; byte *pbVar4; byte *pbVar5; pbVar5 = output; while( true ) { while( true ) { bVar3 = *input; pbVar4 = input + 1; if ((bVar3 & 0x80) != 0) break; do { *pbVar5 = *pbVar4; pbVar4 = pbVar4 + 1; pbVar5 = pbVar5 + 1; bVar1 = bVar3 != 0; bVar3 = bVar3 - 1; input = pbVar4; } while (bVar1); } bVar2 = bVar3 & 0x7f; if (bVar3 == 0xff) break; bVar3 = *pbVar4; input = input + 2; do { *pbVar5 = bVar3; pbVar5 = pbVar5 + 1; bVar1 = bVar2 != 0; bVar2 = bVar2 - 1; } while (bVar1); } return (int)pbVar5 - (int)output; }
20.125
65
0.568323
Raspberryfloof
827b174cd67919159e166af7f99b41b40f3f4abd
1,579
hpp
C++
source/Estrutura_de_dados/Lista_adjacencia.hpp
AmandaACLucio/GraphLibrary
518b610045e6f359588264644d0bd9f70e41b14d
[ "MIT" ]
null
null
null
source/Estrutura_de_dados/Lista_adjacencia.hpp
AmandaACLucio/GraphLibrary
518b610045e6f359588264644d0bd9f70e41b14d
[ "MIT" ]
null
null
null
source/Estrutura_de_dados/Lista_adjacencia.hpp
AmandaACLucio/GraphLibrary
518b610045e6f359588264644d0bd9f70e41b14d
[ "MIT" ]
null
null
null
#ifndef __LISTAADJACENCIA_H__ #define __LISTAADJACENCIA_H__ #include <iostream> #include <vector> #include "Estrutura_de_dados.hpp" using namespace std; class NodeList { public: /* data */ //NodeList* prior; NodeList* next; int data; double weight; NodeList(int dataa); NodeList(int dataa, double weight); void set(int i); int get(); NodeList* get_next(); void add(NodeList* data); }; class ListaAdjacencia { private: NodeList* top; NodeList* last; NodeList* nextIterator; int iterator=0; int sizeLista; public: ListaAdjacencia(); ListaAdjacencia(int node); bool add(int data); void show(); bool search(int i); int size(); NodeList* getNodePosition(int position); NodeList* getTop(); bool sortedInsert(int val); bool sortedInsert(int val, double newWeight); }; class VectorListaAdjacencia: public EstruturaDeDados { private: vector<ListaAdjacencia> vetorDeListas; public: //VectorListaAdjacencia(int newSizeVector); void setSize(int newSizeVector); bool addAresta(int valor1, int valor2); bool addAresta(int valor1, int valor2, double weight); void show(bool weight); int vizinhoDeVertice(int vertice, int posicaoVizinho); pair <int,double> vizinhoDeVertice(int vertice, int posicaoVizinho, bool weight); int sizeVertice(int vertice); }; #endif
22.557143
89
0.61368
AmandaACLucio
827b8cd12246fcf20532ef276d85d0e6527aabb7
1,057
hpp
C++
peopleextractor_interface_sma/src/SceneframeQueue.hpp
fbredius/IMOVE
912b4d0696e88acfc0ce7bc556eecf8fc423c4d3
[ "MIT" ]
3
2018-04-24T10:04:37.000Z
2018-05-11T08:27:03.000Z
peopleextractor_interface_sma/src/SceneframeQueue.hpp
fbredius/IMOVE
912b4d0696e88acfc0ce7bc556eecf8fc423c4d3
[ "MIT" ]
null
null
null
peopleextractor_interface_sma/src/SceneframeQueue.hpp
fbredius/IMOVE
912b4d0696e88acfc0ce7bc556eecf8fc423c4d3
[ "MIT" ]
3
2018-05-16T08:44:19.000Z
2020-12-04T16:04:32.000Z
#ifndef PEOPLEEXTRACTORINTERFACESMA_SCENEFRAMEQUEUE_H #define PEOPLEEXTRACTORINTERFACESMA_SCENEFRAMEQUEUE_H #include <boost/interprocess/offset_ptr.hpp> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/containers/deque.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <string> #include "Image.hpp" namespace peopleextractor_interface_sma { //Define an STL compatible allocator of ints that allocates from the managed_shared_memory. //This allocator will allow placing containers in the segment typedef boost::interprocess::allocator<boost::interprocess::offset_ptr<Image>, boost::interprocess::managed_shared_memory::segment_manager> SceneframeQueueSMA; //Alias a deque that uses the previous STL-like allocator so that allocates its values from the segment typedef boost::interprocess::deque<boost::interprocess::offset_ptr<Image>, SceneframeQueueSMA> SceneframeQueue; const char* const NAME_SCENEFRAME_QUEUE = "SceneframeQueue"; } #endif //PEOPLEEXTRACTORINTERFACESMA_SCENEFRAMEQUEUE_H
44.041667
160
0.835383
fbredius
827e173e708ac980282c7a271edb5fe592253724
11,296
cpp
C++
2d_plane_move_animation_not_fully_complted_game/2DPlaneGame.cpp
quang-vn26/Computer-Graphics--OpenGL-GLUT
581ee34aee63c60069f9029861fcc92d5b7ef002
[ "MIT" ]
19
2017-02-06T07:18:07.000Z
2021-07-01T18:25:52.000Z
2d_plane_move_animation_not_fully_complted_game/2DPlaneGame.cpp
Shifath472533/Computer-Graphics--OpenGL-GLUT
0c44b5d94ff0182db72ae7e99e63f88e0d3aa9c6
[ "MIT" ]
null
null
null
2d_plane_move_animation_not_fully_complted_game/2DPlaneGame.cpp
Shifath472533/Computer-Graphics--OpenGL-GLUT
0c44b5d94ff0182db72ae7e99e63f88e0d3aa9c6
[ "MIT" ]
36
2016-11-19T11:17:47.000Z
2021-11-29T01:14:07.000Z
/* Desh, Salman Rahman: 13-23239-1 Amin, H.M. Ruhul: 13-23624-1 Hassan, Jahidul: 13-25373-1 Mahdi, Dewan Osman: 13-25368-3 */ #include <sstream> #include <stdio.h> #include <iostream> #include <windows.h> #include <GL/glut.h> #include <GL/freeglut.h> using namespace std; int viewY, viewX; int move_unit = 5; int m=0; int passAViewX=1, passBViewX=1; float passCViewX=1, passDViewX=1; void myInit (void) { glClearColor(0.0, 0.8, 1.0, 0.0); glPointSize(4.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 640.0, 0.0, 480.0); } /*Plane_Control_Keyboard*/ void keyboard(int key, int x, int y){ if (key == GLUT_KEY_UP){ viewY -= move_unit; cout<<"KEYBOARD_UP | "; } if (key == GLUT_KEY_DOWN){ viewY += move_unit; cout<<"KEYBOARD_DOWN | "; } if (key == GLUT_KEY_LEFT){ viewX -= move_unit; cout<<"KEYBOARD_LEFT | "; } if (key == GLUT_KEY_RIGHT){ viewX += move_unit; cout<<"KEYBOARD_RIGHT | "; } } void drawBitmapText(string caption, int score, float r, float g, float b, float x,float y,float z) { glColor3f(r,g,b); glRasterPos3f(x,y,z); stringstream strm; strm << caption << score; string text = strm.str(); for(string::iterator it = text.begin(); it != text.end(); ++it) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18 , *it); } } /*void viewScore(){ int s=0, m=10; do{ //drawBitmapText("Score: ", s, 255, 0 , 0, 550, 450, 0 ); drawBitmapText("Score: ", m, 255,0,0,100,400,0); //Sleep(1000); //s++; //system("CLS"); } while(s!=0); }*/ /*void print(int x, int y,int z, char *string) { //set the position of the text in the window using the x, y and z coordinates glRasterPos3f(x,y,z); //get the length of the string to display int len = (int) strlen(string); //loop to display character by character for(int f=0;f<10;f++){ for (int i = 0;i<len;i++) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24,string[i]); } } };*/ void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /******************************************/ /*------- custom code starts -------*/ drawBitmapText("Game Score: ", m, 255,255,255,530,450,0); /*plane_tail*/ glColor3ub (153, 76, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(10 + viewX, 330 - viewY); glVertex2i(15 + viewX, 330 - viewY); glVertex2i(35 + viewX, 310 - viewY); glVertex2i(15 + viewX, 290 - viewY); glEnd(); /*plane_wing_back*/ glColor3ub (204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(90 + viewX, 330 - viewY); glVertex2i(85 + viewX, 330 - viewY); glVertex2i(50 + viewX, 290 - viewY); glEnd(); /*plane_wing_design_back*/ glColor3ub (153, 76, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(90 + viewX, 330 - viewY); glVertex2i(88 + viewX, 330 - viewY); glVertex2i(55 + viewX, 290 - viewY); glEnd(); /*plane_body*/ glColor3ub (255, 128, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 280 - viewY); glVertex2i(30 + viewX, 280 - viewY); glVertex2i(15 + viewX, 290 - viewY); glVertex2i(35 + viewX, 310 - viewY); glVertex2i(80 + viewX, 310 - viewY); glVertex2i(90 + viewX, 300 - viewY); glEnd(); /*plane_body_design*/ glColor3ub(204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 295 - viewY); glVertex2i(30 + viewX, 295 - viewY); glVertex2i(30 + viewX, 300 - viewY); glVertex2i(90 + viewX, 300 - viewY); glEnd(); /*plane_front*/ glColor3ub (204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 280 - viewY); glVertex2i(90 + viewX, 300 - viewY); glVertex2i(100 + viewX, 285 - viewY); glVertex2i(100 + viewX, 280 - viewY); glEnd(); /*plane_pilot_glass*/ glColor3ub (204, 229, 255); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(90 + viewX, 300 - viewY); glVertex2i(80 + viewX, 310 - viewY); glVertex2i(75 + viewX, 305 - viewY); glVertex2i(75 + viewX, 300 - viewY); glEnd(); /*plane_wing*/ glColor3ub (204, 102, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(35 + viewX, 260 - viewY); glVertex2i(25 + viewX, 260 - viewY); glVertex2i(50 + viewX, 290 - viewY); glEnd(); /*plane_wing_design*/ glColor3ub (153, 76, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(80 + viewX, 290 - viewY); glVertex2i(35 + viewX, 260 - viewY); glVertex2i(30 + viewX, 260 - viewY); glVertex2i(55 + viewX, 290 - viewY); glEnd(); /*============DANGER_BOX_01===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(800 - passAViewX, 240); glVertex2i(770 - passAViewX, 240); glVertex2i(770 - passAViewX, 200); glVertex2i(800 - passAViewX, 200); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 240); glVertex2i(780 - passAViewX, 240); glVertex2i(780 - passAViewX, 230); glVertex2i(790 - passAViewX, 230); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 230); glVertex2i(780 - passAViewX, 230); glVertex2i(780 - passAViewX, 220); glVertex2i(790 - passAViewX, 220); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 220); glVertex2i(780 - passAViewX, 220); glVertex2i(780 - passAViewX, 210); glVertex2i(790 - passAViewX, 210); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passAViewX, 210); glVertex2i(780 - passAViewX, 210); glVertex2i(780 - passAViewX, 200); glVertex2i(790 - passAViewX, 200); glEnd(); /*============DANGER_BOX_02===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(800 - passBViewX, 140); glVertex2i(770 - passBViewX, 140); glVertex2i(770 - passBViewX, 100); glVertex2i(800 - passBViewX, 100); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 140); glVertex2i(780 - passBViewX, 140); glVertex2i(780 - passBViewX, 130); glVertex2i(790 - passBViewX, 130); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 130); glVertex2i(780 - passBViewX, 130); glVertex2i(780 - passBViewX, 120); glVertex2i(790 - passBViewX, 120); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 120); glVertex2i(780 - passBViewX, 120); glVertex2i(780 - passBViewX, 110); glVertex2i(790 - passBViewX, 110); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(790 - passBViewX, 110); glVertex2i(780 - passBViewX, 110); glVertex2i(780 - passBViewX, 100); glVertex2i(790 - passBViewX, 100); glEnd(); /*============DANGER_BOX_03===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(700 - passCViewX, 440); glVertex2i(670 - passCViewX, 440); glVertex2i(670 - passCViewX, 400); glVertex2i(700 - passCViewX, 400); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 440); glVertex2i(680 - passCViewX, 440); glVertex2i(680 - passCViewX, 430); glVertex2i(690 - passCViewX, 430); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 430); glVertex2i(680 - passCViewX, 430); glVertex2i(680 - passCViewX, 420); glVertex2i(690 - passCViewX, 420); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 420); glVertex2i(680 - passCViewX, 420); glVertex2i(680 - passCViewX, 410); glVertex2i(690 - passCViewX, 410); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passCViewX, 410); glVertex2i(680 - passCViewX, 410); glVertex2i(680 - passCViewX, 400); glVertex2i(690 - passCViewX, 400); glEnd(); /*============DANGER_BOX_04===============================*/ /*main_box*/ glColor3ub (178, 190, 181); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(700 - passDViewX, 340); glVertex2i(670 - passDViewX, 340); glVertex2i(670 - passDViewX, 300); glVertex2i(700 - passDViewX, 300); glEnd(); /*--black*/ glColor3ub (0, 0 , 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 340); glVertex2i(680 - passDViewX, 340); glVertex2i(680 - passDViewX, 330); glVertex2i(690 - passDViewX, 330); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 330); glVertex2i(680 - passDViewX, 330); glVertex2i(680 - passDViewX, 320); glVertex2i(690 - passDViewX, 320); glEnd(); /*--black*/ glColor3ub (0, 0, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 320); glVertex2i(680 - passDViewX, 320); glVertex2i(680 - passDViewX, 310); glVertex2i(690 - passDViewX, 310); glEnd(); /*--yellow*/ glColor3ub (255, 2555, 0); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(690 - passDViewX, 310); glVertex2i(680 - passDViewX, 310); glVertex2i(680 - passDViewX, 300); glVertex2i(690 - passDViewX, 300); glEnd(); /*=====================LAND=========================*/ glColor3ub (43, 29 ,14); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(0, 0); glVertex2i(1000, 0); glVertex2i(1000, 35); glVertex2i(0, 35); glEnd(); glColor3ub (101, 101, 33); glPointSize(4.0); glBegin(GL_POLYGON); glVertex2i(0, 35); glVertex2i(1000, 35); glVertex2i(1000, 45); glVertex2i(0, 45); glEnd(); glFlush (); /*------- custom code ends -------*/ /******************************************/ glutSwapBuffers(); glutPostRedisplay(); } /*Timer_Control_Object*/ void timerLoopA(int t1) { if (passAViewX >= 0) { passAViewX += 3; } if(passAViewX >= 1050) { passAViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopA, 0); } void timerLoopB(int t2) { if (passBViewX >= 0) { passBViewX += 2; } if(passBViewX >= 1050) { passBViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopB, 0); } void timerLoopC(int t3) { if (passCViewX >= 0) { passCViewX += 2.5; } if(passCViewX >= 1050) { passCViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopC, 0); } void timerLoopD(int t4) { if (passDViewX >= 0) { passDViewX += 2.75; } if(passDViewX >= 1050) { passDViewX=0; m += 5; } glutPostRedisplay(); glutTimerFunc(15, timerLoopD, 0); } /*void score(){ int s=0; for (;;){ system("CLS"); glRasterPos2f(400, 400); glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, s); s++; Sleep(1000); } }*/ /*main_function*/ void main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(1208, 720); glutInitWindowPosition(0, 0); glutCreateWindow("Plane"); glutDisplayFunc(myDisplay); glutSpecialFunc(keyboard); glutTimerFunc(0, timerLoopA, 0); glutTimerFunc(0, timerLoopB, 0); glutTimerFunc(0, timerLoopC, 0); glutTimerFunc(0, timerLoopD, 0); myInit(); glutMainLoop(); }
58.833333
7,532
0.652443
quang-vn26
827f167147a810e89a1ba8ee85df3d023cd0481a
637
cpp
C++
2407/5414965_AC_0MS_168K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
2407/5414965_AC_0MS_168K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
2407/5414965_AC_0MS_168K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<cstdio> #include<algorithm> using namespace std; int main(){ const int PRE_PROCESS_SIZE=40000; bool prime[PRE_PROCESS_SIZE]; fill(prime,prime+PRE_PROCESS_SIZE,true); prime[0]=prime[1]=false; for(int i=2;i<PRE_PROCESS_SIZE;i++) if(prime[i]) for(int j=2;i*j<PRE_PROCESS_SIZE;j++) prime[i*j]=false; while(true){ int n; scanf("%d",&n); if(n==0) break; int count=1; for(int i=2;i*i<=n;i++){ if(prime[i] && n%i==0){ count*=i-1; n/=i; while(n%i==0){ count*=i; n/=i; } } } if(n>1) count*=n-1; printf("%d\n",count); } return 0; }
17.694444
42
0.546311
vandreas19
827ff691aea0c1d644e56b7c68dc752920ded987
252
cpp
C++
TopCoder/Plugin/moj_4/template.cpp
vios-fish/CompetitiveProgramming
6953f024e4769791225c57ed852cb5efc03eb94b
[ "MIT" ]
null
null
null
TopCoder/Plugin/moj_4/template.cpp
vios-fish/CompetitiveProgramming
6953f024e4769791225c57ed852cb5efc03eb94b
[ "MIT" ]
null
null
null
TopCoder/Plugin/moj_4/template.cpp
vios-fish/CompetitiveProgramming
6953f024e4769791225c57ed852cb5efc03eb94b
[ "MIT" ]
null
null
null
// Paste me into the FileEdit configuration dialog #include <string> #include <vector> using namespace std; class $CLASSNAME$ { public: $RC$ $METHODNAME$( $METHODPARMS$ ) { } }; $BEGINCUT$ $TESTCODE$ $DEFAULTMAIN$ $ENDCUT$
13.263158
51
0.634921
vios-fish
82828aaf2a72e1e22729ae93936a2525175825e0
2,265
cpp
C++
C++/best-time-to-buy-and-sell-stock-iv.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/best-time-to-buy-and-sell-stock-iv.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/best-time-to-buy-and-sell-stock-iv.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n) // Space: O(n) class Solution { public: int maxProfit(int k, vector<int> &prices) { vector<int> profits; vector<pair<int, int>> v_p_stk; // mono stack, where v is increasing and p is strictly decreasing for (int v = -1, p = -1; p + 1 < size(prices);) { // at most O(n) peaks, so v_p_stk and profits are both at most O(n) space for (v = p + 1; v + 1 < size(prices); ++v) { if (prices[v] < prices[v + 1]) { break; } } for (p = v; p + 1 < size(prices); ++p) { if (prices[p] > prices[p + 1]) { break; } } while (!empty(v_p_stk) && (prices[v_p_stk.back().first] > prices[v])) { // not overlapped const auto [last_v, last_p] = move(v_p_stk.back()); v_p_stk.pop_back(); profits.emplace_back(prices[last_p] - prices[last_v]); // count [prices[last_v], prices[last_p]] interval } while (!empty(v_p_stk) && (prices[v_p_stk.back().second] <= prices[p])) { // overlapped // prices[last_v] <= prices[v] <= prices[last_p] <= prices[p], // treat overlapped as [prices[v], prices[last_p]], [prices[last_v], prices[p]] intervals due to invariant max profit const auto [last_v, last_p] = move(v_p_stk.back()); v_p_stk.pop_back(); profits.emplace_back(prices[last_p] - prices[v]); // count [prices[v], prices[last_p]] interval v = last_v; } v_p_stk.emplace_back(v, p); // keep [prices[last_v], prices[p]] interval to check overlapped } while (!empty(v_p_stk)) { const auto [last_v, last_p] = move(v_p_stk.back()); v_p_stk.pop_back(); profits.emplace_back(prices[last_p] - prices[last_v]); // count [prices[last_v], prices[last_p]] interval } if (k > size(profits)) { k = size(profits); } else { nth_element(begin(profits), begin(profits) + k - 1, end(profits), greater<int>()); } return accumulate(cbegin(profits), cbegin(profits) + k, 0); // top k profits of nonoverlapped intervals } };
50.333333
133
0.525828
Priyansh2
828b7339b36cd74b8b5b4eb120f9ec9abb663a3b
209
cpp
C++
sources/main.cpp
Mitrius/Multicore
f0b0ef11124975ec534c20523ed1f01110118bd0
[ "MIT" ]
null
null
null
sources/main.cpp
Mitrius/Multicore
f0b0ef11124975ec534c20523ed1f01110118bd0
[ "MIT" ]
null
null
null
sources/main.cpp
Mitrius/Multicore
f0b0ef11124975ec534c20523ed1f01110118bd0
[ "MIT" ]
null
null
null
#include "mkl.h" #include "../headers/calculations.h" int main(int _argc, char const *argv[]) { std::string filePath = argv[1]; //calculateRef(filePath); calculateImpl(filePath); return 0; }
17.416667
39
0.650718
Mitrius
8291a742c3635163474558213adaba98cff1107e
1,875
cpp
C++
hiro/core/widget/combo-button.cpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
hiro/core/widget/combo-button.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
hiro/core/widget/combo-button.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
#if defined(Hiro_ComboButton) auto mComboButton::allocate() -> pObject* { return new pComboButton(*this); } auto mComboButton::destruct() -> void { for(auto& item : state.items) item->destruct(); mWidget::destruct(); } // auto mComboButton::append(sComboButtonItem item) -> type& { if(!state.items) item->state.selected = true; state.items.append(item); item->setParent(this, itemCount() - 1); signal(append, item); return *this; } auto mComboButton::doChange() const -> void { if(state.onChange) return state.onChange(); } auto mComboButton::item(unsigned position) const -> ComboButtonItem { if(position < itemCount()) return state.items[position]; return {}; } auto mComboButton::itemCount() const -> unsigned { return state.items.size(); } auto mComboButton::items() const -> vector<ComboButtonItem> { vector<ComboButtonItem> items; for(auto& item : state.items) items.append(item); return items; } auto mComboButton::onChange(const function<void ()>& callback) -> type& { state.onChange = callback; return *this; } auto mComboButton::remove(sComboButtonItem item) -> type& { signal(remove, item); state.items.remove(item->offset()); for(auto n : range(item->offset(), itemCount())) { state.items[n]->adjustOffset(-1); } item->setParent(); return *this; } auto mComboButton::reset() -> type& { signal(reset); for(auto& item : state.items) item->setParent(); state.items.reset(); return *this; } auto mComboButton::selected() const -> ComboButtonItem { for(auto& item : state.items) { if(item->selected()) return item; } return {}; } auto mComboButton::setParent(mObject* parent, signed offset) -> type& { for(auto& item : state.items) item->destruct(); mObject::setParent(parent, offset); for(auto& item : state.items) item->setParent(this, item->offset()); return *this; } #endif
24.038462
73
0.6816
mp-lee
8294af14be5df43cb4c26411ef116d3853524cb4
13,057
cpp
C++
applications/mne_matching_pursuit/release/moc_enhancededitorwindow.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
applications/mne_matching_pursuit/release/moc_enhancededitorwindow.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
applications/mne_matching_pursuit/release/moc_enhancededitorwindow.cpp
ChunmingGu/mne-cpp-master
36f21b3ab0c65a133027da83fa8e2a652acd1485
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'enhancededitorwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../enhancededitorwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'enhancededitorwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.10.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Enhancededitorwindow_t { QByteArrayData data[36]; char stringdata0[986]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Enhancededitorwindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Enhancededitorwindow_t qt_meta_stringdata_Enhancededitorwindow = { { QT_MOC_LITERAL(0, 0, 20), // "Enhancededitorwindow" QT_MOC_LITERAL(1, 21, 10), // "dict_saved" QT_MOC_LITERAL(2, 32, 0), // "" QT_MOC_LITERAL(3, 33, 26), // "on_chb_allCombined_toggled" QT_MOC_LITERAL(4, 60, 7), // "checked" QT_MOC_LITERAL(5, 68, 37), // "on_cb_AtomFormula_currentInde..." QT_MOC_LITERAL(6, 106, 4), // "arg1" QT_MOC_LITERAL(7, 111, 28), // "on_sb_Atomcount_valueChanged" QT_MOC_LITERAL(8, 140, 28), // "on_btt_DeleteFormula_clicked" QT_MOC_LITERAL(9, 169, 33), // "on_sb_SampleCount_editingFini..." QT_MOC_LITERAL(10, 203, 30), // "on_dsb_StepVauleA_valueChanged" QT_MOC_LITERAL(11, 234, 30), // "on_dsb_StepVauleB_valueChanged" QT_MOC_LITERAL(12, 265, 30), // "on_dsb_StepVauleC_valueChanged" QT_MOC_LITERAL(13, 296, 30), // "on_dsb_StepVauleD_valueChanged" QT_MOC_LITERAL(14, 327, 30), // "on_dsb_StepVauleE_valueChanged" QT_MOC_LITERAL(15, 358, 30), // "on_dsb_StepVauleF_valueChanged" QT_MOC_LITERAL(16, 389, 30), // "on_dsb_StepVauleG_valueChanged" QT_MOC_LITERAL(17, 420, 30), // "on_dsb_StepVauleH_valueChanged" QT_MOC_LITERAL(18, 451, 31), // "on_dsb_StartValueA_valueChanged" QT_MOC_LITERAL(19, 483, 31), // "on_dsb_StartValueB_valueChanged" QT_MOC_LITERAL(20, 515, 31), // "on_dsb_StartValueC_valueChanged" QT_MOC_LITERAL(21, 547, 31), // "on_dsb_StartValueD_valueChanged" QT_MOC_LITERAL(22, 579, 31), // "on_dsb_StartValueE_valueChanged" QT_MOC_LITERAL(23, 611, 31), // "on_dsb_StartValueF_valueChanged" QT_MOC_LITERAL(24, 643, 31), // "on_dsb_StartValueG_valueChanged" QT_MOC_LITERAL(25, 675, 31), // "on_dsb_StartValueH_valueChanged" QT_MOC_LITERAL(26, 707, 29), // "on_dsb_EndValueA_valueChanged" QT_MOC_LITERAL(27, 737, 29), // "on_dsb_EndValueB_valueChanged" QT_MOC_LITERAL(28, 767, 29), // "on_dsb_EndValueC_valueChanged" QT_MOC_LITERAL(29, 797, 29), // "on_dsb_EndValueD_valueChanged" QT_MOC_LITERAL(30, 827, 29), // "on_dsb_EndValueE_valueChanged" QT_MOC_LITERAL(31, 857, 29), // "on_dsb_EndValueF_valueChanged" QT_MOC_LITERAL(32, 887, 29), // "on_dsb_EndValueG_valueChanged" QT_MOC_LITERAL(33, 917, 29), // "on_dsb_EndValueH_valueChanged" QT_MOC_LITERAL(34, 947, 21), // "on_pushButton_clicked" QT_MOC_LITERAL(35, 969, 16) // "on_formula_saved" }, "Enhancededitorwindow\0dict_saved\0\0" "on_chb_allCombined_toggled\0checked\0" "on_cb_AtomFormula_currentIndexChanged\0" "arg1\0on_sb_Atomcount_valueChanged\0" "on_btt_DeleteFormula_clicked\0" "on_sb_SampleCount_editingFinished\0" "on_dsb_StepVauleA_valueChanged\0" "on_dsb_StepVauleB_valueChanged\0" "on_dsb_StepVauleC_valueChanged\0" "on_dsb_StepVauleD_valueChanged\0" "on_dsb_StepVauleE_valueChanged\0" "on_dsb_StepVauleF_valueChanged\0" "on_dsb_StepVauleG_valueChanged\0" "on_dsb_StepVauleH_valueChanged\0" "on_dsb_StartValueA_valueChanged\0" "on_dsb_StartValueB_valueChanged\0" "on_dsb_StartValueC_valueChanged\0" "on_dsb_StartValueD_valueChanged\0" "on_dsb_StartValueE_valueChanged\0" "on_dsb_StartValueF_valueChanged\0" "on_dsb_StartValueG_valueChanged\0" "on_dsb_StartValueH_valueChanged\0" "on_dsb_EndValueA_valueChanged\0" "on_dsb_EndValueB_valueChanged\0" "on_dsb_EndValueC_valueChanged\0" "on_dsb_EndValueD_valueChanged\0" "on_dsb_EndValueE_valueChanged\0" "on_dsb_EndValueF_valueChanged\0" "on_dsb_EndValueG_valueChanged\0" "on_dsb_EndValueH_valueChanged\0" "on_pushButton_clicked\0on_formula_saved" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Enhancededitorwindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 32, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 174, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 3, 1, 175, 2, 0x08 /* Private */, 5, 1, 178, 2, 0x08 /* Private */, 7, 1, 181, 2, 0x08 /* Private */, 8, 0, 184, 2, 0x08 /* Private */, 9, 0, 185, 2, 0x08 /* Private */, 10, 1, 186, 2, 0x08 /* Private */, 11, 1, 189, 2, 0x08 /* Private */, 12, 1, 192, 2, 0x08 /* Private */, 13, 1, 195, 2, 0x08 /* Private */, 14, 1, 198, 2, 0x08 /* Private */, 15, 1, 201, 2, 0x08 /* Private */, 16, 1, 204, 2, 0x08 /* Private */, 17, 1, 207, 2, 0x08 /* Private */, 18, 1, 210, 2, 0x08 /* Private */, 19, 1, 213, 2, 0x08 /* Private */, 20, 1, 216, 2, 0x08 /* Private */, 21, 1, 219, 2, 0x08 /* Private */, 22, 1, 222, 2, 0x08 /* Private */, 23, 1, 225, 2, 0x08 /* Private */, 24, 1, 228, 2, 0x08 /* Private */, 25, 1, 231, 2, 0x08 /* Private */, 26, 1, 234, 2, 0x08 /* Private */, 27, 1, 237, 2, 0x08 /* Private */, 28, 1, 240, 2, 0x08 /* Private */, 29, 1, 243, 2, 0x08 /* Private */, 30, 1, 246, 2, 0x08 /* Private */, 31, 1, 249, 2, 0x08 /* Private */, 32, 1, 252, 2, 0x08 /* Private */, 33, 1, 255, 2, 0x08 /* Private */, 34, 0, 258, 2, 0x08 /* Private */, 35, 0, 259, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::Bool, 4, QMetaType::Void, QMetaType::QString, 6, QMetaType::Void, QMetaType::Int, 6, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Double, 6, QMetaType::Void, QMetaType::Void, 0 // eod }; void Enhancededitorwindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Enhancededitorwindow *_t = static_cast<Enhancededitorwindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->dict_saved(); break; case 1: _t->on_chb_allCombined_toggled((*reinterpret_cast< bool(*)>(_a[1]))); break; case 2: _t->on_cb_AtomFormula_currentIndexChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 3: _t->on_sb_Atomcount_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 4: _t->on_btt_DeleteFormula_clicked(); break; case 5: _t->on_sb_SampleCount_editingFinished(); break; case 6: _t->on_dsb_StepVauleA_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 7: _t->on_dsb_StepVauleB_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 8: _t->on_dsb_StepVauleC_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 9: _t->on_dsb_StepVauleD_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 10: _t->on_dsb_StepVauleE_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 11: _t->on_dsb_StepVauleF_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 12: _t->on_dsb_StepVauleG_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 13: _t->on_dsb_StepVauleH_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 14: _t->on_dsb_StartValueA_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 15: _t->on_dsb_StartValueB_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 16: _t->on_dsb_StartValueC_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 17: _t->on_dsb_StartValueD_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 18: _t->on_dsb_StartValueE_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 19: _t->on_dsb_StartValueF_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 20: _t->on_dsb_StartValueG_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 21: _t->on_dsb_StartValueH_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 22: _t->on_dsb_EndValueA_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 23: _t->on_dsb_EndValueB_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 24: _t->on_dsb_EndValueC_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 25: _t->on_dsb_EndValueD_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 26: _t->on_dsb_EndValueE_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 27: _t->on_dsb_EndValueF_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 28: _t->on_dsb_EndValueG_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 29: _t->on_dsb_EndValueH_valueChanged((*reinterpret_cast< double(*)>(_a[1]))); break; case 30: _t->on_pushButton_clicked(); break; case 31: _t->on_formula_saved(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { typedef void (Enhancededitorwindow::*_t)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&Enhancededitorwindow::dict_saved)) { *result = 0; return; } } } } const QMetaObject Enhancededitorwindow::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_Enhancededitorwindow.data, qt_meta_data_Enhancededitorwindow, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *Enhancededitorwindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Enhancededitorwindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Enhancededitorwindow.stringdata0)) return static_cast<void*>(this); return QWidget::qt_metacast(_clname); } int Enhancededitorwindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 32) qt_static_metacall(this, _c, _id, _a); _id -= 32; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 32) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 32; } return _id; } // SIGNAL 0 void Enhancededitorwindow::dict_saved() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } QT_WARNING_POP QT_END_MOC_NAMESPACE
45.179931
112
0.650303
ChunmingGu
82975711f45a5ce8804471a2f43e00dadc3516b1
441
cpp
C++
10_smart_pointers/10_02_unique_ptr_as_raii/10_02_00_unique_ptr_as_raii.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
13
2020-09-01T14:57:21.000Z
2021-11-24T06:00:26.000Z
10_smart_pointers/10_02_unique_ptr_as_raii/10_02_00_unique_ptr_as_raii.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
5
2020-06-11T14:13:00.000Z
2021-07-14T05:27:53.000Z
10_smart_pointers/10_02_unique_ptr_as_raii/10_02_00_unique_ptr_as_raii.cpp
pAbogn/cpp_courses
6ffa7da5cc440af3327139a38cfdefcfaae1ebed
[ "MIT" ]
10
2021-03-22T07:54:36.000Z
2021-09-15T04:03:32.000Z
// Smart pointer with unique ownership #include <memory> #include <cassert> int main() { std::unique_ptr<int> uptr1(new int(1)); int val = *uptr1; std::unique_ptr<int> uptr2 = uptr1; // Fail std::unique_ptr<int> uptr3 = std::move(uptr1); // OK assert(uptr3); assert(uptr1); uptr3.reset(new int(2)); // Object 1 is destroyed, uptr3 points to object 2 // When ~uptr3 is called - object 2 is destroyed }
20.045455
79
0.637188
pAbogn
8299e8bbef89bb086c2f5153fbf9a281e009a0d7
106
cpp
C++
CPP/CPPASTL/Day01/index.cpp
wolflion/Code2018
352ec55527602eb592b1936ec9d4c7d3a2368bb8
[ "Apache-2.0" ]
null
null
null
CPP/CPPASTL/Day01/index.cpp
wolflion/Code2018
352ec55527602eb592b1936ec9d4c7d3a2368bb8
[ "Apache-2.0" ]
null
null
null
CPP/CPPASTL/Day01/index.cpp
wolflion/Code2018
352ec55527602eb592b1936ec9d4c7d3a2368bb8
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; #define MAX 1024 int main() { cout << MAX << endl; return 0; }
10.6
21
0.660377
wolflion
8299f4ed8b13761148537ce51959a8ffaacb9d93
834
cpp
C++
Arrays/Two Sum.cpp
nitishkalra/Coding-Problems-Solved
3f5944a2bfb78f2ad7992c6224ef3c1099566fc8
[ "MIT" ]
2
2020-11-05T07:34:14.000Z
2020-11-05T07:47:15.000Z
Arrays/Two Sum.cpp
nitishkalra/Coding-Problems-Solved
3f5944a2bfb78f2ad7992c6224ef3c1099566fc8
[ "MIT" ]
null
null
null
Arrays/Two Sum.cpp
nitishkalra/Coding-Problems-Solved
3f5944a2bfb78f2ad7992c6224ef3c1099566fc8
[ "MIT" ]
1
2020-11-05T07:34:16.000Z
2020-11-05T07:34:16.000Z
Leetcode - Two Sum //Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. //You may assume that each input would have exactly one solution, and you may not use the same element twice. //You can return the answer in any order. class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> hm; vector<int> result; for(int i=0;i<nums.size();i++){ hm[nums[i]] = i; } for(int i=0;i<nums.size();i++){ if(hm.find(target-nums[i])!=hm.end()){ if(hm[target-nums[i]]==i) continue; result.push_back(i); result.push_back(hm[target-nums[i]]); break; } } return result; } };
30.888889
123
0.567146
nitishkalra
82a4be72e1d357e8362128381c9a8ff01eed5ac3
5,081
hpp
C++
include/my_async/udp_client/impl/client_base_impl.hpp
rnascunha/my_async
5fbe3a46e87a2d74fc07d16252a3b3cf488b4684
[ "MIT" ]
null
null
null
include/my_async/udp_client/impl/client_base_impl.hpp
rnascunha/my_async
5fbe3a46e87a2d74fc07d16252a3b3cf488b4684
[ "MIT" ]
null
null
null
include/my_async/udp_client/impl/client_base_impl.hpp
rnascunha/my_async
5fbe3a46e87a2d74fc07d16252a3b3cf488b4684
[ "MIT" ]
1
2021-03-10T13:02:13.000Z
2021-03-10T13:02:13.000Z
#ifndef UDP_CLIENT_BASE_SESSION_IMPL_HPP__ #define UDP_CLIENT_BASE_SESSION_IMPL_HPP__ #include "../client_base.hpp" using boost::asio::ip::udp; namespace My_Async{ namespace UDP{ template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: Client_Base(boost::asio::io_context& ioc, const udp::endpoint& ep) : socket_(ioc, ep){} template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: Client_Base(boost::asio::io_context& ioc) : socket_(ioc, udp::endpoint(udp::v4(), 0)){} template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: Client_Base(boost::asio::io_context& ioc, unsigned short port) : socket_(ioc, udp::endpoint(udp::v4(), port)){} template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: open(udp::endpoint const& endpoint) noexcept { endpoint_ = endpoint; on_open(); do_read(); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: write(std::shared_ptr<OutContainer const> data) noexcept { boost::asio::post( socket_.get_executor(), std::bind( &self_type::writing, derived().shared_from_this(), data) ); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: write(OutContainer const data) noexcept { write(std::make_shared<OutContainer const>(std::move(data))); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: close(boost::system::error_code& ec) noexcept { socket_.close(ec); on_close(ec); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> udp::endpoint Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: endpoint() const { return endpoint_; } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> udp::endpoint Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: local_endpoint() const { return socket_.local_endpoint(); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: fail(boost::system::error_code ec, char const* what) noexcept { if(ec == boost::asio::error::operation_aborted || ec == boost::asio::error::bad_descriptor) return; on_error(ec, what); close(ec); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: do_read() noexcept { socket_.async_receive_from( boost::asio::dynamic_buffer(buffer_).prepare(ReadBufferSize), endpoint_, std::bind( &self_type::on_read, derived().shared_from_this(), std::placeholders::_1, //error_code std::placeholders::_2 //bytes transfered ) ); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: on_read(boost::system::error_code ec, std::size_t bytes_transfered) noexcept { if(ec) return fail(ec, "read"); buffer_.resize(bytes_transfered); read_handler(buffer_); buffer_.erase(buffer_.begin(), buffer_.end()); do_read(); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: writing(std::shared_ptr<OutContainer const> const data) noexcept { queue_.push_back(data); if(queue_.size() > 1) return; do_write(); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: do_write() noexcept{ socket_.async_send_to( boost::asio::buffer(*queue_.front()), endpoint_, std::bind( &self_type::on_write, derived().shared_from_this(), std::placeholders::_1, std::placeholders::_2 ) ); } template<typename Derived, typename InContainer, typename OutContainer, std::size_t ReadBufferSize> void Client_Base<Derived, InContainer, OutContainer, ReadBufferSize>:: on_write(boost::system::error_code ec, std::size_t) noexcept { if(ec) return fail(ec, "write"); queue_.erase(queue_.begin()); if(! queue_.empty()) do_write(); } }//UDP }//My_Async #endif /* UDP_CLIENT_BASE_SESSION_IMPL_HPP__ */
23.095455
76
0.758906
rnascunha
82a5256542dd6d2a2fa6fc2596ef857ba1c64171
756
hpp
C++
c++/include/celerite2/utils.hpp
jacksonloper/celerite2
e413e28dc43ba33e67960b51a9cbbac43c2f58df
[ "MIT" ]
38
2020-10-10T02:43:53.000Z
2022-03-30T09:59:21.000Z
c++/include/celerite2/utils.hpp
jacksonloper/celerite2
e413e28dc43ba33e67960b51a9cbbac43c2f58df
[ "MIT" ]
34
2020-10-06T18:50:47.000Z
2022-01-28T10:33:04.000Z
c++/include/celerite2/utils.hpp
jacksonloper/celerite2
e413e28dc43ba33e67960b51a9cbbac43c2f58df
[ "MIT" ]
6
2020-11-09T18:12:54.000Z
2022-02-03T20:20:59.000Z
#ifndef _CELERITE2_UTILS_HPP_DEFINED_ #define _CELERITE2_UTILS_HPP_DEFINED_ #include <Eigen/Core> #include <cassert> namespace celerite2 { namespace utils { #define ASSERT_SAME_OR_DYNAMIC(VAL, J) assert((VAL == Eigen::Dynamic) || (VAL == J)) // adapted from https://academy.realm.io/posts/how-we-beat-cpp-stl-binary-search/ template <typename T> inline int search_sorted(const Eigen::MatrixBase<T> &x, const typename T::Scalar &value) { const int N = x.rows(); int low = -1, high = N; while (high - low > 1) { int probe = (low + high) / 2; auto v = x(probe); if (v > value) high = probe; else low = probe; } return high; } } // namespace utils } // namespace celerite2 #endif // _CELERITE2_UTILS_HPP_DEFINED_
23.625
90
0.671958
jacksonloper