hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
044a6e5ea4d8fd7b3fa8bc61819aeac5b8914a5e | 6,555 | ipp | C++ | include/stats_incl/quant/qf.ipp | JohnGalbraith/stats | 309c0e92d2326a58cad4544124c614e6a8a46079 | [
"Apache-2.0"
] | 381 | 2017-07-16T17:34:02.000Z | 2022-03-30T09:47:58.000Z | include/stats_incl/quant/qf.ipp | myhhub/stats | 309c0e92d2326a58cad4544124c614e6a8a46079 | [
"Apache-2.0"
] | 29 | 2017-07-14T20:45:42.000Z | 2022-01-25T20:59:08.000Z | include/stats_incl/quant/qf.ipp | myhhub/stats | 309c0e92d2326a58cad4544124c614e6a8a46079 | [
"Apache-2.0"
] | 70 | 2017-10-25T14:16:11.000Z | 2022-01-25T20:57:02.000Z | /*################################################################################
##
## Copyright (C) 2011-2021 Keith O'Hara
##
## This file is part of the StatsLib C++ library.
##
## 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.
##
################################################################################*/
/*
* quantile function of the F-distribution
*/
//
// single input
namespace internal
{
template<typename T>
statslib_constexpr
T
qf_compute_adj(const T I_inv_val, const T ab_ratio)
noexcept
{
return( I_inv_val / (ab_ratio*(T(1) - I_inv_val)) );
}
template<typename T>
statslib_constexpr
T
qf_compute(const T p, const T a_par, const T b_par)
noexcept
{
return qf_compute_adj(gcem::incomplete_beta_inv(a_par,b_par,p),a_par/b_par);
}
template<typename T>
statslib_constexpr
T
qf_limit_vals_dof(const T p, const T df1_par, const T df2_par)
noexcept
{
return( // df1 == +Inf and df2 == +Inf
GCINT::all_posinf(df1_par,df2_par) ? \
T(1) :
// df1 == +Inf
GCINT::is_posinf(df1_par) ? \
df2_par / qchisq(T(1)-p,df2_par) :
// df2 == +Inf
qchisq(p,df1_par) / df1_par );
}
template<typename T>
statslib_constexpr
T
qf_vals_check(const T p, const T df1_par, const T df2_par)
noexcept
{
return( !f_sanity_check(df1_par,df2_par) ? \
STLIM<T>::quiet_NaN() :
//
!prob_val_check(p) ? \
STLIM<T>::quiet_NaN() :
//
p == T(0) ? \
T(0) :
p == T(1) ? \
STLIM<T>::infinity() :
// 0 < p < 1
GCINT::any_posinf(df1_par,df2_par) ? \
qf_limit_vals_dof(p,df1_par,df2_par) :
//
qf_compute(p,df1_par/T(2),df2_par/T(2)) );
}
template<typename T1, typename T2, typename T3, typename TC = common_return_t<T1,T2,T3>>
statslib_constexpr
TC
qf_type_check(const T1 p, const T2 df1_par, const T3 df2_par)
noexcept
{
return qf_vals_check(static_cast<TC>(p),static_cast<TC>(df1_par),static_cast<TC>(df2_par));
}
}
/**
* @brief Quantile function of the F-distribution
*
* @param p a real-valued input.
* @param df1_par a degrees of freedom parameter, a real-valued input.
* @param df2_par a degrees of freedom parameter, a real-valued input.
*
* @return the quantile function evaluated at \c p.
*
* Example:
* \code{.cpp} stats::qf(0.5,10.0,12.0); \endcode
*/
template<typename T1, typename T2, typename T3>
statslib_constexpr
common_return_t<T1,T2,T3>
qf(const T1 p, const T2 df1_par, const T3 df2_par)
noexcept
{
return internal::qf_type_check(p,df1_par,df2_par);
}
//
// vector/matrix input
namespace internal
{
#ifdef STATS_ENABLE_INTERNAL_VEC_FEATURES
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
void
qf_vec(const eT* __stats_pointer_settings__ vals_in, const T1 df1_par, const T2 df2_par,
rT* __stats_pointer_settings__ vals_out, const ullint_t num_elem)
{
EVAL_DIST_FN_VEC(qf,vals_in,vals_out,num_elem,df1_par,df2_par);
}
#endif
}
/**
* @brief Quantile function of the F-distribution
*
* @param x a standard vector.
* @param df1_par a degrees of freedom parameter, a real-valued input.
* @param df2_par a degrees of freedom parameter, a real-valued input.
*
* @return a vector of quantile values corresponding to the elements of \c x.
*
* Example:
* \code{.cpp}
* std::vector<double> x = {0.3, 0.5, 0.9};
* stats::qf(x,3.0,2.0);
* \endcode
*/
#ifdef STATS_ENABLE_STDVEC_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
std::vector<rT>
qf(const std::vector<eT>& x, const T1 df1_par, const T2 df2_par)
{
STDVEC_DIST_FN(qf_vec,df1_par,df2_par);
}
#endif
/**
* @brief Quantile function of the F-distribution
*
* @param X a matrix of input values.
* @param df1_par a degrees of freedom parameter, a real-valued input.
* @param df2_par a degrees of freedom parameter, a real-valued input.
*
* @return a matrix of quantile values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* arma::mat X = { {0.2, 0.7, 0.1},
* {0.9, 0.3, 0.87} };
* stats::qf(X,3.0,2.0);
* \endcode
*/
#ifdef STATS_ENABLE_ARMA_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT>
statslib_inline
ArmaMat<rT>
qf(const ArmaMat<eT>& X, const T1 df1_par, const T2 df2_par)
{
ARMA_DIST_FN(qf_vec,df1_par,df2_par);
}
template<typename mT, typename tT, typename T1, typename T2>
statslib_inline
mT
qf(const ArmaGen<mT,tT>& X, const T1 df1_par, const T2 df2_par)
{
return qf(X.eval(),df1_par,df2_par);
}
#endif
/**
* @brief Quantile function of the F-distribution
*
* @param X a matrix of input values.
* @param df1_par a degrees of freedom parameter, a real-valued input.
* @param df2_par a degrees of freedom parameter, a real-valued input.
*
* @return a matrix of quantile values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* stats::qf(X,3.0,2.0);
* \endcode
*/
#ifdef STATS_ENABLE_BLAZE_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT, bool To>
statslib_inline
BlazeMat<rT,To>
qf(const BlazeMat<eT,To>& X, const T1 df1_par, const T2 df2_par)
{
BLAZE_DIST_FN(qf_vec,df1_par,df2_par);
}
#endif
/**
* @brief Quantile function of the F-distribution
*
* @param X a matrix of input values.
* @param df1_par a degrees of freedom parameter, a real-valued input.
* @param df2_par a degrees of freedom parameter, a real-valued input.
*
* @return a matrix of quantile values corresponding to the elements of \c X.
*
* Example:
* \code{.cpp}
* stats::qf(X,3.0,2.0);
* \endcode
*/
#ifdef STATS_ENABLE_EIGEN_WRAPPERS
template<typename eT, typename T1, typename T2, typename rT, int iTr, int iTc>
statslib_inline
EigenMat<rT,iTr,iTc>
qf(const EigenMat<eT,iTr,iTc>& X, const T1 df1_par, const T2 df2_par)
{
EIGEN_DIST_FN(qf_vec,df1_par,df2_par);
}
#endif
| 26.22 | 95 | 0.65614 | [
"vector"
] |
044e43a15f6c22ccc13ff5613dd2a9486a75cfe8 | 3,571 | cpp | C++ | src/StringFunctions.cpp | simul/glfx | a192e069d4df45a31c10ca9adafe82e95dd09915 | [
"BSD-2-Clause"
] | 20 | 2015-03-01T14:01:27.000Z | 2019-11-23T04:41:30.000Z | src/StringFunctions.cpp | simul/glfx | a192e069d4df45a31c10ca9adafe82e95dd09915 | [
"BSD-2-Clause"
] | 1 | 2015-08-30T08:00:54.000Z | 2015-09-06T15:31:33.000Z | src/StringFunctions.cpp | simul/glfx | a192e069d4df45a31c10ca9adafe82e95dd09915 | [
"BSD-2-Clause"
] | 10 | 2015-03-04T11:34:39.000Z | 2020-01-17T07:23:50.000Z | #include "StringFunctions.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#ifndef _MSC_VER
#define sprintf_s(buffer, buffer_size, stringbuffer, ...) (snprintf(buffer, buffer_size, stringbuffer, ##__VA_ARGS__))
#endif
using std::string;
using std::vector;
size_t ttab;
bool IsWhitespace(char c)
{
return (c==' '||c==13||c==10||c=='\t');
}
void ClipWhitespace(std::string &Line)
{
while(Line.length()?IsWhitespace(Line[0]):false)
Line=Line.substr(1,Line.length()-1);
while(Line.length()?IsWhitespace(Line[Line.length()-1]):false)
Line=Line.substr(0,Line.length()-1);
}
void Tab(string &out)
{
for(size_t i=0;i<ttab;i++)
out+="\t";
}
size_t GoToLine(const string &Str,size_t line)
{
size_t pos=0;
char txt[100];
sprintf_s(txt,99,"\r\n");
string CR;
for(size_t i=0;i<line;i++)
{
pos=Str.find(13,pos);
pos++;
}
//pos++;
return pos;
}
string stringof(int i)
{
char txt[100];
sprintf_s(txt,99,"%d",i);
return string(txt);
}
string stringof(float f)
{
char txt[100];
sprintf_s(txt,99,"%g",f);
return string(txt);
}
string StringOf(int i)
{
char txt[100];
sprintf_s(txt,99,"%d",i);
return string(txt);
}
string StringOf(float i)
{
char txt[100];
sprintf_s(txt,99,"%g",i);
return string(txt);
}
extern std::string digits(const char *txt)
{
std::string d;
const char *t=txt;
while(*t)
{
if(*t>='0'&&*t<='9')
d+=*t;
t++;
}
return d;
}
void StripDirectoryFromFilename(string &str)
{
int pos=(int)str.find("\\");
int fs_pos=(int)str.find("/");
if(pos<0||(fs_pos>=0&&fs_pos<pos))
pos=fs_pos;
do
{
str=str.substr(pos+1,str.length()-pos);
pos=(int)str.find("\\");
fs_pos=(int)str.find("/");
if(pos<0||(fs_pos>=0&&fs_pos<pos))
pos=fs_pos;
} while(pos>=0);
}
string GetDirectoryFromFilename(const string &str)
{
int pos=(int)str.find_last_of("\\");
int fs_pos=(int)str.find_last_of("/");
if(pos<0||(fs_pos>=0&&fs_pos>pos))
pos=fs_pos;
if(pos<0)
return "";
return str.substr(0,pos);
}
std::string stringFormat(std::string fmt, ...)
{
int size=(int)fmt.size()+100;
std::string str;
va_list ap;
int n=-1;
const char *format_str=fmt.c_str();
while(n<0||n>=size)
{
str.resize(size);
va_start(ap, fmt);
//n = vsnprintf_s((char *)str.c_str(), size, size,format_str, ap);
n = vsnprintf((char *)str.c_str(), size,format_str, ap);
va_end(ap);
if(n> -1 && n < size)
{
str.resize(n);
return str;
}
if (n > -1)
size=n+1;
else
size*=2;
}
return str;
}
const char *QuickFormat(const char *format_str,...)
{
int size=(int)strlen(format_str)+100;
static std::string str;
va_list ap;
int n=-1;
while(n<0||n>=size)
{
str.resize(size);
va_start(ap, format_str);
//n = vsnprintf_s((char *)str.c_str(), size, size,format_str, ap);
n = vsnprintf((char *)str.c_str(), size,format_str, ap);
va_end(ap);
if(n> -1 && n < size)
{
str.resize(n);
return str.c_str();
}
if (n > -1)
size=n+1;
else
size*=2;
}
return str.c_str();
}
void find_and_replace(std::string& source, std::string const& find, std::string const& replace)
{
for(std::string::size_type i = 0; (i = source.find(find, i)) != std::string::npos;)
{
source.replace(i, find.length(), replace);
i += replace.length() - find.length() + 1;
}
}
vector<string> split(const string& source, char separator)
{
vector<string> vec;
int pos=0;
while(pos>=0&&pos<source.length())
{
int nextpos=(int)source.find(separator,pos);
if(nextpos<0)
nextpos=(int)source.length();
if(nextpos>=0)
vec.push_back(source.substr(pos,nextpos-pos));
pos=nextpos+1;
}
return vec;
} | 19.407609 | 118 | 0.633156 | [
"vector"
] |
0453d3741eafeece208eae02409fc802f3b9c465 | 34,234 | cpp | C++ | Atomic/AtTreeStore.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 4 | 2019-11-10T21:56:40.000Z | 2021-12-11T20:10:55.000Z | Atomic/AtTreeStore.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | null | null | null | Atomic/AtTreeStore.cpp | denisbider/Atomic | 8e8e979a6ef24d217a77f17fa81a4129f3506952 | [
"MIT"
] | 1 | 2019-11-11T08:38:59.000Z | 2019-11-11T08:38:59.000Z | #include "AtIncludes.h"
#include "AtTreeStore.h"
#include "AtNumCvt.h"
namespace At
{
// TreeStore::Node
void TreeStore::Node::Encode(Enc& enc) const
{
m_parentId.EncodeBin(enc);
EncodeVarStr(enc, m_key);
EncodeVarStr(enc, m_data);
}
bool TreeStore::Node::Decode(Seq& s)
{
Seq key, data;
if (!m_parentId.DecodeBin(s) ||
!DecodeVarStr(s, key) ||
!DecodeVarStr(s, data))
return false;
m_key = key;
m_data = data;
return true;
}
bool TreeStore::Node::SkipDecode(Seq& s)
{
Seq key, data;
if (!ObjId::SkipDecodeBin(s) ||
!DecodeVarStr(s, key) ||
!DecodeVarStr(s, data))
return false;
return true;
}
// TreeStore::BucketEntry
void TreeStore::BucketEntry::Encode(Enc& enc) const
{
EncodeVarStr(enc, m_key);
m_objId.EncodeBin(enc);
}
bool TreeStore::BucketEntry::Decode(Seq& s)
{
if (!DecodeVarStr(s, m_key) ||
!m_objId.DecodeBin(s))
return false;
return true;
}
// TreeStore::ChildBucket
void TreeStore::ChildBucket::InsertEntry(sizet index, Seq key, ObjId objId)
{
if (index > 0)
EnsureAbort(key >= m_entries[index - 1].m_key);
if (index == m_entries.Len())
m_entries.Add();
else
{
EnsureAbort(index < m_entries.Len());
EnsureAbort(key <= m_entries[index].m_key);
m_entries.Insert(index, BucketEntry());
}
m_entries[index].m_key = key;
m_entries[index].m_objId = objId;
m_encodedSize += m_entries[index].EncodedSize();
m_dirty = true;
}
TreeStore::FindKeyResult::E TreeStore::ChildBucket::FindLastKeyLessThan(Seq key, sizet& index) const
{
index = SIZE_MAX;
if (!m_entries.Any())
return FindKeyResult::Empty;
for (sizet i=0; i!=m_entries.Len(); ++i)
if (m_entries[i].m_key >= key)
{
if (i != 0) { index = i-1; return FindKeyResult::Found; }
else if (m_entries[i].m_key > key) return FindKeyResult::FirstKeyGreater;
else return FindKeyResult::FirstKeyEqual;
}
index = m_entries.Len() - 1;
return FindKeyResult::Found;
}
void TreeStore::ChildBucket::ReplaceEntryKey(sizet index, Seq newKey)
{
EnsureAbort(index < m_entries.Len());
if (index > 0) EnsureAbort(newKey >= m_entries[index - 1].m_key);
if (index + 1 < m_entries.Len()) EnsureAbort(newKey <= m_entries[index + 1].m_key);
m_encodedSize -= m_entries[index].EncodedSize();
m_entries[index].m_key = newKey;
m_encodedSize += m_entries[index].EncodedSize();
m_dirty = true;
}
void TreeStore::ChildBucket::Split(ChildBucket& first, ChildBucket& second, sizet maxSize)
{
EnsureAbort(m_entries.Len() >= 2);
EnsureAbort(!first.m_entries.Any());
EnsureAbort(!second.m_entries.Any());
first.m_height = m_height;
second.m_height = m_height;
auto transferEntry = [this] (ChildBucket& x, sizet i)
{ x.m_encodedSize += x.m_entries.Add(m_entries[i]).EncodedSize(); };
sizet i;
for (i=0; i!=m_entries.Len(); ++i)
{
// Split the buckets approximately in two according to encoded size,
// but make sure neither bucket exceeds maxSize
if (first.m_encodedSize + m_entries[i].EncodedSize() > maxSize)
break;
transferEntry(first, i);
if (first.m_encodedSize >= maxSize / 2)
{
++i;
break;
}
}
for (; i!=m_entries.Len(); ++i)
transferEntry(second, i);
EnsureAbort(first.m_entries.Len() + second.m_entries.Len() == m_entries.Len());
EnsureAbort(second.m_encodedSize <= maxSize);
first.m_dirty = true;
second.m_dirty = true;
ClearEntries();
++m_height;
}
void TreeStore::ChildBucket::AppendEntriesFrom(ChildBucket& x)
{
if (!x.m_entries.Any())
return;
if (m_entries.Any())
EnsureAbort(m_entries.Last().m_key <= x.m_entries.First().m_key);
for (BucketEntry& entry : x.m_entries)
m_encodedSize += m_entries.Add(entry).EncodedSize();
x.ClearEntries();
m_dirty = true;
}
void TreeStore::ChildBucket::RemoveEntry(sizet index)
{
EnsureAbort(index < m_entries.Len());
m_encodedSize -= m_entries[index].EncodedSize();
EnsureAbort(m_encodedSize >= MinimumEncodedSize);
EnsureAbort(m_encodedSize < (SIZE_MAX - (SIZE_MAX/10)));
m_entries.Erase(index, 1);
m_dirty = true;
}
void TreeStore::ChildBucket::ReplaceWithEntriesFrom(ChildBucket& x)
{
m_height = x.m_height;
m_entries.ResizeExact(x.m_entries.Len());
for (sizet i=0; i!=m_entries.Len(); ++i)
m_entries[i] = x.m_entries[i];
m_encodedSize = x.m_encodedSize;
m_dirty = true;
}
void TreeStore::ChildBucket::ClearEntries()
{
if (m_entries.Any())
{
m_entries.Free();
m_encodedSize = MinimumEncodedSize;
m_dirty = true;
}
}
void TreeStore::ChildBucket::Encode(Enc& enc) const
{
EncodeByte(enc, (byte) m_height);
EncodeUInt32(enc, NumCast<uint32>(m_entries.Len()));
for (sizet i=0; i!=m_entries.Len(); ++i)
m_entries[i].Encode(enc);
m_dirty = false;
}
bool TreeStore::ChildBucket::Decode(Seq& s)
{
Seq origStr = s;
uint32 n;
if (!DecodeByte(s, m_height) ||
!DecodeUInt32(s, n))
return false;
m_entries.ResizeExact(n);
for (uint32 i=0; i!=n; ++i)
if (!m_entries[i].Decode(s))
return false;
m_encodedSize = (sizet) (s.p - origStr.p);
m_dirty = false;
return true;
}
// TreeStore
Str const TreeStore::KeyBeyondLast = Str().Bytes(TreeStore::MaxKeySize + 1, 0xFF);
void TreeStore::Init()
{
m_objectStore.Init();
m_objectStore.RunTxExclusive( [&] () { InitTx(); } );
}
void TreeStore::InsertNode(Node& node, ObjId parentRefObjId, bool uniqueKey)
{
EnsureThrow(node.m_key.Len() <= MaxKeySize);
EnsureThrow(node.m_parentId != ObjId::None);
// Insert node
sizet nodeSize { node.EncodedSize() };
ChildBucket childBucket { ObjId::None };
if (nodeSize < ExternalNodeSizeThreshold)
{
// Node is small enough, can be stored internally
Rp<RcStr> nodeObj = new RcStr;
{
Enc& enc = nodeObj.Ref();
Enc::Meter meter = enc.FixMeter(1 + nodeSize + childBucket.EncodedSize());
EncodeByte(enc, NodeType::Internal);
node.Encode(enc);
childBucket.Encode(enc);
EnsureAbort(meter.Met());
}
node.m_nodeId = m_objectStore.InsertObject(nodeObj);
node.m_contentObjId = node.m_nodeId;
}
else
{
// Node is too large, must be stored in a separate object
Rp<RcStr> contentObj = new RcStr;
{
Enc& enc = contentObj.Ref();
Enc::Meter meter = enc.FixMeter(node.EncodedSize());
node.Encode(enc);
EnsureAbort(meter.Met());
}
node.m_contentObjId = m_objectStore.InsertObject(contentObj);
Rp<RcStr> nodeObj { new RcStr };
{
Enc& enc = nodeObj.Ref();
Enc::Meter meter = enc.FixMeter(1 + ObjId::EncodedSize + childBucket.EncodedSize());
EncodeByte(enc, NodeType::External);
node.m_contentObjId.EncodeBin(enc);
childBucket.Encode(enc);
EnsureAbort(meter.Met());
}
node.m_nodeId = m_objectStore.InsertObject(nodeObj);
}
AddChildToParent(node, parentRefObjId, uniqueKey);
}
bool TreeStore::GetNodeById(Node& node, ObjId refObjId)
{
Rp<RcStr> nodeObj { m_objectStore.RetrieveObject(node.m_nodeId, refObjId) };
if (!nodeObj.Any())
return false;
Seq nodeStr { nodeObj.Ref() };
uint nodeType;
EnsureAbort(DecodeByte(nodeStr, nodeType));
if (nodeType == NodeType::Internal)
{
node.m_contentObjId = node.m_nodeId;
EnsureAbort(node.Decode(nodeStr));
}
else
{
EnsureAbort(node.m_contentObjId.DecodeBin(nodeStr));
Rp<RcStr> contentObj { m_objectStore.RetrieveObject(node.m_contentObjId, node.m_nodeId) };
EnsureAbort(contentObj.Any());
Seq contentStr { contentObj.Ref() };
EnsureAbort(node.Decode(contentStr));
}
ChildBucket rootBucket { node.m_nodeId };
EnsureAbort(rootBucket.Decode(nodeStr));
node.m_hasChildren = rootBucket.Any();
return true;
}
void TreeStore::FindChildren_Forward(ObjId parentId, Seq keyFirst, Seq keyBeyondLast, std::function<bool (Seq, ObjId, ObjId)> onMatch)
{
if (keyBeyondLast == keyFirst)
return;
// Retrieve parent node
Rp<RcStr> parentObj = m_objectStore.RetrieveObject(parentId, ObjId::None);
if (!parentObj.Any())
return;
Seq parentNodeBlob;
BucketCx bucketCx = parentId;
ExtractRootBucket(parentObj, parentNodeBlob, bucketCx.m_rootBucket);
if (!bucketCx.m_rootBucket.Any())
return;
// Find path to leaf bucket for first key
BucketPath path = bucketCx;
while (true)
{
BucketPathStep& step = path.DeepestStep();
ChildBucket const& bucket = path.DeepestBucket();
FindKeyResult::E fkr = bucket.FindLastKeyLessThan(keyFirst, step.m_index);
if (fkr != FindKeyResult::Found)
step.m_index = 0;
if (bucket.Height() == 0)
break;
// Not yet at leaf bucket, search deeper
EnsureAbort(fkr != FindKeyResult::Empty);
LoadNextDeeperBucketInPath(path);
}
// Found starting leaf bucket. Enumerate matches
bool foundMatchStart {};
while (path.Any())
{
BucketPathStep& step = path.DeepestStep();
ChildBucket const& bucket = path.DeepestBucket();
BucketEntry const& bucketEntry = bucket[step.m_index];
if (bucketEntry.m_key >= keyBeyondLast)
break;
if (!foundMatchStart && bucketEntry.m_key >= keyFirst)
foundMatchStart = true;
if (foundMatchStart)
if (!onMatch(bucketEntry.m_key, bucketEntry.m_objId, step.m_bucket->GetObjId()))
return;
LoadNextLeafBucketEntryInPath(path);
}
}
void TreeStore::FindChildren_Reverse(ObjId parentId, Seq keyFirst, Seq keyBeyondLast, std::function<bool (Seq, ObjId, ObjId)> onMatch)
{
if (keyBeyondLast == keyFirst)
return;
// Retrieve parent node
Rp<RcStr> parentObj = m_objectStore.RetrieveObject(parentId, ObjId::None);
if (!parentObj.Any())
return;
Seq parentNodeBlob;
BucketCx bucketCx { parentId };
ExtractRootBucket(parentObj, parentNodeBlob, bucketCx.m_rootBucket);
if (!bucketCx.m_rootBucket.Any())
return;
// Find path to leaf bucket for last key before specified
BucketPath path = bucketCx;
while (true)
{
BucketPathStep& step = path.DeepestStep();
ChildBucket const& bucket = path.DeepestBucket();
FindKeyResult::E fkr = bucket.FindLastKeyLessThan(keyBeyondLast, step.m_index);
if (fkr != FindKeyResult::Found)
return;
if (bucket.Height() == 0)
break;
// Not yet at leaf bucket, search deeper
EnsureAbort(fkr != FindKeyResult::Empty);
LoadNextDeeperBucketInPath(path);
}
// Found last leaf bucket. Enumerate matches
while (path.Any())
{
BucketPathStep& step = path.DeepestStep();
ChildBucket const& bucket = path.DeepestBucket();
BucketEntry const& bucketEntry = bucket[step.m_index];
if (bucketEntry.m_key < keyFirst)
break;
if (!onMatch(bucketEntry.m_key, bucketEntry.m_objId, step.m_bucket->GetObjId()))
return;
LoadPrevLeafBucketEntryInPath(path);
}
}
void TreeStore::ReplaceNode(Node& node, bool uniqueKey)
{
// Read original node. Node must exist. If it has been removed, it must have been previously read by this transaction,
// so that RetrieveObject will throw RetryTxException instead of returning null.
Node origNode;
origNode.m_nodeId = node.m_nodeId;
Rp<RcStr> origNodeObj { m_objectStore.RetrieveObject(origNode.m_nodeId, ObjId::None) };
EnsureAbort(origNodeObj.Any());
Seq origNodeStr { origNodeObj.Ref() };
uint origNodeType;
EnsureAbort(DecodeByte(origNodeStr, origNodeType));
bool haveExternalNode {};
if (origNodeType == NodeType::Internal)
{
node.m_contentObjId = node.m_nodeId;
EnsureAbort(origNode.Decode(origNodeStr));
}
else
{
haveExternalNode = true;
EnsureAbort(node.m_contentObjId.DecodeBin(origNodeStr));
Rp<RcStr> contentObj { m_objectStore.RetrieveObject(node.m_contentObjId, node.m_nodeId) };
EnsureAbort(contentObj.Any());
Seq contentStr { contentObj.Ref() };
EnsureAbort(origNode.Decode(contentStr));
}
// Write new node
sizet nodeSize { node.EncodedSize() };
if (nodeSize < ExternalNodeSizeThreshold)
{
ChildBucket rootBucket { node.m_nodeId };
EnsureAbort(rootBucket.Decode(origNodeStr));
// If there's an external node, remove it
if (haveExternalNode)
{
m_objectStore.RemoveObject(node.m_contentObjId, node.m_nodeId);
node.m_contentObjId = node.m_nodeId;
}
// Write internal node
Rp<RcStr> newNodeObj = new RcStr;
{
Enc& enc = newNodeObj.Ref();
Enc::Meter meter = enc.FixMeter(1 + nodeSize + rootBucket.EncodedSize());
EncodeByte(enc, NodeType::Internal);
node.Encode(enc);
rootBucket.Encode(enc);
EnsureAbort(meter.Met());
}
m_objectStore.ReplaceObject(node.m_nodeId, ObjId::None, newNodeObj);
}
else
{
// Write the external node
Rp<RcStr> newContentObj { new RcStr };
{
Enc& enc = newContentObj.Ref();
Enc::Meter meter = enc.FixMeter(nodeSize);
node.Encode(enc);
EnsureAbort(meter.Met());
}
if (haveExternalNode)
{
// Replace existing external node
m_objectStore.ReplaceObject(node.m_contentObjId, node.m_nodeId, newContentObj);
}
else
{
ChildBucket rootBucket { node.m_nodeId };
EnsureAbort(rootBucket.Decode(origNodeStr));
// Create new external node
node.m_contentObjId = m_objectStore.InsertObject(newContentObj);
// Write the main node
Rp<RcStr> newNodeObj { new RcStr };
{
Enc& enc = newNodeObj.Ref();
Enc::Meter meter = enc.FixMeter(1 + ObjId::EncodedSize + rootBucket.EncodedSize());
EncodeByte(enc, NodeType::External);
node.m_contentObjId.EncodeBin(enc);
rootBucket.Encode(enc);
EnsureAbort(meter.Met());
}
m_objectStore.ReplaceObject(node.m_nodeId, ObjId::None, newNodeObj);
}
}
// Update parent reference, if necessary
if (node.m_nodeId != ObjId::Root && (node.m_key != origNode.m_key || node.m_parentId != origNode.m_parentId))
{
if (node.m_parentId != origNode.m_parentId)
{
// Ensure that a cycle is not being created
ObjId ancestorId = node.m_parentId;
ObjId refId = node.m_nodeId;
while (ancestorId != ObjId::Root)
{
EnsureAbort(ancestorId != node.m_nodeId);
Node ancestor;
ancestor.m_nodeId = ancestorId;
EnsureAbort(GetNodeById(ancestor, refId));
ancestorId = ancestor.m_parentId;
refId = ancestorId;
}
}
RemoveChildFromParent(origNode);
AddChildToParent(node, ObjId::None, uniqueKey);
}
}
ChildCount TreeStore::RemoveNodeChildren(ObjId nodeId)
{
// Enumerate node's children
ChildCount childCount;
Vec<ObjIdWithRef> removeNodes;
auto addNodeToRemove = [&] (Seq, ObjId objId, ObjId bucketId) -> bool { removeNodes.Add(objId, bucketId); return true; };
removeNodes.Add(nodeId, ObjId::None);
EnumAllChildren(nodeId, addNodeToRemove);
childCount.m_nrDirectChildren = removeNodes.Len() - 1;
for (sizet i=1; i!=removeNodes.Len(); ++i)
EnumAllChildren(removeNodes[i].m_objId, addNodeToRemove);
childCount.m_nrAllDescendants = removeNodes.Len() - 1;
// Remove node's children
for (sizet i=0; i!=removeNodes.Len(); ++i)
{
ObjIdWithRef const& rn { removeNodes[i] };
// Read node to remove
Node node;
node.m_nodeId = rn.m_objId;
Rp<RcStr> nodeObj { m_objectStore.RetrieveObject(node.m_nodeId, rn.m_refObjId) };
EnsureAbort(nodeObj.Any());
Seq nodeStr { nodeObj.Ref() };
uint nodeType;
EnsureAbort(DecodeByte(nodeStr, nodeType));
bool haveExternalNode {};
if (nodeType == NodeType::Internal)
{
EnsureAbort(node.Decode(nodeStr));
node.m_contentObjId = node.m_nodeId;
}
else
{
haveExternalNode = true;
EnsureAbort(node.m_contentObjId.DecodeBin(nodeStr));
}
BucketCx bucketCx { rn.m_objId };
EnsureAbort(bucketCx.m_rootBucket.Decode(nodeStr));
// Walk and remove child buckets
BucketPath path { bucketCx };
while (path.DeepestBucket().Height() > 0)
LoadNextDeeperBucketInPath(path);
while (path.Depth() > 1)
{
BucketPath curLevelPath { path };
do
{
ObjId removeBucketId { curLevelPath.DeepestBucket().GetObjId() };
ChangePathToSucceedingBucketOfSameHeight(curLevelPath);
m_objectStore.RemoveObject(removeBucketId, ObjId::None);
}
while (curLevelPath.Any());
path.PopDeepestStep();
}
if (i > 0)
{
// Remove node
if (haveExternalNode)
m_objectStore.RemoveObject(node.m_contentObjId, ObjId::None);
m_objectStore.RemoveObject(rn.m_objId, ObjId::None);
}
else
{
// Update node with cleared root bucket
bucketCx.m_rootBucket.ClearEntries();
Rp<RcStr> newNodeObj(new RcStr);
sizet nodeSize { node.EncodedSize() };
sizet newNodeSize { 1 +
If(haveExternalNode, sizet, ObjId::EncodedSize, nodeSize) +
bucketCx.m_rootBucket.EncodedSize() };
{
Enc& enc = newNodeObj.Ref();
Enc::Meter meter = enc.FixMeter(newNodeSize);
EncodeByte(enc, (byte) nodeType);
if (haveExternalNode)
node.m_contentObjId.EncodeBin(enc);
else
node.Encode(enc);
bucketCx.m_rootBucket.Encode(enc);
EnsureAbort(meter.Met());
}
m_objectStore.ReplaceObject(nodeId, ObjId::None, newNodeObj);
}
}
return childCount;
}
void TreeStore::RemoveNode(ObjId nodeId)
{
EnsureAbort(nodeId != ObjId::Root);
Node node;
node.m_nodeId = nodeId;
Rp<RcStr> nodeObj { m_objectStore.RetrieveObject(node.m_nodeId, ObjId::None) };
if (!nodeObj.Any())
return;
// Decode node
Seq nodeStr { nodeObj.Ref() };
uint nodeType;
EnsureAbort(DecodeByte(nodeStr, nodeType));
bool haveExternalNode {};
if (nodeType == NodeType::Internal)
{
EnsureAbort(node.Decode(nodeStr));
node.m_contentObjId = node.m_nodeId;
}
else
{
haveExternalNode = true;
EnsureAbort(node.m_contentObjId.DecodeBin(nodeStr));
Rp<RcStr> contentObj { m_objectStore.RetrieveObject(node.m_contentObjId, node.m_nodeId) };
EnsureAbort(contentObj.Any());
Seq contentStr { contentObj.Ref() };
EnsureAbort(node.Decode(contentStr));
}
ChildBucket rootBucket { node.m_nodeId };
EnsureAbort(rootBucket.Decode(nodeStr));
// Node to be removed must not have children
EnsureAbort(!rootBucket.Any());
// Remove node
if (haveExternalNode)
m_objectStore.RemoveObject(node.m_contentObjId, ObjId::None);
m_objectStore.RemoveObject(node.m_nodeId, ObjId::None);
RemoveChildFromParent(node);
}
// Private methods
void TreeStore::InitTx()
{
Rp<RcStr> rootObj { m_objectStore.RetrieveObject(ObjId::Root, ObjId::None) };
if (!rootObj.Any())
{
// No root object in database yet.
// Insert empty root object.
Node rootNode;
ChildBucket childBucket { ObjId::None };
rootObj.Set(new RcStr);
{
Enc& enc = rootObj.Ref();
Enc::Meter meter = enc.FixMeter(1 + rootNode.EncodedSize() + childBucket.EncodedSize());
EncodeByte(enc, NodeType::Internal);
rootNode.Encode(enc);
childBucket.Encode(enc);
EnsureAbort(meter.Met());
}
ObjId insertedId = m_objectStore.InsertObject(rootObj);
EnsureAbort(insertedId == ObjId::Root);
}
}
void TreeStore::ExtractRootBucket(Rp<RcStr> const& nodeObj, Seq& nodeBlob, ChildBucket& rootBucket)
{
Seq nodeStr(nodeObj.Ref());
Seq origNodeStr = nodeStr;
{
uint nodeType;
EnsureAbort(DecodeByte(nodeStr, nodeType));
if (nodeType == NodeType::Internal) EnsureAbort(Node::SkipDecode(nodeStr));
else EnsureAbort(ObjId::SkipDecodeBin(nodeStr));
nodeBlob = Seq(origNodeStr.p, (sizet) (nodeStr.p - origNodeStr.p));
}
EnsureAbort(rootBucket.Decode(nodeStr));
}
void TreeStore::LoadNextDeeperBucketInPath(BucketPath& path)
{
ObjId bucketObjId { path.DeepestBucketCurEntry().m_objId };
// See if the bucket is already loaded
BucketCx& bucketCx { path.GetBucketCx() };
for (std::unique_ptr<ChildBucket>& childBucket : bucketCx.m_buckets)
if (childBucket->GetObjId() == bucketObjId)
{
path.AddDeepestStep(BucketPathStep(*childBucket));
return;
}
// Load bucket
Rp<RcStr> bucketObj { m_objectStore.RetrieveObject(bucketObjId, path.DeepestBucket().GetObjId()) };
EnsureAbort(bucketObj.Any());
Seq bucketStr { bucketObj.Ref() };
bucketCx.m_bucketObjs.Add(bucketObj);
ChildBucket& bucket = *bucketCx.m_buckets.Add(std::make_unique<ChildBucket>(bucketObjId));
EnsureAbort(bucket.Decode(bucketStr));
EnsureAbort(bucket.Any()); // Non-root bucket must not be empty
path.AddDeepestStep(BucketPathStep(bucket));
}
void TreeStore::ChangePathToPrecedingBucketOfSameHeight(BucketPath& path)
{
sizet depth = path.Depth();
// Go up as far as necessary
do
path.PopDeepestStep();
while (path.Any() && path.DeepestStep().m_index == 0);
if (!path.Any())
return; // There is no preceding sibling. Result is null path
--(path.DeepestStep().m_index);
// Go down to preceding bucket on same level
do
{
LoadNextDeeperBucketInPath(path);
EnsureAbort(path.DeepestBucket().Any());
path.DeepestStep().m_index = path.DeepestBucket().NrEntries() - 1;
}
while (path.Depth() != depth);
}
void TreeStore::ChangePathToSucceedingBucketOfSameHeight(BucketPath& path)
{
sizet depth = path.Depth();
// Go up as far as necessary
do
path.PopDeepestStep();
while (path.Any() && path.DeepestStep().m_index == path.DeepestBucket().NrEntries() - 1);
if (!path.Any())
return; // There is no succeeding sibling. Result is null path
++(path.DeepestStep().m_index);
// Go down to succeeding bucket on same level
do
LoadNextDeeperBucketInPath(path);
while (path.Depth() != depth);
}
void TreeStore::LoadNextLeafBucketEntryInPath(BucketPath& path)
{
EnsureAbort(path.DeepestBucket().Height() == 0);
while (++(path.DeepestStep().m_index) >= path.DeepestBucket().NrEntries())
{
// We're at end of current bucket. Go up a level and find the next bucket
path.PopDeepestStep();
if (!path.Any())
return;
}
while (path.DeepestBucket().Height() > 0)
LoadNextDeeperBucketInPath(path);
}
void TreeStore::LoadPrevLeafBucketEntryInPath(BucketPath& path)
{
EnsureAbort(path.DeepestBucket().Height() == 0);
while (path.DeepestStep().m_index == 0)
{
// We're at end of current bucket. Go up a level and find the next bucket
path.PopDeepestStep();
if (!path.Any())
return;
}
--(path.DeepestStep().m_index);
if (path.DeepestBucket().Height() > 0)
{
while (path.DeepestBucket().Height() > 0)
LoadNextDeeperBucketInPath(path);
sizet nrEntries = path.DeepestBucket().NrEntries();
EnsureAbort(nrEntries);
path.DeepestStep().m_index = nrEntries - 1;
}
}
void TreeStore::ReplaceRootBucket(Seq nodeBlob, ChildBucket& rootBucket)
{
EnsureAbort(rootBucket.GetObjId() != ObjId::None);
Rp<RcStr> obj { new RcStr };
{
Enc& enc = obj.Ref();
Enc::Meter meter = enc.FixMeter(nodeBlob.n + rootBucket.EncodedSize());
EncodeVerbatim(enc, nodeBlob);
rootBucket.Encode(enc);
EnsureAbort(meter.Met());
}
m_objectStore.ReplaceObject(rootBucket.GetObjId(), ObjId::None, obj);
}
void TreeStore::ReplaceNonRootBucket(ChildBucket& bucket)
{
EnsureAbort(bucket.GetObjId() != ObjId::None);
EnsureAbort(bucket.Any()); // Non-root bucket must not be empty
Rp<RcStr> bucketObj { new RcStr };
{
Enc& enc = bucketObj.Ref();
Enc::Meter meter = enc.FixMeter(bucket.EncodedSize());
bucket.Encode(enc);
EnsureAbort(meter.Met());
}
m_objectStore.ReplaceObject(bucket.GetObjId(), ObjId::None, bucketObj);
}
void TreeStore::InsertNonRootBucket(ChildBucket& bucket)
{
EnsureAbort(bucket.GetObjId() == ObjId::None);
Rp<RcStr> bucketObj(new RcStr);
{
Enc& enc = bucketObj.Ref();
Enc::Meter meter = enc.FixMeter(bucket.EncodedSize());
bucket.Encode(enc);
EnsureAbort(meter.Met());
}
bucket.SetObjId(m_objectStore.InsertObject(bucketObj));
};
void TreeStore::AddChildToParent(Node const& childNode, ObjId parentRefObjId, bool uniqueKey)
{
// Retrieve parent node. Parent node must exist, or if it has been removed, it must have been previously read,
// or the reference object must have changed, so that RetrieveObject will throw RetryTxException instead of returning null.
Rp<RcStr> parentObj { m_objectStore.RetrieveObject(childNode.m_parentId, parentRefObjId) };
EnsureAbort(parentObj.Any());
Seq parentNodeBlob;
BucketCx bucketCx { childNode.m_parentId };
ExtractRootBucket(parentObj, parentNodeBlob, bucketCx.m_rootBucket);
// Find bucket to which this child should be added
BucketPath path { bucketCx };
FindKeyResult::E fkr;
while (true)
{
BucketPathStep& step { path.DeepestStep() };
fkr = step.m_bucket->FindLastKeyLessThan(childNode.m_key, step.m_index);
if (path.DeepestBucket().Height() == 0)
break;
if (fkr != FindKeyResult::Found)
{
EnsureAbort(fkr != FindKeyResult::Empty); // Must not be empty because not a leaf bucket
if (fkr == FindKeyResult::FirstKeyGreater)
step.m_bucket->ReplaceEntryKey(0, childNode.m_key);
step.m_index = 0;
}
// Not yet at leaf bucket, search deeper
LoadNextDeeperBucketInPath(path);
}
// Found leaf bucket. If necessary, verify that key is unique
if (uniqueKey)
{
// If a unique key violation is detected at this point, we can't throw a nicer exception type.
// The object store was modified in InsertNode or ReplaceNode. There is no way to recover without aborting the transaction.
// To permit recovery, the application must detect the conflict before trying to modify the database in error.
EnsureThrow(fkr != FindKeyResult::FirstKeyEqual);
if (fkr == FindKeyResult::Found)
{
BucketPath uniqueCheckPath { path };
LoadNextLeafBucketEntryInPath(uniqueCheckPath);
if (uniqueCheckPath.Any())
EnsureThrow(childNode.m_key < uniqueCheckPath.DeepestBucketCurEntry().m_key);
}
}
// Start by updating the leaf bucket, then update buckets to the top
bool haveObjIdToAdd { true };
Seq keyToAdd { childNode.m_key };
ObjId objIdToAdd { childNode.m_nodeId };
do
{
if (haveObjIdToAdd)
{
sizet index { path.DeepestStep().m_index };
if (index == SIZE_MAX) path.DeepestBucket().InsertEntry(0, keyToAdd, objIdToAdd);
else path.DeepestBucket().InsertEntry(index + 1, keyToAdd, objIdToAdd);
}
if (path.DeepestBucket().Dirty())
{
if (path.Depth() == 1)
{
// Updating root bucket
haveObjIdToAdd = false;
if (bucketCx.m_rootBucket.EncodedSize() > MaxRootBucketSize)
{
// Root bucket must be split
ChildBucket split1 { ObjId::None }, split2 { ObjId::None };
bucketCx.m_rootBucket.Split(split1, split2, MaxRootBucketSize);
InsertNonRootBucket(split1);
InsertNonRootBucket(split2);
// Add entries to new root bucket
bucketCx.m_rootBucket.InsertEntry(0, split1[0].m_key, split1.GetObjId());
bucketCx.m_rootBucket.InsertEntry(1, split2[0].m_key, split2.GetObjId());
}
ReplaceRootBucket(parentNodeBlob, bucketCx.m_rootBucket);
}
else
{
// Updating non-root bucket
if (path.DeepestBucket().EncodedSize() < MaxNonRootBucketSize)
{
ReplaceNonRootBucket(path.DeepestBucket());
haveObjIdToAdd = false;
}
else
{
// Bucket must be split
ChildBucket split1 { path.DeepestBucket().GetObjId() }, split2 { ObjId::None };
path.DeepestBucket().Split(split1, split2, MaxNonRootBucketSize);
ReplaceNonRootBucket(split1);
InsertNonRootBucket(split2);
keyToAdd = split2[0].m_key;
objIdToAdd = split2.GetObjId();
}
}
}
path.PopDeepestStep();
}
while (path.Any());
}
void TreeStore::RemoveChildFromParent(Node const& childNode)
{
// Retrieve parent node
Rp<RcStr> parentObj { m_objectStore.RetrieveObject(childNode.m_parentId, childNode.m_nodeId) };
EnsureAbort(parentObj.Any()); // Parent node must be successfully retrieved if child node exists
Seq parentNodeBlob;
BucketCx bucketCx(childNode.m_parentId);
ExtractRootBucket(parentObj, parentNodeBlob, bucketCx.m_rootBucket);
// Find bucket containing this child
BucketPath path(bucketCx);
while (true)
{
BucketPathStep& step = path.DeepestStep();
FindKeyResult::E fkr = step.m_bucket->FindLastKeyLessThan(childNode.m_key, step.m_index);
if (fkr == FindKeyResult::FirstKeyEqual)
step.m_index = 0;
else
EnsureAbort(step.m_index != SIZE_MAX);
if (step.m_bucket->Height() == 0)
break;
// Not yet at leaf bucket, search deeper
LoadNextDeeperBucketInPath(path);
}
while (path.DeepestBucketCurEntry().m_objId != childNode.m_nodeId)
{
EnsureAbort(path.DeepestBucketCurEntry().m_key <= Seq(childNode.m_key));
LoadNextLeafBucketEntryInPath(path);
EnsureAbort(path.Any());
}
EnsureAbort(path.DeepestBucketCurEntry().m_key == Seq(childNode.m_key));
RemoveDeepestBucketCurEntry(path);
UpdateDirtyBuckets(parentNodeBlob, bucketCx);
}
void TreeStore::RemoveDeepestBucketCurEntry(BucketPath& path)
{
Seq removedKey(path.DeepestBucketCurEntry().m_key);
path.DeepestBucket().RemoveEntry(path.DeepestStep().m_index);
if (!path.DeepestBucket().Any())
{
// No more entries in bucket
if (path.Depth() > 1)
{
// Bucket is non-root, and is now empty. Delete it, then proceed to remove its entry from parent bucket
RemoveAndPopDeepestBucket(path);
RemoveDeepestBucketCurEntry(path);
}
}
else if (path.Depth() == 1)
{
// Is root bucket
if (path.RootBucket().NrEntries() == 1 && path.RootBucket().Height() > 0)
{
// Root bucket now has only one child bucket. Replace root bucket with first deeper bucket having more than one entry
path.RootStep().m_index = 0;
do
LoadNextDeeperBucketInPath(path);
while (path.DeepestBucket().NrEntries() == 1 && path.DeepestBucket().Height() > 0);
path.RootBucket().ReplaceWithEntriesFrom(path.DeepestBucket());
do
RemoveAndPopDeepestBucket(path);
while (path.Depth() > 1);
}
}
else
{
// If we removed the first bucket entry, update key information in parent buckets
if (path.DeepestStep().m_index == 0)
{
BucketPath fixKeyPath(path);
Seq newKey(path.DeepestBucketCurEntry().m_key);
do
{
fixKeyPath.PopDeepestStep();
EnsureAbort(fixKeyPath.DeepestBucketCurEntry().m_key == removedKey);
fixKeyPath.DeepestBucket().ReplaceEntryKey(fixKeyPath.DeepestStep().m_index, newKey);
}
while (fixKeyPath.Depth() > 1 && fixKeyPath.DeepestStep().m_index == 0);
}
// Join with neighboring buckets, if possible and necessary
sizet curBucketSize = path.DeepestBucket().EncodedSize();
if (curBucketSize <= BucketJoinThreshold)
{
BucketPath prevBucketPath(path);
ChangePathToPrecedingBucketOfSameHeight(prevBucketPath);
BucketPath nextBucketPath(path);
ChangePathToSucceedingBucketOfSameHeight(nextBucketPath);
sizet prevBucketSize = If(!prevBucketPath.Any(), sizet, SIZE_MAX, prevBucketPath.DeepestBucket().EncodedSize());
sizet nextBucketSize = If(!nextBucketPath.Any(), sizet, SIZE_MAX, nextBucketPath.DeepestBucket().EncodedSize());
EnsureAbort(prevBucketSize != SIZE_MAX || nextBucketSize != SIZE_MAX);
BucketPath* joinBucketPath1 = nullptr;
BucketPath* joinBucketPath2 = nullptr;
if (prevBucketSize < nextBucketSize)
{
if (prevBucketSize + curBucketSize <= MaxNonRootBucketSize)
{
// Join current bucket with previous
joinBucketPath1 = &prevBucketPath;
joinBucketPath2 = &path;
}
}
else
{
if (curBucketSize + nextBucketSize <= MaxNonRootBucketSize)
{
// Join current bucket with next
joinBucketPath1 = &path;
joinBucketPath2 = &nextBucketPath;
}
}
if (joinBucketPath1)
{
// Join buckets
EnsureAbort(joinBucketPath2);
joinBucketPath1->DeepestBucket().AppendEntriesFrom(joinBucketPath2->DeepestBucket());
RemoveAndPopDeepestBucket(*joinBucketPath2);
RemoveDeepestBucketCurEntry(*joinBucketPath2);
}
}
}
}
void TreeStore::RemoveAndPopDeepestBucket(BucketPath& path)
{
ObjId objId { path.DeepestBucket().GetObjId() };
m_objectStore.RemoveObject(objId, ObjId::None);
path.PopDeepestStep();
BucketCx& bucketCx { path.GetBucketCx() };
sizet nrRemoved {};
for (sizet i=0; i!=bucketCx.m_buckets.Len(); )
if (bucketCx.m_buckets[i]->GetObjId() != objId)
++i;
else
{
bucketCx.m_buckets.Erase(i, 1);
++nrRemoved;
}
EnsureAbort(nrRemoved == 1);
}
void TreeStore::UpdateDirtyBuckets(Seq parentNodeBlob, BucketCx& bucketCx)
{
if (bucketCx.m_rootBucket.Dirty())
ReplaceRootBucket(parentNodeBlob, bucketCx.m_rootBucket);
for (std::unique_ptr<ChildBucket>& childBucket : bucketCx.m_buckets)
if (childBucket->Dirty())
ReplaceNonRootBucket(*childBucket);
}
}
| 27.083861 | 136 | 0.659315 | [
"object"
] |
045723536cc3ed04bb624389e6ec78f0fa859860 | 96,937 | cc | C++ | uhdm-plugin/UhdmAst.cc | hzeller/yosys-symbiflow-plugins | 10f1af6fc5f472dfee7a18fffd1b7069f73f65e4 | [
"0BSD"
] | null | null | null | uhdm-plugin/UhdmAst.cc | hzeller/yosys-symbiflow-plugins | 10f1af6fc5f472dfee7a18fffd1b7069f73f65e4 | [
"0BSD"
] | null | null | null | uhdm-plugin/UhdmAst.cc | hzeller/yosys-symbiflow-plugins | 10f1af6fc5f472dfee7a18fffd1b7069f73f65e4 | [
"0BSD"
] | null | null | null | #include <algorithm>
#include <cstring>
#include <functional>
#include <vector>
#include "UhdmAst.h"
#include "frontends/ast/ast.h"
#include "frontends/verilog/verilog_frontend.h"
#include "headers/uhdm.h"
#include "libs/sha1/sha1.h"
#include "vpi_user.h"
YOSYS_NAMESPACE_BEGIN
static void sanitize_symbol_name(std::string &name)
{
if (!name.empty()) {
auto pos = name.find_last_of('@');
name = name.substr(pos + 1);
// symbol names must begin with '\'
name.insert(0, "\\");
}
}
static std::string get_name(vpiHandle obj_h, bool prefer_full_name = false)
{
auto first_check = prefer_full_name ? vpiFullName : vpiName;
auto last_check = prefer_full_name ? vpiName : vpiFullName;
std::string name;
if (auto s = vpi_get_str(first_check, obj_h)) {
name = s;
} else if (auto s = vpi_get_str(vpiDefName, obj_h)) {
name = s;
} else if (auto s = vpi_get_str(last_check, obj_h)) {
name = s;
}
if (name.rfind('.') != std::string::npos) {
name = name.substr(name.rfind('.') + 1);
}
sanitize_symbol_name(name);
return name;
}
static std::string strip_package_name(std::string name)
{
auto sep_index = name.find("::");
if (sep_index != string::npos) {
name = name.substr(sep_index + 1);
name[0] = '\\';
}
return name;
}
void UhdmAst::visit_one_to_many(const std::vector<int> child_node_types, vpiHandle parent_handle, const std::function<void(AST::AstNode *)> &f)
{
for (auto child : child_node_types) {
vpiHandle itr = vpi_iterate(child, parent_handle);
while (vpiHandle vpi_child_obj = vpi_scan(itr)) {
UhdmAst uhdm_ast(this, shared, indent + " ");
auto *child_node = uhdm_ast.process_object(vpi_child_obj);
f(child_node);
vpi_release_handle(vpi_child_obj);
}
vpi_release_handle(itr);
}
}
void UhdmAst::visit_one_to_one(const std::vector<int> child_node_types, vpiHandle parent_handle, const std::function<void(AST::AstNode *)> &f)
{
for (auto child : child_node_types) {
vpiHandle itr = vpi_handle(child, parent_handle);
if (itr) {
UhdmAst uhdm_ast(this, shared, indent + " ");
auto *child_node = uhdm_ast.process_object(itr);
f(child_node);
}
vpi_release_handle(itr);
}
}
void UhdmAst::visit_range(vpiHandle obj_h, const std::function<void(AST::AstNode *)> &f)
{
std::vector<AST::AstNode *> range_nodes;
visit_one_to_many({vpiRange}, obj_h, [&](AST::AstNode *node) { range_nodes.push_back(node); });
if (range_nodes.size() > 1) {
auto multirange_node = new AST::AstNode(AST::AST_MULTIRANGE);
multirange_node->is_packed = true;
multirange_node->children = range_nodes;
f(multirange_node);
} else if (!range_nodes.empty()) {
f(range_nodes[0]);
}
}
void UhdmAst::visit_default_expr(vpiHandle obj_h)
{
UhdmAst initial_ast(parent, shared, indent);
UhdmAst block_ast(&initial_ast, shared, indent);
block_ast.visit_one_to_one({vpiExpr}, obj_h, [&](AST::AstNode *expr_node) {
auto mod = find_ancestor({AST::AST_MODULE});
AST::AstNode *initial_node = nullptr;
AST::AstNode *block_node = nullptr;
auto assign_node = new AST::AstNode(AST::AST_ASSIGN_EQ);
auto id_node = new AST::AstNode(AST::AST_IDENTIFIER);
id_node->str = current_node->str;
for (auto child : mod->children) {
if (child->type == AST::AST_INITIAL) {
initial_node = child;
break;
}
}
// Ensure single AST_INITIAL node is located in AST_MODULE
// before any AST_ALWAYS
if (initial_node == nullptr) {
initial_node = new AST::AstNode(AST::AST_INITIAL);
auto insert_it = find_if(mod->children.begin(), mod->children.end(), [](AST::AstNode *node) { return (node->type == AST::AST_ALWAYS); });
mod->children.insert(insert_it, initial_node);
}
// Ensure single AST_BLOCK node in AST_INITIAL
if (!initial_node->children.empty() && initial_node->children[0]) {
block_node = initial_node->children[0];
} else {
block_node = new AST::AstNode(AST::AST_BLOCK);
initial_node->children.push_back(block_node);
}
auto block_child =
find_if(block_node->children.begin(), block_node->children.end(), [](AST::AstNode *node) { return (node->type == AST::AST_ASSIGN_EQ); });
// Insert AST_ASSIGN_EQ nodes that came from
// custom_var or int_var before any other AST_ASSIGN_EQ
// Especially before ones explicitly placed in initial block in source code
block_node->children.insert(block_child, assign_node);
assign_node->children.push_back(id_node);
initial_ast.current_node = initial_node;
block_ast.current_node = block_node;
assign_node->children.push_back(expr_node);
});
}
AST::AstNode *UhdmAst::process_value(vpiHandle obj_h)
{
s_vpi_value val;
vpi_get_value(obj_h, &val);
std::string strValType;
if (val.format) { // Needed to handle parameter nodes without typespecs and constants
switch (val.format) {
case vpiScalarVal:
return AST::AstNode::mkconst_int(val.value.scalar, false, 1);
case vpiBinStrVal: {
strValType = "'b";
break;
}
case vpiDecStrVal: {
strValType = "'d";
break;
}
case vpiHexStrVal: {
strValType = "'h";
break;
}
// Surelog reports constant integers as a unsigned, but by default int is signed
// so we are treating here UInt in the same way as if they would be Int
case vpiUIntVal:
case vpiIntVal: {
auto size = vpi_get(vpiSize, obj_h);
auto c = AST::AstNode::mkconst_int(val.value.integer, true, size ? size : 64);
if (size == 0)
c->is_unsized = true;
return c;
}
case vpiRealVal:
return AST::AstNode::mkconst_real(val.value.real);
case vpiStringVal:
return AST::AstNode::mkconst_str(val.value.str);
default: {
const uhdm_handle *const handle = (const uhdm_handle *)obj_h;
const UHDM::BaseClass *const object = (const UHDM::BaseClass *)handle->object;
report_error("%s:%d: Encountered unhandled constant format %d\n", object->VpiFile().c_str(), object->VpiLineNo(), val.format);
}
}
// handle vpiBinStrVal, vpiDecStrVal and vpiHexStrVal
if (std::strchr(val.value.str, '\'')) {
return VERILOG_FRONTEND::const2ast(val.value.str, 0, false);
} else {
auto size = vpi_get(vpiSize, obj_h);
if (size == 0) {
auto c = AST::AstNode::mkconst_int(atoi(val.value.str), true, 64);
c->is_unsized = true;
return c;
} else {
return VERILOG_FRONTEND::const2ast(std::to_string(size) + strValType + val.value.str, 0, false);
}
}
}
return nullptr;
}
AST::AstNode *UhdmAst::make_ast_node(AST::AstNodeType type, std::vector<AST::AstNode *> children, bool prefer_full_name)
{
auto node = new AST::AstNode(type);
node->str = get_name(obj_h, prefer_full_name);
auto it = node_renames.find(node->str);
if (it != node_renames.end())
node->str = it->second;
if (auto filename = vpi_get_str(vpiFile, obj_h)) {
node->filename = filename;
}
if (unsigned int line = vpi_get(vpiLineNo, obj_h)) {
node->location.first_line = node->location.last_line = line;
}
node->children = children;
return node;
}
static void add_or_replace_child(AST::AstNode *parent, AST::AstNode *child)
{
if (!child->str.empty()) {
auto it = std::find_if(parent->children.begin(), parent->children.end(),
[child](AST::AstNode *existing_child) { return existing_child->str == child->str; });
if (it != parent->children.end()) {
// If port direction is already set, copy it to replaced child node
if ((*it)->is_input || (*it)->is_output) {
child->is_input = (*it)->is_input;
child->is_output = (*it)->is_output;
child->port_id = (*it)->port_id;
if (child->type == AST::AST_MEMORY)
child->type = AST::AST_WIRE;
}
if (!(*it)->children.empty() && child->children.empty()) {
// This is a bit ugly, but if the child we're replacing has children and
// our node doesn't, we copy its children to not lose any information
for (auto grandchild : (*it)->children) {
child->children.push_back(grandchild->clone());
if (child->type == AST::AST_WIRE && grandchild->type == AST::AST_WIRETYPE)
child->is_custom_type = true;
}
}
// Special case for a wire with multirange
if (child->children.size() > 1 && child->type == AST::AST_WIRE && child->children[0]->type == AST::AST_RANGE &&
child->children[1]->type == AST::AST_RANGE) {
auto multirange_node = new AST::AstNode(AST::AST_MULTIRANGE);
multirange_node->is_packed = true;
for (auto *c : child->children) {
multirange_node->children.push_back(c);
}
child->children.clear();
child->children.push_back(multirange_node);
}
delete *it;
*it = child;
return;
}
parent->children.push_back(child);
} else if (child->type == AST::AST_INITIAL) {
// Special case for initials
// Ensure that there is only one AST_INITIAL in the design
// And there is only one AST_BLOCK inside that initial
// Copy nodes from child initial to parent initial
auto initial_node_it =
find_if(parent->children.begin(), parent->children.end(), [](AST::AstNode *node) { return (node->type == AST::AST_INITIAL); });
if (initial_node_it != parent->children.end()) {
AST::AstNode *initial_node = *initial_node_it;
log_assert(!(initial_node->children.empty()));
log_assert(initial_node->children[0]->type == AST::AST_BLOCK);
log_assert(!(child->children.empty()));
log_assert(child->children[0]->type == AST::AST_BLOCK);
AST::AstNode *block_node = initial_node->children[0];
AST::AstNode *child_block_node = child->children[0];
// Place the contents of child block node inside parent block
for (auto child_block_child : child_block_node->children)
block_node->children.push_back(child_block_child->clone());
// Place the remaining contents of child initial node inside the parent initial
for (auto initial_child = child->children.begin() + 1; initial_child != child->children.end(); ++initial_child) {
initial_node->children.push_back((*initial_child)->clone());
}
} else {
// Parent AST_INITIAL does not exist
// Place child AST_INITIAL before AST_ALWAYS if found
auto insert_it =
find_if(parent->children.begin(), parent->children.end(), [](AST::AstNode *node) { return (node->type == AST::AST_ALWAYS); });
parent->children.insert(insert_it, 1, child);
}
} else {
parent->children.push_back(child);
}
}
void UhdmAst::make_cell(vpiHandle obj_h, AST::AstNode *cell_node, AST::AstNode *type_node)
{
if (cell_node->children.empty() || (!cell_node->children.empty() && cell_node->children[0]->type != AST::AST_CELLTYPE)) {
auto typeNode = new AST::AstNode(AST::AST_CELLTYPE);
typeNode->str = type_node->str;
cell_node->children.insert(cell_node->children.begin(), typeNode);
}
// Add port connections as arguments
vpiHandle port_itr = vpi_iterate(vpiPort, obj_h);
while (vpiHandle port_h = vpi_scan(port_itr)) {
std::string arg_name;
if (auto s = vpi_get_str(vpiName, port_h)) {
arg_name = s;
sanitize_symbol_name(arg_name);
}
auto arg_node = new AST::AstNode(AST::AST_ARGUMENT);
arg_node->str = arg_name;
arg_node->filename = cell_node->filename;
arg_node->location = cell_node->location;
visit_one_to_one({vpiHighConn}, port_h, [&](AST::AstNode *node) {
if (node) {
if (node->type == AST::AST_PARAMETER || node->type == AST::AST_LOCALPARAM) {
node->type = AST::AST_IDENTIFIER;
}
arg_node->children.push_back(node);
}
});
cell_node->children.push_back(arg_node);
shared.report.mark_handled(port_h);
vpi_release_handle(port_h);
}
vpi_release_handle(port_itr);
}
void UhdmAst::move_type_to_new_typedef(AST::AstNode *current_node, AST::AstNode *type_node)
{
auto typedef_node = new AST::AstNode(AST::AST_TYPEDEF);
typedef_node->location = type_node->location;
typedef_node->filename = type_node->filename;
typedef_node->str = strip_package_name(type_node->str);
if (std::find(shared.type_names.begin(), shared.type_names.end(), std::make_pair(type_node->str, current_node->str)) != shared.type_names.end())
return;
shared.type_names.push_back(std::make_pair(type_node->str, current_node->str));
if (type_node->type == AST::AST_STRUCT) {
type_node->str.clear();
typedef_node->children.push_back(type_node);
current_node->children.push_back(typedef_node);
} else if (type_node->type == AST::AST_ENUM) {
if (type_node->attributes.count("\\enum_base_type")) {
auto base_type = type_node->attributes["\\enum_base_type"];
auto wire_node = new AST::AstNode(AST::AST_WIRE);
for (auto c : base_type->children) {
std::string enum_item_str = "\\enum_value_";
log_assert(!c->children.empty());
log_assert(c->children[0]->type == AST::AST_CONSTANT);
int width = 1;
bool is_signed = c->children[0]->is_signed;
if (c->children.size() == 2) {
width = c->children[1]->children[0]->integer + 1;
}
RTLIL::Const val = c->children[0]->bitsAsConst(width, is_signed);
enum_item_str.append(val.as_string());
wire_node->attributes[enum_item_str.c_str()] = AST::AstNode::mkconst_str(c->str);
}
typedef_node->children.push_back(wire_node);
current_node->children.push_back(typedef_node);
delete type_node;
} else {
type_node->str = "$enum" + std::to_string(shared.next_enum_id());
for (auto *enum_item : type_node->children) {
enum_item->attributes["\\enum_base_type"] = AST::AstNode::mkconst_str(type_node->str);
}
auto wire_node = new AST::AstNode(AST::AST_WIRE);
wire_node->attributes["\\enum_type"] = AST::AstNode::mkconst_str(type_node->str);
if (!type_node->children.empty() && type_node->children[0]->children.size() > 1) {
wire_node->children.push_back(type_node->children[0]->children[1]->clone());
}
typedef_node->children.push_back(wire_node);
current_node->children.push_back(type_node);
current_node->children.push_back(typedef_node);
}
} else {
type_node->str.clear();
typedef_node->children.push_back(type_node);
current_node->children.push_back(typedef_node);
}
}
AST::AstNode *UhdmAst::find_ancestor(const std::unordered_set<AST::AstNodeType> &types)
{
auto searched_node = this;
while (searched_node) {
if (searched_node->current_node) {
if (types.find(searched_node->current_node->type) != types.end()) {
return searched_node->current_node;
}
}
searched_node = searched_node->parent;
}
return nullptr;
}
void UhdmAst::process_design()
{
current_node = make_ast_node(AST::AST_DESIGN);
visit_one_to_many({UHDM::uhdmallInterfaces, UHDM::uhdmallPackages, UHDM::uhdmallModules, UHDM::uhdmtopModules}, obj_h, [&](AST::AstNode *node) {
if (node) {
shared.top_nodes[node->str] = node;
}
});
// Once we walked everything, unroll that as children of this node
for (auto pair : shared.top_nodes) {
if (!pair.second)
continue;
if (!pair.second->get_bool_attribute(ID::partial)) {
if (pair.second->type == AST::AST_PACKAGE)
current_node->children.insert(current_node->children.begin(), pair.second);
else
current_node->children.push_back(pair.second);
} else {
log_warning("Removing unused module: %s from the design.\n", pair.second->str.c_str());
delete pair.second;
}
}
}
void UhdmAst::process_parameter()
{
auto type = vpi_get(vpiLocalParam, obj_h) == 1 ? AST::AST_LOCALPARAM : AST::AST_PARAMETER;
current_node = make_ast_node(type, {}, true);
// if (vpi_get_str(vpiImported, obj_h) != "") { } //currently unused
std::vector<AST::AstNode *> range_nodes;
visit_range(obj_h, [&](AST::AstNode *node) {
if (node)
range_nodes.push_back(node);
});
vpiHandle typespec_h = vpi_handle(vpiTypespec, obj_h);
if (typespec_h) {
int typespec_type = vpi_get(vpiType, typespec_h);
switch (typespec_type) {
case vpiBitTypespec:
case vpiLogicTypespec: {
current_node->is_logic = true;
visit_range(typespec_h, [&](AST::AstNode *node) { range_nodes.push_back(node); });
shared.report.mark_handled(typespec_h);
break;
}
case vpiEnumTypespec:
case vpiRealTypespec:
case vpiIntTypespec: {
shared.report.mark_handled(typespec_h);
break;
}
case vpiStructTypespec: {
visit_one_to_one({vpiTypespec}, obj_h, [&](AST::AstNode *node) {
auto it = shared.param_types.find(current_node->str);
if (it == shared.param_types.end())
shared.param_types.insert(std::make_pair(current_node->str, node));
});
break;
}
default: {
const uhdm_handle *const handle = (const uhdm_handle *)typespec_h;
const UHDM::BaseClass *const object = (const UHDM::BaseClass *)handle->object;
report_error("%s:%d: Encountered unhandled typespec in process_parameter: '%s' of type '%s'\n", object->VpiFile().c_str(),
object->VpiLineNo(), object->VpiName().c_str(), UHDM::VpiTypeName(typespec_h).c_str());
break;
}
}
vpi_release_handle(typespec_h);
} else {
AST::AstNode *constant_node = process_value(obj_h);
if (constant_node) {
constant_node->filename = current_node->filename;
constant_node->location = current_node->location;
current_node->children.push_back(constant_node);
}
}
if (range_nodes.size() > 1) {
auto multirange_node = new AST::AstNode(AST::AST_MULTIRANGE);
multirange_node->is_packed = true;
multirange_node->children = range_nodes;
current_node->children.push_back(multirange_node);
} else if (range_nodes.size() == 1) {
current_node->children.push_back(range_nodes[0]);
}
}
void UhdmAst::process_port()
{
current_node = make_ast_node(AST::AST_WIRE);
current_node->port_id = shared.next_port_id();
vpiHandle lowConn_h = vpi_handle(vpiLowConn, obj_h);
if (lowConn_h) {
vpiHandle actual_h = vpi_handle(vpiActual, lowConn_h);
auto actual_type = vpi_get(vpiType, actual_h);
switch (actual_type) {
case vpiModport: {
vpiHandle iface_h = vpi_handle(vpiInterface, actual_h);
if (iface_h) {
std::string cellName, ifaceName;
if (auto s = vpi_get_str(vpiName, actual_h)) {
cellName = s;
sanitize_symbol_name(cellName);
}
if (auto s = vpi_get_str(vpiDefName, iface_h)) {
ifaceName = s;
sanitize_symbol_name(ifaceName);
}
current_node->type = AST::AST_INTERFACEPORT;
auto typeNode = new AST::AstNode(AST::AST_INTERFACEPORTTYPE);
// Skip '\' in cellName
typeNode->str = ifaceName + '.' + cellName.substr(1, cellName.length());
current_node->children.push_back(typeNode);
shared.report.mark_handled(actual_h);
shared.report.mark_handled(iface_h);
vpi_release_handle(iface_h);
}
break;
}
case vpiInterface: {
auto typeNode = new AST::AstNode(AST::AST_INTERFACEPORTTYPE);
if (auto s = vpi_get_str(vpiDefName, actual_h)) {
typeNode->str = s;
sanitize_symbol_name(typeNode->str);
}
current_node->type = AST::AST_INTERFACEPORT;
current_node->children.push_back(typeNode);
shared.report.mark_handled(actual_h);
break;
}
case vpiLogicVar:
case vpiLogicNet: {
current_node->is_logic = true;
current_node->is_signed = vpi_get(vpiSigned, actual_h);
visit_range(actual_h, [&](AST::AstNode *node) {
if (node->type == AST::AST_MULTIRANGE)
node->is_packed = true;
current_node->children.push_back(node);
});
shared.report.mark_handled(actual_h);
break;
}
case vpiPackedArrayVar:
visit_one_to_many({vpiElement}, actual_h, [&](AST::AstNode *node) {
if (node && GetSize(node->children) == 1) {
current_node->children.push_back(node->children[0]);
if (node->children[0]->type == AST::AST_WIRETYPE) {
current_node->is_custom_type = true;
}
}
});
visit_one_to_many({vpiRange}, actual_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
shared.report.mark_handled(actual_h);
break;
case vpiPackedArrayNet:
visit_one_to_many({vpiRange}, actual_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
shared.report.mark_handled(actual_h);
break;
case vpiArrayVar:
visit_one_to_many({vpiRange}, actual_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
shared.report.mark_handled(actual_h);
break;
case vpiEnumNet:
case vpiStructNet:
case vpiArrayNet:
case vpiStructVar:
case vpiEnumVar:
case vpiIntVar:
break;
default: {
const uhdm_handle *const handle = (const uhdm_handle *)actual_h;
const UHDM::BaseClass *const object = (const UHDM::BaseClass *)handle->object;
report_error("%s:%d: Encountered unhandled type in process_port: %s\n", object->VpiFile().c_str(), object->VpiLineNo(),
UHDM::VpiTypeName(actual_h).c_str());
break;
}
}
shared.report.mark_handled(lowConn_h);
vpi_release_handle(actual_h);
vpi_release_handle(lowConn_h);
}
visit_one_to_one({vpiTypedef}, obj_h, [&](AST::AstNode *node) {
if (node) {
if (!current_node->children.empty() && current_node->children[0]->type != AST::AST_WIRETYPE) {
if (!node->str.empty()) {
auto wiretype_node = new AST::AstNode(AST::AST_WIRETYPE);
wiretype_node->str = node->str;
// wiretype needs to be 1st node (if port have also another range nodes)
current_node->children.insert(current_node->children.begin(), wiretype_node);
current_node->is_custom_type = true;
} else {
// anonymous typedef, just move children
current_node->children = std::move(node->children);
}
}
delete node;
}
});
if (const int n = vpi_get(vpiDirection, obj_h)) {
if (n == vpiInput) {
current_node->is_input = true;
} else if (n == vpiOutput) {
current_node->is_output = true;
} else if (n == vpiInout) {
current_node->is_input = true;
current_node->is_output = true;
}
}
}
void UhdmAst::process_module()
{
std::string type = vpi_get_str(vpiDefName, obj_h);
std::string name = vpi_get_str(vpiName, obj_h) ? vpi_get_str(vpiName, obj_h) : type;
bool is_module_instance = type != name;
sanitize_symbol_name(type);
sanitize_symbol_name(name);
type = strip_package_name(type);
name = strip_package_name(name);
if (!is_module_instance) {
if (shared.top_nodes.find(type) != shared.top_nodes.end()) {
current_node = shared.top_nodes[type];
visit_one_to_many(
{vpiModule, vpiInterface, vpiParameter, vpiParamAssign, vpiPort, vpiNet, vpiArrayNet, vpiGenScopeArray, vpiContAssign, vpiVariables},
obj_h, [&](AST::AstNode *node) {
if (node) {
add_or_replace_child(current_node, node);
}
});
auto it = current_node->attributes.find(ID::partial);
if (it != current_node->attributes.end()) {
delete it->second;
current_node->attributes.erase(it);
}
} else {
current_node = make_ast_node(AST::AST_MODULE);
current_node->str = type;
shared.top_nodes[current_node->str] = current_node;
current_node->attributes[ID::partial] = AST::AstNode::mkconst_int(1, false, 1);
visit_one_to_many({vpiTypedef}, obj_h, [&](AST::AstNode *node) {
if (node) {
move_type_to_new_typedef(current_node, node);
}
});
visit_one_to_many({vpiModule, vpiInterface, vpiParameter, vpiParamAssign, vpiPort, vpiNet, vpiArrayNet, vpiGenScopeArray, vpiContAssign,
vpiProcess, vpiTaskFunc},
obj_h, [&](AST::AstNode *node) {
if (node) {
if (node->type == AST::AST_ASSIGN && node->children.size() < 2)
return;
add_or_replace_child(current_node, node);
}
});
}
} else {
// Not a top module, create instance
current_node = make_ast_node(AST::AST_CELL);
std::string module_parameters;
visit_one_to_many({vpiParamAssign}, obj_h, [&](AST::AstNode *node) {
if (node && node->type == AST::AST_PARAMETER) {
if (shared.top_nodes.count(type) && !(!node->children.empty() && node->children[0]->type != AST::AST_CONSTANT)) {
if (!node->children[0]->str.empty())
module_parameters += node->str + "=" + node->children[0]->str;
else
module_parameters += node->str + "=" + std::to_string(node->children[0]->integer);
}
delete node;
}
});
// rename module in same way yosys do
std::string module_name;
if (module_parameters.size() > 60)
module_name = "$paramod$" + sha1(module_parameters) + type;
else if (!module_parameters.empty())
module_name = "$paramod" + type + module_parameters;
else
module_name = type;
auto module_node = shared.top_nodes[module_name];
if (!module_node) {
module_node = shared.top_nodes[type];
if (!module_node) {
module_node = new AST::AstNode(AST::AST_MODULE);
module_node->str = type;
module_node->attributes[ID::partial] = AST::AstNode::mkconst_int(2, false, 1);
shared.top_nodes[module_node->str] = module_node;
}
if (!module_parameters.empty()) {
module_node = module_node->clone();
}
}
module_node->str = module_name;
shared.top_nodes[module_node->str] = module_node;
auto cell_instance = vpi_get(vpiCellInstance, obj_h);
if (cell_instance) {
module_node->attributes[ID::whitebox] = AST::AstNode::mkconst_int(1, false, 1);
}
visit_one_to_many({vpiParamAssign}, obj_h, [&](AST::AstNode *node) {
if (node) {
auto parent_node = std::find_if(module_node->children.begin(), module_node->children.end(), [&](AST::AstNode *child) -> bool {
return ((child->type == AST::AST_PARAMETER) || (child->type == AST::AST_LOCALPARAM)) && child->str == node->str &&
// skip real parameters as they are currently not working: https://github.com/alainmarcel/Surelog/issues/1035
child->type != AST::AST_REALVALUE;
});
if (parent_node != module_node->children.end()) {
if ((*parent_node)->type == AST::AST_PARAMETER) {
if (cell_instance ||
(!node->children.empty() &&
node->children[0]->type !=
AST::AST_CONSTANT)) { // if cell is a blackbox or we need to simplify parameter first, left setting parameters to yosys
// We only want to add AST_PARASET for parameters that is different than already set
// to match the name yosys gives to the module.
// Note: this should also be applied for other (not only cell_instance) modules
// but as we are using part of the modules parsed by sv2v and other
// part by uhdm, we need to always rename module if it is parametrized,
// Otherwise, verilog frontend can use module parsed by uhdm and try to set
// parameters, but this module would be already parametrized
if ((node->children[0]->integer != (*parent_node)->children[0]->integer ||
node->children[0]->str != (*parent_node)->children[0]->str)) {
node->type = AST::AST_PARASET;
current_node->children.push_back(node);
}
} else {
add_or_replace_child(module_node, node);
}
} else {
add_or_replace_child(module_node, node);
}
} else if ((module_node->attributes.count(ID::partial) && module_node->attributes[ID::partial]->integer == 2)) {
// When module definition is not parsed by Surelog, left setting parameters to yosys
node->type = AST::AST_PARASET;
current_node->children.push_back(node);
}
}
});
// TODO: setting keep attribute probably shouldn't be needed,
// but without this, modules that are generated in genscope are removed
// for now lets just add this attribute
module_node->attributes[ID::keep] = AST::AstNode::mkconst_int(1, false, 1);
if (module_node->attributes.count(ID::partial)) {
AST::AstNode *attr = module_node->attributes.at(ID::partial);
if (attr->type == AST::AST_CONSTANT)
if (attr->integer == 1) {
delete attr;
module_node->attributes.erase(ID::partial);
}
}
auto typeNode = new AST::AstNode(AST::AST_CELLTYPE);
typeNode->str = module_node->str;
current_node->children.insert(current_node->children.begin(), typeNode);
visit_one_to_many({vpiVariables, vpiNet, vpiArrayNet}, obj_h, [&](AST::AstNode *node) {
if (node) {
add_or_replace_child(module_node, node);
}
});
visit_one_to_many({vpiInterface, vpiModule, vpiPort, vpiGenScopeArray}, obj_h, [&](AST::AstNode *node) {
if (node) {
add_or_replace_child(module_node, node);
}
});
make_cell(obj_h, current_node, module_node);
}
}
void UhdmAst::process_struct_typespec()
{
current_node = make_ast_node(AST::AST_STRUCT);
visit_one_to_many({vpiTypespecMember}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
void UhdmAst::process_packed_array_typespec()
{
current_node = make_ast_node(AST::AST_WIRE);
visit_one_to_one({vpiElemTypespec}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->str = node->str;
}
});
}
void UhdmAst::process_typespec_member()
{
current_node = make_ast_node(AST::AST_STRUCT_ITEM);
current_node->str = current_node->str.substr(1);
vpiHandle typespec_h = vpi_handle(vpiTypespec, obj_h);
int typespec_type = vpi_get(vpiType, typespec_h);
switch (typespec_type) {
case vpiBitTypespec:
case vpiLogicTypespec: {
current_node->is_logic = true;
visit_range(typespec_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
shared.report.mark_handled(typespec_h);
break;
}
case vpiIntTypespec: {
current_node->is_signed = true;
shared.report.mark_handled(typespec_h);
break;
}
case vpiStructTypespec:
case vpiEnumTypespec: {
visit_one_to_one({vpiTypespec}, obj_h, [&](AST::AstNode *node) {
if (typespec_type == vpiStructTypespec) {
auto str = current_node->str;
node->cloneInto(current_node);
current_node->str = str;
delete node;
} else if (typespec_type == vpiEnumTypespec) {
current_node->children.push_back(node);
} else {
delete node;
}
});
break;
}
case vpiPackedArrayTypespec:
visit_one_to_one({vpiTypespec}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->str = node->str;
}
});
break;
default: {
const uhdm_handle *const handle = (const uhdm_handle *)typespec_h;
const UHDM::BaseClass *const object = (const UHDM::BaseClass *)handle->object;
report_error("%s:%d: Encountered unhandled typespec in process_typespec_member: '%s' of type '%s'\n", object->VpiFile().c_str(),
object->VpiLineNo(), object->VpiName().c_str(), UHDM::VpiTypeName(typespec_h).c_str());
break;
}
}
vpi_release_handle(typespec_h);
}
void UhdmAst::process_enum_typespec()
{
current_node = make_ast_node(AST::AST_ENUM);
visit_one_to_one({vpiTypedefAlias}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->attributes["\\enum_base_type"] = node->clone();
}
});
visit_one_to_many({vpiEnumConst}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
vpiHandle typespec_h = vpi_handle(vpiBaseTypespec, obj_h);
if (typespec_h) {
int typespec_type = vpi_get(vpiType, typespec_h);
switch (typespec_type) {
case vpiLogicTypespec: {
current_node->is_logic = true;
bool has_range = false;
visit_range(typespec_h, [&](AST::AstNode *node) {
has_range = true;
for (auto child : current_node->children) {
child->children.push_back(node->clone());
}
delete node;
});
if (!has_range) // range is needed for simplify
for (auto child : current_node->children)
child->children.push_back(make_ast_node(AST::AST_RANGE, {AST::AstNode::mkconst_int(0, true)}));
shared.report.mark_handled(typespec_h);
break;
}
case vpiIntTypespec: {
current_node->is_signed = true;
shared.report.mark_handled(typespec_h);
break;
}
default: {
const uhdm_handle *const handle = (const uhdm_handle *)typespec_h;
const UHDM::BaseClass *const object = (const UHDM::BaseClass *)handle->object;
report_error("%s:%d: Encountered unhandled typespec in process_enum_typespec: '%s' of type '%s'\n", object->VpiFile().c_str(),
object->VpiLineNo(), object->VpiName().c_str(), UHDM::VpiTypeName(typespec_h).c_str());
break;
}
}
vpi_release_handle(typespec_h);
}
}
void UhdmAst::process_enum_const()
{
current_node = make_ast_node(AST::AST_ENUM_ITEM);
AST::AstNode *constant_node = process_value(obj_h);
if (constant_node) {
constant_node->filename = current_node->filename;
constant_node->location = current_node->location;
current_node->children.push_back(constant_node);
}
}
void UhdmAst::process_custom_var()
{
current_node = make_ast_node(AST::AST_WIRE);
visit_one_to_one({vpiTypespec}, obj_h, [&](AST::AstNode *node) {
if (node->str.empty()) {
// anonymous typespec, move the children to variable
current_node->type = node->type;
current_node->children = std::move(node->children);
delete node;
} else {
// custom var in gen scope have definition with declaration
auto *parent = find_ancestor({AST::AST_GENBLOCK, AST::AST_BLOCK});
auto wiretype_node = new AST::AstNode(AST::AST_WIRETYPE);
wiretype_node->str = node->str;
current_node->children.push_back(wiretype_node);
if (parent &&
std::find(shared.type_names.begin(), shared.type_names.end(), std::make_pair(node->str, parent->str)) == shared.type_names.end() &&
!node->children.empty()) {
move_type_to_new_typedef(parent, node);
} else {
delete node;
}
}
});
auto type = vpi_get(vpiType, obj_h);
if (type == vpiEnumVar || type == vpiStructVar) {
visit_default_expr(obj_h);
}
current_node->is_custom_type = true;
}
void UhdmAst::process_int_var()
{
current_node = make_ast_node(AST::AST_WIRE);
auto left_const = AST::AstNode::mkconst_int(31, true);
auto right_const = AST::AstNode::mkconst_int(0, true);
auto range = new AST::AstNode(AST::AST_RANGE, left_const, right_const);
current_node->children.push_back(range);
current_node->is_signed = true;
visit_default_expr(obj_h);
}
void UhdmAst::process_real_var()
{
auto module_node = find_ancestor({AST::AST_MODULE});
auto wire_node = make_ast_node(AST::AST_WIRE);
auto left_const = AST::AstNode::mkconst_int(63, true);
auto right_const = AST::AstNode::mkconst_int(0, true);
auto range = new AST::AstNode(AST::AST_RANGE, left_const, right_const);
wire_node->children.push_back(range);
wire_node->is_signed = true;
module_node->children.push_back(wire_node);
current_node = make_ast_node(AST::AST_IDENTIFIER);
visit_default_expr(obj_h);
}
void UhdmAst::process_array_var()
{
current_node = make_ast_node(AST::AST_WIRE);
vpiHandle itr = vpi_iterate(vpi_get(vpiType, obj_h) == vpiArrayVar ? vpiReg : vpiElement, obj_h);
while (vpiHandle reg_h = vpi_scan(itr)) {
if (vpi_get(vpiType, reg_h) == vpiStructVar || vpi_get(vpiType, reg_h) == vpiEnumVar) {
vpiHandle typespec_h = vpi_handle(vpiTypespec, reg_h);
std::string name = vpi_get_str(vpiName, typespec_h);
sanitize_symbol_name(name);
auto wiretype_node = new AST::AstNode(AST::AST_WIRETYPE);
wiretype_node->str = name;
current_node->children.push_back(wiretype_node);
current_node->is_custom_type = true;
shared.report.mark_handled(reg_h);
shared.report.mark_handled(typespec_h);
vpi_release_handle(typespec_h);
} else if (vpi_get(vpiType, reg_h) == vpiLogicVar) {
current_node->is_logic = true;
visit_one_to_many({vpiRange}, reg_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
vpi_release_handle(reg_h);
}
vpi_release_handle(itr);
visit_one_to_many({vpiRange}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
if (current_node->children.size() == 2 && current_node->children[0]->type == AST::AST_RANGE &&
current_node->children[1]->type == AST::AST_RANGE) {
current_node->type = AST::AST_MEMORY;
}
}
void UhdmAst::process_param_assign()
{
current_node = make_ast_node(AST::AST_PARAMETER);
visit_one_to_one({vpiLhs}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->type = node->type;
current_node->str = node->str;
// Here we need to copy any ranges that is already present in lhs,
// but we want to skip actual value, as it is set in rhs
for (auto *c : node->children) {
if (c->type != AST::AST_CONSTANT) {
current_node->children.push_back(c->clone());
}
}
shared.param_types[current_node->str] = shared.param_types[node->str];
delete node;
}
});
visit_one_to_one({vpiRhs}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.insert(current_node->children.begin(), node);
}
});
}
void UhdmAst::process_cont_assign_var_init()
{
current_node = make_ast_node(AST::AST_INITIAL);
auto block_node = make_ast_node(AST::AST_BLOCK);
auto assign_node = make_ast_node(AST::AST_ASSIGN_LE);
block_node->children.push_back(assign_node);
current_node->children.push_back(block_node);
visit_one_to_one({vpiLhs, vpiRhs}, obj_h, [&](AST::AstNode *node) {
if (node) {
if (node->type == AST::AST_WIRE || node->type == AST::AST_PARAMETER || node->type == AST::AST_LOCALPARAM) {
assign_node->children.push_back(new AST::AstNode(AST::AST_IDENTIFIER));
assign_node->children.back()->str = node->str;
} else {
assign_node->children.push_back(node);
}
}
});
}
void UhdmAst::process_cont_assign_net()
{
current_node = make_ast_node(AST::AST_ASSIGN);
visit_one_to_one({vpiLhs, vpiRhs}, obj_h, [&](AST::AstNode *node) {
if (node) {
if (node->type == AST::AST_WIRE || node->type == AST::AST_PARAMETER || node->type == AST::AST_LOCALPARAM) {
current_node->children.push_back(new AST::AstNode(AST::AST_IDENTIFIER));
current_node->children.back()->str = node->str;
} else {
current_node->children.push_back(node);
}
}
});
}
void UhdmAst::process_cont_assign()
{
auto net_decl_assign = vpi_get(vpiNetDeclAssign, obj_h);
vpiHandle node_lhs_h = vpi_handle(vpiLhs, obj_h);
auto lhs_net_type = vpi_get(vpiNetType, node_lhs_h);
vpi_release_handle(node_lhs_h);
// Check if lhs is a subtype of a net
bool isNet;
if (lhs_net_type >= vpiWire && lhs_net_type <= vpiUwire)
isNet = true;
else
// lhs is a variable
isNet = false;
if (net_decl_assign && !isNet)
process_cont_assign_var_init();
else
process_cont_assign_net();
}
void UhdmAst::process_assignment()
{
auto type = vpi_get(vpiBlocking, obj_h) == 1 ? AST::AST_ASSIGN_EQ : AST::AST_ASSIGN_LE;
current_node = make_ast_node(type);
visit_one_to_one({vpiLhs, vpiRhs}, obj_h, [&](AST::AstNode *node) {
if (node) {
if (node->type == AST::AST_PARAMETER || node->type == AST::AST_LOCALPARAM) {
node->type = AST::AST_IDENTIFIER;
}
current_node->children.push_back(node);
}
});
if (current_node->children.size() == 1 && current_node->children[0]->type == AST::AST_WIRE) {
auto top_node = find_ancestor({AST::AST_MODULE});
if (!top_node)
return;
top_node->children.push_back(current_node->children[0]->clone());
current_node = nullptr;
}
}
void UhdmAst::process_net()
{
current_node = make_ast_node(AST::AST_WIRE);
auto net_type = vpi_get(vpiNetType, obj_h);
current_node->is_reg = net_type == vpiReg;
current_node->is_output = net_type == vpiOutput;
current_node->is_logic = !current_node->is_reg;
current_node->is_signed = vpi_get(vpiSigned, obj_h);
visit_one_to_one({vpiTypespec}, obj_h, [&](AST::AstNode *node) {
if (node) {
auto wiretype_node = new AST::AstNode(AST::AST_WIRETYPE);
wiretype_node->str = node->str;
// wiretype needs to be 1st node
current_node->children.insert(current_node->children.begin(), wiretype_node);
current_node->is_custom_type = true;
}
});
visit_range(obj_h, [&](AST::AstNode *node) {
current_node->children.push_back(node);
if (node->type == AST::AST_MULTIRANGE) {
node->is_packed = true;
}
});
}
void UhdmAst::process_packed_array_net()
{
current_node = make_ast_node(AST::AST_WIRE);
visit_one_to_many({vpiElement}, obj_h, [&](AST::AstNode *node) {
if (node && GetSize(node->children) == 1)
current_node->children.push_back(node->children[0]);
current_node->is_custom_type = node->is_custom_type;
});
visit_one_to_many({vpiRange}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
void UhdmAst::process_array_net()
{
current_node = make_ast_node(AST::AST_WIRE);
vpiHandle itr = vpi_iterate(vpiNet, obj_h);
while (vpiHandle net_h = vpi_scan(itr)) {
auto net_type = vpi_get(vpiType, net_h);
if (net_type == vpiLogicNet) {
current_node->is_logic = true;
current_node->is_signed = vpi_get(vpiSigned, net_h);
visit_range(net_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
shared.report.mark_handled(net_h);
} else if (net_type == vpiStructNet) {
vpiHandle typespec_h = vpi_handle(vpiTypespec, net_h);
std::string name = vpi_get_str(vpiName, typespec_h);
sanitize_symbol_name(name);
auto wiretype_node = new AST::AstNode(AST::AST_WIRETYPE);
wiretype_node->str = name;
current_node->children.push_back(wiretype_node);
current_node->is_custom_type = true;
shared.report.mark_handled(net_h);
shared.report.mark_handled(typespec_h);
vpi_release_handle(typespec_h);
}
vpi_release_handle(net_h);
}
vpi_release_handle(itr);
visit_one_to_many({vpiRange}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
if (current_node->children.size() == 2) { // If there is 2 ranges, change type to AST_MEMORY
current_node->type = AST::AST_MEMORY;
}
}
void UhdmAst::process_package()
{
current_node = make_ast_node(AST::AST_PACKAGE);
visit_one_to_many({vpiParameter, vpiParamAssign}, obj_h, [&](AST::AstNode *node) {
if (node) {
node->str = strip_package_name(node->str);
add_or_replace_child(current_node, node);
}
});
visit_one_to_many({vpiTypedef}, obj_h, [&](AST::AstNode *node) {
if (node) {
move_type_to_new_typedef(current_node, node);
}
});
visit_one_to_many({vpiTaskFunc}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
}
void UhdmAst::process_interface()
{
std::string type = vpi_get_str(vpiDefName, obj_h);
std::string name = vpi_get_str(vpiName, obj_h) ? vpi_get_str(vpiName, obj_h) : type;
sanitize_symbol_name(type);
sanitize_symbol_name(name);
AST::AstNode *elaboratedInterface;
// Check if we have encountered this object before
if (shared.top_nodes.find(type) != shared.top_nodes.end()) {
// Was created before, fill missing
elaboratedInterface = shared.top_nodes[type];
visit_one_to_many({vpiPort}, obj_h, [&](AST::AstNode *node) {
if (node) {
add_or_replace_child(elaboratedInterface, node);
}
});
} else {
// Encountered for the first time
elaboratedInterface = new AST::AstNode(AST::AST_INTERFACE);
elaboratedInterface->str = name;
visit_one_to_many({vpiNet, vpiPort, vpiModport}, obj_h, [&](AST::AstNode *node) {
if (node) {
add_or_replace_child(elaboratedInterface, node);
}
});
}
shared.top_nodes[elaboratedInterface->str] = elaboratedInterface;
if (name != type) {
// Not a top module, create instance
current_node = make_ast_node(AST::AST_CELL);
make_cell(obj_h, current_node, elaboratedInterface);
} else {
current_node = elaboratedInterface;
}
}
void UhdmAst::process_modport()
{
current_node = make_ast_node(AST::AST_MODPORT);
visit_one_to_many({vpiIODecl}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
}
void UhdmAst::process_io_decl()
{
current_node = nullptr;
visit_one_to_one({vpiExpr}, obj_h, [&](AST::AstNode *node) { current_node = node; });
if (current_node == nullptr) {
current_node = make_ast_node(AST::AST_MODPORTMEMBER);
visit_range(obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
visit_one_to_one({vpiTypedef}, obj_h, [&](AST::AstNode *node) {
if (node) {
if (!node->str.empty()) {
auto wiretype_node = new AST::AstNode(AST::AST_WIRETYPE);
wiretype_node->str = node->str;
// wiretype needs to be 1st node (if port have also another range nodes)
current_node->children.insert(current_node->children.begin(), wiretype_node);
current_node->is_custom_type = true;
} else {
// anonymous typedef, just move children
for (auto child : node->children) {
current_node->children.push_back(child->clone());
}
}
delete node;
}
});
if (const int n = vpi_get(vpiDirection, obj_h)) {
if (n == vpiInput) {
current_node->is_input = true;
} else if (n == vpiOutput) {
current_node->is_output = true;
} else if (n == vpiInout) {
current_node->is_input = true;
current_node->is_output = true;
}
}
}
void UhdmAst::process_always()
{
current_node = make_ast_node(AST::AST_ALWAYS);
visit_one_to_one({vpiStmt}, obj_h, [&](AST::AstNode *node) {
if (node) {
AST::AstNode *block = nullptr;
if (node->type != AST::AST_BLOCK) {
block = new AST::AstNode(AST::AST_BLOCK, node);
} else {
block = node;
}
current_node->children.push_back(block);
}
});
switch (vpi_get(vpiAlwaysType, obj_h)) {
case vpiAlwaysComb:
current_node->attributes[ID::always_comb] = AST::AstNode::mkconst_int(1, false);
break;
case vpiAlwaysFF:
current_node->attributes[ID::always_ff] = AST::AstNode::mkconst_int(1, false);
break;
case vpiAlwaysLatch:
current_node->attributes[ID::always_latch] = AST::AstNode::mkconst_int(1, false);
break;
default:
break;
}
}
void UhdmAst::process_event_control()
{
current_node = make_ast_node(AST::AST_BLOCK);
visit_one_to_one({vpiCondition}, obj_h, [&](AST::AstNode *node) {
if (node) {
auto process_node = find_ancestor({AST::AST_ALWAYS});
process_node->children.push_back(node);
}
// is added inside vpiOperation
});
visit_one_to_one({vpiStmt}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
}
void UhdmAst::process_initial()
{
current_node = make_ast_node(AST::AST_INITIAL);
visit_one_to_one({vpiStmt}, obj_h, [&](AST::AstNode *node) {
if (node) {
if (node->type != AST::AST_BLOCK) {
auto block_node = make_ast_node(AST::AST_BLOCK);
block_node->children.push_back(node);
node = block_node;
}
current_node->children.push_back(node);
}
});
}
void UhdmAst::process_begin()
{
current_node = make_ast_node(AST::AST_BLOCK);
visit_one_to_many({vpiStmt}, obj_h, [&](AST::AstNode *node) {
if (node) {
if ((node->type == AST::AST_ASSIGN_EQ || node->type == AST::AST_ASSIGN_LE) && node->children.size() == 1) {
auto func_node = find_ancestor({AST::AST_FUNCTION, AST::AST_TASK});
if (!func_node)
return;
auto wire_node = new AST::AstNode(AST::AST_WIRE);
wire_node->type = AST::AST_WIRE;
wire_node->str = node->children[0]->str;
func_node->children.push_back(wire_node);
} else {
current_node->children.push_back(node);
}
}
});
}
void UhdmAst::process_operation()
{
auto operation = vpi_get(vpiOpType, obj_h);
switch (operation) {
case vpiStreamRLOp:
process_stream_op();
break;
case vpiEventOrOp:
case vpiListOp:
process_list_op();
break;
case vpiCastOp:
process_cast_op();
break;
case vpiInsideOp:
process_inside_op();
break;
case vpiAssignmentPatternOp:
process_assignment_pattern_op();
break;
default: {
current_node = make_ast_node(AST::AST_NONE);
visit_one_to_many({vpiOperand}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
switch (operation) {
case vpiMinusOp:
current_node->type = AST::AST_NEG;
break;
case vpiPlusOp:
current_node->type = AST::AST_POS;
break;
case vpiPosedgeOp:
current_node->type = AST::AST_POSEDGE;
break;
case vpiNegedgeOp:
current_node->type = AST::AST_NEGEDGE;
break;
case vpiUnaryAndOp:
current_node->type = AST::AST_REDUCE_AND;
break;
case vpiUnaryOrOp:
current_node->type = AST::AST_REDUCE_OR;
break;
case vpiUnaryXorOp:
current_node->type = AST::AST_REDUCE_XOR;
break;
case vpiUnaryXNorOp:
current_node->type = AST::AST_REDUCE_XNOR;
break;
case vpiUnaryNandOp: {
current_node->type = AST::AST_REDUCE_AND;
auto not_node = new AST::AstNode(AST::AST_LOGIC_NOT, current_node);
current_node = not_node;
break;
}
case vpiUnaryNorOp: {
current_node->type = AST::AST_REDUCE_OR;
auto not_node = new AST::AstNode(AST::AST_LOGIC_NOT, current_node);
current_node = not_node;
break;
}
case vpiBitNegOp:
current_node->type = AST::AST_BIT_NOT;
break;
case vpiBitAndOp:
current_node->type = AST::AST_BIT_AND;
break;
case vpiBitOrOp:
current_node->type = AST::AST_BIT_OR;
break;
case vpiBitXorOp:
current_node->type = AST::AST_BIT_XOR;
break;
case vpiBitXnorOp:
current_node->type = AST::AST_BIT_XNOR;
break;
case vpiLShiftOp:
current_node->type = AST::AST_SHIFT_LEFT;
break;
case vpiRShiftOp:
current_node->type = AST::AST_SHIFT_RIGHT;
break;
case vpiNotOp:
current_node->type = AST::AST_LOGIC_NOT;
break;
case vpiLogAndOp:
current_node->type = AST::AST_LOGIC_AND;
break;
case vpiLogOrOp:
current_node->type = AST::AST_LOGIC_OR;
break;
case vpiEqOp:
current_node->type = AST::AST_EQ;
break;
case vpiNeqOp:
current_node->type = AST::AST_NE;
break;
case vpiCaseEqOp:
current_node->type = AST::AST_EQX;
break;
case vpiGtOp:
current_node->type = AST::AST_GT;
break;
case vpiGeOp:
current_node->type = AST::AST_GE;
break;
case vpiLtOp:
current_node->type = AST::AST_LT;
break;
case vpiLeOp:
current_node->type = AST::AST_LE;
break;
case vpiSubOp:
current_node->type = AST::AST_SUB;
break;
case vpiAddOp:
current_node->type = AST::AST_ADD;
break;
case vpiMultOp:
current_node->type = AST::AST_MUL;
break;
case vpiDivOp:
current_node->type = AST::AST_DIV;
break;
case vpiModOp:
current_node->type = AST::AST_MOD;
break;
case vpiArithLShiftOp:
current_node->type = AST::AST_SHIFT_SLEFT;
break;
case vpiArithRShiftOp:
current_node->type = AST::AST_SHIFT_SRIGHT;
break;
case vpiPowerOp:
current_node->type = AST::AST_POW;
break;
case vpiPostIncOp: // TODO: Make this an actual post-increment op (currently it's a pre-increment)
case vpiPreIncOp: {
current_node->type = AST::AST_ASSIGN_EQ;
auto id = current_node->children[0]->clone();
auto add_node = new AST::AstNode(AST::AST_ADD, id, AST::AstNode::mkconst_int(1, true));
add_node->filename = current_node->filename;
add_node->location = current_node->location;
current_node->children.push_back(add_node);
break;
}
case vpiPostDecOp: // TODO: Make this an actual post-decrement op (currently it's a pre-decrement)
case vpiPreDecOp: {
current_node->type = AST::AST_ASSIGN_EQ;
auto id = current_node->children[0]->clone();
auto add_node = new AST::AstNode(AST::AST_SUB, id, AST::AstNode::mkconst_int(1, true));
add_node->filename = current_node->filename;
add_node->location = current_node->location;
current_node->children.push_back(add_node);
break;
}
case vpiConditionOp:
current_node->type = AST::AST_TERNARY;
break;
case vpiConcatOp: {
current_node->type = AST::AST_CONCAT;
std::reverse(current_node->children.begin(), current_node->children.end());
break;
}
case vpiMultiConcatOp:
current_node->type = AST::AST_REPLICATE;
break;
case vpiAssignmentOp:
current_node->type = AST::AST_ASSIGN_EQ;
break;
case vpiStreamLROp: {
auto concat_node = current_node->children.back();
current_node->children.pop_back();
delete current_node;
current_node = concat_node;
break;
}
case vpiNullOp: {
delete current_node;
current_node = nullptr;
break;
}
default: {
delete current_node;
current_node = nullptr;
const uhdm_handle *const handle = (const uhdm_handle *)obj_h;
const UHDM::BaseClass *const object = (const UHDM::BaseClass *)handle->object;
report_error("%s:%d: Encountered unhandled operation type %d\n", object->VpiFile().c_str(), object->VpiLineNo(), operation);
}
}
}
}
}
void UhdmAst::process_stream_op()
{
// Create a for loop that does what a streaming operator would do
auto block_node = find_ancestor({AST::AST_BLOCK, AST::AST_ALWAYS, AST::AST_INITIAL});
auto process_node = find_ancestor({AST::AST_ALWAYS, AST::AST_INITIAL});
auto module_node = find_ancestor({AST::AST_MODULE, AST::AST_FUNCTION, AST::AST_PACKAGE});
log_assert(module_node);
if (!process_node) {
if (module_node->type != AST::AST_FUNCTION) {
// Create a @* always block
process_node = make_ast_node(AST::AST_ALWAYS);
module_node->children.push_back(process_node);
block_node = make_ast_node(AST::AST_BLOCK);
process_node->children.push_back(block_node);
} else {
// Create only block
block_node = make_ast_node(AST::AST_BLOCK);
module_node->children.push_back(block_node);
}
}
auto loop_id = shared.next_loop_id();
auto loop_counter =
make_ast_node(AST::AST_WIRE, {make_ast_node(AST::AST_RANGE, {AST::AstNode::mkconst_int(31, false), AST::AstNode::mkconst_int(0, false)})});
loop_counter->is_reg = true;
loop_counter->is_signed = true;
loop_counter->str = "\\loop" + std::to_string(loop_id) + "::i";
module_node->children.insert(module_node->children.end() - 1, loop_counter);
auto loop_counter_ident = make_ast_node(AST::AST_IDENTIFIER);
loop_counter_ident->str = loop_counter->str;
auto lhs_node = find_ancestor({AST::AST_ASSIGN, AST::AST_ASSIGN_EQ, AST::AST_ASSIGN_LE})->children[0];
// Temp var to allow concatenation
AST::AstNode *temp_var = nullptr;
AST::AstNode *bits_call = nullptr;
if (lhs_node->type == AST::AST_WIRE) {
module_node->children.insert(module_node->children.begin(), lhs_node->clone());
temp_var = lhs_node->clone(); // if we already have wire as lhs, we want to create the same wire for temp_var
lhs_node->delete_children();
lhs_node->type = AST::AST_IDENTIFIER;
bits_call = make_ast_node(AST::AST_FCALL, {lhs_node->clone()});
bits_call->str = "\\$bits";
} else {
// otherwise, we need to calculate size using bits fcall
bits_call = make_ast_node(AST::AST_FCALL, {lhs_node->clone()});
bits_call->str = "\\$bits";
temp_var =
make_ast_node(AST::AST_WIRE, {make_ast_node(AST::AST_RANGE, {make_ast_node(AST::AST_SUB, {bits_call, AST::AstNode::mkconst_int(1, false)}),
AST::AstNode::mkconst_int(0, false)})});
}
temp_var->str = "\\loop" + std::to_string(loop_id) + "::temp";
module_node->children.insert(module_node->children.end() - 1, temp_var);
auto temp_var_ident = make_ast_node(AST::AST_IDENTIFIER);
temp_var_ident->str = temp_var->str;
auto temp_assign = make_ast_node(AST::AST_ASSIGN_EQ, {temp_var_ident});
block_node->children.push_back(temp_assign);
// Assignment in the loop's block
auto assign_node = make_ast_node(AST::AST_ASSIGN_EQ, {lhs_node->clone(), temp_var_ident->clone()});
AST::AstNode *slice_size = nullptr; // First argument in streaming op
visit_one_to_many({vpiOperand}, obj_h, [&](AST::AstNode *node) {
if (!slice_size && node->type == AST::AST_CONSTANT) {
slice_size = node;
} else {
temp_assign->children.push_back(node);
}
});
if (!slice_size) {
slice_size = AST::AstNode::mkconst_int(1, true);
}
// Initialization of the loop counter to 0
auto init_stmt = make_ast_node(AST::AST_ASSIGN_EQ, {loop_counter_ident, AST::AstNode::mkconst_int(0, true)});
// Loop condition (loop counter < $bits(RHS))
auto cond_stmt =
make_ast_node(AST::AST_LE, {loop_counter_ident->clone(), make_ast_node(AST::AST_SUB, {bits_call->clone(), slice_size->clone()})});
// Increment loop counter
auto inc_stmt =
make_ast_node(AST::AST_ASSIGN_EQ, {loop_counter_ident->clone(), make_ast_node(AST::AST_ADD, {loop_counter_ident->clone(), slice_size})});
// Range on the LHS of the assignment
auto lhs_range = make_ast_node(AST::AST_RANGE);
auto lhs_selfsz = make_ast_node(
AST::AST_SELFSZ, {make_ast_node(AST::AST_SUB, {make_ast_node(AST::AST_SUB, {bits_call->clone(), AST::AstNode::mkconst_int(1, true)}),
loop_counter_ident->clone()})});
lhs_range->children.push_back(make_ast_node(AST::AST_ADD, {lhs_selfsz, AST::AstNode::mkconst_int(0, true)}));
lhs_range->children.push_back(
make_ast_node(AST::AST_SUB, {make_ast_node(AST::AST_ADD, {lhs_selfsz->clone(), AST::AstNode::mkconst_int(1, true)}), slice_size->clone()}));
// Range on the RHS of the assignment
auto rhs_range = make_ast_node(AST::AST_RANGE);
auto rhs_selfsz = make_ast_node(AST::AST_SELFSZ, {loop_counter_ident->clone()});
rhs_range->children.push_back(
make_ast_node(AST::AST_SUB, {make_ast_node(AST::AST_ADD, {rhs_selfsz, slice_size->clone()}), AST::AstNode::mkconst_int(1, true)}));
rhs_range->children.push_back(make_ast_node(AST::AST_ADD, {rhs_selfsz->clone(), AST::AstNode::mkconst_int(0, true)}));
// Put ranges on the sides of the assignment
assign_node->children[0]->children.push_back(lhs_range);
assign_node->children[1]->children.push_back(rhs_range);
// Putting the loop together
auto loop_node = make_ast_node(AST::AST_FOR);
loop_node->str = "$loop" + std::to_string(loop_id);
loop_node->children.push_back(init_stmt);
loop_node->children.push_back(cond_stmt);
loop_node->children.push_back(inc_stmt);
loop_node->children.push_back(make_ast_node(AST::AST_BLOCK, {assign_node}));
loop_node->children[3]->str = "\\stream_op_block" + std::to_string(loop_id);
block_node->children.push_back(make_ast_node(AST::AST_BLOCK, {loop_node}));
// Do not create a node
shared.report.mark_handled(obj_h);
}
void UhdmAst::process_list_op()
{
// Add all operands as children of process node
if (auto parent_node = find_ancestor({AST::AST_ALWAYS, AST::AST_COND})) {
visit_one_to_many({vpiOperand}, obj_h, [&](AST::AstNode *node) {
// add directly to process/cond node
if (node) {
parent_node->children.push_back(node);
}
});
}
// Do not create a node
shared.report.mark_handled(obj_h);
}
void UhdmAst::process_cast_op()
{
current_node = make_ast_node(AST::AST_NONE);
visit_one_to_many({vpiOperand}, obj_h, [&](AST::AstNode *node) {
node->cloneInto(current_node);
delete node;
});
vpiHandle typespec_h = vpi_handle(vpiTypespec, obj_h);
shared.report.mark_handled(typespec_h);
vpi_release_handle(typespec_h);
}
void UhdmAst::process_inside_op()
{
current_node = make_ast_node(AST::AST_EQ);
AST::AstNode *lhs = nullptr;
visit_one_to_many({vpiOperand}, obj_h, [&](AST::AstNode *node) {
if (!lhs) {
lhs = node;
}
if (current_node->children.size() < 2) {
current_node->children.push_back(node);
} else {
auto or_node = new AST::AstNode(AST::AST_LOGIC_OR);
or_node->filename = current_node->filename;
or_node->location = current_node->location;
auto eq_node = new AST::AstNode(AST::AST_EQ);
eq_node->filename = current_node->filename;
eq_node->location = current_node->location;
or_node->children.push_back(current_node);
or_node->children.push_back(eq_node);
eq_node->children.push_back(lhs->clone());
eq_node->children.push_back(node);
current_node = or_node;
}
});
}
void UhdmAst::process_assignment_pattern_op()
{
current_node = make_ast_node(AST::AST_CONCAT);
if (auto param_node = find_ancestor({AST::AST_PARAMETER, AST::AST_LOCALPARAM})) {
std::map<size_t, AST::AstNode *> ordered_children;
visit_one_to_many({vpiOperand}, obj_h, [&](AST::AstNode *node) {
if (node->type == AST::AST_ASSIGN || node->type == AST::AST_ASSIGN_EQ || node->type == AST::AST_ASSIGN_LE) {
// Find at what position in the concat should we place this node
auto key = node->children[0]->str;
key = key.substr(key.find('.') + 1);
auto param_type = shared.param_types[param_node->str];
size_t pos =
std::find_if(param_type->children.begin(), param_type->children.end(), [key](AST::AstNode *child) { return child->str == key; }) -
param_type->children.begin();
ordered_children.insert(std::make_pair(pos, node->children[1]->clone()));
} else {
current_node->children.push_back(node);
}
});
for (auto p : ordered_children) {
current_node->children.push_back(p.second);
}
return;
}
auto assign_node = find_ancestor({AST::AST_ASSIGN, AST::AST_ASSIGN_EQ, AST::AST_ASSIGN_LE});
auto proc_node = find_ancestor({AST::AST_BLOCK, AST::AST_ALWAYS, AST::AST_INITIAL, AST::AST_MODULE, AST::AST_PACKAGE, AST::AST_CELL});
if (proc_node && proc_node->type == AST::AST_CELL && shared.top_nodes.count(proc_node->children[0]->str)) {
proc_node = shared.top_nodes[proc_node->children[0]->str];
}
std::vector<AST::AstNode *> assignments;
visit_one_to_many({vpiOperand}, obj_h, [&](AST::AstNode *node) {
if (node->type == AST::AST_ASSIGN || node->type == AST::AST_ASSIGN_EQ || node->type == AST::AST_ASSIGN_LE) {
assignments.push_back(node);
} else {
current_node->children.push_back(node);
}
});
std::reverse(current_node->children.begin(), current_node->children.end());
if (!assignments.empty()) {
if (current_node->children.empty()) {
delete assign_node->children[0];
assign_node->children[0] = assignments[0]->children[0];
current_node = assignments[0]->children[1];
assignments[0]->children.clear();
delete assignments[0];
proc_node->children.insert(proc_node->children.end(), assignments.begin() + 1, assignments.end());
} else {
proc_node->children.insert(proc_node->children.end(), assignments.begin(), assignments.end());
}
}
}
void UhdmAst::process_tagged_pattern()
{
auto assign_node = find_ancestor({AST::AST_ASSIGN, AST::AST_ASSIGN_EQ, AST::AST_ASSIGN_LE});
auto assign_type = AST::AST_ASSIGN;
AST::AstNode *lhs_node = nullptr;
if (assign_node) {
assign_type = assign_node->type;
lhs_node = assign_node->children[0];
} else {
lhs_node = new AST::AstNode(AST::AST_IDENTIFIER);
lhs_node->str = find_ancestor({AST::AST_WIRE, AST::AST_MEMORY, AST::AST_PARAMETER, AST::AST_LOCALPARAM})->str;
}
current_node = new AST::AstNode(assign_type);
current_node->children.push_back(lhs_node->clone());
auto typespec_h = vpi_handle(vpiTypespec, obj_h);
if (vpi_get(vpiType, typespec_h) == vpiStringTypespec) {
std::string field_name = vpi_get_str(vpiName, typespec_h);
if (field_name != "default") { // TODO: better support of the default keyword
current_node->children[0]->str += '.' + field_name;
}
} else if (vpi_get(vpiType, typespec_h) == vpiIntegerTypespec) {
s_vpi_value val;
vpi_get_value(typespec_h, &val);
auto range = new AST::AstNode(AST::AST_RANGE);
auto index = AST::AstNode::mkconst_int(val.value.integer, false);
range->children.push_back(index);
current_node->children[0]->children.push_back(range);
}
vpi_release_handle(typespec_h);
visit_one_to_one({vpiPattern}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
void UhdmAst::process_bit_select()
{
current_node = make_ast_node(AST::AST_IDENTIFIER);
visit_one_to_one({vpiIndex}, obj_h, [&](AST::AstNode *node) {
auto range_node = new AST::AstNode(AST::AST_RANGE, node);
range_node->filename = current_node->filename;
range_node->location = current_node->location;
current_node->children.push_back(range_node);
});
}
void UhdmAst::process_part_select()
{
current_node = make_ast_node(AST::AST_IDENTIFIER);
vpiHandle parent_h = vpi_handle(vpiParent, obj_h);
current_node->str = get_name(parent_h);
vpi_release_handle(parent_h);
auto range_node = new AST::AstNode(AST::AST_RANGE);
range_node->filename = current_node->filename;
range_node->location = current_node->location;
visit_one_to_one({vpiLeftRange, vpiRightRange}, obj_h, [&](AST::AstNode *node) { range_node->children.push_back(node); });
current_node->children.push_back(range_node);
}
void UhdmAst::process_indexed_part_select()
{
current_node = make_ast_node(AST::AST_IDENTIFIER);
vpiHandle parent_h = vpi_handle(vpiParent, obj_h);
current_node->str = get_name(parent_h);
vpi_release_handle(parent_h);
// TODO: check if there are other types, for now only handle 1 and 2 (+: and -:)
auto indexed_part_select_type = vpi_get(vpiIndexedPartSelectType, obj_h) == 1 ? AST::AST_ADD : AST::AST_SUB;
auto range_node = new AST::AstNode(AST::AST_RANGE);
range_node->filename = current_node->filename;
range_node->location = current_node->location;
visit_one_to_one({vpiBaseExpr}, obj_h, [&](AST::AstNode *node) { range_node->children.push_back(node); });
visit_one_to_one({vpiWidthExpr}, obj_h, [&](AST::AstNode *node) {
auto right_range_node = new AST::AstNode(indexed_part_select_type);
right_range_node->children.push_back(range_node->children[0]->clone());
right_range_node->children.push_back(node);
auto sub = new AST::AstNode(indexed_part_select_type == AST::AST_ADD ? AST::AST_SUB : AST::AST_ADD);
sub->children.push_back(right_range_node);
sub->children.push_back(AST::AstNode::mkconst_int(1, false, 1));
range_node->children.push_back(sub);
// range_node->children.push_back(right_range_node);
});
if (indexed_part_select_type == AST::AST_ADD) {
std::reverse(range_node->children.begin(), range_node->children.end());
}
current_node->children.push_back(range_node);
}
void UhdmAst::process_var_select()
{
current_node = make_ast_node(AST::AST_IDENTIFIER);
visit_one_to_many({vpiIndex}, obj_h, [&](AST::AstNode *node) {
if (node->str == current_node->str) {
for (auto child : node->children) {
current_node->children.push_back(child);
}
node->children.clear();
delete node;
} else {
auto range_node = new AST::AstNode(AST::AST_RANGE);
range_node->filename = current_node->filename;
range_node->location = current_node->location;
range_node->children.push_back(node);
current_node->children.push_back(range_node);
}
});
if (current_node->children.size() > 1) {
auto multirange_node = new AST::AstNode(AST::AST_MULTIRANGE);
multirange_node->is_packed = true;
multirange_node->children = current_node->children;
current_node->children.clear();
current_node->children.push_back(multirange_node);
}
}
void UhdmAst::process_if_else()
{
current_node = make_ast_node(AST::AST_CASE);
visit_one_to_one({vpiCondition}, obj_h, [&](AST::AstNode *node) {
auto reduce_node = new AST::AstNode(AST::AST_REDUCE_BOOL, node);
current_node->children.push_back(reduce_node);
});
// If true:
auto *condition = new AST::AstNode(AST::AST_COND);
auto *constant = AST::AstNode::mkconst_int(1, false, 1);
condition->children.push_back(constant);
visit_one_to_one({vpiStmt}, obj_h, [&](AST::AstNode *node) {
auto *statements = new AST::AstNode(AST::AST_BLOCK);
statements->children.push_back(node);
condition->children.push_back(statements);
});
current_node->children.push_back(condition);
// Else:
if (vpi_get(vpiType, obj_h) == vpiIfElse) {
auto *condition = new AST::AstNode(AST::AST_COND);
auto *elseBlock = new AST::AstNode(AST::AST_DEFAULT);
condition->children.push_back(elseBlock);
visit_one_to_one({vpiElseStmt}, obj_h, [&](AST::AstNode *node) {
auto *statements = new AST::AstNode(AST::AST_BLOCK);
statements->children.push_back(node);
condition->children.push_back(statements);
});
current_node->children.push_back(condition);
}
}
void UhdmAst::process_for()
{
current_node = make_ast_node(AST::AST_FOR);
auto loop_id = shared.next_loop_id();
current_node->str = "$loop" + std::to_string(loop_id);
auto parent_node = find_ancestor({AST::AST_FUNCTION, AST::AST_GENBLOCK, AST::AST_MODULE});
visit_one_to_many({vpiForInitStmt}, obj_h, [&](AST::AstNode *node) {
if (node->type == AST::AST_ASSIGN_LE)
node->type = AST::AST_ASSIGN_EQ;
auto lhs = node->children[0];
if (lhs->type == AST::AST_WIRE) {
auto old_str = lhs->str;
lhs->str = '\\' + current_node->str.substr(1) + "::" + lhs->str.substr(1);
node_renames.insert(std::make_pair(old_str, lhs->str));
auto *wire = lhs->clone();
wire->is_reg = true;
parent_node->children.push_back(wire);
lhs->type = AST::AST_IDENTIFIER;
lhs->is_signed = false;
lhs->delete_children();
}
current_node->children.push_back(node);
});
visit_one_to_one({vpiCondition}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
visit_one_to_many({vpiForIncStmt}, obj_h, [&](AST::AstNode *node) {
if (node->type == AST::AST_ASSIGN_LE)
node->type = AST::AST_ASSIGN_EQ;
current_node->children.push_back(node);
});
visit_one_to_one({vpiStmt}, obj_h, [&](AST::AstNode *node) {
auto *statements = make_ast_node(AST::AST_BLOCK);
statements->str = current_node->str; // Needed in simplify step
statements->children.push_back(node);
current_node->children.push_back(statements);
});
}
void UhdmAst::process_gen_scope_array()
{
current_node = make_ast_node(AST::AST_GENBLOCK);
visit_one_to_many({vpiGenScope}, obj_h, [&](AST::AstNode *genscope_node) {
for (auto *child : genscope_node->children) {
if (child->type == AST::AST_PARAMETER || child->type == AST::AST_LOCALPARAM) {
auto param_str = child->str.substr(1);
auto array_str = "[" + param_str + "]";
genscope_node->visitEachDescendant([&](AST::AstNode *node) {
auto pos = node->str.find(array_str);
if (pos != std::string::npos) {
node->type = AST::AST_PREFIX;
auto *param = new AST::AstNode(AST::AST_IDENTIFIER);
param->str = child->str;
auto *field = new AST::AstNode(AST::AST_IDENTIFIER);
field->str = "\\" + node->str.substr(node->str.rfind(']') + 2);
node->str = node->str.substr(0, node->str.find('['));
node->children.push_back(param);
node->children.push_back(field);
}
});
}
}
current_node->children.insert(current_node->children.end(), genscope_node->children.begin(), genscope_node->children.end());
genscope_node->children.clear();
delete genscope_node;
});
}
void UhdmAst::process_gen_scope()
{
current_node = make_ast_node(AST::AST_GENBLOCK);
visit_one_to_many({vpiParamAssign, vpiParameter, vpiNet, vpiArrayNet, vpiVariables, vpiContAssign, vpiProcess, vpiModule, vpiGenScopeArray},
obj_h, [&](AST::AstNode *node) {
if (node) {
if ((node->type == AST::AST_PARAMETER || node->type == AST::AST_LOCALPARAM) && node->children.empty()) {
delete node; // skip parameters without any children
} else {
current_node->children.push_back(node);
}
}
});
}
void UhdmAst::process_case()
{
current_node = make_ast_node(AST::AST_CASE);
visit_one_to_one({vpiCondition}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
visit_one_to_many({vpiCaseItem}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
void UhdmAst::process_case_item()
{
current_node = make_ast_node(AST::AST_COND);
visit_one_to_many({vpiExpr}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
if (current_node->children.empty()) {
current_node->children.push_back(new AST::AstNode(AST::AST_DEFAULT));
}
visit_one_to_one({vpiStmt}, obj_h, [&](AST::AstNode *node) {
if (node->type != AST::AST_BLOCK) {
auto block_node = new AST::AstNode(AST::AST_BLOCK);
block_node->children.push_back(node);
node = block_node;
}
current_node->children.push_back(node);
});
}
void UhdmAst::process_range()
{
current_node = make_ast_node(AST::AST_RANGE);
visit_one_to_one({vpiLeftRange, vpiRightRange}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
void UhdmAst::process_return()
{
current_node = make_ast_node(AST::AST_ASSIGN_EQ);
auto func_node = find_ancestor({AST::AST_FUNCTION, AST::AST_TASK});
if (!func_node->children.empty()) {
auto lhs = new AST::AstNode(AST::AST_IDENTIFIER);
lhs->str = func_node->children[0]->str;
current_node->children.push_back(lhs);
}
visit_one_to_one({vpiCondition}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
}
void UhdmAst::process_function()
{
current_node = make_ast_node(vpi_get(vpiType, obj_h) == vpiFunction ? AST::AST_FUNCTION : AST::AST_TASK);
visit_one_to_one({vpiReturn}, obj_h, [&](AST::AstNode *node) {
if (node) {
auto net_type = vpi_get(vpiNetType, obj_h);
node->is_reg = net_type == vpiReg;
node->str = current_node->str;
current_node->children.push_back(node);
}
});
visit_one_to_many({vpiIODecl}, obj_h, [&](AST::AstNode *node) {
node->type = AST::AST_WIRE;
current_node->children.push_back(node);
});
visit_one_to_many({vpiVariables}, obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
visit_one_to_one({vpiStmt}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
}
void UhdmAst::process_logic_var()
{
current_node = make_ast_node(AST::AST_WIRE);
current_node->is_logic = true;
// TODO: add const attribute, but it seems it is little more
// then just setting boolean value
// current_node->is_const = vpi_get(vpiConstantVariable, obj_h);
visit_one_to_one({vpiTypespec}, obj_h, [&](AST::AstNode *node) {
if (node) {
auto wiretype_node = new AST::AstNode(AST::AST_WIRETYPE);
wiretype_node->str = node->str;
// wiretype needs to be 1st node (if port have also another range nodes)
current_node->children.insert(current_node->children.begin(), wiretype_node);
current_node->is_custom_type = true;
}
});
visit_range(obj_h, [&](AST::AstNode *node) { current_node->children.push_back(node); });
visit_default_expr(obj_h);
}
void UhdmAst::process_sys_func_call()
{
current_node = make_ast_node(AST::AST_FCALL);
if (current_node->str == "\\$signed") {
current_node->type = AST::AST_TO_SIGNED;
} else if (current_node->str == "\\$unsigned") {
current_node->type = AST::AST_TO_UNSIGNED;
} else if (current_node->str == "\\$display" || current_node->str == "\\$time") {
current_node->type = AST::AST_TCALL;
current_node->str = current_node->str.substr(1);
} else if (current_node->str == "\\$readmemh") {
current_node->type = AST::AST_TCALL;
}
visit_one_to_many({vpiArgument}, obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
}
void UhdmAst::process_func_call()
{
current_node = make_ast_node(AST::AST_FCALL);
visit_one_to_many({vpiArgument}, obj_h, [&](AST::AstNode *node) {
if (node) {
if (node->type == AST::AST_PARAMETER || node->type == AST::AST_LOCALPARAM) {
node->type = AST::AST_IDENTIFIER;
node->children.clear();
}
current_node->children.push_back(node);
}
});
}
void UhdmAst::process_immediate_assert()
{
current_node = make_ast_node(AST::AST_ASSERT);
visit_one_to_one({vpiExpr}, obj_h, [&](AST::AstNode *n) {
if (n) {
current_node->children.push_back(n);
}
});
}
void UhdmAst::process_hier_path()
{
current_node = make_ast_node(AST::AST_IDENTIFIER);
current_node->str = "\\";
visit_one_to_many({vpiActual}, obj_h, [&](AST::AstNode *node) {
if (current_node->str == "\\" && !node->children.empty() && node->children[0]->type == AST::AST_RANGE) {
current_node->type = AST::AST_PREFIX;
current_node->str = node->str;
current_node->children.push_back(node->children[0]->children[0]->clone());
delete node;
} else {
if (current_node->type == AST::AST_IDENTIFIER) {
if (current_node->str != "\\") {
current_node->str += ".";
}
current_node->str += node->str.substr(1);
current_node->children = std::move(node->children);
delete node;
} else {
current_node->children.push_back(node);
}
}
});
}
void UhdmAst::process_logic_typespec()
{
current_node = make_ast_node(AST::AST_WIRE);
current_node->is_logic = true;
visit_range(obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
if (!current_node->str.empty()) {
move_type_to_new_typedef(find_ancestor({AST::AST_MODULE, AST::AST_PACKAGE}), current_node->clone());
}
}
void UhdmAst::process_int_typespec()
{
current_node = make_ast_node(AST::AST_WIRE);
auto left_const = AST::AstNode::mkconst_int(31, true);
auto right_const = AST::AstNode::mkconst_int(0, true);
auto range = new AST::AstNode(AST::AST_RANGE, left_const, right_const);
current_node->children.push_back(range);
current_node->is_signed = true;
if (!current_node->str.empty()) {
move_type_to_new_typedef(find_ancestor({AST::AST_MODULE, AST::AST_PACKAGE}), current_node);
}
}
void UhdmAst::process_string_var()
{
current_node = make_ast_node(AST::AST_WIRE);
current_node->is_string = true;
// FIXME:
// this is only basic support for strings,
// currently yosys doesn't support dynamic resize of wire
// based on string size
// here we try to get size of string based on provided const string
// if it is not available, we are setting size to explicite 64 bits
visit_one_to_one({vpiExpr}, obj_h, [&](AST::AstNode *expr_node) {
if (expr_node->type == AST::AST_CONSTANT) {
auto left_const = AST::AstNode::mkconst_int(expr_node->range_left, true);
auto right_const = AST::AstNode::mkconst_int(expr_node->range_right, true);
auto range = make_ast_node(AST::AST_RANGE, {left_const, right_const});
current_node->children.push_back(range);
}
});
if (current_node->children.empty()) {
auto left_const = AST::AstNode::mkconst_int(64, true);
auto right_const = AST::AstNode::mkconst_int(0, true);
auto range = make_ast_node(AST::AST_RANGE, {left_const, right_const});
current_node->children.push_back(range);
}
visit_default_expr(obj_h);
}
void UhdmAst::process_string_typespec()
{
current_node = make_ast_node(AST::AST_WIRE);
current_node->is_string = true;
// FIXME:
// this is only basic support for strings,
// currently yosys doesn't support dynamic resize of wire
// based on string size
// here, we are setting size to explicite 64 bits
auto left_const = AST::AstNode::mkconst_int(64, true);
auto right_const = AST::AstNode::mkconst_int(0, true);
auto range = make_ast_node(AST::AST_RANGE, {left_const, right_const});
current_node->children.push_back(range);
}
void UhdmAst::process_bit_typespec()
{
current_node = make_ast_node(AST::AST_WIRE);
visit_range(obj_h, [&](AST::AstNode *node) {
if (node) {
current_node->children.push_back(node);
}
});
if (!current_node->str.empty()) {
move_type_to_new_typedef(find_ancestor({AST::AST_MODULE, AST::AST_PACKAGE}), current_node);
}
}
AST::AstNode *UhdmAst::process_object(vpiHandle obj_handle)
{
obj_h = obj_handle;
const unsigned object_type = vpi_get(vpiType, obj_h);
const uhdm_handle *const handle = (const uhdm_handle *)obj_h;
const UHDM::BaseClass *const object = (const UHDM::BaseClass *)handle->object;
if (shared.debug_flag) {
std::cout << indent << "Object '" << object->VpiName() << "' of type '" << UHDM::VpiTypeName(obj_h) << '\'' << std::endl;
}
switch (object_type) {
case vpiDesign:
process_design();
break;
case vpiParameter:
process_parameter();
break;
case vpiPort:
process_port();
break;
case vpiModule:
process_module();
break;
case vpiStructTypespec:
process_struct_typespec();
break;
case vpiPackedArrayTypespec:
process_packed_array_typespec();
break;
case vpiTypespecMember:
process_typespec_member();
break;
case vpiEnumTypespec:
process_enum_typespec();
break;
case vpiEnumConst:
process_enum_const();
break;
case vpiEnumVar:
case vpiEnumNet:
case vpiStructVar:
case vpiStructNet:
process_custom_var();
break;
case vpiIntVar:
process_int_var();
break;
case vpiRealVar:
process_real_var();
break;
case vpiPackedArrayVar:
case vpiArrayVar:
process_array_var();
break;
case vpiParamAssign:
process_param_assign();
break;
case vpiContAssign:
process_cont_assign();
break;
case vpiAssignStmt:
case vpiAssignment:
process_assignment();
break;
case vpiRefVar:
case vpiRefObj:
current_node = make_ast_node(AST::AST_IDENTIFIER);
break;
case vpiNet:
process_net();
break;
case vpiArrayNet:
process_array_net();
break;
case vpiPackedArrayNet:
process_packed_array_net();
break;
case vpiPackage:
process_package();
break;
case vpiInterface:
process_interface();
break;
case vpiModport:
process_modport();
break;
case vpiIODecl:
process_io_decl();
break;
case vpiAlways:
process_always();
break;
case vpiEventControl:
process_event_control();
break;
case vpiInitial:
process_initial();
break;
case vpiNamedBegin:
case vpiBegin:
process_begin();
break;
case vpiCondition:
case vpiOperation:
process_operation();
break;
case vpiTaggedPattern:
process_tagged_pattern();
break;
case vpiBitSelect:
process_bit_select();
break;
case vpiPartSelect:
process_part_select();
break;
case vpiIndexedPartSelect:
process_indexed_part_select();
break;
case vpiVarSelect:
process_var_select();
break;
case vpiIf:
case vpiIfElse:
process_if_else();
break;
case vpiFor:
process_for();
break;
case vpiGenScopeArray:
process_gen_scope_array();
break;
case vpiGenScope:
process_gen_scope();
break;
case vpiCase:
process_case();
break;
case vpiCaseItem:
process_case_item();
break;
case vpiConstant:
current_node = process_value(obj_h);
break;
case vpiRange:
process_range();
break;
case vpiReturn:
process_return();
break;
case vpiFunction:
case vpiTask:
process_function();
break;
case vpiBitVar:
case vpiLogicVar:
process_logic_var();
break;
case vpiSysFuncCall:
process_sys_func_call();
break;
case vpiFuncCall:
process_func_call();
break;
case vpiTaskCall:
current_node = make_ast_node(AST::AST_TCALL);
break;
case vpiImmediateAssert:
if (!shared.no_assert)
process_immediate_assert();
break;
case vpiHierPath:
process_hier_path();
break;
case UHDM::uhdmimport:
break;
case vpiDelayControl:
break;
case vpiLogicTypespec:
process_logic_typespec();
break;
case vpiIntTypespec:
process_int_typespec();
break;
case vpiBitTypespec:
process_bit_typespec();
break;
case vpiStringVar:
process_string_var();
break;
case vpiStringTypespec:
process_string_typespec();
break;
case vpiProgram:
default:
report_error("%s:%d: Encountered unhandled object '%s' of type '%s'\n", object->VpiFile().c_str(), object->VpiLineNo(),
object->VpiName().c_str(), UHDM::VpiTypeName(obj_h).c_str());
break;
}
// Check if we initialized the node in switch-case
if (current_node) {
if (current_node->type != AST::AST_NONE) {
shared.report.mark_handled(object);
return current_node;
}
}
return nullptr;
}
AST::AstNode *UhdmAst::visit_designs(const std::vector<vpiHandle> &designs)
{
current_node = new AST::AstNode(AST::AST_DESIGN);
for (auto design : designs) {
UhdmAst ast(this, shared, indent);
auto *nodes = ast.process_object(design);
// Flatten multiple designs into one
for (auto child : nodes->children) {
current_node->children.push_back(child);
}
}
return current_node;
}
void UhdmAst::report_error(const char *format, ...) const
{
va_list args;
va_start(args, format);
if (shared.stop_on_error) {
logv_error(format, args);
} else {
logv_warning(format, args);
}
}
YOSYS_NAMESPACE_END
| 39.695741 | 150 | 0.595242 | [
"object",
"vector"
] |
045724b2abf2de378a4fea07346fd003be3f1777 | 38,341 | cpp | C++ | src/nbl/asset/CGraphicsPipelineLoaderMTL.cpp | Erfan-Ahmadi/Nabla | 1ea023d3333f4fade4268b20ac878546fb4d5c82 | [
"Apache-2.0"
] | 2 | 2021-02-08T23:33:54.000Z | 2021-02-09T18:21:16.000Z | src/nbl/asset/CGraphicsPipelineLoaderMTL.cpp | Erfan-Ahmadi/Nabla | 1ea023d3333f4fade4268b20ac878546fb4d5c82 | [
"Apache-2.0"
] | null | null | null | src/nbl/asset/CGraphicsPipelineLoaderMTL.cpp | Erfan-Ahmadi/Nabla | 1ea023d3333f4fade4268b20ac878546fb4d5c82 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2020 - DevSH Graphics Programming Sp. z O.O.
// This file is part of the "Nabla Engine".
// For conditions of distribution and use, see copyright notice in nabla.h
#include <utility>
#include <regex>
#include "nbl/asset/asset.h"
#include "os.h"
#include "nbl/asset/CGraphicsPipelineLoaderMTL.h"
#include "nbl/asset/IGLSLEmbeddedIncludeLoader.h"
#include "nbl/builtin/MTLdefaults.h"
namespace
{
/*
constexpr const char* FRAG_SHADER_NO_UV_PBR =
R"(#version 430 core
layout (location = 0) in vec3 LocalPos;
layout (location = 1) in vec3 ViewPos;
layout (location = 2) in vec3 Normal;
layout (location = 0) out vec4 OutColor;
layout (push_constant) uniform Block {
vec3 ambient;
vec3 albedo;//MTL's diffuse
vec3 specular;
vec3 emissive;
vec4 Tf;//w component doesnt matter
float shininess;
float opacity;
float bumpFactor;
//PBR
float ior;
float roughness;
float metallic;
float sheen;
float clearcoatThickness;
float clearcoatRoughness;
float anisotropy;
float anisoRotation;
//extra info
uint extra;
} PC;
#define PI 3.14159265359
#define FLT_MIN 1.175494351e-38
#include <nbl/builtin/glsl/bsdf/brdf/diffuse/oren_nayar.glsl>
#include <nbl/builtin/glsl/bsdf/brdf/specular/ndf/ggx_trowbridge_reitz.glsl>
#include <nbl/builtin/glsl/bsdf/brdf/specular/geom/ggx_smith.glsl>
#include <nbl/builtin/glsl/bsdf/brdf/specular/fresnel/fresnel.glsl>
void main()
{
vec3 N = normalize(Normal);
//some approximation for computing tangents without UV
vec3 c1 = cross(N, vec3(0.0, 0.0, 1.0));
vec3 c2 = cross(N, vec3(0.0, 1.0, 0.0));
vec3 T = (dot(c1,c1) > dot(c2,c2)) ? c1 : c2;
T = normalize(T);
vec3 B = normalize(cross(N,T));
vec3 V = -ViewPos;
vec3 NdotV = dot(N,V);
#define NdotL NdotV
#define NdotH NdotV
vec3 color = PC.params.emissive*0.01;
if (NdotL > FLT_MIN)
{
float lightDistance2 = dot(V,V);
float Vrcplen = inversesqrt(lightDistance2);
NdotV *= Vrcplen;
V *= Vrcplen;
vec3 TdotV = dot(T,V);
vec3 BdotV = dot(B,V);
#define TdotL TdotV
#define BdotL BdotV
#define TdotH TdotV
#define BdotH BdotV
float at = sqrt(PC.params.roughness);
float ab = at*(1.0 - PC.params.anisotropy);
float fr = nbl_glsl_fresnel_dielectric(PC.params.ior, NdotV);
float one_minus_fr = 1.0-fr;
float diffuseFactor = 1.0 - one_minus_fr*one_minus_fr;
float diffuse = 0.0;
if (PC.params.metallic < 1.0)
{
if (PC.params.roughness==0.0)
diffuse = 1.0/PI;
else
diffuse = oren_nayar(PC.params.roughness, N, V, V, NdotL, NdotV);
}
float specular = 0.0;
if (NdotV > FLT_MIN)
{
float ndf = GGXBurleyAnisotropic(PC.params.anisotropy, PC.params.roughness, TdotH, BdotH, NdotH);
float geom = GGXSmithHeightCorrelated_aniso_wo_numerator(at, ab, TdotL, TdotV, BdotL, BdotV, NdotL, NdotV);
specular = ndf*geom*fr;
}
color += (diffuseFactor*diffuse*PC.params.albedo + specular) * NdotL / lightDistance2;
}
OutColor = vec4(color*PC.params.transmissionFilter, 1.0);
}
)";
*/
}
using namespace nbl;
using namespace asset;
template<typename AssetType, IAsset::E_TYPE assetType>
static core::smart_refctd_ptr<AssetType> getDefaultAsset(const char* _key, IAssetManager* _assetMgr)
{
size_t storageSz = 1ull;
asset::SAssetBundle bundle;
const IAsset::E_TYPE types[]{ assetType, static_cast<IAsset::E_TYPE>(0u) };
_assetMgr->findAssets(storageSz, &bundle, _key, types);
if (bundle.isEmpty())
return nullptr;
auto assets = bundle.getContents();
//assert(assets.first != assets.second);
return core::smart_refctd_ptr_static_cast<AssetType>(assets.begin()[0]);
}
#define VERT_SHADER_NO_UV_CACHE_KEY "nbl/builtin/shaders/loaders/mtl/vertex_no_uv.vert"
#define VERT_SHADER_UV_CACHE_KEY "nbl/builtin/shaders/loaders/mtl/vertex_uv.vert"
#define FRAG_SHADER_NO_UV_CACHE_KEY "nbl/builtin/shaders/loaders/mtl/fragment_no_uv.frag"
#define FRAG_SHADER_UV_CACHE_KEY "nbl/builtin/shaders/loaders/mtl/fragment_uv.frag"
CGraphicsPipelineLoaderMTL::CGraphicsPipelineLoaderMTL(IAssetManager* _am) : m_assetMgr{_am}
{
//create vertex shaders and insert them into cache
auto registerShader = [&](auto constexprStringType, ICPUSpecializedShader::E_SHADER_STAGE stage) -> void
{
auto data = m_assetMgr->getFileSystem()->loadBuiltinData<decltype(constexprStringType)>();
auto unspecializedShader = core::make_smart_refctd_ptr<asset::ICPUShader>(std::move(data), asset::ICPUShader::buffer_contains_glsl);
ICPUSpecializedShader::SInfo specInfo(
{}, nullptr, "main", stage,
stage!=ICPUSpecializedShader::ESS_VERTEX ? "?IrrlichtBAW PipelineLoaderMTL FragmentShader?":"?IrrlichtBAW PipelineLoaderMTL VertexShader?"
);
auto shader = core::make_smart_refctd_ptr<asset::ICPUSpecializedShader>(std::move(unspecializedShader),std::move(specInfo));
insertBuiltinAssetIntoCache(m_assetMgr, core::smart_refctd_ptr_static_cast<IAsset>(std::move(shader)), decltype(constexprStringType)::value);
};
registerShader(NBL_CORE_UNIQUE_STRING_LITERAL_TYPE(VERT_SHADER_NO_UV_CACHE_KEY){},ICPUSpecializedShader::ESS_VERTEX);
registerShader(NBL_CORE_UNIQUE_STRING_LITERAL_TYPE(VERT_SHADER_UV_CACHE_KEY) {}, ICPUSpecializedShader::ESS_VERTEX);
registerShader(NBL_CORE_UNIQUE_STRING_LITERAL_TYPE(FRAG_SHADER_NO_UV_CACHE_KEY){},ICPUSpecializedShader::ESS_FRAGMENT);
registerShader(NBL_CORE_UNIQUE_STRING_LITERAL_TYPE(FRAG_SHADER_UV_CACHE_KEY){},ICPUSpecializedShader::ESS_FRAGMENT);
}
void CGraphicsPipelineLoaderMTL::initialize()
{
constexpr const char* MISSING_MTL_PIPELINE_NO_UV_CACHE_KEY = "nbl/builtin/graphics_pipeline/loaders/mtl/missing_material_pipeline_no_uv";
constexpr const char* MISSING_MTL_PIPELINE_UV_CACHE_KEY = "nbl/builtin/graphics_pipeline/loaders/mtl/missing_material_pipeline_uv";
SAssetLoadParams assetLoadParams;
auto default_mtl_file = m_assetMgr->getFileSystem()->createMemoryReadFile(DUMMY_MTL_CONTENT, strlen(DUMMY_MTL_CONTENT), "default IrrlichtBAW material");
auto bundle = loadAsset(default_mtl_file, assetLoadParams);
auto pipelineAssets = bundle.getContents().begin();
default_mtl_file->drop();
auto pNoUV = pipelineAssets[0];
auto pUV = pipelineAssets[1];
insertBuiltinAssetIntoCache(m_assetMgr, pNoUV, MISSING_MTL_PIPELINE_NO_UV_CACHE_KEY);
insertBuiltinAssetIntoCache(m_assetMgr, pUV, MISSING_MTL_PIPELINE_UV_CACHE_KEY);
}
bool CGraphicsPipelineLoaderMTL::isALoadableFileFormat(io::IReadFile* _file) const
{
if (!_file)
return false;
const size_t prevPos = _file->getPos();
_file->seek(0ull);
std::string mtl;
mtl.resize(_file->getSize());
_file->read(mtl.data(), _file->getSize());
_file->seek(prevPos);
return mtl.find("newmtl") != std::string::npos;
}
core::smart_refctd_ptr<ICPUPipelineLayout> CGraphicsPipelineLoaderMTL::makePipelineLayoutFromMtl(SContext& _ctx, const SMtl& _mtl, bool _noDS3)
{
const auto cacheKey = _ctx.layoutCacheKey(_mtl.clamp, _noDS3);
if (auto found = _ctx.layoutCache.find(cacheKey); found != _ctx.layoutCache.end())
return found->second;
//assumes all supported textures are always present
//since vulkan doesnt support bindings with no/null descriptor, absent textures will be filled with dummy 2D texture (while creating desc set)
auto bindings = core::make_refctd_dynamic_array<core::smart_refctd_dynamic_array<ICPUDescriptorSetLayout::SBinding>>(static_cast<size_t>(CMTLPipelineMetadata::EMP_REFL_POSX)+1ull);
ICPUDescriptorSetLayout::SBinding bnd;
bnd.count = 1u;
bnd.stageFlags = ICPUSpecializedShader::ESS_FRAGMENT;
bnd.type = EDT_COMBINED_IMAGE_SAMPLER;
bnd.binding = 0u;
std::fill(bindings->begin(), bindings->end(), bnd);
core::smart_refctd_ptr<ICPUSampler> samplers[2];
samplers[0] = getDefaultAsset<ICPUSampler,IAsset::ET_SAMPLER>("nbl/builtin/samplers/default", m_assetMgr);
samplers[1] = getDefaultAsset<ICPUSampler, IAsset::ET_SAMPLER>("nbl/builtin/samplers/default_clamp_to_border", m_assetMgr);
for (uint32_t i = 0u; i <= CMTLPipelineMetadata::EMP_REFL_POSX; ++i)
{
(*bindings)[i].binding = i;
const uint32_t clamp = (_mtl.clamp >> i) & 1u;
(*bindings)[i].samplers = samplers + clamp;
}
auto ds1layout = getDefaultAsset<ICPUDescriptorSetLayout, IAsset::ET_DESCRIPTOR_SET_LAYOUT>("nbl/builtin/descriptor_set_layout/basic_view_parameters", m_assetMgr);
core::smart_refctd_ptr<ICPUDescriptorSetLayout> ds3Layout = _noDS3 ? nullptr : core::make_smart_refctd_ptr<ICPUDescriptorSetLayout>(bindings->begin(), bindings->end());
SPushConstantRange pcRng;
pcRng.stageFlags = ICPUSpecializedShader::ESS_FRAGMENT;
pcRng.offset = 0u;
pcRng.size = sizeof(SMtl::params);
//if intellisense shows error here, it's most likely intellisense's fault and it'll build fine anyway
static_assert(sizeof(SMtl::params)<=ICPUMeshBuffer::MAX_PUSH_CONSTANT_BYTESIZE, "It must fit in push constants!");
//ds with textures for material goes to set=3
auto layout = core::make_smart_refctd_ptr<ICPUPipelineLayout>(&pcRng, &pcRng+1, nullptr, std::move(ds1layout), nullptr, std::move(ds3Layout));
_ctx.layoutCache.insert({ cacheKey, layout });
return layout;
}
SAssetBundle CGraphicsPipelineLoaderMTL::loadAsset(io::IReadFile* _file, const IAssetLoader::SAssetLoadParams& _params, IAssetLoader::IAssetLoaderOverride* _override, uint32_t _hierarchyLevel)
{
constexpr uint32_t POSITION = 0u;
constexpr uint32_t UV = 2u;
constexpr uint32_t NORMAL = 3u;
constexpr uint32_t BND_NUM = 0u;
SContext ctx(
asset::IAssetLoader::SAssetLoadContext{
_params,
_file
},
_hierarchyLevel,
_override
);
const io::path fullName = _file->getFileName();
const std::string relPath = (io::IFileSystem::getFileDir(fullName)+"/").c_str();
auto materials = readMaterials(_file);
constexpr uint32_t PIPELINE_PERMUTATION_COUNT = 2u;
core::vector<core::smart_refctd_ptr<ICPURenderpassIndependentPipeline>> pipelines(materials.size()*PIPELINE_PERMUTATION_COUNT);
for (size_t i = 0ull; i < materials.size(); ++i)
{
SVertexInputParams vtxParams;
SBlendParams blendParams;
SPrimitiveAssemblyParams primParams;
SRasterizationParams rasterParams;
const uint32_t illum = materials[i].params.extra&0xfu;
if (illum==4u || illum==6u || illum==7u || illum==9u)
{
blendParams.blendParams[0].blendEnable = true;
blendParams.blendParams[0].srcColorFactor = EBF_ONE;
blendParams.blendParams[0].srcAlphaFactor = EBF_ONE;
blendParams.blendParams[0].dstColorFactor = EBF_ONE_MINUS_SRC_ALPHA;
blendParams.blendParams[0].dstAlphaFactor = EBF_ONE_MINUS_SRC_ALPHA;
}
else if (materials[i].maps[CMTLPipelineMetadata::EMP_OPACITY].size() || materials[i].params.opacity!=1.f)
{
blendParams.blendParams[0].blendEnable = true;
blendParams.blendParams[0].srcColorFactor = EBF_SRC_ALPHA;
blendParams.blendParams[0].srcAlphaFactor = EBF_SRC_ALPHA;
blendParams.blendParams[0].dstColorFactor = EBF_ONE_MINUS_SRC_ALPHA;
blendParams.blendParams[0].dstAlphaFactor = EBF_ONE_MINUS_SRC_ALPHA;
}
const uint32_t j = i*PIPELINE_PERMUTATION_COUNT;
vtxParams.enabledAttribFlags = (1u << POSITION) | (1u << NORMAL);
vtxParams.enabledBindingFlags = 1u << BND_NUM;
vtxParams.bindings[BND_NUM].stride = 24u;
vtxParams.bindings[BND_NUM].inputRate = EVIR_PER_VERTEX;
//position
vtxParams.attributes[POSITION].binding = BND_NUM;
vtxParams.attributes[POSITION].format = EF_R32G32B32_SFLOAT;
vtxParams.attributes[POSITION].relativeOffset = 0u;
//normal
vtxParams.attributes[NORMAL].binding = BND_NUM;
vtxParams.attributes[NORMAL].format = EF_A2B10G10R10_SNORM_PACK32;
vtxParams.attributes[NORMAL].relativeOffset = 20u;
auto layout = makePipelineLayoutFromMtl(ctx, materials[i], true);
auto shaders = getShaders(false);
constexpr size_t DS1_METADATA_ENTRY_CNT = 3ull;
core::smart_refctd_dynamic_array<IPipelineMetadata::ShaderInputSemantic> shaderInputsMetadata = core::make_refctd_dynamic_array<decltype(shaderInputsMetadata)>(DS1_METADATA_ENTRY_CNT);
{
ICPUDescriptorSetLayout* ds1layout = layout->getDescriptorSetLayout(1u);
constexpr IPipelineMetadata::E_COMMON_SHADER_INPUT types[DS1_METADATA_ENTRY_CNT]{IPipelineMetadata::ECSI_WORLD_VIEW_PROJ, IPipelineMetadata::ECSI_WORLD_VIEW, IPipelineMetadata::ECSI_WORLD_VIEW_INVERSE_TRANSPOSE};
constexpr uint32_t sizes[DS1_METADATA_ENTRY_CNT]{sizeof(SBasicViewParameters::MVP), sizeof(SBasicViewParameters::MV), sizeof(SBasicViewParameters::NormalMat)};
constexpr uint32_t relOffsets[DS1_METADATA_ENTRY_CNT]{offsetof(SBasicViewParameters,MVP), offsetof(SBasicViewParameters,MV), offsetof(SBasicViewParameters,NormalMat)};
for (uint32_t i = 0u; i < DS1_METADATA_ENTRY_CNT; ++i)
{
auto& semantic = (shaderInputsMetadata->end()-i-1u)[0];
semantic.type = types[i];
semantic.descriptorSection.type = IPipelineMetadata::ShaderInput::ET_UNIFORM_BUFFER;
semantic.descriptorSection.uniformBufferObject.binding = ds1layout->getBindings().begin()[0].binding;
semantic.descriptorSection.uniformBufferObject.set = 1u;
semantic.descriptorSection.uniformBufferObject.relByteoffset = relOffsets[i];
semantic.descriptorSection.uniformBufferObject.bytesize = sizes[i];
semantic.descriptorSection.shaderAccessFlags = ICPUSpecializedShader::ESS_VERTEX;
}
}
pipelines[j] = core::make_smart_refctd_ptr<ICPURenderpassIndependentPipeline>(std::move(layout), nullptr, nullptr, vtxParams, blendParams, primParams, rasterParams);
pipelines[j]->setShaderAtIndex(ICPURenderpassIndependentPipeline::ESSI_VERTEX_SHADER_IX, shaders.first.get());
pipelines[j]->setShaderAtIndex(ICPURenderpassIndependentPipeline::ESSI_FRAGMENT_SHADER_IX, shaders.second.get());
m_assetMgr->setAssetMetadata(pipelines[j].get(), core::make_smart_refctd_ptr<CMTLPipelineMetadata>(materials[i].params, std::string(materials[i].name), nullptr, 0u, core::smart_refctd_ptr(shaderInputsMetadata)));
//uv
vtxParams.enabledAttribFlags |= (1u << UV);
vtxParams.attributes[UV].binding = BND_NUM;
vtxParams.attributes[UV].format = EF_R32G32_SFLOAT;
vtxParams.attributes[UV].relativeOffset = 12u;
layout = makePipelineLayoutFromMtl(ctx, materials[i], false);
shaders = getShaders(true);
core::smart_refctd_ptr<ICPUDescriptorSet> ds3;
{
const std::string dsCacheKey = std::string(fullName.c_str()) + "?" + materials[i].name + "?_ds";
if (_override)
{
const asset::IAsset::E_TYPE types[]{ asset::IAsset::ET_DESCRIPTOR_SET, (asset::IAsset::E_TYPE)0u };
auto ds_bundle = _override->findCachedAsset(dsCacheKey, types, ctx.inner, _hierarchyLevel + ICPUMesh::DESC_SET_HIERARCHYLEVELS_BELOW);
if (!ds_bundle.isEmpty())
{
ds3 = core::smart_refctd_ptr_static_cast<ICPUDescriptorSet>(ds_bundle.getContents().begin()[0]);
}
else
{
auto views = loadImages(relPath.c_str(), materials[i], ctx);
ds3 = makeDescSet(std::move(views), layout->getDescriptorSetLayout(3u));
if (ds3)
{
SAssetBundle bundle{ ds3 };
_override->insertAssetIntoCache(bundle, dsCacheKey, ctx.inner, _hierarchyLevel + ICPURenderpassIndependentPipeline::DESC_SET_HIERARCHYLEVELS_BELOW);
}
}
}
else
{
SAssetLoadParams assetloadparams;
auto default_imageview_bundle = m_assetMgr->getAsset("nbl/builtin/image_views/dummy2d", assetloadparams);
if (!default_imageview_bundle.isEmpty())
{
auto assetptr = core::smart_refctd_ptr_static_cast<ICPUImageView>(default_imageview_bundle.getContents().begin()[0]);
image_views_set_t views;
views[0] = assetptr;
ds3 = makeDescSet(std::move(views), layout->getDescriptorSetLayout(3u));
}
}
}
pipelines[j+1u] = core::make_smart_refctd_ptr<ICPURenderpassIndependentPipeline>(std::move(layout), nullptr, nullptr, vtxParams, blendParams, primParams, rasterParams);
pipelines[j+1u]->setShaderAtIndex(ICPURenderpassIndependentPipeline::ESSI_VERTEX_SHADER_IX, shaders.first.get());
pipelines[j+1u]->setShaderAtIndex(ICPURenderpassIndependentPipeline::ESSI_FRAGMENT_SHADER_IX, shaders.second.get());
m_assetMgr->setAssetMetadata(pipelines[j+1u].get(), core::make_smart_refctd_ptr<CMTLPipelineMetadata>(materials[i].params, std::move(materials[i].name), std::move(ds3), 1u, std::move(shaderInputsMetadata)));
}
materials.clear();
return asset::SAssetBundle(std::move(pipelines));
}
namespace
{
//! skip space characters and stop on first non-space
const char* goFirstWord(const char* buf, const char* const _bufEnd, bool acrossNewlines = true)
{
// skip space characters
if (acrossNewlines)
while ((buf != _bufEnd) && core::isspace(*buf))
++buf;
else
while ((buf != _bufEnd) && core::isspace(*buf) && (*buf != '\n'))
++buf;
return buf;
}
//! skip current word and stop at beginning of next one
const char* goNextWord(const char* buf, const char* const _bufEnd, bool acrossNewlines = true)
{
// skip current word
while ((buf != _bufEnd) && !core::isspace(*buf))
++buf;
return goFirstWord(buf, _bufEnd, acrossNewlines);
}
//! Read until line break is reached and stop at the next non-space character
const char* goNextLine(const char* buf, const char* const _bufEnd)
{
// look for newline characters
while (buf != _bufEnd)
{
// found it, so leave
if (*buf == '\n' || *buf == '\r')
break;
++buf;
}
return goFirstWord(buf, _bufEnd);
}
uint32_t copyWord(char* outBuf, const char* const inBuf, uint32_t outBufLength, const char* const _bufEnd)
{
if (!outBufLength)
return 0;
if (!inBuf)
{
*outBuf = 0;
return 0;
}
uint32_t i = 0;
while (inBuf[i])
{
if (core::isspace(inBuf[i]) || &(inBuf[i]) == _bufEnd)
break;
++i;
}
uint32_t length = core::min(i, outBufLength - 1u);
for (uint32_t j = 0u; j < length; ++j)
outBuf[j] = inBuf[j];
outBuf[length] = 0;
return length;
}
const char* goAndCopyNextWord(char* outBuf, const char* inBuf, uint32_t outBufLength, const char* _bufEnd)
{
inBuf = goNextWord(inBuf, _bufEnd, false);
copyWord(outBuf, inBuf, outBufLength, _bufEnd);
return inBuf;
}
}
const char* CGraphicsPipelineLoaderMTL::readTexture(const char* _bufPtr, const char* const _bufEnd, SMtl* _currMaterial, const char* _mapType) const
{
static const core::unordered_map<std::string, CMTLPipelineMetadata::E_MAP_TYPE> str2type =
{
{"Ka", CMTLPipelineMetadata::EMP_AMBIENT},
{"Kd", CMTLPipelineMetadata::EMP_DIFFUSE},
{"Ke", CMTLPipelineMetadata::EMP_EMISSIVE},
{"Ks", CMTLPipelineMetadata::EMP_SPECULAR},
{"Ns", CMTLPipelineMetadata::EMP_SHININESS},
{"d", CMTLPipelineMetadata::EMP_OPACITY},
{"bump", CMTLPipelineMetadata::EMP_BUMP},
{"disp", CMTLPipelineMetadata::EMP_DISPLACEMENT},
{"refl", CMTLPipelineMetadata::EMP_REFL_POSX},
{"norm", CMTLPipelineMetadata::EMP_NORMAL},
{"Pr", CMTLPipelineMetadata::EMP_ROUGHNESS},
{"Pm", CMTLPipelineMetadata::EMP_METALLIC},
{"Ps", CMTLPipelineMetadata::EMP_SHEEN}
};
static const core::unordered_map<std::string, CMTLPipelineMetadata::E_MAP_TYPE> refl_str2type =
{
{"top", CMTLPipelineMetadata::EMP_REFL_POSY},
{"bottom", CMTLPipelineMetadata::EMP_REFL_NEGY},
{"front", CMTLPipelineMetadata::EMP_REFL_NEGZ},
{"back", CMTLPipelineMetadata::EMP_REFL_POSZ},
{"left", CMTLPipelineMetadata::EMP_REFL_NEGX},
{"right", CMTLPipelineMetadata::EMP_REFL_POSX}
};
constexpr static size_t WORD_BUFFER_LENGTH = 512ull;
char tmpbuf[WORD_BUFFER_LENGTH]{};
std::string mapTypeStr = _mapType;
if (mapTypeStr.compare(0ull, 4ull, "map_")==0)
mapTypeStr.erase(0ull, 4ull);
CMTLPipelineMetadata::E_MAP_TYPE mapType = CMTLPipelineMetadata::EMP_COUNT;
auto found = str2type.find(mapTypeStr);
if (found != str2type.end())
mapType = found->second;
constexpr uint32_t ILLUM_MODEL_BITS = 4u;
_currMaterial->params.extra |= (1u << (ILLUM_MODEL_BITS + mapType));
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
while (tmpbuf[0]=='-')
{
if (mapType==CMTLPipelineMetadata::EMP_REFL_POSX && strncmp(tmpbuf, "-type", 5)==0)
{
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (strlen(tmpbuf) >= 8ull) //shortest one is "cube_top"
{
found = refl_str2type.find(tmpbuf+5); //skip "cube_"
if (found != refl_str2type.end())
mapType = found->second;
}
}
else if (strncmp(_bufPtr,"-bm",3)==0)
{
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
sscanf(tmpbuf, "%f", &_currMaterial->params.bumpFactor);
}
else
if (strncmp(_bufPtr,"-blendu",7)==0)
_bufPtr = goNextWord(_bufPtr, _bufEnd);
else
if (strncmp(_bufPtr,"-blendv",7)==0)
_bufPtr = goNextWord(_bufPtr, _bufEnd);
else
if (strncmp(_bufPtr,"-cc",3)==0)
_bufPtr = goNextWord(_bufPtr, _bufEnd);
else
if (strncmp(_bufPtr,"-clamp",6)==0)
{
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (mapType != CMTLPipelineMetadata::EMP_COUNT)
{
uint32_t clamp = (strcmp("off", tmpbuf) != 0);
_currMaterial->clamp |= (clamp<<mapType);
}
}
else
if (strncmp(_bufPtr,"-texres",7)==0)
_bufPtr = goNextWord(_bufPtr, _bufEnd);
else
if (strncmp(_bufPtr,"-type",5)==0)
_bufPtr = goNextWord(_bufPtr, _bufEnd);
else
if (strncmp(_bufPtr,"-mm",3)==0)
{
_bufPtr = goNextWord(_bufPtr, _bufEnd);
_bufPtr = goNextWord(_bufPtr, _bufEnd);
}
else
if (strncmp(_bufPtr,"-o",2)==0) // texture coord translation
{
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (!core::isdigit(tmpbuf[0]))
continue;
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (!core::isdigit(tmpbuf[0]))
continue;
}
else
if (strncmp(_bufPtr,"-s",2)==0) // texture coord scale
{
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (!core::isdigit(tmpbuf[0]))
continue;
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (!core::isdigit(tmpbuf[0]))
continue;
}
else
if (strncmp(_bufPtr,"-t",2)==0)
{
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
// next parameters are optional, so skip rest of loop if no number is found
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (!core::isdigit(tmpbuf[0]))
continue;
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
if (!core::isdigit(tmpbuf[0]))
continue;
}
// get next word
_bufPtr = goAndCopyNextWord(tmpbuf, _bufPtr, WORD_BUFFER_LENGTH, _bufEnd);
}
if (mapType != CMTLPipelineMetadata::EMP_COUNT)
{
std::string path = tmpbuf;
std::replace(path.begin(), path.end(), '\\', '/');
_currMaterial->maps[mapType] = std::move(path);
}
return _bufPtr;
}
std::pair<core::smart_refctd_ptr<ICPUSpecializedShader>, core::smart_refctd_ptr<ICPUSpecializedShader>> CGraphicsPipelineLoaderMTL::getShaders(bool _hasUV)
{
auto vs = getDefaultAsset<ICPUSpecializedShader, IAsset::ET_SPECIALIZED_SHADER>(_hasUV ? VERT_SHADER_UV_CACHE_KEY : VERT_SHADER_NO_UV_CACHE_KEY, m_assetMgr);
auto fs = getDefaultAsset<ICPUSpecializedShader, IAsset::ET_SPECIALIZED_SHADER>(_hasUV ? FRAG_SHADER_UV_CACHE_KEY : FRAG_SHADER_NO_UV_CACHE_KEY, m_assetMgr);
return { std::move(vs), std::move(fs) };
}
auto CGraphicsPipelineLoaderMTL::loadImages(const char* _relDir, const SMtl& _mtl, SContext& _ctx) -> image_views_set_t
{
images_set_t images;
image_views_set_t views;
std::string relDir = _relDir;
for (uint32_t i = 0u; i < images.size(); ++i)
{
SAssetLoadParams lp;
if (_mtl.maps[i].size() )
{
io::path output;
core::getFileNameExtension(output,_mtl.maps[i].c_str());
if (output == ".dds")
{
auto bundle = interm_getAssetInHierarchy(m_assetMgr, relDir + _mtl.maps[i], lp, _ctx.topHierarchyLevel + ICPURenderpassIndependentPipeline::IMAGE_HIERARCHYLEVELS_BELOW, _ctx.loaderOverride);
if (!bundle.isEmpty())
views[i] = core::smart_refctd_ptr_static_cast<ICPUImageView>(bundle.getContents().begin()[0]);
}else
{
auto bundle = interm_getAssetInHierarchy(m_assetMgr, relDir+_mtl.maps[i], lp, _ctx.topHierarchyLevel+ICPURenderpassIndependentPipeline::IMAGE_HIERARCHYLEVELS_BELOW, _ctx.loaderOverride);
if (!bundle.isEmpty())
images[i] = core::smart_refctd_ptr_static_cast<ICPUImage>(bundle.getContents().begin()[0]);
}
}
}
auto allCubemapFacesAreSameSizeAndFormat = [](const core::smart_refctd_ptr<ICPUImage>* _faces) {
const VkExtent3D sz = (*_faces)->getCreationParameters().extent;
const E_FORMAT fmt = (*_faces)->getCreationParameters().format;
for (uint32_t i = 1u; i < 6u; ++i)
{
const auto& img = _faces[i];
if (!img)
continue;
if (img->getCreationParameters().format != fmt)
return false;
const VkExtent3D sz_ = img->getCreationParameters().extent;
if (sz.width != sz_.width || sz.height != sz_.height || sz.depth != sz_.depth)
return false;
}
return true;
};
//make reflection cubemap
if (images[CMTLPipelineMetadata::EMP_REFL_POSX])
{
assert(allCubemapFacesAreSameSizeAndFormat(images.data() + CMTLPipelineMetadata::EMP_REFL_POSX));
size_t bufSz = 0ull;
//assuming all cubemap layer images are same size and same format
const size_t alignment = 1u<<core::findLSB(images[CMTLPipelineMetadata::EMP_REFL_POSX]->getRegions().begin()->bufferRowLength);
core::vector<ICPUImage::SBufferCopy> regions_;
regions_.reserve(6ull);
for (uint32_t i = CMTLPipelineMetadata::EMP_REFL_POSX; i < CMTLPipelineMetadata::EMP_REFL_POSX + 6u; ++i)
{
assert(images[i]);
#ifndef _NBL_DEBUG
if (images[i])
{
#endif
//assuming each image has just 1 region
assert(images[i]->getRegions().size()==1ull);
regions_.push_back(images[i]->getRegions().begin()[0]);
regions_.back().bufferOffset = core::roundUp(regions_.back().bufferOffset, alignment);
regions_.back().imageSubresource.baseArrayLayer = (i - CMTLPipelineMetadata::EMP_REFL_POSX);
bufSz += images[i]->getImageDataSizeInBytes();
#ifndef _NBL_DEBUG
}
#endif
}
auto imgDataBuf = core::make_smart_refctd_ptr<ICPUBuffer>(bufSz);
for (uint32_t i = CMTLPipelineMetadata::EMP_REFL_POSX, j = 0u; i < CMTLPipelineMetadata::EMP_REFL_POSX + 6u; ++i)
{
#ifndef _NBL_DEBUG
if (images[i])
{
#endif
void* dst = reinterpret_cast<uint8_t*>(imgDataBuf->getPointer()) + regions_[j].bufferOffset;
const void* src = reinterpret_cast<const uint8_t*>(images[i]->getBuffer()->getPointer()) + images[i]->getRegions().begin()[0].bufferOffset;
const size_t sz = images[i]->getImageDataSizeInBytes();
memcpy(dst, src, sz);
++j;
#ifndef _NBL_DEBUG
}
#endif
}
//assuming all cubemap layer images are same size and same format
ICPUImage::SCreationParams cubemapParams = images[CMTLPipelineMetadata::EMP_REFL_POSX]->getCreationParameters();
cubemapParams.arrayLayers = 6u;
cubemapParams.type = IImage::ET_2D;
auto cubemap = ICPUImage::create(std::move(cubemapParams));
auto regions = core::make_refctd_dynamic_array<core::smart_refctd_dynamic_array<ICPUImage::SBufferCopy>>(regions_);
cubemap->setBufferAndRegions(std::move(imgDataBuf), regions);
//new image goes to EMP_REFL_POSX index and other ones get nulled-out
images[CMTLPipelineMetadata::EMP_REFL_POSX] = std::move(cubemap);
for (uint32_t i = CMTLPipelineMetadata::EMP_REFL_POSX + 1u; i < CMTLPipelineMetadata::EMP_REFL_POSX + 6u; ++i)
{
images[i] = nullptr;
}
}
for (uint32_t i = 0u; i < views.size(); ++i)
{
if (!images[i])
continue;
const std::string viewCacheKey = _mtl.maps[i] + "?view";
if (auto view = getDefaultAsset<ICPUImageView,IAsset::ET_IMAGE_VIEW>(viewCacheKey.c_str(), m_assetMgr))
{
views[i] = std::move(view);
continue;
}
constexpr IImageView<ICPUImage>::E_TYPE viewType[2]{ IImageView<ICPUImage>::ET_2D, IImageView<ICPUImage>::ET_CUBE_MAP };
constexpr uint32_t layerCount[2]{ 1u, 6u };
const bool isCubemap = (i == CMTLPipelineMetadata::EMP_REFL_POSX);
ICPUImageView::SCreationParams viewParams;
viewParams.flags = static_cast<ICPUImageView::E_CREATE_FLAGS>(0u);
viewParams.format = images[i]->getCreationParameters().format;
viewParams.viewType = viewType[isCubemap];
viewParams.subresourceRange.baseArrayLayer = 0u;
viewParams.subresourceRange.layerCount = layerCount[isCubemap];
viewParams.subresourceRange.baseMipLevel = 0u;
viewParams.subresourceRange.levelCount = 1u;
viewParams.image = std::move(images[i]);
views[i] = ICPUImageView::create(std::move(viewParams));
SAssetBundle bundle{views[i]};
_ctx.loaderOverride->insertAssetIntoCache(bundle, viewCacheKey, _ctx.inner, _ctx.topHierarchyLevel+ICPURenderpassIndependentPipeline::IMAGEVIEW_HIERARCHYLEVELS_BELOW);
}
return views;
}
core::smart_refctd_ptr<ICPUDescriptorSet> CGraphicsPipelineLoaderMTL::makeDescSet(image_views_set_t&& _views, ICPUDescriptorSetLayout* _dsLayout)
{
if (!_dsLayout)
return nullptr;
auto ds = core::make_smart_refctd_ptr<asset::ICPUDescriptorSet>(
core::smart_refctd_ptr<ICPUDescriptorSetLayout>(_dsLayout)
);
auto dummy2d = getDefaultAsset<ICPUImageView, IAsset::ET_IMAGE_VIEW>("nbl/builtin/image_views/dummy2d", m_assetMgr);
for (uint32_t i = 0u; i <= CMTLPipelineMetadata::EMP_REFL_POSX; ++i)
{
auto desc = ds->getDescriptors(i).begin();
desc->desc = _views[i] ? std::move(_views[i]) : dummy2d;
desc->image.imageLayout = EIL_UNDEFINED;
desc->image.sampler = nullptr; //not needed, immutable (in DS layout) samplers are used
}
return ds;
}
auto CGraphicsPipelineLoaderMTL::readMaterials(io::IReadFile* _file) const -> core::vector<SMtl>
{
std::string mtl;
mtl.resize(_file->getSize());
_file->read(mtl.data(), _file->getSize());
const char* bufPtr = mtl.c_str();
const char* const bufEnd = mtl.c_str()+mtl.size();
constexpr static size_t WORD_BUFFER_LENGTH = 512ull;
char tmpbuf[WORD_BUFFER_LENGTH]{};
auto readFloat = [&tmpbuf, &bufPtr, bufEnd] {
float f = 0.f;
bufPtr = goAndCopyNextWord(tmpbuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
sscanf(tmpbuf, "%f", &f);
return f;
};
auto readRGB = [&readFloat] {
core::vector3df_SIMD rgb(1.f);
rgb.r = readFloat();
rgb.g = readFloat();
rgb.b = readFloat();
return rgb;
};
core::vector<SMtl> materials;
SMtl* currMaterial = nullptr;
while (bufPtr != bufEnd)
{
copyWord(tmpbuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
if (currMaterial && (strncmp("map_", tmpbuf, 4u)==0 || strcmp("refl", tmpbuf)==0 || strcmp("norm", tmpbuf)==0 || strcmp("bump", tmpbuf)==0 || strcmp("disp", tmpbuf)==0))
{
readTexture(bufPtr, bufEnd, currMaterial, tmpbuf);
}
switch (*bufPtr)
{
case 'n': // newmtl
{
materials.push_back({});
currMaterial = &materials.back();
// extract new material's name
bufPtr = goAndCopyNextWord(tmpbuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
currMaterial->name = tmpbuf;
}
break;
case 'a': // aniso, anisor
if (currMaterial)
{
if (bufPtr[5] == 'r')
currMaterial->params.anisoRotation = readFloat();
else
currMaterial->params.anisotropy = readFloat();
}
break;
case 'i': // illum - illumination
if (currMaterial)
{
bufPtr = goAndCopyNextWord(tmpbuf, bufPtr, WORD_BUFFER_LENGTH, bufEnd);
currMaterial->params.extra |= (atol(tmpbuf)&0x0f);//illum values are in range [0;10]
}
break;
case 'N':
if (currMaterial)
{
switch (bufPtr[1])
{
case 's': // Ns - shininess
currMaterial->params.shininess = readFloat();
break;
case 'i': // Ni - refraction index
currMaterial->params.IoR = readFloat();
break;
}
}
break;
case 'K':
if (currMaterial)
{
switch (bufPtr[1])
{
case 'd': // Kd = diffuse
currMaterial->params.diffuse = readRGB();
break;
case 's': // Ks = specular
currMaterial->params.specular = readRGB();
break;
case 'a': // Ka = ambience
currMaterial->params.ambient = readRGB();
break;
case 'e': // Ke = emissive
currMaterial->params.emissive = readRGB();
break;
} // end switch(bufPtr[1])
} // end case 'K': if (currMaterial)...
break;
case 'P':
if (currMaterial)
{
switch (bufPtr[1])
{
case 'r':
currMaterial->params.roughness = readFloat();
break;
case 'm':
currMaterial->params.metallic = readFloat();
break;
case 's':
currMaterial->params.sheen = readFloat();
break;
case 'c':
switch (bufPtr[2])
{
case 'r':
currMaterial->params.clearcoatRoughness = readFloat();
break;
case 0:
currMaterial->params.clearcoatThickness = readFloat();
break;
}
break;
}
}
break;
case 'd': // d - transparency
if (currMaterial)
currMaterial->params.opacity = readFloat();
break;
case 'T':
if (currMaterial)
{
switch (bufPtr[1])
{
case 'f': // Tf - Transmitivity
currMaterial->params.transmissionFilter = readRGB();
sprintf(tmpbuf, "%s, %s: Detected Tf parameter, it won't be used in generated shader - fallback to alpha=0.5 instead", _file->getFileName().c_str(), currMaterial->name.c_str());
os::Printer::log(tmpbuf, ELL_WARNING);
break;
case 'r': // Tr, transparency = 1.0-d
currMaterial->params.opacity = (1.f - readFloat());
break;
}
}
break;
default: // comments or not recognised
break;
} // end switch(bufPtr[0])
// go to next line
bufPtr = goNextLine(bufPtr, bufEnd);
} // end while (bufPtr)
return materials;
}
| 40.615466 | 224 | 0.638872 | [
"vector"
] |
04582bebd9cf4e43cecf400701497ffe6f2f6c8b | 1,580 | cc | C++ | third_party/blink/renderer/core/html/html_object_element_test.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/core/html/html_object_element_test.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/core/html/html_object_element_test.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/html/html_object_element.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/testing/dummy_page_holder.h"
namespace blink {
class HTMLObjectElementTest : public testing::Test {
protected:
void SetUp() final {
dummy_page_holder_ = DummyPageHolder::Create(IntSize(800, 600));
}
Document& GetDocument() { return dummy_page_holder_->GetDocument(); }
private:
std::unique_ptr<DummyPageHolder> dummy_page_holder_;
};
TEST_F(HTMLObjectElementTest, FallbackRecalcForReattach) {
GetDocument().body()->SetInnerHTMLFromString(R"HTML(
<object id='obj' data='dummy'></object>
)HTML");
HTMLObjectElement* object =
ToHTMLObjectElement(GetDocument().getElementById("obj"));
ASSERT_TRUE(object);
Node* slot = object->GetShadowRoot()->firstChild();
ASSERT_TRUE(slot);
GetDocument().View()->UpdateAllLifecyclePhases();
object->RenderFallbackContent();
GetDocument().Lifecycle().AdvanceTo(DocumentLifecycle::kInStyleRecalc);
GetDocument().documentElement()->RecalcStyle(kForce);
EXPECT_TRUE(IsHTMLSlotElement(slot));
EXPECT_TRUE(object->UseFallbackContent());
EXPECT_TRUE(object->GetNonAttachedStyle());
EXPECT_TRUE(slot->GetNonAttachedStyle());
}
} // namespace blink
| 31.6 | 73 | 0.759494 | [
"object"
] |
0460883041663ce763481aa1aa3c7007bff0bcf4 | 5,996 | cpp | C++ | sc-memory/sc-memory/sc_utils.cpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | null | null | null | sc-memory/sc-memory/sc_utils.cpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | null | null | null | sc-memory/sc-memory/sc_utils.cpp | kroschenko/sc-machine | 10a9535b3b9151ed683d351f2d222a95fc078e2b | [
"MIT"
] | null | null | null | /*
* This source file is part of an OSTIS project. For the latest info, see http://ostis.net
* Distributed under the MIT License
* (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT)
*/
#include "sc_utils.hpp"
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <sstream>
namespace utils
{
void StringUtils::ToLowerCase(std::string & str)
{
std::transform(
str.begin(),
str.end(),
str.begin(),
tolower);
}
//-----------------------------------------------------------------------
void StringUtils::ToUpperCase(std::string & str)
{
std::transform(
str.begin(),
str.end(),
str.begin(),
toupper);
}
bool StringUtils::StartsWith(std::string const & str, std::string const & pattern, bool lowerCase)
{
size_t thisLen = str.length();
size_t patternLen = pattern.length();
if (thisLen < patternLen || patternLen == 0)
return false;
std::string startOfThis = str.substr(0, patternLen);
if (lowerCase)
StringUtils::ToLowerCase(startOfThis);
return (startOfThis == pattern);
}
bool StringUtils::EndsWith(std::string const & str, std::string const & pattern, bool lowerCase)
{
size_t thisLen = str.length();
size_t patternLen = pattern.length();
if (thisLen < patternLen || patternLen == 0)
return false;
std::string endOfThis = str.substr(thisLen - patternLen, patternLen);
if (lowerCase)
StringUtils::ToLowerCase(endOfThis);
return (endOfThis == pattern);
}
std::string StringUtils::GetFileExtension(std::string const & filename)
{
// get file extension
std::string path = filename;
std::replace(path.begin(), path.end(), '\\', '/');
size_t start = path.find_last_of('/');
size_t n = path.find(".", start);
if (n == std::string::npos)
return {};
return path.substr(n + 1, std::string::npos);
}
void StringUtils::SplitFilename(std::string const & qualifiedName, std::string & outBasename, std::string & outPath)
{
std::string path = qualifiedName;
// Replace \ with / first
std::replace(path.begin(), path.end(), '\\', '/');
// split based on final /
size_t i = path.find_last_of('/');
if (i == std::string::npos)
{
outPath.clear();
outBasename = qualifiedName;
}
else
{
outBasename = path.substr(i + 1, path.size() - i - 1);
outPath = path.substr(0, i + 1);
}
}
void StringUtils::SplitString(std::string const & str, char delim, std::vector<std::string> & outList)
{
outList.clear();
std::istringstream ss(str);
std::string item;
while (std::getline(ss, item, delim))
outList.push_back(item);
}
std::string StringUtils::NormalizeFilePath(std::string const & init, bool makeLowerCase)
{
const char* bufferSrc = init.c_str();
int pathLen = (int)init.size();
int indexSrc = 0;
int indexDst = 0;
int metaPathArea = 0;
char reservedBuf[1024];
char* bufferDst = reservedBuf;
bool isDestAllocated = false;
if (pathLen > 1023)
{
//if source path is to long ensure we don't do a buffer overrun by allocating some
//new memory
isDestAllocated = true;
bufferDst = new char[pathLen + 1];
}
//The outer loop loops over directories
while (indexSrc < pathLen)
{
if ((bufferSrc[indexSrc] == '\\') || (bufferSrc[indexSrc] == '/'))
{
//check if we have a directory delimiter if so skip it (we should already
//have written such a delimiter by this point
++indexSrc;
continue;
}
else
{
//check if there is a directory to skip of type ".\"
if ((bufferSrc[indexSrc] == '.') &&
((bufferSrc[indexSrc + 1] == '\\') || (bufferSrc[indexSrc + 1] == '/')))
{
indexSrc += 2;
continue;
}
//check if there is a directory to skip of type "..\"
else if ((bufferSrc[indexSrc] == '.') && (bufferSrc[indexSrc + 1] == '.') &&
((bufferSrc[indexSrc + 2] == '\\') || (bufferSrc[indexSrc + 2] == '/')))
{
if (indexDst > metaPathArea)
{
//skip a directory backward in the destination path
do {
--indexDst;
} while ((indexDst > metaPathArea) && (bufferDst[indexDst - 1] != '/'));
indexSrc += 3;
continue;
}
else
{
//we are about to write "..\" to the destination buffer
//ensure we will not remove this in future "skip directories"
metaPathArea += 3;
}
}
}
//transfer the current directory name from the source to the destination
while (indexSrc < pathLen)
{
char curChar = bufferSrc[indexSrc];
if (makeLowerCase) curChar = tolower(curChar);
if ((curChar == '\\') || (curChar == '/')) curChar = '/';
bufferDst[indexDst] = curChar;
++indexDst;
++indexSrc;
if (curChar == '/') break;
}
}
bufferDst[indexDst] = 0;
std::string normalized(bufferDst);
if (isDestAllocated)
{
delete[] bufferDst;
}
return normalized;
}
std::string StringUtils::ReplaceAll(std::string const & source, std::string const & replaceWhat, std::string const & replaceWithWhat)
{
std::string result = source;
std::string::size_type pos = 0;
while (1)
{
pos = result.find(replaceWhat, pos);
if (pos == std::string::npos)
break;
result.replace(pos, replaceWhat.size(), replaceWithWhat);
pos += replaceWithWhat.size();
}
return result;
}
void StringUtils::TrimLeft(std::string & str)
{
if (str.empty())
return;
size_t i = 0;
while (i < str.size() && std::isspace(str[i]))
++i;
if (i < str.size())
str = str.substr(i);
else
str = "";
}
void StringUtils::TrimRight(std::string & str)
{
if (str.empty())
return;
size_t i = str.size() - 1;
while (i > 0 && std::isspace(str[i]))
--i;
if (i > 0)
str = str.substr(0, i + 1);
else
str = "";
}
void StringUtils::Trim(std::string & str)
{
TrimLeft(str);
TrimRight(str);
}
int Random::Int()
{
return std::rand();
}
} // namespace utils
| 24.080321 | 133 | 0.601234 | [
"vector",
"transform"
] |
0465112f7b6fa0ff6154710b98f4ad8733d7bab4 | 1,168 | cpp | C++ | test/container/data.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | test/container/data.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | test/container/data.cpp | vinzenz/fcppt | 3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/container/data.hpp>
#include <fcppt/container/data_end.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/test/unit_test.hpp>
#include <iterator>
#include <vector>
#include <fcppt/config/external_end.hpp>
FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)
BOOST_AUTO_TEST_CASE(
container_data
)
{
FCPPT_PP_POP_WARNING
typedef std::vector<
int
> int_vector;
int_vector container;
BOOST_CHECK(
fcppt::container::data(
container
)
==
nullptr
);
BOOST_CHECK(
fcppt::container::data_end(
container
)
==
nullptr
);
container.push_back(
1
);
container.push_back(
2
);
BOOST_CHECK_EQUAL(
std::distance(
fcppt::container::data(
container
),
fcppt::container::data_end(
container
)
),
2
);
}
| 16.685714 | 61 | 0.711473 | [
"vector"
] |
04680c9687b67c15a0de97591b87a82eded0834a | 1,151 | cc | C++ | cpp/leetcode/257.binary-tree-paths.cc | liubang/laboratory | 747f239a123cd0c2e5eeba893b9a4d1536555b1e | [
"MIT"
] | 3 | 2021-03-03T13:18:23.000Z | 2022-02-09T07:49:24.000Z | cpp/leetcode/257.binary-tree-paths.cc | liubang/laboratory | 747f239a123cd0c2e5eeba893b9a4d1536555b1e | [
"MIT"
] | null | null | null | cpp/leetcode/257.binary-tree-paths.cc | liubang/laboratory | 747f239a123cd0c2e5eeba893b9a4d1536555b1e | [
"MIT"
] | 1 | 2021-03-29T15:21:42.000Z | 2021-03-29T15:21:42.000Z | #include <gtest/gtest.h>
#include <string>
#include <vector>
#include "includes/tree.h"
namespace {
class Solution {
public:
using TreeNode = leetcode::tree::TreeNode;
std::vector<std::string> binaryTreePaths(TreeNode* root) {
std::vector<std::string> ret;
std::string cur;
dfs(&ret, cur, root);
return ret;
}
private:
void dfs(std::vector<std::string>* ret, std::string& cur, TreeNode* node) {
cur.append(std::to_string(node->val));
int size = cur.length();
if (!node->left && !node->right) {
ret->push_back(cur);
return;
}
if (node->left) {
cur.append("->");
dfs(ret, cur, node->left);
cur.erase(cur.begin() + size, cur.end());
}
if (node->right) {
cur.append("->");
dfs(ret, cur, node->right);
cur.erase(cur.begin() + size, cur.end());
}
}
};
} // namespace
TEST(Leetcode, binary_tree_paths) {
Solution s;
{
auto root = leetcode::tree::create({"11", "22", "23", "null", "59"});
std::vector<std::string> exp = {"11->22->59", "11->23"};
EXPECT_EQ(exp, s.binaryTreePaths(root));
leetcode::tree::destroy(root);
}
}
| 22.568627 | 77 | 0.577758 | [
"vector"
] |
04682ad530145472f2e3308d1b7f96db8ceee486 | 4,354 | hh | C++ | libsrc/pylith/topology/MeshOps.hh | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | null | null | null | libsrc/pylith/topology/MeshOps.hh | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | null | null | null | libsrc/pylith/topology/MeshOps.hh | Grant-Block/pylith | f6338261b17551eba879da998a5aaf2d91f5f658 | [
"MIT"
] | null | null | null | // -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ======================================================================
//
/**
* @file libsrc/topology/MeshOps.hh
*
* @brief Simple operations on a Mesh object.
*/
#if !defined(pylith_topology_meshops_hh)
#define pylith_topology_meshops_hh
#include "topologyfwd.hh" // forward declarations
#include "pylith/utils/petscfwd.h" // USES PetscDM
#include "pylith/utils/array.hh" // USES int_array
#include "spatialdata/geocoords/geocoordsfwd.hh"
#include "spatialdata/units/unitsfwd.hh"
class pylith::topology::MeshOps {
friend class TestMeshOps; // unit testing
// PUBLIC METHODS //////////////////////////////////////////////////////////////////////////////////////////////////
public:
/** Create subdomain mesh using label.
*
* @param[in] mesh Mesh for domain.
* @param[in] label Name of label marking subdomain.
* @param[in] labelValue Value of label marking subdomain.
* @param[in] descriptiveLabel Descriptive label for subdomain.
*
* @returns Mesh for subdomain.
*/
static
pylith::topology::Mesh* createSubdomainMesh(const pylith::topology::Mesh& mesh,
const char* label,
const int labelValue,
const char* descriptiveLabel);
/** Create lower dimension mesh using label.
*
* @param[in] mesh Mesh for domain.
* @param[in] label Label for vertices marking lower dimension domain.
*
* @returns Lower dimension mesh.
*/
static
pylith::topology::Mesh* createLowerDimMesh(const pylith::topology::Mesh& mesh,
const char* label);
/** Create 0-dimension mesh from points.
*
* @param[in] pointCoords Array of coordinates of points [numPoints*spaceDim].
* @param[in] numPoints Number of points.
* @param[in] cs Coordinate system for points.
* @param[in] lengthScale Length scale for nondimensionalization.
* @param[in] comm MPI communicator.
*/
static
pylith::topology::Mesh* createFromPoints(const PylithReal* points,
const size_t numPoints,
const spatialdata::geocoords::CoordSys* cs,
const PylithReal lengthScale,
MPI_Comm comm);
/** Nondimensionalize the finite-element mesh.
*
* @param mesh Finite-element mesh.
* @param normalizer Nondimensionalizer.
*/
static
void nondimensionalize(Mesh* const mesh,
const spatialdata::units::Nondimensional& normalizer);
/** Check topology of mesh.
*
* @param mesh Finite-element mesh.
*/
static
void checkTopology(const Mesh& mesh);
/** Determine is mesh contains simplex cells (i.e., line, tri, tet).
*
* @returns True if mesh contains simplex cells.
*/
static
bool isSimplexMesh(const Mesh& mesh);
static
bool isCohesiveCell(const PetscDM dmMesh,
const PetscInt cell);
/** Check to make sure material id of every cell matches the id of
* one of the materials.
*
* @param[in] mesh Finite-element mesh.
* @param[in] materialIds Array of ids for all materials and interior interfaces.
*/
static
void checkMaterialIds(const Mesh& mesh,
pylith::int_array& materialIds);
// NOT IMPLEMENTED /////////////////////////////////////////////////////////////////////////////////////////////////
private:
MeshOps(void); ///< Not Implemented
MeshOps(const MeshOps&); ///< Not implemented
const MeshOps& operator=(const MeshOps&); ///< Not implemented
}; // MeshOps
#endif // pylith_topology_meshops_hh
// End of file
| 32.984848 | 120 | 0.559486 | [
"mesh",
"object"
] |
04710b6932273c0edf2f630376cbf27546fbf812 | 10,904 | cpp | C++ | src/FunctorOps.cpp | hyunsukimsokcho/souffle | 3a60ce40455f38ded069d28de8405236b94529ed | [
"UPL-1.0"
] | null | null | null | src/FunctorOps.cpp | hyunsukimsokcho/souffle | 3a60ce40455f38ded069d28de8405236b94529ed | [
"UPL-1.0"
] | null | null | null | src/FunctorOps.cpp | hyunsukimsokcho/souffle | 3a60ce40455f38ded069d28de8405236b94529ed | [
"UPL-1.0"
] | null | null | null |
#include "FunctorOps.h"
#include "utility/FunctionalUtil.h"
#include "utility/MiscUtil.h"
#include <cassert>
#include <cctype>
#include <map>
#include <memory>
#include <ostream>
#include <utility>
#include <vector>
namespace souffle {
namespace {
char const* functorOpNameLegacy(FunctorOp op) {
switch (op) {
/** Unary Functor Operators */
case FunctorOp::ORD: return "ord";
case FunctorOp::STRLEN: return "strlen";
case FunctorOp::NEG:
case FunctorOp::FNEG: return "-";
case FunctorOp::BNOT:
case FunctorOp::UBNOT: return "bnot";
case FunctorOp::LNOT:
case FunctorOp::ULNOT: return "lnot";
case FunctorOp::I2F:
case FunctorOp::S2F:
case FunctorOp::U2F: return "to_float";
case FunctorOp::F2I:
case FunctorOp::S2I:
case FunctorOp::U2I: return "to_number";
case FunctorOp::I2S:
case FunctorOp::F2S:
case FunctorOp::U2S: return "to_string";
case FunctorOp::F2U:
case FunctorOp::I2U:
case FunctorOp::S2U: return "to_unsigned";
/** Binary Functor Operators */
case FunctorOp::ADD:
case FunctorOp::FADD:
case FunctorOp::UADD: return "+";
case FunctorOp::SUB:
case FunctorOp::USUB:
case FunctorOp::FSUB: return "-";
case FunctorOp::MUL:
case FunctorOp::UMUL:
case FunctorOp::FMUL: return "*";
case FunctorOp::DIV:
case FunctorOp::UDIV:
case FunctorOp::FDIV: return "/";
case FunctorOp::EXP:
case FunctorOp::FEXP:
case FunctorOp::UEXP: return "^";
case FunctorOp::MOD:
case FunctorOp::UMOD: return "%";
case FunctorOp::BAND:
case FunctorOp::UBAND: return "band";
case FunctorOp::BOR:
case FunctorOp::UBOR: return "bor";
case FunctorOp::BXOR:
case FunctorOp::UBXOR: return "bxor";
case FunctorOp::BSHIFT_L:
case FunctorOp::UBSHIFT_L: return "bshl";
case FunctorOp::BSHIFT_R:
case FunctorOp::UBSHIFT_R: return "bshr";
case FunctorOp::BSHIFT_R_UNSIGNED:
case FunctorOp::UBSHIFT_R_UNSIGNED: return "bshru";
case FunctorOp::LAND:
case FunctorOp::ULAND: return "land";
case FunctorOp::LOR:
case FunctorOp::ULOR: return "lor";
case FunctorOp::LXOR:
case FunctorOp::ULXOR: return "lxor";
case FunctorOp::RANGE:
case FunctorOp::URANGE:
case FunctorOp::FRANGE: return "range";
/* N-ary Functor Operators */
case FunctorOp::MAX:
case FunctorOp::UMAX:
case FunctorOp::FMAX:
case FunctorOp::SMAX: return "max";
case FunctorOp::MIN:
case FunctorOp::UMIN:
case FunctorOp::FMIN:
case FunctorOp::SMIN: return "min";
case FunctorOp::CAT: return "cat";
/** Ternary Functor Operators */
case FunctorOp::SUBSTR: return "substr";
}
UNREACHABLE_BAD_CASE_ANALYSIS
}
char const* functorOpNameSymbol(FunctorOp op) {
switch (op) {
/** Unary Functor Operators */
case FunctorOp::NEG:
case FunctorOp::FNEG: return FUNCTOR_INTRINSIC_PREFIX_NEGATE_NAME;
case FunctorOp::BNOT:
case FunctorOp::UBNOT: return "~";
case FunctorOp::LNOT:
case FunctorOp::ULNOT: return "!";
case FunctorOp::EXP:
case FunctorOp::FEXP:
case FunctorOp::UEXP: return "**";
case FunctorOp::BAND:
case FunctorOp::UBAND: return "&";
case FunctorOp::BOR:
case FunctorOp::UBOR: return "|";
case FunctorOp::BXOR:
case FunctorOp::UBXOR: return "^";
case FunctorOp::BSHIFT_L:
case FunctorOp::UBSHIFT_L: return "<<";
case FunctorOp::BSHIFT_R:
case FunctorOp::UBSHIFT_R: return ">>";
case FunctorOp::BSHIFT_R_UNSIGNED:
case FunctorOp::UBSHIFT_R_UNSIGNED: return ">>>";
case FunctorOp::LAND:
case FunctorOp::ULAND: return "&&";
case FunctorOp::LOR:
case FunctorOp::ULOR: return "||";
case FunctorOp::LXOR:
case FunctorOp::ULXOR: return "^^";
default: return functorOpNameLegacy(op);
}
}
using TAttr = TypeAttribute;
using FOp = FunctorOp;
#define OP_1(op, t0, tDst) \
{ functorOpNameSymbol(FOp::op), {TAttr::t0}, TAttr::tDst, FOp::op }
#define OP_2(op, t0, t1, tDst, multi) \
{ functorOpNameSymbol(FOp::op), {TAttr::t0, TAttr::t1}, TAttr::tDst, FOp::op, false, multi }
#define OP_3(op, t0, t1, t2, tDst, multi) \
{ functorOpNameSymbol(FOp::op), {TAttr::t0, TAttr::t1, TAttr::t2}, TAttr::tDst, FOp::op, false, multi }
#define OP_1_MONO(op, ty) OP_1(op, ty, ty)
#define OP_2_MONO(op, ty, multi) OP_2(op, ty, ty, ty, multi)
#define OP_3_MONO(op, ty, multi) OP_3(op, ty, ty, ty, ty, multi)
#define OP_1_INTEGRAL(op) OP_1_MONO(op, Signed), OP_1_MONO(U##op, Unsigned)
#define OP_2_INTEGRAL_EX(op, multi) OP_2_MONO(op, Signed, multi), OP_2_MONO(U##op, Unsigned, multi)
#define OP_3_INTEGRAL_EX(op, multi) OP_3_MONO(op, Signed, multi), OP_3_MONO(U##op, Unsigned, multi)
#define OP_2_INTEGRAL(op) OP_2_INTEGRAL_EX(op, false)
#define OP_2_NUMERIC(op) OP_2_MONO(F##op, Float, false), OP_2_INTEGRAL(op)
#define OP_2_NUMERIC_MULTI(op) OP_2_MONO(F##op, Float, true), OP_2_INTEGRAL_EX(op, true)
#define OP_3_NUMERIC_MULTI(op) OP_3_MONO(F##op, Float, true), OP_3_INTEGRAL_EX(op, true)
#define VARIADIC(op, ty) \
{ functorOpNameLegacy(FOp::op), {TAttr::ty}, TAttr::ty, FOp::op, true }
#define VARIADIC_ORDERED(op) \
VARIADIC(op, Signed), VARIADIC(U##op, Unsigned), VARIADIC(F##op, Float), VARIADIC(S##op, Symbol)
const std::vector<IntrinsicFunctor> FUNCTOR_INTRINSICS = {
{FUNCTOR_INTRINSIC_PREFIX_NEGATE_NAME, {TAttr::Signed}, TAttr::Signed, FunctorOp::NEG},
{FUNCTOR_INTRINSIC_PREFIX_NEGATE_NAME, {TAttr::Float}, TAttr::Float, FunctorOp::FNEG},
OP_1(F2I, Float, Signed),
OP_1(F2S, Float, Symbol),
OP_1(F2U, Float, Unsigned),
OP_1(I2F, Signed, Float),
OP_1(I2S, Signed, Symbol),
OP_1(I2U, Signed, Unsigned),
OP_1(S2F, Symbol, Float),
OP_1(S2I, Symbol, Signed),
OP_1(S2U, Symbol, Unsigned),
OP_1(U2F, Unsigned, Float),
OP_1(U2I, Unsigned, Signed),
OP_1(U2S, Unsigned, Symbol),
OP_2_NUMERIC(ADD),
OP_2_NUMERIC(SUB),
OP_2_NUMERIC(MUL),
OP_2_NUMERIC(DIV),
OP_2_INTEGRAL(MOD),
OP_2_NUMERIC(EXP),
OP_2_INTEGRAL(LAND),
OP_1_INTEGRAL(LNOT),
OP_2_INTEGRAL(LOR),
OP_2_INTEGRAL(LXOR),
OP_2_INTEGRAL(BAND),
OP_1_INTEGRAL(BNOT),
OP_2_INTEGRAL(BOR),
OP_2_INTEGRAL(BSHIFT_L),
OP_2_INTEGRAL(BSHIFT_R),
OP_2_INTEGRAL(BSHIFT_R_UNSIGNED),
OP_2_INTEGRAL(BXOR),
OP_2_NUMERIC_MULTI(RANGE),
OP_3_NUMERIC_MULTI(RANGE),
VARIADIC_ORDERED(MAX),
VARIADIC_ORDERED(MIN),
// `ord` is a weird functor that exposes the internal raw value of any type.
OP_1(ORD, Signed, Signed),
OP_1(ORD, Unsigned, Signed),
OP_1(ORD, Float, Signed),
OP_1(ORD, Symbol, Signed),
OP_1(ORD, Record, Signed),
VARIADIC(CAT, Symbol),
OP_1(STRLEN, Symbol, Signed),
OP_3(SUBSTR, Symbol, Signed, Signed, Symbol, false),
};
template <typename F>
IntrinsicFunctors pickFunctors(F&& f) {
IntrinsicFunctors xs;
for (auto&& x : FUNCTOR_INTRINSICS)
if (f(x)) xs.push_back(x);
return xs;
}
} // namespace
IntrinsicFunctors functorBuiltIn(FunctorOp op) {
return pickFunctors([&](auto&& x) { return x.op == op; });
}
IntrinsicFunctors functorBuiltIn(std::string_view symbol) {
return pickFunctors([&](auto&& x) { return x.symbol == symbol; });
}
IntrinsicFunctors functorBuiltIn(std::string_view symbol, const std::vector<TypeAttribute>& params) {
return pickFunctors([&](auto&& x) {
auto paramsOk =
x.variadic ? all_of(params, [&](auto t) { return t == x.params[0]; }) : x.params == params;
return x.symbol == symbol && paramsOk;
});
}
bool isValidFunctorOpArity(std::string_view symbol, size_t arity) {
return any_of(FUNCTOR_INTRINSICS, [&](auto&& x) {
auto arityOk = x.params.size() == arity || x.variadic;
return x.symbol == symbol && arityOk;
});
}
bool isFunctorMultiResult(FunctorOp op) {
auto&& xs = functorBuiltIn(op);
return xs.front().get().multipleResults;
}
bool isInfixFunctorOp(std::string_view symbol) {
assert(!symbol.empty() && "no functors have an empty name");
// arithmetic/bitwise/logical negation are prefix ops
if (symbol == FUNCTOR_INTRINSIC_PREFIX_NEGATE_NAME) return false;
if (symbol == "!") return false;
if (symbol == "~") return false;
auto alphaUnderscore = symbol == "_" || isalpha(symbol.at(0));
return !alphaUnderscore;
}
bool isInfixFunctorOp(const FunctorOp op) {
auto&& xs = functorBuiltIn(op);
return isInfixFunctorOp(xs.front().get().symbol);
}
FunctorOp getMinOp(const std::string& type) {
switch (type[0]) {
case 'f': return FunctorOp::FMIN;
case 'u': return FunctorOp::UMIN;
case 'i': return FunctorOp::MIN;
default: return FunctorOp::MIN;
}
}
FunctorOp getMaxOp(const std::string& type) {
switch (type[0]) {
case 'f': return FunctorOp::FMAX;
case 'u': return FunctorOp::UMAX;
case 'i': return FunctorOp::MAX;
default: return FunctorOp::MAX;
}
}
std::ostream& operator<<(std::ostream& os, FunctorOp op) {
return os << functorOpNameLegacy(op);
}
// must defined after `FUNCTOR_INTRINSICS` to ensure correct ctor ordering.
#ifndef NDEBUG
namespace {
struct FUNCTOR_INTRINSIC_SANCHECKER {
FUNCTOR_INTRINSIC_SANCHECKER() {
std::map<FunctorOp, IntrinsicFunctors> byOp;
for (auto&& x : FUNCTOR_INTRINSICS) {
byOp[x.op].push_back(x);
assert((!x.variadic || x.params.size() == 1) && "variadics must have a single parameter");
}
for (auto&& [_, xs] : byOp) {
auto&& multiResult = xs.front().get().multipleResults;
auto&& symbol = xs.front().get().symbol;
for (auto&& x : xs) {
// this can be relaxed but would require removing the `isFunctorMultiResult : FunctorOp`
// overload
assert(x.get().multipleResults == multiResult &&
"all overloads for op must have same `multipleResults`");
// this can be relaxed but would require removing the `isInfixFunctorOp : FunctorOp` overload
assert(x.get().symbol == symbol && "all overloads for op must have same `symbol`");
}
}
}
} FUNCTOR_INTRINSIC_SANCHECKER;
} // namespace
#endif
} // namespace souffle
| 34.289308 | 109 | 0.621056 | [
"vector"
] |
047c8c31f0788f4ef40287df528454a0e4ad5e86 | 7,879 | cpp | C++ | Game/Source/Cores/CharacterCore.cpp | wobbier/MitchGame | a7b4099e93b8775de1797a7351bb0159d31a88a2 | [
"MIT"
] | null | null | null | Game/Source/Cores/CharacterCore.cpp | wobbier/MitchGame | a7b4099e93b8775de1797a7351bb0159d31a88a2 | [
"MIT"
] | null | null | null | Game/Source/Cores/CharacterCore.cpp | wobbier/MitchGame | a7b4099e93b8775de1797a7351bb0159d31a88a2 | [
"MIT"
] | null | null | null | #include "CharacterCore.h"
#include "Components/Transform.h"
#include "Components/Camera.h"
#include "Engine/Input.h"
#include "Events/EventManager.h"
#include "optick.h"
#include "Components/Character.h"
#include "Components/Audio/AudioSource.h"
#include "Cores/AudioCore.h"
#include "Engine/Engine.h"
#include "Engine/World.h"
#include "Mathf.h"
#include "imgui.h"
#include "Components/Physics/CharacterController.h"
#include "CLog.h"
#include "Cores/PhysicsCore.h"
#include "Cores/SceneGraph.h"
#include "Components/Graphics/Model.h"
#include "Components/Physics/Rigidbody.h"
#include "Components/Graphics/Mesh.h"
#include "ECS/EntityHandle.h"
CharacterCore::CharacterCore()
: Base(ComponentFilter().Requires<Transform>().Requires<Character>().Requires<CharacterController>())
{
m_bluePortalShot = new AudioSource("Assets/Sounds/portalgun_shoot_blue1.wav");
m_orangePortalShot = new AudioSource("Assets/Sounds/portalgun_shoot_red1.wav");
m_invalidPortalSounds.reserve(4);
for (int i = 0; i < 4; ++i)
{
m_invalidPortalSounds.push_back(new AudioSource("Assets/Sounds/Gun/portal_invalid_surface_0" + std::to_string(i + 1) + ".wav"));
}
AudioCore* audioCore = static_cast<AudioCore*>(GetEngine().GetWorld().lock()->GetCore(AudioCore::GetTypeId()));
audioCore->InitComponent(*m_bluePortalShot);
audioCore->InitComponent(*m_orangePortalShot);
for (int i = 0; i < 4; ++i)
{
AudioSource* source = new AudioSource("Assets/Sounds/Gun/portal_invalid_surface_0" + std::to_string(i + 1) + ".wav");
m_invalidPortalSounds.push_back(source);
audioCore->InitComponent(*source);
}
}
void CharacterCore::Init()
{
}
void CharacterCore::OnEntityAdded(Entity& NewEntity)
{
if (m_camera)
{
BRUH("It looks like we already have one character.");
return;
}
m_playerTransform = &NewEntity.GetComponent<Transform>();
m_controller = &NewEntity.GetComponent<CharacterController>();
Transform* camera = m_playerTransform->GetChildByName("Camera");
if (!camera)
{
BRUH("Could not find child: 'Camera'");
return;
}
EntityHandle& cameraEnt = camera->Parent;
m_camera = &cameraEnt->GetComponent<Camera>();
m_cameraTransform = &cameraEnt->GetComponent<Transform>();
}
void CharacterCore::OnEntityRemoved(Entity& InEntity)
{
}
void CharacterCore::Update(float dt)
{
if (!m_camera)
{
return;
}
//HandlePortalShots();
HandleMouseLook(dt);
return;
}
#if ME_EDITOR
void CharacterCore::OnEditorInspect()
{
Base::OnEditorInspect();
ImGui::DragFloat("Movement Speed", &m_movementSpeed);
ImGui::DragFloat("Look Sensitivity", &LookSensitivity);
}
#endif
void CharacterCore::HandlePortalShots()
{
Input& input = GetEngine().GetInput();
bool isPrimaryFireDown = input.IsMouseButtonDown(MouseButton::Left);
if (isPrimaryFireDown && !m_prevPrimaryFireDown)
{
if (FirePortal(true))
{
m_bluePortalShot->Play(false);
}
else
{
m_invalidPortalSounds[random(0, m_invalidPortalSounds.size() - 1)]->Play();
}
}
m_prevPrimaryFireDown = isPrimaryFireDown;
bool isSecondaryFireDown = input.IsMouseButtonDown(MouseButton::Right);
if (isSecondaryFireDown && !m_prevSecondaryFireDown)
{
if (FirePortal(false))
{
m_orangePortalShot->Play(false);
}
else
{
m_invalidPortalSounds[random(0, m_invalidPortalSounds.size() - 1)]->Play();
}
}
m_prevSecondaryFireDown = isSecondaryFireDown;
}
void CharacterCore::HandleMouseLook(float dt)
{
Vector2 newPos = m_camera->OutputSize / 2.f;
Input& input = GetEngine().GetInput();
if (m_firstUpdate || input.IsKeyDown(KeyCode::R))
{
//GetEngine().GetInput().SetMousePosition(newPos);
//MousePosition = GetEngine().GetInput().GetMousePosition();
previousMousePos = input.GetMousePosition();
m_firstUpdate = false;
return;
}
Vector2 currentState = input.GetMousePosition();
float XOffset = ((currentState.x - previousMousePos.x) * LookSensitivity) * dt;
float YOffest = ((currentState.y - previousMousePos.y) * LookSensitivity) * dt;
previousMousePos = currentState;
float Yaw = m_camera->Yaw -= XOffset;
float Pitch = m_camera->Pitch += YOffest;
if (Pitch > 89.0f)
Pitch = 89.0f;
if (Pitch < -89.0f)
Pitch = -89.0f;
Vector3 Front;
Front.x = (cos(Mathf::Radians(Yaw - 90.0f)) * cos(Mathf::Radians(Pitch)));
Front.y = (sin(Mathf::Radians(Pitch)));
Front.z = (sin(Mathf::Radians(Yaw - 90.0f)) * cos(Mathf::Radians(Pitch)));
m_cameraTransform->SetRotation(Vector3(Pitch, 0.0f, 0.0f));
m_playerTransform->SetRotation(Vector3(0.0f, -Yaw, 0.0f));
if (input.IsKeyDown(KeyCode::W))
{
m_controller->Walk(Front.Cross(Vector3::Up).Cross(Vector3::Up).Normalized() * m_movementSpeed * dt);
}
if (input.IsKeyDown(KeyCode::S))
{
m_controller->Walk(Front.Cross(Vector3::Up).Cross(-Vector3::Up).Normalized() * m_movementSpeed * dt);
}
if (input.IsKeyDown(KeyCode::D))
{
m_controller->Walk(Front.Cross(Vector3::Up).Normalized() * m_movementSpeed * dt);
}
if (input.IsKeyDown(KeyCode::A))
{
m_controller->Walk(Front.Cross(-Vector3::Up).Normalized() * m_movementSpeed * dt);
}
if (input.IsKeyDown(KeyCode::Space))
{
m_controller->Jump();
}
//GetEngine().GetInput().SetMousePosition(newPos);
}
bool CharacterCore::FirePortal(bool IsBluePortal)
{
auto world = GetEngine().GetWorld().lock();
PhysicsCore* physics = static_cast<PhysicsCore*>(world->GetCore(PhysicsCore::GetTypeId()));
if (!physics)
{
return false;
}
std::vector<Vector3> directions = {
{1.f, 0.f, 0.f}, // right
{-1.f, 0.f, 0.f}, // left
{0.f, 1.f, 0.f}, // up
{0.f, -1.f, 0.f}, // down
};
std::vector<Vector3> directionsHit;
directionsHit.reserve(4);
bool canFitPortal = true;
RaycastHit ray;
if (physics->Raycast(m_cameraTransform->GetWorldPosition(), m_cameraTransform->GetWorldPosition() + m_cameraTransform->Front() * 20.0f, ray))
{
Transform& trans = ray.What->Parent->GetComponent<Transform>();
BRUH("HIT" + trans.GetName());
for (int i = 0; i < directions.size(); ++i)
{
Vector3 position = ray.Position + directions[i].Cross(ray.Normal).Normalized();
RaycastHit boundsRay;
canFitPortal = canFitPortal && (physics->Raycast(position + ray.Normal, position - ray.Normal * 20.0f, boundsRay));
directionsHit.push_back(boundsRay.Position);
}
}
else
{
canFitPortal = false;
}
if (canFitPortal)
{
//for (int i = 0; i < directionsHit.size(); ++i)
//{
// auto hitEnt = world->CreateEntity().lock();
// Transform& hitEntTransform = hitEnt->AddComponent<Transform>("PortalBounds");
// hitEntTransform.SetWorldPosition(directionsHit[i]);
// hitEntTransform.SetScale(0.1f);
// hitEnt->AddComponent<Model>("Assets/Cube.fbx");
//}
//{
// auto hitEnt = world->CreateEntity().lock();
// Transform& hitEntTransform = hitEnt->AddComponent<Transform>("PortalNormal");
// hitEntTransform.SetWorldPosition(ray.Position + ray.Normal);
// hitEntTransform.SetScale(0.1f);
// hitEnt->AddComponent<Model>("Assets/Cube.fbx");
//}
auto hitEnt = world->CreateEntity();
Transform& hitEntTransform = hitEnt->AddComponent<Transform>("Portal");
hitEntTransform.SetWorldPosition(ray.Position + (ray.Normal * .01f));
hitEntTransform.SetScale(Vector3(2.f, 2.5f, 0.01f));
if (ray.Normal.y >= 0.98f)
{
hitEntTransform.SetRotation(Vector3(90.f, m_playerTransform->GetWorldRotation().y, 0.f));
}
else
{
hitEntTransform.LookAt(ray.Normal);
}
//Portal& portal = hitEnt->AddComponent<Portal>(IsBluePortal ? Portal::PortalType::Blue : Portal::PortalType::Orange);
//portal.Observer = m_cameraTransform;
//Rigidbody& rigidbody = hitEnt->AddComponent<Rigidbody>();
//rigidbody.SetMass(0.f);
//PortalMaterial* mat = new PortalMaterial();
//Mesh& meshComp = hitEnt->AddComponent<Mesh>(Moonlight::MeshType::Plane, mat);
//meshComp.MeshMaterial->DiffuseColor = { 1.f, 1.f, 1.f };
}
return canFitPortal;
}
void CharacterCore::OnStart()
{
GetEngine().GetInput().SetMouseCapture(true);
}
| 28.139286 | 142 | 0.709989 | [
"mesh",
"vector",
"model",
"transform"
] |
0480a1796cc51f51eeae2045ba28d07a5b6b3b8b | 1,373 | cpp | C++ | graphs/lca_fast.cpp | prince776/CodeBook | 874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b | [
"CC0-1.0"
] | null | null | null | graphs/lca_fast.cpp | prince776/CodeBook | 874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b | [
"CC0-1.0"
] | null | null | null | graphs/lca_fast.cpp | prince776/CodeBook | 874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b | [
"CC0-1.0"
] | 1 | 2021-11-20T10:14:08.000Z | 2021-11-20T10:14:08.000Z | struct HLD_LCA {
using graph = std::vector<std::vector<int>>;
HLD_LCA(const graph &G, int root = 0)
: N((int)G.size()),
g(G),
par(N),
start(N),
depth(N),
sz(N),
in_time(N) {
par[root] = -1;
timer = 0;
dfs_sz(root);
start[root] = root;
dfs_hld(root);
}
bool is_anc(int u, int v) {
return in_time[u] <= in_time[v] && in_time[u] + sz[u] >= in_time[v];
}
void dfs_sz(int u) {
sz[u] = 1;
for (auto &v : g[u]) {
par[v] = u;
depth[v] = depth[u] + 1;
g[v].erase(find(begin(g[v]), end(g[v]), u));
dfs_sz(v);
sz[u] += sz[v];
if (sz[v] > sz[g[u][0]]) swap(v, g[u][0]);
}
}
void dfs_hld(int u) {
in_time[u] = timer++;
for (auto &v : g[u]) {
start[v] = (v == g[u][0] ? start[u] : v);
dfs_hld(v);
}
}
int lca(int u, int v) {
for (; start[u] != start[v]; v = par[start[v]])
if (depth[start[u]] > depth[start[v]]) swap(u, v);
return depth[u] < depth[v] ? u : v;
}
int dist(int u, int v) {
return depth[u] + depth[v] - 2 * depth[lca(u, v)];
}
int N;
graph g;
std::vector<int> par, start, depth, sz, in_time;
int timer;
};
| 24.963636 | 76 | 0.410779 | [
"vector"
] |
0481b6afb567de3314f3f06309710b355d646b78 | 11,159 | cpp | C++ | src/IECoreMaya/SceneShape.cpp | lucienfostier/cortex | b9916ee4c0392e41934df0e6d4e4b696c0e857ab | [
"BSD-3-Clause"
] | 1 | 2018-09-02T13:05:18.000Z | 2018-09-02T13:05:18.000Z | src/IECoreMaya/SceneShape.cpp | lucienfostier/cortex | b9916ee4c0392e41934df0e6d4e4b696c0e857ab | [
"BSD-3-Clause"
] | 1 | 2018-11-07T19:40:15.000Z | 2018-11-07T19:40:15.000Z | src/IECoreMaya/SceneShape.cpp | noizfactory/cortex | c2b5bd154d9d7919a0c498f865c5e40a7687e1ce | [
"BSD-3-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "IECoreScene/SharedSceneInterfaces.h"
#include "IECoreScene/LinkedScene.h"
#include "IECoreMaya/SceneShape.h"
#include "IECoreMaya/LiveScene.h"
#include "IECoreMaya/MayaTypeIds.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MFnStringData.h"
#include "maya/MPlugArray.h"
#include "maya/MFnDagNode.h"
#include "maya/MTime.h"
using namespace IECore;
using namespace IECoreScene;
using namespace IECoreMaya;
MTypeId SceneShape::id = SceneShapeId;
MObject SceneShape::aSceneFilePlug;
MObject SceneShape::aSceneRootPlug;
// registers this class in LiveScene
SceneShape::LiveSceneAddOn SceneShape::g_liveSceneAddon;
SceneShape::LiveSceneAddOn::LiveSceneAddOn()
{
LiveScene::registerCustomObject( SceneShape::hasSceneShapeObject, SceneShape::readSceneShapeObject );
LiveScene::registerCustomAttributes( SceneShape::sceneShapeAttributeNames, SceneShape::readSceneShapeAttribute );
LiveScene::registerCustomTags( SceneShape::hasTag, SceneShape::readTags );
}
SceneShape::SceneShape()
: m_sceneDirty( true )
{
}
SceneShape::~SceneShape()
{
}
void *SceneShape::creator()
{
return new SceneShape;
}
void SceneShape::postConstructor()
{
SceneShapeInterface::postConstructor();
setRenderable( true );
}
MStatus SceneShape::initialize()
{
MStatus s = inheritAttributesFrom( "ieSceneShapeInterface" );
MFnTypedAttribute tAttr;
// will need to check for sceneFile extensions
aSceneFilePlug = tAttr.create( "file", "scf", MFnData::kString, &s );
assert( s );
s = addAttribute( aSceneFilePlug );
assert( s );
aSceneRootPlug = tAttr.create( "root", "scr", MFnData::kString, MFnStringData().create( "/" ), &s );
assert( s );
s = addAttribute( aSceneRootPlug );
assert( s );
attributeAffects( aSceneFilePlug, aTransform );
attributeAffects( aSceneFilePlug, aBound );
attributeAffects( aSceneFilePlug, aOutputObjects );
attributeAffects( aSceneFilePlug, aAttributes );
attributeAffects( aSceneRootPlug, aTransform );
attributeAffects( aSceneRootPlug, aBound );
attributeAffects( aSceneRootPlug, aOutputObjects );
attributeAffects( aSceneRootPlug, aAttributes );
return s;
}
IECoreScene::ConstSceneInterfacePtr SceneShape::getSceneInterface()
{
if( !m_sceneDirty )
{
return m_scene;
}
MPlug pSceneFile( thisMObject(), aSceneFilePlug );
MString sceneFile;
pSceneFile.getValue( sceneFile );
MPlug pSceneRoot( thisMObject(), aSceneRootPlug );
MString sceneRoot;
pSceneRoot.getValue( sceneRoot );
try
{
m_scene = IECoreScene::SharedSceneInterfaces::get( sceneFile.asChar() );
IECoreScene::SceneInterface::Path rootPath;
IECoreScene::SceneInterface::stringToPath( sceneRoot.asChar(), rootPath );
m_scene = m_scene->scene( rootPath );
m_sceneDirty = false;
}
catch( std::exception &e )
{
m_scene = 0;
}
return m_scene;
}
MStatus SceneShape::setDependentsDirty( const MPlug &plug, MPlugArray &plugArray )
{
if( plug == aSceneFilePlug || plug == aSceneRootPlug )
{
m_sceneDirty = true;
setDirty();
childChanged( kBoundingBoxChanged );
}
return SceneShapeInterface::setDependentsDirty( plug, plugArray );
}
SceneShape *SceneShape::findScene( const MDagPath &p, bool noIntermediate, MDagPath *dagPath )
{
// Parse all children because numberOfShapesDirectlyBelow does not include intermediate shapes
unsigned int childCount = p.childCount();
for ( unsigned int c = 0; c < childCount; c++ )
{
MStatus st;
MObject childObject = p.child( c, &st );
if( st )
{
MFnDagNode fnChildDag(childObject);
MPxNode* userNode = fnChildDag.userNode();
if( userNode && userNode->typeId() == SceneShapeId )
{
if ( noIntermediate && fnChildDag.isIntermediateObject() )
{
continue;
}
SceneShape *sceneShape = dynamic_cast< SceneShape * >( userNode );
if ( !sceneShape )
{
throw Exception( "Could not get a pointer to SceneShape!");
}
if ( dagPath )
{
MDagPath childDag;
fnChildDag.getPath( childDag );
*dagPath = childDag;
}
return sceneShape;
}
}
}
return 0;
}
bool SceneShape::hasSceneShapeLink( const MDagPath &p )
{
MDagPath dagPath;
SceneShape *sceneShape = findScene( p, true, &dagPath );
if ( !sceneShape )
{
return false;
}
MFnDagNode fnChildDag( dagPath );
MStatus st;
MPlug objectOnlyPlug = fnChildDag.findPlug( aObjectOnly, &st );
if( !st )
{
throw Exception( "Could not find 'objectOnly' plug in SceneShape!");
}
// if we're doing objects only, we just output the object directly, so we don't need link attributes...
if( objectOnlyPlug.asBool() )
{
return false;
}
if ( !sceneShape->getSceneInterface() )
{
return false;
}
// so if it's not object only, then we know the scene loads everything and we can create a link to it.
return true;
}
ConstObjectPtr SceneShape::readSceneShapeLink( const MDagPath &p )
{
MDagPath dagPath;
SceneShape *sceneShape = findScene( p, true, &dagPath );
if ( !sceneShape )
{
throw Exception("readSceneShapeLink: Could not find SceneShape!");
}
ConstSceneInterfacePtr scene = sceneShape->getSceneInterface();
if ( !scene )
{
throw Exception( "Empty scene!");
}
MFnDagNode fnChildDag( dagPath );
MStatus st;
MPlug timePlug = fnChildDag.findPlug( aTime, &st );
if( !st )
{
throw Exception( "Could not find 'time' plug in SceneShape!");
}
// if time plug is connected to maya global time, then we assume there's no time remapping between the Maya scene and the loaded scene.
MPlugArray array;
timePlug.connectedTo( array, true, false, &st );
if( !st )
{
throw Exception( "Could not find 'time' plug connections in SceneShape!");
}
for ( unsigned int i = 0; i < array.length(); i++ )
{
if ( array[i].name() == "time1.outTime" )
{
/// connected to time, so no time remapping between maya scene and loaded scene.
return LinkedScene::linkAttributeData( scene.get() );
}
}
/// couldn't find connection to maya time, so this node is mapping the time some other way.
MTime time;
timePlug.getValue( time );
return LinkedScene::linkAttributeData( scene.get(), time.as( MTime::kSeconds ) );
}
void SceneShape::sceneShapeAttributeNames( const MDagPath &p, SceneInterface::NameList &attributeNames )
{
MDagPath dagPath;
SceneShape *sceneShape = findScene( p, false, &dagPath );
if ( !sceneShape )
{
return;
}
SceneInterface::NameList sceneAttrNames;
ConstSceneInterfacePtr scene = sceneShape->getSceneInterface();
if ( !scene )
{
return;
}
scene->attributeNames( sceneAttrNames );
attributeNames.insert( attributeNames.end(), sceneAttrNames.begin(), sceneAttrNames.end() );
MFnDagNode fnChildDag( dagPath );
if( !fnChildDag.isIntermediateObject() && hasSceneShapeLink( p ) )
{
attributeNames.push_back( LinkedScene::linkAttribute );
}
}
ConstObjectPtr SceneShape::readSceneShapeAttribute( const MDagPath &p, SceneInterface::Name attributeName )
{
MDagPath dagPath;
SceneShape *sceneShape = findScene( p, false, &dagPath );
if ( !sceneShape )
{
return nullptr;
}
MFnDagNode fnChildDag( dagPath );
if( attributeName == LinkedScene::linkAttribute )
{
if( !fnChildDag.isIntermediateObject() )
{
return readSceneShapeLink(p);
}
}
ConstSceneInterfacePtr scene = sceneShape->getSceneInterface();
if ( !scene )
{
return 0;
}
MPlug timePlug = fnChildDag.findPlug( aTime );
MTime time;
timePlug.getValue( time );
try
{
return scene->readAttribute( attributeName, time.as( MTime::kSeconds ) );
}
catch( ... )
{
return 0;
}
}
bool SceneShape::hasSceneShapeObject( const MDagPath &p )
{
MDagPath dagPath;
SceneShape *sceneShape = findScene( p, true, &dagPath );
if ( !sceneShape )
{
return false;
}
MFnDagNode fnChildDag( dagPath );
MStatus st;
MPlug objectOnlyPlug = fnChildDag.findPlug( aObjectOnly, &st );
if( !st )
{
throw Exception( "Could not find 'objectOnly' plug in SceneShape!");
}
// if we're rendering object and children than it should only be represented as a link to the scene and no objects.
if( !objectOnlyPlug.asBool() )
{
return false;
}
IECoreScene::ConstSceneInterfacePtr sceneInterface = sceneShape->getSceneInterface();
if( !sceneInterface )
{
return false;
}
return sceneInterface->hasObject();
}
ConstObjectPtr SceneShape::readSceneShapeObject( const MDagPath &p )
{
SceneShape *sceneShape = findScene( p, true );
if ( !sceneShape )
{
return 0;
}
MPlug pTime( sceneShape->thisMObject(), aTime );
MTime time;
pTime.getValue( time );
double t = time.as( MTime::kSeconds );
return sceneShape->getSceneInterface()->readObject( t );
}
bool SceneShape::hasTag( const MDagPath &p, const SceneInterface::Name &tag, int filter )
{
SceneShape *sceneShape = findScene( p, false );
if ( !sceneShape )
{
return false;
}
/// \todo Perhaps getSceneInterface() should return a raw pointer?
/// Also perhaps it shouldn't be prefixed with "get" since there is no
/// corresponding set.
const SceneInterface *scene = sceneShape->getSceneInterface().get();
if ( !scene )
{
return false;
}
return scene->hasTag( tag, filter );
}
void SceneShape::readTags( const MDagPath &p, SceneInterface::NameList &tags, int filter )
{
SceneShape *sceneShape = findScene( p, false );
if ( !sceneShape )
{
return;
}
const SceneInterface *scene = sceneShape->getSceneInterface().get();
if ( !scene )
{
return;
}
scene->readTags( tags, filter );
}
| 26.569048 | 136 | 0.710637 | [
"object"
] |
04823dbb31459ff1ce68858379651d58f4ee4239 | 7,510 | hpp | C++ | src/xercesc/validators/common/CMLeaf.hpp | rherardi/xerces-c-src_2_7_0 | a23711292bba70519940d7e6aeb07100319b607c | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-04-10T00:26:48.000Z | 2018-04-10T00:26:48.000Z | src/xercesc/validators/common/CMLeaf.hpp | rherardi/xerces-c-src_2_7_0 | a23711292bba70519940d7e6aeb07100319b607c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/xercesc/validators/common/CMLeaf.hpp | rherardi/xerces-c-src_2_7_0 | a23711292bba70519940d7e6aeb07100319b607c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright 1999-2001,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: CMLeaf.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#if !defined(CMLEAF_HPP)
#define CMLEAF_HPP
#include <xercesc/validators/common/CMNode.hpp>
XERCES_CPP_NAMESPACE_BEGIN
//
// This class represents a leaf in the content spec node tree of an
// element's content model. It just has an element qname and a position value,
// the latter of which is used during the building of a DFA.
//
class CMLeaf : public CMNode
{
public :
// -----------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------
CMLeaf
(
QName* const element
, const unsigned int position = (~0)
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
CMLeaf
(
QName* const element
, const unsigned int position
, const bool adopt
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
~CMLeaf();
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
QName* getElement();
const QName* getElement() const;
unsigned int getPosition() const;
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
void setPosition(const unsigned int newPosition);
// -----------------------------------------------------------------------
// Implementation of public CMNode virtual interface
// -----------------------------------------------------------------------
bool isNullable() const;
protected :
// -----------------------------------------------------------------------
// Implementation of protected CMNode virtual interface
// -----------------------------------------------------------------------
void calcFirstPos(CMStateSet& toSet) const;
void calcLastPos(CMStateSet& toSet) const;
private :
// -----------------------------------------------------------------------
// Private data members
//
// fElement
// This is the element that this leaf represents.
//
// fPosition
// Part of the algorithm to convert a regex directly to a DFA
// numbers each leaf sequentially. If its -1, that means its an
// epsilon node. All others are non-epsilon positions.
//
// fAdopt
// This node is responsible for the storage of the fElement QName.
// -----------------------------------------------------------------------
QName* fElement;
unsigned int fPosition;
bool fAdopt;
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
CMLeaf(const CMLeaf&);
CMLeaf& operator=(const CMLeaf&);
};
// -----------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------
inline CMLeaf::CMLeaf( QName* const element
, const unsigned int position
, MemoryManager* const manager) :
CMNode(ContentSpecNode::Leaf, manager)
, fElement(0)
, fPosition(position)
, fAdopt(false)
{
if (!element)
{
fElement = new (fMemoryManager) QName
(
XMLUni::fgZeroLenString
, XMLUni::fgZeroLenString
, XMLElementDecl::fgInvalidElemId
, fMemoryManager
);
// We have to be responsible for this QName - override default fAdopt
fAdopt = true;
}
else
{
fElement = element;
}
}
inline CMLeaf::CMLeaf( QName* const element
, const unsigned int position
, const bool adopt
, MemoryManager* const manager) :
CMNode(ContentSpecNode::Leaf, manager)
, fElement(0)
, fPosition(position)
, fAdopt(adopt)
{
if (!element)
{
fElement = new (fMemoryManager) QName
(
XMLUni::fgZeroLenString
, XMLUni::fgZeroLenString
, XMLElementDecl::fgInvalidElemId
, fMemoryManager
);
// We have to be responsible for this QName - override adopt parameter
fAdopt = true;
}
else
{
fElement = element;
}
}
inline CMLeaf::~CMLeaf()
{
if (fAdopt)
delete fElement;
}
// ---------------------------------------------------------------------------
// Getter methods
// ---------------------------------------------------------------------------
inline QName* CMLeaf::getElement()
{
return fElement;
}
inline const QName* CMLeaf::getElement() const
{
return fElement;
}
inline unsigned int CMLeaf::getPosition() const
{
return fPosition;
}
// ---------------------------------------------------------------------------
// Setter methods
// ---------------------------------------------------------------------------
inline void CMLeaf::setPosition(const unsigned int newPosition)
{
fPosition = newPosition;
}
// ---------------------------------------------------------------------------
// Implementation of public CMNode virtual interface
// ---------------------------------------------------------------------------
inline bool CMLeaf::isNullable() const
{
// Leaf nodes are never nullable unless its an epsilon node
return (fPosition == -1);
}
// ---------------------------------------------------------------------------
// Implementation of protected CMNode virtual interface
// ---------------------------------------------------------------------------
inline void CMLeaf::calcFirstPos(CMStateSet& toSet) const
{
// If we are an epsilon node, then the first pos is an empty set
if (fPosition == -1)
{
toSet.zeroBits();
return;
}
// Otherwise, its just the one bit of our position
toSet.setBit(fPosition);
}
inline void CMLeaf::calcLastPos(CMStateSet& toSet) const
{
// If we are an epsilon node, then the last pos is an empty set
if (fPosition == -1)
{
toSet.zeroBits();
return;
}
// Otherwise, its just the one bit of our position
toSet.setBit(fPosition);
}
XERCES_CPP_NAMESPACE_END
#endif
| 30.778689 | 80 | 0.447537 | [
"model"
] |
04878888e56904f1560aa84dea89569ef3bec993 | 6,343 | hpp | C++ | Common/src/Protocol.hpp | Rhoban/RhIO | 3420308a864cdc0e9cd33a051904bdc7d6fe5281 | [
"MIT"
] | 7 | 2015-10-04T08:23:45.000Z | 2021-05-22T09:59:45.000Z | Common/src/Protocol.hpp | Rhoban/RhIO | 3420308a864cdc0e9cd33a051904bdc7d6fe5281 | [
"MIT"
] | 4 | 2016-07-10T11:36:47.000Z | 2020-03-06T14:06:09.000Z | Common/src/Protocol.hpp | Rhoban/RhIO | 3420308a864cdc0e9cd33a051904bdc7d6fe5281 | [
"MIT"
] | 7 | 2016-07-15T06:08:14.000Z | 2019-09-20T17:25:45.000Z | #ifndef RHIO_PROTOCOL_HPP
#define RHIO_PROTOCOL_HPP
#include <vector>
#include <string>
namespace RhIO
{
/**
* Server replier and Server publisher port
*/
extern unsigned int ServersPortBase;
/**
* Protocol message type
*/
enum MsgType : uint8_t
{
/**
* Client.
* Ask for listing children Nodes.
* Args:
* String: absolute node name to inspect
*/
MsgAskChildren,
/**
* Client.
* Ask for listing values of type Bool,
* Int, Float or Str at given Node name.
* Args:
* String: absolute node name
*/
MsgAskValuesBool,
MsgAskValuesInt,
MsgAskValuesFloat,
MsgAskValuesStr,
/**
* Client.
* Ask for values of type Bool, Int,
* Float, Str
* Args:
* String: absolute value name
*/
MsgGetBool,
MsgGetInt,
MsgGetFloat,
MsgGetStr,
/**
* Client.
* Ask for values update for type
* Bool, Int, Float and Str
* Args:
* String: absolute value name to update
* Bool : new value
* or
* Int : new value
* or
* Float : new value
* or
* Str : new value
*/
MsgSetBool,
MsgSetInt,
MsgSetFloat,
MsgSetStr,
/**
* Client.
* Ask for value meta data for type
* Bool, Int, Float and Str
* Args:
* String: absolute value name to update
*/
MsgAskMetaBool,
MsgAskMetaInt,
MsgAskMetaFloat,
MsgAskMetaStr,
/**
* Client
* Ask for streaming enable and disable
* on given absolute value name (for any type).
* (Streaming watcher is incremented/decremented)
* Args:
* String: absolute value name
*/
MsgEnableStreamingValue,
MsgDisableStreamingValue,
/**
* Client
* Ask for streaming enable and disable
* on given absolute stream name (for any type).
* (Streaming watcher is incremented/decremented)
* Args:
* String: absolute stream name
*/
MsgEnableStreamingStream,
MsgDisableStreamingStream,
/**
* Client
* Ask for streaming enable and disable
* on given absolute frame name.
* (Streaming watcher is incremented/decremented)
* Args:
* String: absolute frame name
*/
MsgEnableStreamingFrame,
MsgDisableStreamingFrame,
/**
* Client.
* Ask for Server persist dump and load for all
* subtree below given node into given server
* side path directory
* Args:
* String: absolute node name
* String: configuration path server side
*/
MsgAskSave,
MsgAskLoad,
/**
* Client.
* List all registered command relative
* name at given node absolute name
* Args:
* String: absolute node name
*/
MsgAskCommands,
/**
* Client.
* Ask the description
* for absolute command name
* Args:
* String: absolute command name
*/
MsgAskCommandDescription,
/**
* Client.
* Ask for listing all commands
* alsolute name.
* Args:
* None
*/
MsgAskAllCommands,
/**
* Client.
* Call the given absolute name command
* with given string arguments list
* Args:
* String: absolute command name
* Int: number of argument
* String: argument 1
* String: argument 2
* ...
*/
MsgAskCall,
/**
* Client.
* List all registered streams relative
* name at given node absolute name
* Args:
* String: absolute node name
*/
MsgAskStreams,
/**
* Client.
* Ask given absolute stream name
* textual comment information
* Args:
* String: absolute stream name
*/
MsgAskDescriptionStream,
/**
* Client.
* List all registered frames relative
* name at given node absolute name
* Args:
* String: absolute node name
*/
MsgAskFrames,
/**
* Client.
* Ask given absolute frame name
* meta information
* Args:
* String: absolute frame name
*/
MsgAskMetaFrame,
/**
* Server.
* An error has occured.
* Args:
* String: error message.
*/
MsgError,
/**
* Server.
* Return all names of asked children
* or values (Bool, Int, Float or Str) of asked Node.
* Args:
* Int: number of values
* String: name 1
* String: name 2
* ...
*/
MsgListNames,
/**
* Server.
* Return the value of asked value
* for type Bool, Int, Float, Str
* Args:
* Bool: value
* or
* Int: value
* or
* Float: value
* or
* Str: value
*/
MsgValBool,
MsgValInt,
MsgValFloat,
MsgValStr,
/**
* Server.
* Acknowledge the requested set
* No arguments
*/
MsgSetOk,
/**
* Server.
* Return all asked value meta information
* for type Bool, Int, Float and Str
* Args:
* String: value comment
* Bool: has minimum
* Bool: has maximum
* Bool: is persisted
* Int: number of watcher for streaming
*
* Bool: minimum value
* Bool: maximum value
* Bool: persisted value
* or
* Int: minimum value
* Int: maximum value
* Int: persisted value
* or
* Float: minimum value
* Float: maximum value
* Float: persisted value
* or
* Str: minimum value
* Str: maximum value
* Str: persisted value
*/
MsgValMetaBool,
MsgValMetaInt,
MsgValMetaFloat,
MsgValMetaStr,
/**
* Server.
* Return streamed values for type
* Bool, Int, Float, Str, Stream or Frame
* Args:
* String: value absolute name
* Int: timestamp
* Bool: value
* or
* Int: value
* or
* Float: value
* or
* Str: value
* or
* Str: value
* or
* Int: size
* Int: image width
* Int: image height
* Data: image raw data
*/
MsgStreamBool,
MsgStreamInt,
MsgStreamFloat,
MsgStreamStr,
MsgStreamStream,
MsgStreamFrame,
/**
* Server.
* Return acknowledge when persist
* operation is finished
*/
MsgPersistOK,
/**
* Server.
* Return the string description
* of asked command
* Args:
* String: the coomand description
*/
MsgCommandDescription,
/**
* Server.
* Return call result of asked
* command call
* Args:
* String: call result
*/
MsgCallResult,
/**
* Server.
* Return description for asked
* stream
*/
MsgDescriptionStream,
/**
* Server.
* Return meta information
* for asked frame
* Args:
* String: frame comment
* Int: frame type
* Int: number of watcher for streaming
*/
MsgValMetaFrame,
/**
* Server.
* Acknowledge previous streaming
* config update
*/
MsgStreamingOK,
};
} // namespace RhIO
#endif
| 18.934328 | 55 | 0.622734 | [
"vector"
] |
048b5367f24a5eea5fbb25e35e7da59dfe921353 | 14,219 | cc | C++ | src/lib/dhcp_ddns/ncr_udp.cc | sebschrader/debian-pkg-isc-kea | 1bdb18f90c48dd9674374fb8454d0efb846656bc | [
"Apache-2.0"
] | null | null | null | src/lib/dhcp_ddns/ncr_udp.cc | sebschrader/debian-pkg-isc-kea | 1bdb18f90c48dd9674374fb8454d0efb846656bc | [
"Apache-2.0"
] | null | null | null | src/lib/dhcp_ddns/ncr_udp.cc | sebschrader/debian-pkg-isc-kea | 1bdb18f90c48dd9674374fb8454d0efb846656bc | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2013-2016 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <dhcp_ddns/dhcp_ddns_log.h>
#include <dhcp_ddns/ncr_udp.h>
#include <boost/bind.hpp>
namespace isc {
namespace dhcp_ddns {
//*************************** UDPCallback ***********************
UDPCallback::UDPCallback (RawBufferPtr& buffer, const size_t buf_size,
UDPEndpointPtr& data_source,
const UDPCompletionHandler& handler)
: handler_(handler), data_(new Data(buffer, buf_size, data_source)) {
if (handler.empty()) {
isc_throw(NcrUDPError, "UDPCallback - handler can't be null");
}
if (!buffer) {
isc_throw(NcrUDPError, "UDPCallback - buffer can't be null");
}
}
void
UDPCallback::operator ()(const boost::system::error_code error_code,
const size_t bytes_transferred) {
// Save the result state and number of bytes transferred.
setErrorCode(error_code);
setBytesTransferred(bytes_transferred);
// Invoke the NameChangeRequest layer completion handler.
// First argument is a boolean indicating success or failure.
// The second is a pointer to "this" callback object. By passing
// ourself in, we make all of the service related data available
// to the completion handler.
handler_(!error_code, this);
}
void
UDPCallback::putData(const uint8_t* src, size_t len) {
if (!src) {
isc_throw(NcrUDPError, "UDPCallback putData, data source is NULL");
}
if (len > data_->buf_size_) {
isc_throw(NcrUDPError, "UDPCallback putData, data length too large");
}
memcpy (data_->buffer_.get(), src, len);
data_->put_len_ = len;
}
//*************************** NameChangeUDPListener ***********************
NameChangeUDPListener::
NameChangeUDPListener(const isc::asiolink::IOAddress& ip_address,
const uint32_t port, const NameChangeFormat format,
RequestReceiveHandler& ncr_recv_handler,
const bool reuse_address)
: NameChangeListener(ncr_recv_handler), ip_address_(ip_address),
port_(port), format_(format), reuse_address_(reuse_address) {
// Instantiate the receive callback. This gets passed into each receive.
// Note that the callback constructor is passed an instance method
// pointer to our completion handler method, receiveCompletionHandler.
RawBufferPtr buffer(new uint8_t[RECV_BUF_MAX]);
UDPEndpointPtr data_source(new asiolink::UDPEndpoint());
recv_callback_.reset(new
UDPCallback(buffer, RECV_BUF_MAX, data_source,
boost::bind(&NameChangeUDPListener::
receiveCompletionHandler, this, _1, _2)));
}
NameChangeUDPListener::~NameChangeUDPListener() {
// Clean up.
stopListening();
}
void
NameChangeUDPListener::open(isc::asiolink::IOService& io_service) {
// create our endpoint and bind the the low level socket to it.
isc::asiolink::UDPEndpoint endpoint(ip_address_, port_);
// Create the low level socket.
try {
asio_socket_.reset(new boost::asio::ip::udp::
socket(io_service.get_io_service(),
(ip_address_.isV4() ? boost::asio::ip::udp::v4() :
boost::asio::ip::udp::v6())));
// Set the socket option to reuse addresses if it is enabled.
if (reuse_address_) {
asio_socket_->set_option(boost::asio::socket_base::reuse_address(true));
}
// Bind the low level socket to our endpoint.
asio_socket_->bind(endpoint.getASIOEndpoint());
} catch (boost::system::system_error& ex) {
asio_socket_.reset();
isc_throw (NcrUDPError, ex.code().message());
}
// Create the asiolink socket from the low level socket.
socket_.reset(new NameChangeUDPSocket(*asio_socket_));
}
void
NameChangeUDPListener::doReceive() {
// Call the socket's asychronous receiving, passing ourself in as callback.
RawBufferPtr recv_buffer = recv_callback_->getBuffer();
socket_->asyncReceive(recv_buffer.get(), recv_callback_->getBufferSize(),
0, recv_callback_->getDataSource().get(),
*recv_callback_);
}
void
NameChangeUDPListener::close() {
// Whether we think we are listening or not, make sure we aren't.
// Since we are managing our own socket, we need to close it ourselves.
// NOTE that if there is a pending receive, it will be canceled, which
// WILL generate an invocation of the callback with error code of
// "operation aborted".
if (asio_socket_) {
if (asio_socket_->is_open()) {
try {
asio_socket_->close();
} catch (boost::system::system_error& ex) {
// It is really unlikely that this will occur.
// If we do reopen later it will be with a new socket
// instance. Repackage exception as one that is conformant
// with the interface.
isc_throw (NcrUDPError, ex.code().message());
}
}
asio_socket_.reset();
}
socket_.reset();
}
void
NameChangeUDPListener::receiveCompletionHandler(const bool successful,
const UDPCallback *callback) {
NameChangeRequestPtr ncr;
Result result = SUCCESS;
if (successful) {
// Make an InputBuffer from our internal array
isc::util::InputBuffer input_buffer(callback->getData(),
callback->getBytesTransferred());
try {
ncr = NameChangeRequest::fromFormat(format_, input_buffer);
} catch (const NcrMessageError& ex) {
// log it and go back to listening
LOG_ERROR(dhcp_ddns_logger, DHCP_DDNS_INVALID_NCR).arg(ex.what());
// Queue up the next receive.
// NOTE: We must call the base class, NEVER doReceive
receiveNext();
return;
}
} else {
boost::system::error_code error_code = callback->getErrorCode();
if (error_code.value() == boost::asio::error::operation_aborted) {
// A shutdown cancels all outstanding reads. For this reason,
// it can be an expected event, so log it as a debug message.
LOG_DEBUG(dhcp_ddns_logger, DBGLVL_TRACE_BASIC,
DHCP_DDNS_NCR_UDP_RECV_CANCELED);
result = STOPPED;
} else {
LOG_ERROR(dhcp_ddns_logger, DHCP_DDNS_NCR_UDP_RECV_ERROR)
.arg(error_code.message());
result = ERROR;
}
}
// Call the application's registered request receive handler.
invokeRecvHandler(result, ncr);
}
//*************************** NameChangeUDPSender ***********************
NameChangeUDPSender::
NameChangeUDPSender(const isc::asiolink::IOAddress& ip_address,
const uint32_t port,
const isc::asiolink::IOAddress& server_address,
const uint32_t server_port, const NameChangeFormat format,
RequestSendHandler& ncr_send_handler,
const size_t send_que_max, const bool reuse_address)
: NameChangeSender(ncr_send_handler, send_que_max),
ip_address_(ip_address), port_(port), server_address_(server_address),
server_port_(server_port), format_(format),
reuse_address_(reuse_address) {
// Instantiate the send callback. This gets passed into each send.
// Note that the callback constructor is passed the an instance method
// pointer to our completion handler, sendCompletionHandler.
RawBufferPtr buffer(new uint8_t[SEND_BUF_MAX]);
UDPEndpointPtr data_source(new asiolink::UDPEndpoint());
send_callback_.reset(new UDPCallback(buffer, SEND_BUF_MAX, data_source,
boost::bind(&NameChangeUDPSender::
sendCompletionHandler, this,
_1, _2)));
}
NameChangeUDPSender::~NameChangeUDPSender() {
// Clean up.
stopSending();
}
void
NameChangeUDPSender::open(isc::asiolink::IOService& io_service) {
// create our endpoint and bind the the low level socket to it.
isc::asiolink::UDPEndpoint endpoint(ip_address_, port_);
// Create the low level socket.
try {
asio_socket_.reset(new boost::asio::ip::udp::
socket(io_service.get_io_service(),
(ip_address_.isV4() ? boost::asio::ip::udp::v4() :
boost::asio::ip::udp::v6())));
// Set the socket option to reuse addresses if it is enabled.
if (reuse_address_) {
asio_socket_->set_option(boost::asio::socket_base::reuse_address(true));
}
// Bind the low leve socket to our endpoint.
asio_socket_->bind(endpoint.getASIOEndpoint());
} catch (boost::system::system_error& ex) {
isc_throw (NcrUDPError, ex.code().message());
}
// Create the asiolink socket from the low level socket.
socket_.reset(new NameChangeUDPSocket(*asio_socket_));
// Create the server endpoint
server_endpoint_.reset(new isc::asiolink::
UDPEndpoint(server_address_, server_port_));
send_callback_->setDataSource(server_endpoint_);
closeWatchSocket();
watch_socket_.reset(new util::WatchSocket());
}
void
NameChangeUDPSender::close() {
// Whether we think we are sending or not, make sure we aren't.
// Since we are managing our own socket, we need to close it ourselves.
// NOTE that if there is a pending send, it will be canceled, which
// WILL generate an invocation of the callback with error code of
// "operation aborted".
if (asio_socket_) {
if (asio_socket_->is_open()) {
try {
asio_socket_->close();
} catch (boost::system::system_error& ex) {
// It is really unlikely that this will occur.
// If we do reopen later it will be with a new socket
// instance. Repackage exception as one that is conformant
// with the interface.
isc_throw (NcrUDPError, ex.code().message());
}
}
asio_socket_.reset();
}
socket_.reset();
closeWatchSocket();
watch_socket_.reset();
}
void
NameChangeUDPSender::doSend(NameChangeRequestPtr& ncr) {
// Now use the NCR to write JSON to an output buffer.
isc::util::OutputBuffer ncr_buffer(SEND_BUF_MAX);
ncr->toFormat(format_, ncr_buffer);
// Copy the wire-ized request to callback. This way we know after
// send completes what we sent (or attempted to send).
send_callback_->putData(static_cast<const uint8_t*>(ncr_buffer.getData()),
ncr_buffer.getLength());
// Call the socket's asychronous send, passing our callback
socket_->asyncSend(send_callback_->getData(), send_callback_->getPutLen(),
send_callback_->getDataSource().get(), *send_callback_);
// Set IO ready marker so sender activity is visible to select() or poll().
// Note, if this call throws it will manifest itself as a throw from
// from sendRequest() which the application calls directly and is documented
// as throwing exceptions; or caught inside invokeSendHandler() which
// will invoke the application's send_handler with an error status.
watch_socket_->markReady();
}
void
NameChangeUDPSender::sendCompletionHandler(const bool successful,
const UDPCallback *send_callback) {
// Clear the IO ready marker.
try {
watch_socket_->clearReady();
} catch (const std::exception& ex) {
// This can only happen if the WatchSocket's select_fd has been
// compromised which is a programmatic error. We'll log the error
// here, then continue on and process the IO result we were given.
// WatchSocket issue will resurface on the next send as a closed
// fd in markReady(). This allows application's handler to deal
// with watch errors more uniformly.
LOG_ERROR(dhcp_ddns_logger, DHCP_DDNS_NCR_UDP_CLEAR_READY_ERROR)
.arg(ex.what());
}
Result result;
if (successful) {
result = SUCCESS;
}
else {
// On a failure, log the error and set the result to ERROR.
boost::system::error_code error_code = send_callback->getErrorCode();
if (error_code.value() == boost::asio::error::operation_aborted) {
LOG_ERROR(dhcp_ddns_logger, DHCP_DDNS_NCR_UDP_SEND_CANCELED)
.arg(error_code.message());
result = STOPPED;
} else {
LOG_ERROR(dhcp_ddns_logger, DHCP_DDNS_NCR_UDP_SEND_ERROR)
.arg(error_code.message());
result = ERROR;
}
}
// Call the application's registered request send handler.
invokeSendHandler(result);
}
int
NameChangeUDPSender::getSelectFd() {
if (!amSending()) {
isc_throw(NotImplemented, "NameChangeUDPSender::getSelectFd"
" not in send mode");
}
return(watch_socket_->getSelectFd());
}
bool
NameChangeUDPSender::ioReady() {
if (watch_socket_) {
return (watch_socket_->isReady());
}
return (false);
}
void
NameChangeUDPSender::closeWatchSocket() {
if (watch_socket_) {
std::string error_string;
watch_socket_->closeSocket(error_string);
if (!error_string.empty()) {
LOG_ERROR(dhcp_ddns_logger, DHCP_DDNS_UDP_SENDER_WATCH_SOCKET_CLOSE_ERROR)
.arg(error_string);
}
}
}
}; // end of isc::dhcp_ddns namespace
}; // end of isc namespace
| 37.32021 | 86 | 0.622055 | [
"object"
] |
048ee84fa133f9b8063efaf46d010d9c7ce03312 | 224,723 | cpp | C++ | libraries/value/test/src/CachingStrategy_test.cpp | n-gineer/ELL | 2e5b93fe13993073a9486fc8720359ae4a49f737 | [
"MIT"
] | 2,094 | 2016-09-28T05:55:24.000Z | 2019-05-04T19:06:36.000Z | libraries/value/test/src/CachingStrategy_test.cpp | n-gineer/ELL | 2e5b93fe13993073a9486fc8720359ae4a49f737 | [
"MIT"
] | 213 | 2017-06-30T12:53:40.000Z | 2019-05-03T06:35:38.000Z | libraries/value/test/src/CachingStrategy_test.cpp | n-gineer/ELL | 2e5b93fe13993073a9486fc8720359ae4a49f737 | [
"MIT"
] | 301 | 2017-03-24T08:40:00.000Z | 2019-05-02T21:22:28.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: CachingStrategy_test.cpp (value)
// Authors: Mason Remy
//
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CachingStrategy_test.h"
#include "TestUtil.h"
#include <value/include/CachingStrategies.h>
#include <value/include/ComputeContext.h>
#include <value/include/EmitterContext.h>
#include <value/include/FunctionDeclaration.h>
#include <value/include/LLVMContext.h>
#include <value/include/LoopNests.h>
#include <value/include/Matrix.h>
#include <value/include/Scalar.h>
#include <value/include/Tensor.h>
#include <value/include/Value.h>
#include <value/include/Vector.h>
#include <value/include/loopnests/CodeGenerator.h>
#include <value/include/loopnests/Kernel.h>
#include <value/include/loopnests/LoopNest.h>
#include <value/include/loopnests/LoopNestPrinter.h>
#include <emitters/include/IRFunctionEmitter.h>
#include <math/include/Matrix.h>
#include <math/include/Tensor.h>
#include <math/include/Vector.h>
#include <utilities/include/FunctionUtils.h>
#include <utilities/include/Logger.h>
#include <testing/include/testing.h>
#include <deque>
#include <iomanip>
#include <iostream>
#include <queue>
#include <sstream>
#include <type_traits>
#include <unordered_map>
#include <vector>
using namespace ell::emitters;
using namespace ell::utilities;
using namespace ell::logging;
using namespace ell::value;
using namespace ell::value::loopnests;
namespace ell
{
// Tests of LoopNest caching strategies
Scalar BLASTCOPY_ValidateOutput_Test1()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int stripeSize = 4;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(N, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
// Test with smaller cache and stripe size than previous test
Scalar BLASTCOPY_ValidateOutput_Test2()
{
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input, expectedOutput
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(N, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
Scalar BLASTCOPY_ValidateMemory_Test1()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int stripeSize = 4;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCached =
{
0, 1, 2, 3,
8, 9, 10, 11,
16, 17, 18, 19,
24, 25, 26, 27,
32, 33, 34, 35,
40, 41, 42, 43,
48, 49, 50, 51,
56, 57, 58, 59,
4, 5, 6, 7,
12, 13, 14, 15,
20, 21, 22, 23,
28, 29, 30, 31,
36, 37, 38, 39,
44, 45, 46, 47,
52, 53, 54, 55,
60, 61, 62, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
// Examine the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
rawCacheValue.SetLayout({ { (int)rawCacheValue.GetLayout().GetMemorySize() } });
auto cacheVector = Vector(rawCacheValue);
return VerifySame(cacheVector, expectedCached);
}
// Smaller stripe size than previous test
Scalar BLASTCOPY_ValidateMemory_Test2()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCached =
{
0, 1,
8, 9,
16, 17,
24, 25,
32, 33,
40, 41,
48, 49,
56, 57,
2, 3,
10, 11,
18, 19,
26, 27,
34, 35,
42, 43,
50, 51,
58, 59,
4, 5,
12, 13,
20, 21,
28, 29,
36, 37,
44, 45,
52, 53,
60, 61,
6, 7,
14, 15,
22, 23,
30, 31,
38, 39,
46, 47,
54, 55,
62, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
// Examine the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
rawCacheValue.SetLayout({ { (int)rawCacheValue.GetLayout().GetMemorySize() } });
auto cacheVector = Vector(rawCacheValue);
return VerifySame(cacheVector, expectedCached);
}
// Same stripe size as previous test, but don't cache entire matrix at once
Scalar BLASTCOPY_ValidateMemory_Test3()
{
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
8, 9,
16, 17,
24, 25,
2, 3,
10, 11,
18, 19,
26, 27,
};
Vector expectedCachedUpperRight =
{
4, 5,
12, 13,
20, 21,
28, 29,
6, 7,
14, 15,
22, 23,
30, 31
};
Vector expectedCachedLowerLeft =
{
32, 33,
40, 41,
48, 49,
56, 57,
34, 35,
42, 43,
50, 51,
58, 59,
};
Vector expectedCachedLowerRight =
{
36, 37,
44, 45,
52, 53,
60, 61,
38, 39,
46, 47,
54, 55,
62, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto topLevelI = i;
auto topLevelJ = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight, cachedLowerLeft, cachedLowerRight)
.Indices(topLevelI, topLevelJ)
.Define([cacheRows, cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Vector cachedLowerLeft, Vector cachedLowerRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
}).ElseIf(j == cacheCols, [&]() {
cachedLowerRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Right:");
DebugPrintVector(cachedLowerRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
If(VerifySame(cachedLowerRight, expectedCachedLowerRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(int M, int N, int cacheRows, int cacheCols, int stripeSize)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(M, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
// input matrix rows evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test1()
{
int M = 8;
int N = 7; // N doesn't evenly divide the number of cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols but does evenly divide stripeSize
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test2()
{
int M = 8;
int N = 6; // N doesn't evenly divide the number of cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test3()
{
int M = 6;
int N = 7; // N doesn't evenly divide the number of cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols but does evenly divide stripe size
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test4()
{
int M = 6;
int N = 6; // N doesn't evenly divide the number of cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, doesn't evenly divide stripe size
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test5()
{
int M = 8;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, evenly divides stripe size
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test6()
{
int M = 8;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, doesn't evenly divides stripe size
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test7()
{
int M = 3;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, does evenly divides stripe size
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test8()
{
int M = 2;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows < cache rows
// input matrix cols multiple of cache cols
Scalar BLASTCOPY_ValidateOutput_BoundaryCondition_Test9()
{
int M = 2;
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedUpperRight, Vector expectedCachedLowerLeft, Vector expectedCachedLowerRight)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto topLevelI = i;
auto topLevelJ = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight, cachedLowerLeft, cachedLowerRight)
.Indices(topLevelI, topLevelJ)
.Define([cacheRows, cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Vector cachedLowerLeft, Vector cachedLowerRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
}).ElseIf(j == cacheCols, [&]() {
cachedLowerRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Right:");
DebugPrintVector(cachedLowerRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
If(VerifySame(cachedLowerRight, expectedCachedLowerRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedLowerLeft)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto topLevelI = i;
auto topLevelJ = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
// No right caches when N < cacheCols
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedLowerLeft)
.Indices(topLevelI, topLevelJ)
.Define([cacheRows](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedLowerLeft, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedUpperRight)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto topLevelI = i;
auto topLevelJ = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight)
.Indices(topLevelI, topLevelJ)
.Define([cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto topLevelI = i;
auto topLevelJ = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
BLASTCopy cachingProvider{};
std::tuple<int, Index, BoundaryConditionHandling> blasTCopyExtras = { stripeSize, jStripe, BoundaryConditionHandling::ZeroPadding };
schedule.Cache(cachingProvider,
input,
{ i, j },
{ cacheRows, cacheCols },
{ iCache, jCache },
std::nullopt, // Order isn't used by BLASTCopy
blasTCopyExtras);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
// No right caches when N < cacheCols
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft)
.Indices(topLevelI, topLevelJ)
.Define([](Value rawCacheValue, Vector cachedUpperLeft, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(cachedUpperLeft, expectedCachedUpperLeft);
}
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test1()
{
int M = 8; // M does evenly divide cache rows
int N = 7; // N doesn't evenly divide cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
7, 8,
14, 15,
21, 22,
2, 3,
9, 10,
16, 17,
23, 24,
};
Vector expectedCachedUpperRight =
{
4, 5,
11, 12,
18, 19,
25, 26,
6, 0,
13, 0,
20, 0,
27, 0
};
Vector expectedCachedLowerLeft =
{
28, 29,
35, 36,
42, 43,
49, 50,
30, 31,
37, 38,
44, 45,
51, 52,
};
Vector expectedCachedLowerRight =
{
32, 33,
39, 40,
46, 47,
53, 54,
34, 0,
41, 0,
48, 0,
55, 0
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test2()
{
int M = 8; // M does evenly divide cache rows
int N = 6; // N doesn't evenly divide cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
// input
// A:
// [ 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, 26, 27, 28, 29],
// [30, 31, 32, 33, 34, 35],
// [36, 37, 38, 39, 40, 41],
// [42, 43, 44, 45, 46, 47]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
6, 7,
12, 13,
18, 19,
2, 3,
8, 9,
14, 15,
20, 21,
};
Vector expectedCachedUpperRight =
{
4, 5,
10, 11,
16, 17,
22, 23,
0, 0,
0, 0,
0, 0,
0, 0
};
Vector expectedCachedLowerLeft =
{
24, 25,
30, 31,
36, 37,
42, 43,
26, 27,
32, 33,
38, 39,
44, 45,
};
Vector expectedCachedLowerRight =
{
28, 29,
34, 35,
40, 41,
46, 47,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test3()
{
int M = 6;
int N = 7; // N doesn't evenly divide the number of cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 26, 27],
// [28, 29, 30, 31, 32, 33, 34],
// [35, 36, 37, 38, 39, 40, 41],
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
7, 8,
14, 15,
21, 22,
2, 3,
9, 10,
16, 17,
23, 24,
};
Vector expectedCachedUpperRight =
{
4, 5,
11, 12,
18, 19,
25, 26,
6, 0,
13, 0,
20, 0,
27, 0
};
// Check that it gets reviewed correctly to keep the cached data contiguous
Vector expectedCachedLowerLeft =
{
28, 29,
35, 36,
30, 31,
37, 38,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedLowerRight =
{
32, 33,
39, 40,
34, 0,
41, 0,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols but does evenly divide stripe size
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test4()
{
int M = 6;
int N = 6; // N doesn't evenly divide the number of cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 26, 27, 28, 29],
// [30, 31, 32, 33, 34, 35]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
6, 7,
12, 13,
18, 19,
2, 3,
8, 9,
14, 15,
20, 21,
};
Vector expectedCachedUpperRight =
{
4, 5,
10, 11,
16, 17,
22, 23,
0, 0,
0, 0,
0, 0,
0, 0
};
Vector expectedCachedLowerLeft =
{
24, 25,
30, 31,
26, 27,
32, 33,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedLowerRight =
{
28, 29,
34, 35,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, doesn't evenly divide stripe size
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test5()
{
int M = 8;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1, 2],
// [ 3, 4, 5],
// [ 6, 7, 8],
// [ 9, 10, 11],
// [12, 13, 14],
// [15, 16, 17],
// [18, 19, 20],
// [21, 22, 23]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
3, 4,
6, 7,
9, 10,
2, 0,
5, 0,
8, 0,
11, 0,
};
Vector expectedCachedLowerLeft =
{
12, 13,
15, 16,
18, 19,
21, 22,
14, 0,
17, 0,
20, 0,
23, 0,
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedLowerLeft);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, evenly divides stripe size
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test6()
{
int M = 8;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1],
// [ 2, 3],
// [ 4, 5],
// [ 6, 7],
// [ 8, 9],
// [10, 11],
// [12, 13],
// [14, 15]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
2, 3,
4, 5,
6, 7,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedLowerLeft =
{
8, 9,
10, 11,
12, 13,
14, 15,
0, 0,
0, 0,
0, 0,
0, 0,
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedLowerLeft);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, doesn't evenly divides stripe size
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test7()
{
int M = 3;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [0, 1, 2],
// [3, 4, 5],
// [6, 7, 8]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
3, 4,
6, 7,
2, 0,
5, 0,
8, 0,
0, 0,
0, 0
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, does evenly divides stripe size
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test8()
{
int M = 2;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1],
// [ 2, 3]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
2, 3,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft);
}
// input matrix rows < cache rows
// input matrix cols multiple of cache cols
Scalar BLASTCOPY_ValidateMemory_BoundaryCondition_Test9()
{
int M = 2;
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1, 2, 3, 4, 5, 6, 7],
// [ 8, 9, 10, 11, 12, 13, 14, 15]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
8, 9,
2, 3,
10, 11,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedUpperRight =
{
4, 5,
12, 13,
6, 7,
14, 15,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight);
}
// Convolution caching tests
// General Caching Strategy
Scalar GeneralCachingStrategy_ValidateOutput_Test1()
{
// Square matrix tiling
loopnests::Index i("i"), j("j");
const int Rows = 8;
const int Columns = 8;
const int SplitSize = 4;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, SplitSize);
auto jBlock = schedule.Split(j, SplitSize);
std::vector<Index> orderedIndices = { iBlock, jBlock, i, j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = SplitSize * SplitSize;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateMemory_Test1()
{
// Square matrix tiling
loopnests::Index i("i"), j("j");
const int Rows = 8;
const int Columns = 8;
const int SplitSize = 4;
// input
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1, 2, 3,
8, 9, 10, 11,
16, 17, 18, 19,
24, 25, 26, 27
};
Vector expectedCachedLowerLeft =
{
32, 33, 34, 35,
40, 41, 42, 43,
48, 49, 50, 51,
56, 57, 58, 59
};
Vector expectedCachedUpperRight =
{
4, 5, 6, 7,
12, 13, 14, 15,
20, 21, 22, 23,
28, 29, 30, 31
};
Vector expectedCachedLowerRight =
{
36, 37, 38, 39,
44, 45, 46, 47,
52, 53, 54, 55,
60, 61, 62, 63
};
// clang-format on
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, SplitSize);
auto jBlock = schedule.Split(j, SplitSize);
schedule.SetOrder({ iBlock, jBlock, i, j });
GeneralCachingStrategy cachingProvider{};
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = SplitSize * SplitSize;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight, cachedLowerLeft, cachedLowerRight)
.Indices(iTopLevel, jTopLevel)
.Define([=](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Vector cachedLowerLeft, Vector cachedLowerRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == SplitSize,
[&]() {
cachedUpperRight = vectorCacheView;
});
})
.ElseIf(i == SplitSize,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
}).ElseIf(j == SplitSize, [&]() {
cachedLowerRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::epilogue, { iBlock, jBlock }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Right:");
DebugPrintVector(cachedLowerRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
If(VerifySame(cachedLowerRight, expectedCachedLowerRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_ValidateOutput_Test2()
{
// BLASTCopy caching
loopnests::Index i("i"), j("j");
const int Rows = 16;
const int Columns = 16;
const int InputCacheRows = 8;
const int InputCacheCols = 8;
const int StripeSize = 4;
const int VecSize = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto jBlock = schedule.Split(j, InputCacheCols);
auto jStripe = schedule.Split(j, StripeSize);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jStripe,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test3()
{
// Progressive BLASTCopy caching
loopnests::Index i("i"), j("j");
const int Rows = 16;
const int Columns = 16;
const int InputCacheRows = 8;
const int InputCacheCols = 8;
const int StripeSize = 4;
const int VecSize = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto jBlock = schedule.Split(j, InputCacheCols);
auto jStripe = schedule.Split(j, StripeSize);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jStripe,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = InputCacheRows * StripeSize;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test4()
{
// BLASTCopy caching with boundary condition on rows
loopnests::Index i("i"), j("j");
const int Rows = 15;
const int Columns = 16;
const int InputCacheRows = 8;
const int InputCacheCols = 8;
const int StripeSize = 4;
const int VecSize = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto jBlock = schedule.Split(j, InputCacheCols);
auto jStripe = schedule.Split(j, StripeSize);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jStripe,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test5()
{
// Square output cache
loopnests::Index i("i"), j("j");
const int Rows = 8;
const int Columns = 8;
const int OutputCacheRows = 2;
const int OutputCacheCols = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iOutput = schedule.Split(i, OutputCacheRows);
auto jOutput = schedule.Split(j, OutputCacheCols);
std::vector<Index> orderedIndices = { iOutput, jOutput, i, j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Output;
std::string cacheName = "cacheOutput";
size_t maxCacheElts = OutputCacheRows * OutputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test6()
{
// Rectangular output cache
loopnests::Index i("i"), j("j");
const int Rows = 8;
const int Columns = 8;
const int OutputCacheRows = 4;
const int OutputCacheCols = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iOutput = schedule.Split(i, OutputCacheRows);
auto jOutput = schedule.Split(j, OutputCacheCols);
std::vector<Index> orderedIndices = { iOutput, jOutput, i, j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Output;
std::string cacheName = "cacheOutput";
size_t maxCacheElts = OutputCacheRows * OutputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test7()
{
// Square matrix tiling with square output cache
loopnests::Index i("i"), j("j");
const int Rows = 8;
const int Columns = 8;
const int InputCacheRows = 4;
const int InputCacheCols = 4;
const int OutputCacheRows = 2;
const int OutputCacheCols = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto jBlock = schedule.Split(j, InputCacheCols);
auto iOutput = schedule.Split(i, OutputCacheRows);
auto jOutput = schedule.Split(j, OutputCacheCols);
std::vector<Index> orderedIndices = { iBlock, jBlock, iOutput, jOutput, i, j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
ArgumentType output_argType = ArgumentType::Output;
std::string output_cacheName = "cacheOutput";
size_t output_maxCacheElts = OutputCacheRows * OutputCacheCols;
size_t output_fillThreshold = output_maxCacheElts;
std::function<void(Scalar, Scalar)> output_reduceFunction = CopyReduce;
auto output_extraCacheParams = std::make_tuple(output_argType,
output_cacheName,
output_maxCacheElts,
output_fillThreshold,
output_reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
output_extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test8()
{
// Rectangular matrix input tiling with different rectangular output cache
loopnests::Index i("i"), j("j");
const int Rows = 8;
const int Columns = 8;
const int InputCacheRows = 4;
const int InputCacheCols = 2;
const int OutputCacheRows = 2;
const int OutputCacheCols = 4;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto iOutput = schedule.Split(i, OutputCacheRows);
auto jOutput = schedule.Split(j, OutputCacheCols);
auto jBlock = schedule.Split(j, InputCacheCols);
std::vector<Index> orderedIndices = { iBlock, iOutput, jOutput, jBlock, i, j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
ArgumentType output_argType = ArgumentType::Output;
std::string output_cacheName = "cacheOutput";
size_t output_maxCacheElts = OutputCacheRows * OutputCacheCols;
size_t output_fillThreshold = output_maxCacheElts;
std::function<void(Scalar, Scalar)> output_reduceFunction = CopyReduce;
auto output_extraCacheParams = std::make_tuple(output_argType,
output_cacheName,
output_maxCacheElts,
output_fillThreshold,
output_reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
output_extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test9()
{
// BLASTCopy input caching with square output cache
loopnests::Index i("i"), j("j");
const int Rows = 16;
const int Columns = 16;
const int InputCacheRows = 8;
const int InputCacheCols = 8;
const int StripeSize = 4;
const int VecSize = 2;
const int OutputCacheRows = 2;
const int OutputCacheCols = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto iOutput = schedule.Split(i, OutputCacheRows);
auto jBlock = schedule.Split(j, InputCacheCols);
auto jStripe = schedule.Split(j, StripeSize);
auto jOutput = schedule.Split(j, OutputCacheCols);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jStripe,
iOutput,
jOutput,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
ArgumentType output_argType = ArgumentType::Output;
std::string output_cacheName = "cacheOutput";
size_t output_maxCacheElts = OutputCacheRows * OutputCacheCols;
size_t output_fillThreshold = output_maxCacheElts;
std::function<void(Scalar, Scalar)> output_reduceFunction = CopyReduce;
auto output_extraCacheParams = std::make_tuple(output_argType,
output_cacheName,
output_maxCacheElts,
output_fillThreshold,
output_reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
output_extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test10()
{
// BLASTCopy input caching with rectangular output cache
loopnests::Index i("i"), j("j");
const int Rows = 16;
const int Columns = 16;
const int InputCacheRows = 8;
const int InputCacheCols = 8;
const int StripeSize = 4;
const int VecSize = 2;
const int OutputCacheRows = 2;
const int OutputCacheCols = 4;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto iOutput = schedule.Split(i, OutputCacheRows);
auto jBlock = schedule.Split(j, InputCacheCols);
auto jStripe = schedule.Split(j, StripeSize);
auto jOutput = schedule.Split(j, OutputCacheCols);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jStripe,
iOutput,
jOutput,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
ArgumentType output_argType = ArgumentType::Output;
std::string output_cacheName = "cacheOutput";
size_t output_maxCacheElts = OutputCacheRows * OutputCacheCols;
size_t output_fillThreshold = output_maxCacheElts;
std::function<void(Scalar, Scalar)> output_reduceFunction = CopyReduce;
auto output_extraCacheParams = std::make_tuple(output_argType,
output_cacheName,
output_maxCacheElts,
output_fillThreshold,
output_reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{ iOutput },
std::nullopt,
output_extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test11()
{
// BLASTCopy output caching
loopnests::Index i("i"), j("j");
const int Rows = 16;
const int Columns = 16;
const int CacheRows = 8;
const int CacheCols = 8;
const int StripeSize = 4;
const int VecSize = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, CacheRows);
auto jBlock = schedule.Split(j, CacheCols);
auto jStripe = schedule.Split(j, StripeSize);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jStripe,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Output;
std::string cacheName = "cacheOutput";
size_t maxCacheElts = CacheRows * CacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test12()
{
// BLASTCopy input caching with same BLASTCopy output caching
loopnests::Index i("i"), j("j");
const int Rows = 16;
const int Columns = 16;
const int CacheRows = 8;
const int CacheCols = 8;
const int StripeSize = 4;
const int VecSize = 2;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, CacheRows);
auto jBlock = schedule.Split(j, CacheCols);
auto jStripe = schedule.Split(j, StripeSize);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jStripe,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = CacheRows * CacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
ArgumentType output_argType = ArgumentType::Output;
std::string output_cacheName = "cacheOutput";
auto output_extraCacheParams = std::make_tuple(output_argType,
output_cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
output_extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_ValidateOutput_Test13()
{
// BLASTCopy input caching with different BLASTCopy output caching
loopnests::Index i("i"), j("j");
const int Rows = 32;
const int Columns = 32;
const int InputCacheRows = 16;
const int InputCacheCols = 16;
const int InputStripeSize = 8;
const int VecSize = 2;
const int OutputCacheRows = 8;
const int OutputCacheCols = InputStripeSize; // == InputStripeSize and in same dimension
const int OutputStripeSize = 4;
auto input = MakeIncrementingMatrix<int>(Rows, Columns, "input");
auto output = MakeMatrix<int>(Rows, Columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, Rows)
.ForAll(j, 0, Columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iBlock = schedule.Split(i, InputCacheRows);
auto iOutput = schedule.Split(i, OutputCacheRows);
auto jBlock = schedule.Split(j, InputCacheCols);
auto jOutput = schedule.Split(j, OutputCacheCols);
auto jInputStripe = jOutput; // Split by the same amount in the same dimension
auto jOutputStripe = schedule.Split(j, OutputStripeSize);
auto jVec = schedule.Split(j, VecSize);
std::vector<Index> orderedIndices = { jBlock,
iBlock,
jOutput,
iOutput,
jOutputStripe,
i,
jVec,
j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = InputCacheRows * InputCacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
ArgumentType output_argType = ArgumentType::Output;
std::string output_cacheName = "cacheOutput";
size_t output_maxCacheElts = OutputCacheRows * OutputCacheCols;
size_t output_fillThreshold = output_maxCacheElts;
std::function<void(Scalar, Scalar)> output_reduceFunction = CopyReduce;
auto output_extraCacheParams = std::make_tuple(output_argType,
output_cacheName,
output_maxCacheElts,
output_fillThreshold,
output_reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
output_extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(int rows, int columns, int outputCacheRows, int outputCacheColumns)
{
// Square output cache
loopnests::Index i("i"), j("j");
auto input = MakeIncrementingMatrix<int>(rows, columns, "input");
auto output = MakeMatrix<int>(rows, columns, "output");
// Define LoopNest
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, rows)
.ForAll(j, 0, columns)
.Do([=](Matrix input_, Matrix output_, Scalar i_, Scalar j_) {
output_(i_, j_) = input_(i_, j_);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iOutput = schedule.Split(i, outputCacheRows);
auto jOutput = schedule.Split(j, outputCacheColumns);
std::vector<Index> orderedIndices = { iOutput, jOutput, i, j };
schedule.SetOrder(orderedIndices);
ArgumentType argType = ArgumentType::Output;
std::string cacheName = "cacheOutput";
size_t maxCacheElts = outputCacheRows * outputCacheColumns;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(output,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
auto loop = nest.GetUnderlyingLoopNest();
DebugDump(loop);
#endif
nest.Run();
return VerifySame(output, input);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test1()
{
const int Rows = 8;
const int Columns = 8;
const int CacheRows = 2;
const int CacheColumns = 3;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test2()
{
const int Rows = 8;
const int Columns = 8;
const int CacheRows = 3;
const int CacheColumns = 2;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test3()
{
const int Rows = 8;
const int Columns = 8;
const int CacheRows = 3;
const int CacheColumns = 3;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test4()
{
const int Rows = 8;
const int Columns = 8;
const int CacheRows = 4;
const int CacheColumns = 5;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test5()
{
const int Rows = 8;
const int Columns = 8;
const int CacheRows = 5;
const int CacheColumns = 4;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test6()
{
const int Rows = 8;
const int Columns = 8;
const int CacheRows = 5;
const int CacheColumns = 5;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test7()
{
const int Rows = 8;
const int Columns = 7;
const int CacheRows = 2;
const int CacheColumns = 2;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test8()
{
const int Rows = 7;
const int Columns = 8;
const int CacheRows = 2;
const int CacheColumns = 2;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
Scalar GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput_Test9()
{
const int Rows = 7;
const int Columns = 7;
const int CacheRows = 2;
const int CacheColumns = 2;
return GeneralCachingStrategy_BoundaryConditionOutput_ValidateOutput(Rows, Columns, CacheRows, CacheColumns);
}
// BLASTCOPY tests from above with GeneralCachingStrategy
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_Test1()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int stripeSize = 4;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(N, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
// Test with smaller cache and stripe size than previous test
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_Test2()
{
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input, expectedOutput
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(N, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
schedule.Cache<GeneralCachingStrategy>(input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_Test1()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int stripeSize = 4;
int vecSize = stripeSize / 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCached =
{
0, 1, 2, 3,
8, 9, 10, 11,
16, 17, 18, 19,
24, 25, 26, 27,
32, 33, 34, 35,
40, 41, 42, 43,
48, 49, 50, 51,
56, 57, 58, 59,
4, 5, 6, 7,
12, 13, 14, 15,
20, 21, 22, 23,
28, 29, 30, 31,
36, 37, 38, 39,
44, 45, 46, 47,
52, 53, 54, 55,
60, 61, 62, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
auto jVec = schedule.Split(j, vecSize);
schedule.SetOrder({ jCache, iCache, jStripe, i, jVec, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
// Examine the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
rawCacheValue.SetLayout({ { (int)rawCacheValue.GetLayout().GetMemorySize() } });
auto cacheVector = Vector(rawCacheValue);
return VerifySame(cacheVector, expectedCached);
}
// Smaller stripe size than previous test
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_Test2()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCached =
{
0, 1,
8, 9,
16, 17,
24, 25,
32, 33,
40, 41,
48, 49,
56, 57,
2, 3,
10, 11,
18, 19,
26, 27,
34, 35,
42, 43,
50, 51,
58, 59,
4, 5,
12, 13,
20, 21,
28, 29,
36, 37,
44, 45,
52, 53,
60, 61,
6, 7,
14, 15,
22, 23,
30, 31,
38, 39,
46, 47,
54, 55,
62, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
// Examine the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
rawCacheValue.SetLayout({ { (int)rawCacheValue.GetLayout().GetMemorySize() } });
auto cacheVector = Vector(rawCacheValue);
return VerifySame(cacheVector, expectedCached);
}
// Same stripe size as previous test, but don't cache entire matrix at once
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_Test3()
{
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
8, 9,
16, 17,
24, 25,
2, 3,
10, 11,
18, 19,
26, 27,
};
Vector expectedCachedUpperRight =
{
4, 5,
12, 13,
20, 21,
28, 29,
6, 7,
14, 15,
22, 23,
30, 31
};
Vector expectedCachedLowerLeft =
{
32, 33,
40, 41,
48, 49,
56, 57,
34, 35,
42, 43,
50, 51,
58, 59,
};
Vector expectedCachedLowerRight =
{
36, 37,
44, 45,
52, 53,
60, 61,
38, 39,
46, 47,
54, 55,
62, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
schedule.SetOrder({ iCache, jCache, jStripe, i, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight, cachedLowerLeft, cachedLowerRight)
.Indices(iTopLevel, jTopLevel)
.Define([cacheRows, cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Vector cachedLowerLeft, Vector cachedLowerRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
}).ElseIf(j == cacheCols, [&]() {
cachedLowerRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Right:");
DebugPrintVector(cachedLowerRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
If(VerifySame(cachedLowerRight, expectedCachedLowerRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(int M, int N, int cacheRows, int cacheCols, int stripeSize)
{
int vecSize = stripeSize / 2;
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(M, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
auto jVec = schedule.Split(j, vecSize);
schedule.SetOrder({ jCache, iCache, jStripe, i, jVec, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
// input matrix rows evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test1()
{
int M = 8;
int N = 7; // N doesn't evenly divide the number of cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols but does evenly divide stripeSize
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test2()
{
int M = 8;
int N = 6; // N doesn't evenly divide the number of cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test3()
{
int M = 6;
int N = 7; // N doesn't evenly divide the number of cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols but does evenly divide stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test4()
{
int M = 6;
int N = 6; // N doesn't evenly divide the number of cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, doesn't evenly divide stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test5()
{
int M = 8;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, evenly divides stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test6()
{
int M = 8;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, doesn't evenly divides stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test7()
{
int M = 3;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, does evenly divides stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test8()
{
int M = 2;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
// input matrix rows < cache rows
// input matrix cols multiple of cache cols
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Test9()
{
int M = 2;
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
return GeneralCachingStrategy_BLASTCOPY_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize);
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedUpperRight, Vector expectedCachedLowerLeft, Vector expectedCachedLowerRight)
{
int vecSize = stripeSize / 2;
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
auto jVec = schedule.Split(j, vecSize);
schedule.SetOrder({ jCache, iCache, jStripe, i, jVec, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight, cachedLowerLeft, cachedLowerRight)
.Indices(iTopLevel, jTopLevel)
.Define([cacheRows, cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Vector cachedLowerLeft, Vector cachedLowerRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
}).ElseIf(j == cacheCols, [&]() {
cachedLowerRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Right:");
DebugPrintVector(cachedLowerRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
If(VerifySame(cachedLowerRight, expectedCachedLowerRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedLowerLeft)
{
int vecSize = stripeSize / 2;
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
auto jVec = schedule.Split(j, vecSize);
schedule.SetOrder({ jCache, iCache, jStripe, i, jVec, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
// No right caches when N < cacheCols
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedLowerLeft)
.Indices(iTopLevel, jTopLevel)
.Define([cacheRows](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedLowerLeft, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedUpperRight)
{
int vecSize = stripeSize / 2;
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
auto jVec = schedule.Split(j, vecSize);
schedule.SetOrder({ jCache, iCache, jStripe, i, jVec, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight)
.Indices(iTopLevel, jTopLevel)
.Define([cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(int M, int N, int cacheRows, int cacheCols, int stripeSize, Vector expectedCachedUpperLeft)
{
int vecSize = stripeSize / 2;
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto jCache = schedule.Split(j, cacheCols);
auto jStripe = schedule.Split(j, stripeSize);
auto jVec = schedule.Split(j, vecSize);
schedule.SetOrder({ jCache, iCache, jStripe, i, jVec, j });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = maxCacheElts;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
// No right caches when N < cacheCols
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft)
.Indices(iTopLevel, jTopLevel)
.Define([](Value rawCacheValue, Vector cachedUpperLeft, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::body, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(cachedUpperLeft, expectedCachedUpperLeft);
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test1()
{
int M = 8; // M does evenly divide cache rows
int N = 7; // N doesn't evenly divide cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
7, 8,
14, 15,
21, 22,
2, 3,
9, 10,
16, 17,
23, 24,
};
Vector expectedCachedUpperRight =
{
4, 5,
11, 12,
18, 19,
25, 26,
6, 0,
13, 0,
20, 0,
27, 0
};
Vector expectedCachedLowerLeft =
{
28, 29,
35, 36,
42, 43,
49, 50,
30, 31,
37, 38,
44, 45,
51, 52,
};
Vector expectedCachedLowerRight =
{
32, 33,
39, 40,
46, 47,
53, 54,
34, 0,
41, 0,
48, 0,
55, 0
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test2()
{
int M = 8; // M does evenly divide cache rows
int N = 6; // N doesn't evenly divide cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
// input
// A:
// [ 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, 26, 27, 28, 29],
// [30, 31, 32, 33, 34, 35],
// [36, 37, 38, 39, 40, 41],
// [42, 43, 44, 45, 46, 47]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
6, 7,
12, 13,
18, 19,
2, 3,
8, 9,
14, 15,
20, 21,
};
Vector expectedCachedUpperRight =
{
4, 5,
10, 11,
16, 17,
22, 23,
0, 0,
0, 0,
0, 0,
0, 0
};
Vector expectedCachedLowerLeft =
{
24, 25,
30, 31,
36, 37,
42, 43,
26, 27,
32, 33,
38, 39,
44, 45,
};
Vector expectedCachedLowerRight =
{
28, 29,
34, 35,
40, 41,
46, 47,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test3()
{
int M = 6;
int N = 7; // N doesn't evenly divide the number of cache columns
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 26, 27],
// [28, 29, 30, 31, 32, 33, 34],
// [35, 36, 37, 38, 39, 40, 41],
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
7, 8,
14, 15,
21, 22,
2, 3,
9, 10,
16, 17,
23, 24,
};
Vector expectedCachedUpperRight =
{
4, 5,
11, 12,
18, 19,
25, 26,
6, 0,
13, 0,
20, 0,
27, 0
};
// Check that it gets reviewed correctly to keep the cached data contiguous
Vector expectedCachedLowerLeft =
{
28, 29,
35, 36,
30, 31,
37, 38,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedLowerRight =
{
32, 33,
39, 40,
34, 0,
41, 0,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
// input matrix rows doesn't evenly divides cache rows
// input matrix cols doesn't evenly divide cache cols but does evenly divide stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test4()
{
int M = 6;
int N = 6; // N doesn't evenly divide the number of cache columns, but does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 26, 27, 28, 29],
// [30, 31, 32, 33, 34, 35]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
6, 7,
12, 13,
18, 19,
2, 3,
8, 9,
14, 15,
20, 21,
};
Vector expectedCachedUpperRight =
{
4, 5,
10, 11,
16, 17,
22, 23,
0, 0,
0, 0,
0, 0,
0, 0
};
Vector expectedCachedLowerLeft =
{
24, 25,
30, 31,
26, 27,
32, 33,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedLowerRight =
{
28, 29,
34, 35,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, doesn't evenly divide stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test5()
{
int M = 8;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1, 2],
// [ 3, 4, 5],
// [ 6, 7, 8],
// [ 9, 10, 11],
// [12, 13, 14],
// [15, 16, 17],
// [18, 19, 20],
// [21, 22, 23]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
3, 4,
6, 7,
9, 10,
2, 0,
5, 0,
8, 0,
11, 0,
};
Vector expectedCachedLowerLeft =
{
12, 13,
15, 16,
18, 19,
21, 22,
14, 0,
17, 0,
20, 0,
23, 0,
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedLowerLeft);
}
// input matrix rows evenly divides cache rows
// input matrix cols < cache cols, evenly divides stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test6()
{
int M = 8;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1],
// [ 2, 3],
// [ 4, 5],
// [ 6, 7],
// [ 8, 9],
// [10, 11],
// [12, 13],
// [14, 15]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
2, 3,
4, 5,
6, 7,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedLowerLeft =
{
8, 9,
10, 11,
12, 13,
14, 15,
0, 0,
0, 0,
0, 0,
0, 0,
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedLowerLeft);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, doesn't evenly divides stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test7()
{
int M = 3;
int N = 3; // N < cache columns, doesn't evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [0, 1, 2],
// [3, 4, 5],
// [6, 7, 8]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
3, 4,
6, 7,
2, 0,
5, 0,
8, 0,
0, 0,
0, 0
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft);
}
// input matrix rows < cache rows
// input matrix cols < cache cols, does evenly divides stripe size
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test8()
{
int M = 2;
int N = 2; // N < cache columns, does evenly divide stripe size
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1],
// [ 2, 3]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
2, 3,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
0, 0,
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft);
}
// input matrix rows < cache rows
// input matrix cols multiple of cache cols
Scalar GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Test9()
{
int M = 2;
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1, 2, 3, 4, 5, 6, 7],
// [ 8, 9, 10, 11, 12, 13, 14, 15]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 1,
8, 9,
2, 3,
10, 11,
0, 0,
0, 0,
0, 0,
0, 0,
};
Vector expectedCachedUpperRight =
{
4, 5,
12, 13,
6, 7,
14, 15,
0, 0,
0, 0,
0, 0,
0, 0
};
// clang-format on
return GeneralCachingStrategy_BLASTCOPY_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(M, N, cacheRows, cacheCols, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight);
}
// General caching strategy Progressive BLASNCopy-style caching
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_Test1()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int blockSize = 4;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(N, N, "expectedOutput");
// input:
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
// Test with smaller cache, block, and stripe size than previous test
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_Test2()
{
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 1;
// input, expectedOutput
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(N, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_Test1()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int blockSize = N;
int stripeSize = 4;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCached =
{
0, 8, 16, 24,
1, 9, 17, 25,
2, 10, 18, 26,
3, 11, 19, 27,
4, 12, 20, 28,
5, 13, 21, 29,
6, 14, 22, 30,
7, 15, 23, 31,
32, 40, 48, 56,
33, 41, 49, 57,
34, 42, 50, 58,
35, 43, 51, 59,
36, 44, 52, 60,
37, 45, 53, 61,
38, 46, 54, 62,
39, 47, 55, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
// Examine the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
rawCacheValue.SetLayout({ { (int)rawCacheValue.GetLayout().GetMemorySize() } });
auto cacheVector = Vector(rawCacheValue);
return VerifySame(cacheVector, expectedCached);
}
// Smaller stripe size than previous test
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_Test2()
{
int N = 8;
int cacheRows = N;
int cacheCols = N;
int blockSize = 4;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCached =
{
0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15,
16, 24, 17, 25, 18, 26, 19, 27, 20, 28, 21, 29, 22, 30, 23, 31,
32, 40, 33, 41, 34, 42, 35, 43, 36, 44, 37, 45, 38, 46, 39, 47,
48, 56, 49, 57, 50, 58, 51, 59, 52, 60, 53, 61, 54, 62, 55, 63,
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
// Examine the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
rawCacheValue.SetLayout({ { (int)rawCacheValue.GetLayout().GetMemorySize() } });
auto cacheVector = Vector(rawCacheValue);
return VerifySame(cacheVector, expectedCached);
}
// Same stripe size as previous test, but don't cache entire matrix at once
// Doesn't test the progressive nature of the cache over blocks
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_Test3()
{
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
auto input = MakeIncrementingMatrix<int>(N, N, "input");
auto output = MakeMatrix<int>(N, N, "output");
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// [56, 57, 58, 59, 60, 61, 62, 63]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 8, 1, 9, 2, 10, 3, 11,
16, 24, 17, 25, 18, 26, 19, 27
};
Vector expectedCachedUpperRight =
{
4, 12, 5, 13, 6, 14, 7, 15,
20, 28, 21, 29, 22, 30, 23, 31
};
Vector expectedCachedLowerLeft =
{
32, 40, 33, 41, 34, 42, 35, 43,
48, 56, 49, 57, 50, 58, 51, 59
};
Vector expectedCachedLowerRight =
{
36, 44, 37, 45, 38, 46, 39, 47,
52, 60, 53, 61, 54, 62, 55, 63
};
// clang-format on
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, N)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight, cachedLowerLeft, cachedLowerRight)
.Indices(iTopLevel, jTopLevel)
.Define([cacheRows, cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Vector cachedLowerLeft, Vector cachedLowerRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
}).ElseIf(j == cacheCols, [&]() {
cachedLowerRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::epilogue, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Right:");
DebugPrintVector(cachedLowerRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
If(VerifySame(cachedLowerRight, expectedCachedLowerRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(int M, int N, int cacheRows, int cacheCols, int blockSize, int stripeSize)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
auto expectedOutput = MakeIncrementingMatrix<int>(M, N, "expectedOutput");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(output, expectedOutput);
}
// input matrix rows doesn't evenly divide cache rows
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test1()
{
int M = 7; // M doesn't evenly divide the number of cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test2()
{
int M = 6; // M doesn't evenly divide the number of cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols doesn't evenly divide cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test3()
{
int M = 7; // M doesn't evenly divide the number of cache rows
int N = 6;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols doesn't evenly divide cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test4()
{
int M = 6; // M doesn't evenly divide the number of cache rows
int N = 6;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, doesn't evenly divide blocksize/stripesize
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test5()
{
int M = 3; // M < cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, evenly divides blocksize/stripesize
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test6()
{
int M = 2; // M < cache rows, evenly divides stripesize
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, doesn't evenly divide blocksize/stripesize
// input matrix cols < cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test7()
{
int M = 3; // M < cache rows, doens't evenly divide stripesize
int N = 3;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, evenly divides blocksize/stripesize
// input matrix cols < cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test8()
{
int M = 2; // M < cache rows, evenly divides stripesize
int N = 2;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows multiple of cache rows
// input matrix cols < cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_SmallBlocks_Test9()
{
int M = 8;
int N = 2; // N < cache cols
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 2;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows doesn't evenly divide cache rows
// input matrix cols evenly divides cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test1()
{
int M = 7; // M doesn't evenly divide the number of cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols evenly divides cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test2()
{
int M = 6; // M doesn't evenly divide the number of cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols doesn't evenly divide cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test3()
{
int M = 7; // M doesn't evenly divide the number of cache rows
int N = 6;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols doesn't evenly divide cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test4()
{
int M = 6; // M doesn't evenly divide the number of cache rows
int N = 6;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, doesn't evenly divide blocksize/stripesize
// input matrix cols evenly divides cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test5()
{
int M = 3; // M < cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, evenly divides blocksize/stripesize
// input matrix cols evenly divides cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test6()
{
int M = 2; // M < cache rows, evenly divides stripesize
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, doesn't evenly divide blocksize/stripesize
// input matrix cols < cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test7()
{
int M = 3; // M < cache rows, doens't evenly divide stripesize
int N = 3;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows < cache rows, evenly divides blocksize/stripesize
// input matrix cols < cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test8()
{
int M = 2; // M < cache rows, evenly divides stripesize
int N = 2;
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
// input matrix rows multiple of cache rows
// input matrix cols < cache cols
// stripeSize == blockSize / 2, blockSize == cacheRows
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_LargeBlocks_Test9()
{
int M = 8;
int N = 2; // N < cache cols
int cacheRows = 4;
int cacheCols = 4;
int blockSize = 4;
int stripeSize = 2;
return GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateOutput_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, blockSize, stripeSize);
}
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(int M, int N, int cacheRows, int cacheCols, int blockSize, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedUpperRight, Vector expectedCachedLowerLeft, Vector expectedCachedLowerRight)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight, cachedLowerLeft, cachedLowerRight)
.Indices(iTopLevel, jTopLevel)
.Define([cacheRows, cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Vector cachedLowerLeft, Vector cachedLowerRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
}).ElseIf(j == cacheCols, [&]() {
cachedLowerRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::epilogue, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Right:");
DebugPrintVector(cachedLowerRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
If(VerifySame(cachedLowerRight, expectedCachedLowerRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(int M, int N, int cacheRows, int cacheCols, int blockSize, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedLowerLeft)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedLowerLeft = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedLowerLeft)
.Indices(iTopLevel, jTopLevel)
.Define([cacheRows](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedLowerLeft, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
});
})
.ElseIf(i == cacheRows,
[&]() {
If(j == 0, [&]() {
cachedLowerLeft = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::epilogue, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Lower Left:");
DebugPrintVector(cachedLowerLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedLowerLeft);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedLowerLeft, expectedCachedLowerLeft) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(int M, int N, int cacheRows, int cacheCols, int blockSize, int stripeSize, Vector expectedCachedUpperLeft, Vector expectedCachedUpperRight)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
auto cachedUpperRight = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft, cachedUpperRight)
.Indices(iTopLevel, jTopLevel)
.Define([cacheCols](Value rawCacheValue, Vector cachedUpperLeft, Vector cachedUpperRight, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
})
.ElseIf(j == cacheCols,
[&]() {
cachedUpperRight = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::epilogue, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
auto ok = MakeScalar<int>("ok");
ok = 1;
auto printError = [&] {
DebugPrint("Upper Left:");
DebugPrintVector(cachedUpperLeft);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperLeft);
DebugPrint("\n");
DebugPrint("\n");
DebugPrint("Upper Right:");
DebugPrintVector(cachedUpperRight);
DebugPrint("\n");
DebugPrintVector(expectedCachedUpperRight);
DebugPrint("\n");
DebugPrint("\n");
};
// TODO : replace nested if's
If(VerifySame(cachedUpperLeft, expectedCachedUpperLeft) == 0, [&]() {
If(VerifySame(cachedUpperRight, expectedCachedUpperRight) == 0, [&]() {
ok = 0;
}).Else(printError);
}).Else(printError);
return ok;
}
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(int M, int N, int cacheRows, int cacheCols, int blockSize, int stripeSize, Vector expectedCachedUpperLeft)
{
auto input = MakeIncrementingMatrix<int>(M, N, "input");
auto output = MakeMatrix<int>(M, N, "output");
Index i("i"), j("j");
auto nest = Using({ input }, ArgumentType::Input)
.Using({ output }, ArgumentType::Output)
.ForAll(i, 0, M)
.ForAll(j, 0, N)
.Do([](Matrix input, Matrix output, Scalar i, Scalar j) {
output(i, j) = input(i, j);
});
auto& schedule = nest.GetSchedule();
auto iTopLevel = i;
auto jTopLevel = j;
auto iCache = schedule.Split(i, cacheRows);
auto iBlock = schedule.Split(i, blockSize);
auto iStripe = schedule.Split(i, stripeSize);
auto jCache = schedule.Split(j, cacheCols);
schedule.SetOrder({ iCache, jCache, iBlock, iStripe, j, i });
ArgumentType argType = ArgumentType::Input;
std::string cacheName = "cacheInput";
size_t maxCacheElts = cacheRows * cacheCols;
size_t fillThreshold = blockSize * cacheCols;
std::function<void(Scalar, Scalar)> reduceFunction = CopyReduce;
auto extraCacheParams = std::make_tuple(argType,
cacheName,
maxCacheElts,
fillThreshold,
reduceFunction,
false);
GeneralCachingStrategy cachingProvider{};
schedule.Cache(cachingProvider,
input,
{ iTopLevel, jTopLevel },
{},
{},
std::nullopt,
extraCacheParams);
// Get a handle to the underlying cached memory
auto rawCacheValue = cachingProvider._rawCache;
int rawCacheSize = (int)rawCacheValue.GetLayout().NumElements();
auto cachedUpperLeft = MakeVector<int>(rawCacheSize);
// Add a low level API kernel to access the underlying cache after it has been filled
auto cacheSpyKernel = loopnests::Kernel("cache_spy_kernel")
.Inputs(rawCacheValue, cachedUpperLeft)
.Indices(iTopLevel, jTopLevel)
.Define([](Value rawCacheValue, Vector cachedUpperLeft, Scalar i, Scalar j) {
auto cacheView = rawCacheValue;
cacheView.SetLayout({ { (int)rawCacheValue.GetLayout().NumElements() } });
auto vectorCacheView = Vector(cacheView);
If(i == 0,
[&]() {
// TODO : remove nested if's
If(j == 0,
[&]() {
cachedUpperLeft = vectorCacheView;
});
});
});
auto cacheSpyPosition = loopnests::CodePositionConstraints{ loopnests::LoopFragmentType::epilogue, { iCache, jCache }, {} };
nest.GetUnderlyingLoopNest().AddKernel(cacheSpyKernel, cacheSpyPosition);
#if 0 // DEBUGGING
DebugDump(nest.GetUnderlyingLoopNest());
#endif
nest.Run();
return VerifySame(cachedUpperLeft, expectedCachedUpperLeft);
}
// input matrix rows doesn't evenly divide cache rows
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test1()
{
int M = 7; // M doesn't evenly divide the number of cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 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, 52, 53, 54, 55]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 8, 1, 9, 2, 10, 3, 11,
16, 24, 17, 25, 18, 26, 19, 27
};
Vector expectedCachedUpperRight =
{
4, 12, 5, 13, 6, 14, 7, 15,
20, 28, 21, 29, 22, 30, 23, 31
};
Vector expectedCachedLowerLeft =
{
32, 40, 33, 41, 34, 42, 35, 43,
48, 0, 49, 0, 50, 0, 51, 0
};
Vector expectedCachedLowerRight =
{
36, 44, 37, 45, 38, 46, 39, 47,
52, 0, 53, 0, 54, 0, 55, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
return smallBlockResult + largeBlockResult;
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test2()
{
int M = 6; // M doesn't evenly divide the number of cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 26, 27, 28, 29, 30, 31]
// [32, 33, 34, 35, 36, 37, 38, 39]
// [40, 41, 42, 43, 44, 45, 46, 47]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 8, 1, 9, 2, 10, 3, 11,
16, 24, 17, 25, 18, 26, 19, 27
};
Vector expectedCachedUpperRight =
{
4, 12, 5, 13, 6, 14, 7, 15,
20, 28, 21, 29, 22, 30, 23, 31
};
Vector expectedCachedLowerLeft =
{
32, 40, 33, 41, 34, 42, 35, 43,
0, 0, 0, 0, 0, 0, 0, 0
};
Vector expectedCachedLowerRight =
{
36, 44, 37, 45, 38, 46, 39, 47,
0, 0, 0, 0, 0, 0, 0, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
return smallBlockResult + largeBlockResult;
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols doesn't evenly divide cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test3()
{
int M = 7; // M doesn't evenly divide the number of cache rows
int N = 6;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 26, 27, 28, 29]
// [30, 31, 32, 33, 34, 35]
// [36, 37, 38, 39, 40, 41]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 6, 1, 7, 2, 8, 3, 9,
12, 18, 13, 19, 14, 20, 15, 21
};
Vector expectedCachedUpperRight =
{
4, 10, 5, 11, 16, 22, 17, 23,
0, 0, 0, 0, 0, 0, 0, 0
};
Vector expectedCachedLowerLeft =
{
24, 30, 25, 31, 26, 32, 27, 33,
36, 0, 37, 0, 38, 0, 39, 0
};
Vector expectedCachedLowerRight =
{
28, 34, 29, 35, 40, 0, 41, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
return smallBlockResult + largeBlockResult;
}
// input matrix rows doesn't evenly divide cache rows, does evenly divide blocksize/stripesize
// input matrix cols doesn't evenly divide cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test4()
{
int M = 6; // M doesn't evenly divide the number of cache rows
int N = 6;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [ 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, 26, 27, 28, 29],
// [30, 31, 32, 33, 34, 35]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 6, 1, 7, 2, 8, 3, 9,
12, 18, 13, 19, 14, 20, 15, 21
};
Vector expectedCachedUpperRight =
{
4, 10, 5, 11, 16, 22, 17, 23,
0, 0, 0, 0, 0, 0, 0, 0
};
Vector expectedCachedLowerLeft =
{
24, 30, 25, 31, 26, 32, 27, 33,
0, 0, 0, 0, 0, 0, 0, 0
};
Vector expectedCachedLowerRight =
{
28, 34, 29, 35, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight, expectedCachedLowerLeft, expectedCachedLowerRight);
return smallBlockResult + largeBlockResult;
}
// input matrix rows < cache rows, doesn't evenly divide blocksize/stripesize
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test5()
{
int M = 3; // M < cache rows
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1, 2, 3, 4, 5, 6, 7],
// [ 8, 9, 10, 11, 12, 13, 14, 15],
// [16, 17, 18, 19, 20, 21, 22, 23]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 8, 1, 9, 2, 10, 3, 11,
16, 0, 17, 0, 18, 0, 19, 0
};
Vector expectedCachedUpperRight =
{
4, 12, 5, 13, 6, 14, 7, 15,
20, 0, 21, 0, 22, 0, 23, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight);
return smallBlockResult + largeBlockResult;
}
// input matrix rows < cache rows, evenly divides blocksize/stripesize
// input matrix cols evenly divides cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test6()
{
int M = 2; // M < cache rows, evenly divides stripesize
int N = 8;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1, 2, 3, 4, 5, 6, 7],
// [ 8, 9, 10, 11, 12, 13, 14, 15]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 8, 1, 9, 2, 10, 3, 11,
0, 0, 0, 0, 0, 0, 0, 0
};
Vector expectedCachedUpperRight =
{
4, 12, 5, 13, 6, 14, 7, 15,
0, 0, 0, 0, 0, 0, 0, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperCachesOnly(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedUpperRight);
return smallBlockResult + largeBlockResult;
}
// input matrix rows < cache rows, doesn't evenly divide blocksize/stripesize
// input matrix cols < cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test7()
{
int M = 3; // M < cache rows, doens't evenly divide stripesize
int N = 3;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [0, 1, 2],
// [3, 4, 5],
// [6, 7, 8]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 3, 1, 4, 2, 5, 6, 0,
7, 0, 8, 0, 0, 0, 0, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft);
return smallBlockResult + largeBlockResult;
}
// input matrix rows < cache rows, evenly divides blocksize/stripesize
// input matrix cols < cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test8()
{
int M = 2; // M < cache rows, evenly divides stripesize
int N = 2;
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [0, 1]
// [2, 3]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 2, 1, 3, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_UpperLeftCacheOnly(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft);
return smallBlockResult + largeBlockResult;
}
// input matrix rows multiple of cache rows
// input matrix cols < cache cols
// blockSize == stripeSize == cacheRows / 2
Scalar GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Test9()
{
int M = 8;
int N = 2; // N < cache cols
int cacheRows = 4;
int cacheCols = 4;
int smallBlockSize = 2;
int largeBlockSize = 4;
int stripeSize = 2;
// input
// A:
// [ 0, 1],
// [ 2, 3],
// [ 4, 5],
// [ 6, 7],
// [ 8, 9],
// [10, 11],
// [12, 13],
// [14, 15]
// clang-format off
Vector expectedCachedUpperLeft =
{
0, 2, 1, 3, 4, 6, 5, 7,
0, 0, 0, 0, 0, 0, 0, 0
};
Vector expectedCachedLowerLeft =
{
8, 10, 9, 11, 12, 14, 13, 15,
0, 0, 0, 0, 0, 0, 0, 0
};
// clang-format on
auto smallBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(M, N, cacheRows, cacheCols, smallBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedLowerLeft);
auto largeBlockResult = GeneralCachingStrategy_ProgressiveBLASNCopy_ValidateMemory_BoundaryCondition_Runner_LeftCachesOnly(M, N, cacheRows, cacheCols, largeBlockSize, stripeSize, expectedCachedUpperLeft, expectedCachedLowerLeft);
return smallBlockResult + largeBlockResult;
}
} // namespace ell
| 36.410078 | 295 | 0.52825 | [
"vector"
] |
049431eb50059c216165a57e629fe103d1ffac44 | 19,122 | cc | C++ | src/sys/appmgr/component_controller_impl.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/sys/appmgr/component_controller_impl.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | src/sys/appmgr/component_controller_impl.cc | billchen1977/fuchsia | d443f9c7b03ad317d1700c2c9457be8ed1147b86 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/sys/appmgr/component_controller_impl.h"
#include <fuchsia/inspect/cpp/fidl.h>
#include <lib/async/default.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/fdio.h>
#include <lib/fit/bridge.h>
#include <lib/fit/function.h>
#include <lib/inspect/service/cpp/service.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/trace/event.h>
#include <lib/zx/job.h>
#include <lib/zx/status.h>
#include <zircon/errors.h>
#include <zircon/types.h>
#include <cinttypes>
#include <string>
#include <utility>
#include <fbl/string_printf.h>
#include <fs/pseudo_file.h>
#include <fs/remote_dir.h>
#include <fs/service.h>
#include <task-utils/walker.h>
#include "fbl/ref_ptr.h"
#include "lib/inspect/service/cpp/service.h"
#include "lib/vfs/cpp/service.h"
#include "src/lib/fsl/handles/object_info.h"
#include "src/sys/appmgr/component_container.h"
#include "src/sys/appmgr/namespace.h"
#include "src/sys/appmgr/realm.h"
namespace component {
using fuchsia::sys::TerminationReason;
namespace {
zx::process DuplicateProcess(const zx::process& process) {
zx::process ret;
zx_status_t status = process.duplicate(ZX_RIGHT_SAME_RIGHTS, &ret);
if (status != ZX_OK) {
FX_LOGS(ERROR) << "Failed to duplicate process handle: " << status;
}
return ret;
}
// TODO(fxbug.dev/46803): The out/diagnostics directory propagation for runners includes a retry.
// The reason of this is that flutter fills the out/ directory *after*
// serving it. Therefore we need to watch that directory to notify.
// Sadly the PseudoDir exposed in the SDK (and used by flutter) returns ZX_ERR_NOT_SUPPORTED on
// Watch. A solution using a watcher is implemented in fxr/366977 pending watch support.
const uint32_t MAX_RETRIES_OUT_DIAGNOSTICS = 30;
const uint32_t OUT_DIAGNOSTICS_INITIAL_RETRY_DELAY_MS = 500;
const uint32_t OUT_DIAGNOSTICS_MAXIMUM_DELAY_MS = 15000;
} // namespace
ComponentRequestWrapper::ComponentRequestWrapper(
fidl::InterfaceRequest<fuchsia::sys::ComponentController> request, int64_t default_return,
fuchsia::sys::TerminationReason default_reason)
: request_(std::move(request)), return_code_(default_return), reason_(default_reason) {}
ComponentRequestWrapper::~ComponentRequestWrapper() {
if (request_) {
FailedComponentController failed(return_code_, reason_, std::move(request_));
}
}
ComponentRequestWrapper::ComponentRequestWrapper(ComponentRequestWrapper&& other) {
*this = std::move(other);
}
void ComponentRequestWrapper::operator=(ComponentRequestWrapper&& other) {
request_ = std::move(other.request_);
return_code_ = std::move(other.return_code_);
reason_ = std::move(other.reason_);
}
void ComponentRequestWrapper::SetReturnValues(int64_t return_code, TerminationReason reason) {
return_code_ = return_code;
reason_ = reason;
}
FailedComponentController::FailedComponentController(
int64_t return_code, TerminationReason termination_reason,
fidl::InterfaceRequest<fuchsia::sys::ComponentController> controller)
: binding_(this), return_code_(return_code), termination_reason_(termination_reason) {
if (controller) {
binding_.Bind(std::move(controller));
}
}
FailedComponentController::~FailedComponentController() {
// This can be false if other side of the channel dies before this object dies.
if (binding_.is_bound()) {
binding_.events().OnTerminated(return_code_, termination_reason_);
}
}
void FailedComponentController::Kill() {}
void FailedComponentController::Detach() {}
ComponentControllerBase::ComponentControllerBase(
fidl::InterfaceRequest<fuchsia::sys::ComponentController> request, std::string url,
std::string args, std::string label, std::string hub_instance_id, fxl::RefPtr<Namespace> ns,
zx::channel exported_dir, zx::channel client_request, uint32_t diagnostics_max_retries)
: executor_(async_get_default_dispatcher()),
binding_(this),
label_(std::move(label)),
hub_instance_id_(std::move(hub_instance_id)),
url_(std::move(url)),
hub_(fbl::MakeRefCounted<fs::PseudoDir>()),
ns_(std::move(ns)),
weak_ptr_factory_(this),
diagnostics_max_retries_(diagnostics_max_retries),
diagnostics_retry_backoff_ms_(OUT_DIAGNOSTICS_INITIAL_RETRY_DELAY_MS) {
if (request.is_valid()) {
binding_.Bind(std::move(request));
binding_.set_error_handler([this](zx_status_t /*status*/) { Kill(); });
}
if (!exported_dir) {
return;
}
exported_dir_.Bind(std::move(exported_dir), async_get_default_dispatcher());
if (client_request) {
fdio_service_connect_at(exported_dir_.channel().get(), "svc", client_request.release());
}
ns_->set_component_id(hub_instance_id_);
hub_.SetName(label_);
hub_.AddEntry("url", url_);
hub_.AddEntry("args", std::move(args));
exported_dir_->Clone(fuchsia::io::OPEN_FLAG_DESCRIBE | fuchsia::io::OPEN_RIGHT_READABLE |
fuchsia::io::OPEN_RIGHT_WRITABLE,
cloned_exported_dir_.NewRequest());
cloned_exported_dir_.events().OnOpen = [this](zx_status_t status,
std::unique_ptr<fuchsia::io::NodeInfo> /*info*/) {
if (status != ZX_OK) {
FX_LOGS(WARNING) << "could not bind out directory for component" << label_ << "): " << status;
return;
}
out_ready_ = true;
auto output_dir =
fbl::MakeRefCounted<fs::RemoteDir>(cloned_exported_dir_.Unbind().TakeChannel());
hub_.PublishOut(std::move(output_dir));
NotifyDiagnosticsDirReady(diagnostics_max_retries_);
TRACE_DURATION_BEGIN("appmgr", "ComponentController::OnDirectoryReady");
SendOnDirectoryReadyEvent();
TRACE_DURATION_END("appmgr", "ComponentController::OnDirectoryReady");
};
cloned_exported_dir_.set_error_handler(
[this](zx_status_t status) { cloned_exported_dir_.Unbind(); });
}
void ComponentControllerBase::NotifyDiagnosticsDirReady(uint32_t max_retries) {
auto promise =
GetDiagnosticsDir()
.and_then([self = weak_ptr_factory_.GetWeakPtr()](
fidl::InterfaceHandle<fuchsia::io::Directory>& dir) {
if (self) {
self->ns_->NotifyComponentDiagnosticsDirReady(self->url_, self->label_,
self->hub_instance_id_, std::move(dir));
}
})
.or_else([self = weak_ptr_factory_.GetWeakPtr(), max_retries](zx_status_t& status) {
if (self && status == ZX_ERR_NOT_FOUND) {
zx::duration next_backoff_duration = zx::msec(self->diagnostics_retry_backoff_ms_);
self->diagnostics_retry_backoff_ms_ = std::min(
self->diagnostics_retry_backoff_ms_ + OUT_DIAGNOSTICS_INITIAL_RETRY_DELAY_MS,
OUT_DIAGNOSTICS_MAXIMUM_DELAY_MS);
async::PostDelayedTask(
self->executor_.dispatcher(),
[self = std::move(self), max_retries]() {
if (self && max_retries > 0) {
self->NotifyDiagnosticsDirReady(max_retries - 1);
}
},
next_backoff_duration);
}
return fit::error(status);
});
executor_.schedule_task(std::move(promise));
}
fit::promise<fidl::InterfaceHandle<fuchsia::io::Directory>, zx_status_t>
ComponentControllerBase::GetDir(std::string path) {
// This error would occur if the method was called when the component out/ directory wasn't ready
// yet. This can be triggered when a listener is attached to a realm and notifies about existing
// components. It could happen that the component exists, but its out is not ready yet. Under such
// scenario, the listener will receive a START event for the existing component, but won't
// receive a DIAGNOSTICS_DIR_READY event during the existing flow. The DIAGNOSTICS_READY_EVENT
// will be triggered later once the out/ directory is ready if the component exposes a
// diagnostics directory.
if (!out_ready_) {
return fit::make_result_promise<fidl::InterfaceHandle<fuchsia::io::Directory>>(
fit::error(ZX_ERR_BAD_STATE));
}
fuchsia::io::NodePtr diagnostics_dir_node;
fit::bridge<void, zx_status_t> bridge;
diagnostics_dir_node.events().OnOpen =
[completer = std::move(bridge.completer), label = label_](
zx_status_t status, std::unique_ptr<fuchsia::io::NodeInfo> node_info) mutable {
if (status != ZX_OK) {
completer.complete_error(status);
} else if (!node_info) {
completer.complete_error(ZX_ERR_NOT_FOUND);
} else if (!node_info->is_directory()) {
completer.complete_error(ZX_ERR_NOT_DIR);
} else {
completer.complete_ok();
}
};
const uint32_t flags = fuchsia::io::OPEN_FLAG_DESCRIBE | fuchsia::io::OPEN_RIGHT_READABLE |
fuchsia::io::OPEN_RIGHT_WRITABLE;
exported_dir_->Open(flags, 0u /* mode */, path, diagnostics_dir_node.NewRequest());
return bridge.consumer.promise().and_then([diagnostics_dir_node =
std::move(diagnostics_dir_node)]() mutable {
auto diagnostics_dir =
fidl::InterfaceHandle<fuchsia::io::Directory>(diagnostics_dir_node.Unbind().TakeChannel());
return fit::make_result_promise<fidl::InterfaceHandle<fuchsia::io::Directory>, zx_status_t>(
fit::ok(std::move(diagnostics_dir)));
});
}
fit::promise<fidl::InterfaceHandle<fuchsia::io::Directory>, zx_status_t>
ComponentControllerBase::GetDiagnosticsDir() {
return GetDir("diagnostics");
}
fit::promise<fidl::InterfaceHandle<fuchsia::io::Directory>, zx_status_t>
ComponentControllerBase::GetServiceDir() {
return GetDir("svc");
}
void ComponentControllerBase::SendOnDirectoryReadyEvent() {
// This can be false if
// 1. Other side of the channel dies before this call happens.
// 2. Component Controller request was not passed while creating the component.
if (binding_.is_bound()) {
binding_.events().OnDirectoryReady();
}
}
void ComponentControllerBase::SendOnTerminationEvent(
int64_t return_code, fuchsia::sys::TerminationReason termination_reason) {
// `binding_.is_bound()` can be false if
// 1. Other side of the channel dies before this call happens.
// 2. Component Controller request was not passed while creating the component.
if (on_terminated_event_sent_ || !binding_.is_bound()) {
return;
}
FX_VLOGS(1) << "Sending termination callback with return code: " << return_code;
binding_.events().OnTerminated(return_code, termination_reason);
on_terminated_event_sent_ = true;
}
ComponentControllerBase::~ComponentControllerBase() { ns_->FlushAndShutdown(ns_); };
HubInfo ComponentControllerBase::HubInfo() {
return component::HubInfo(label_, hub_instance_id_, hub_.dir());
}
void ComponentControllerBase::Detach() {
binding_.set_error_handler([](zx_status_t /*status*/) {});
}
ComponentControllerImpl::ComponentControllerImpl(
fidl::InterfaceRequest<fuchsia::sys::ComponentController> request,
ComponentContainer<ComponentControllerImpl>* container, zx::job job, zx::process process,
std::string url, std::string args, std::string label, fxl::RefPtr<Namespace> ns,
zx::channel exported_dir, zx::channel client_request, zx::channel package_handle)
: ComponentControllerBase(std::move(request), std::move(url), std::move(args), std::move(label),
std::to_string(fsl::GetKoid(process.get())), std::move(ns),
std::move(exported_dir), std::move(client_request)),
container_(container),
job_(std::move(job)),
process_(std::move(process)),
process_koid_(std::to_string(fsl::GetKoid(process_.get()))),
job_koid_(std::to_string(fsl::GetKoid(job_.get()))),
wait_(this, process_.get(), ZX_TASK_TERMINATED),
system_diagnostics_(DuplicateProcess(process_)) {
zx_status_t status = wait_.Begin(async_get_default_dispatcher());
FX_DCHECK(status == ZX_OK);
hub()->SetJobId(job_koid_);
hub()->SetProcessId(process_koid_);
// Serve connections to the system_diagnostics interface.
auto system_diagnostics = fbl::MakeRefCounted<fs::PseudoDir>();
system_diagnostics->AddEntry(
fuchsia::inspect::Tree::Name_,
fbl::MakeRefCounted<fs::Service>(
[handler = inspect::MakeTreeHandler(&system_diagnostics_.inspector())](zx::channel chan) {
handler(fidl::InterfaceRequest<fuchsia::inspect::Tree>(std::move(chan)));
return ZX_OK;
}));
hub()->AddEntry("system_diagnostics", system_diagnostics);
hub()->AddIncomingServices(this->incoming_services());
if (package_handle.is_valid()) {
hub()->AddPackageHandle(fbl::MakeRefCounted<fs::RemoteDir>(std::move(package_handle)));
}
zx::job watch_job;
if (job_.duplicate(ZX_RIGHT_SAME_RIGHTS, &watch_job) != ZX_OK) {
FX_LOGS(ERROR) << "Failed to duplicate job handle";
}
ComputeComponentInstancePath();
auto realm = this->ns()->realm();
if (realm && realm->cpu_watcher() && !instance_path_.empty()) {
realm->cpu_watcher()->AddTask(instance_path_, std::move(watch_job));
}
}
ComponentControllerImpl::~ComponentControllerImpl() {
zx_info_handle_basic_t info = {};
// Two ways we end up here:
// 1) OnHandleReady() destroys this object; in which case, process is dead.
// 2) Our owner destroys this object; in which case, the process may still be
// alive.
if (job_) {
job_.get_info(ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr);
job_.kill();
// Our owner destroyed this object before we could obtain a termination
// reason.
SendOnTerminationEvent(-1, TerminationReason::UNKNOWN);
}
auto realm = this->ns()->realm();
if (realm && realm->cpu_watcher()) {
if (!instance_path_.empty()) {
realm->cpu_watcher()->RemoveTask(instance_path_);
}
}
// Clean up system diagnostics before deleting the backing objects.
hub()->dir()->RemoveEntry("system_diagnostics");
}
void ComponentControllerImpl::Kill() {
FX_VLOGS(1) << "ComponentControllerImpl::Kill() called";
TRACE_DURATION("appmgr", "ComponentController::Kill");
if (job_) {
job_.kill();
job_.reset();
}
}
bool ComponentControllerImpl::SendReturnCodeIfTerminated() {
// Get process info.
zx_info_process_t process_info;
zx_status_t result =
process_.get_info(ZX_INFO_PROCESS, &process_info, sizeof(process_info), NULL, NULL);
FX_DCHECK(result == ZX_OK);
if (process_info.exited) {
SendOnTerminationEvent(process_info.return_code, TerminationReason::EXITED);
}
return process_info.exited;
}
zx_status_t ComponentControllerImpl::AddSubComponentHub(const component::HubInfo& hub_info) {
hub()->EnsureComponentDir();
return hub()->AddComponent(hub_info);
}
zx_status_t ComponentControllerImpl::RemoveSubComponentHub(const component::HubInfo& hub_info) {
return hub()->RemoveComponent(hub_info);
}
// Called when process terminates, regardless of if Kill() was invoked.
void ComponentControllerImpl::Handler(async_dispatcher_t* dispatcher, async::WaitBase* wait,
zx_status_t status, const zx_packet_signal* signal) {
FX_DCHECK(status == ZX_OK);
FX_DCHECK(signal->observed == ZX_TASK_TERMINATED);
FX_VLOGS(1) << "ComponentControllerImpl::Handler() called";
bool terminated = SendReturnCodeIfTerminated();
FX_DCHECK(terminated);
process_.reset();
container_->ExtractComponent(this);
// The destructor of the temporary returned by ExtractComponent destroys
// |this| at the end of the previous statement.
}
void ComponentControllerImpl::ComputeComponentInstancePath() {
if (!instance_path_.empty()) {
return;
}
std::vector<std::string> path;
auto realm = this->ns()->realm();
if (realm) {
instance_path_.push_back(this->label());
auto cur = realm;
while (cur) {
instance_path_.push_back(cur->label());
cur = cur->parent();
}
std::reverse(instance_path_.begin(), instance_path_.end());
instance_path_.push_back(job_koid_);
}
}
ComponentBridge::ComponentBridge(fidl::InterfaceRequest<fuchsia::sys::ComponentController> request,
fuchsia::sys::ComponentControllerPtr remote_controller,
ComponentContainer<ComponentBridge>* container, std::string url,
std::string args, std::string label, std::string hub_instance_id,
fxl::RefPtr<Namespace> ns, zx::channel exported_dir,
zx::channel client_request,
std::optional<zx::channel> package_handle)
: ComponentControllerBase(std::move(request), std::move(url), std::move(args), std::move(label),
hub_instance_id, std::move(ns), std::move(exported_dir),
std::move(client_request), MAX_RETRIES_OUT_DIAGNOSTICS),
remote_controller_(std::move(remote_controller)),
container_(std::move(container)),
termination_reason_(TerminationReason::UNKNOWN) {
// Forward termination callbacks from the remote component over the bridge.
remote_controller_.events().OnTerminated = [this](int64_t return_code,
TerminationReason termination_reason) mutable {
// Propagate the events to the external proxy.
if (on_terminated_event_) {
on_terminated_event_(return_code, termination_reason);
}
SendOnTerminationEvent(return_code, termination_reason);
remote_controller_.events().OnTerminated = nullptr;
container_->ExtractComponent(this);
};
remote_controller_.events().OnDirectoryReady = [this] { SendOnDirectoryReadyEvent(); };
remote_controller_.set_error_handler([this](zx_status_t status) {
if (remote_controller_.events().OnTerminated != nullptr) {
remote_controller_.events().OnTerminated(-1, TerminationReason::UNKNOWN);
}
});
// The destructor of the temporary returned by ExtractComponent destroys
// |this| at the end of the previous statement.
hub()->AddIncomingServices(this->incoming_services());
if (package_handle.has_value() && package_handle->is_valid()) {
hub()->AddPackageHandle(fbl::MakeRefCounted<fs::RemoteDir>(std::move(*package_handle)));
}
}
void ComponentBridge::NotifyStopped() {
ns()->NotifyComponentStopped(url(), label(), hub_instance_id());
}
ComponentBridge::~ComponentBridge() {
if (remote_controller_.events().OnTerminated) {
SendOnTerminationEvent(-1, termination_reason_);
}
}
void ComponentBridge::SetParentJobId(const std::string& id) { hub()->SetJobId(id); }
void ComponentBridge::Kill() { remote_controller_->Kill(); }
void ComponentBridge::SetTerminationReason(TerminationReason termination_reason) {
termination_reason_ = termination_reason;
}
} // namespace component
| 39.672199 | 100 | 0.698829 | [
"object",
"vector"
] |
04970bf48531d51ea2c8c8cf5377345699b74838 | 83,169 | cpp | C++ | src/graysvr/CObjBase.cpp | JakubLinhart/SphereServer99 | 989e5819f781af87390b12656291138d00648ec8 | [
"Apache-2.0"
] | null | null | null | src/graysvr/CObjBase.cpp | JakubLinhart/SphereServer99 | 989e5819f781af87390b12656291138d00648ec8 | [
"Apache-2.0"
] | null | null | null | src/graysvr/CObjBase.cpp | JakubLinhart/SphereServer99 | 989e5819f781af87390b12656291138d00648ec8 | [
"Apache-2.0"
] | null | null | null | #include "graysvr.h" // predef header
#include "../network/send.h"
bool CObjBaseTemplate::IsDeleted() const
{
ADDTOCALLSTACK("CObjBaseTemplate::IsDeleted");
return (!m_UID.IsValidUID() || (GetParent() == &g_World.m_ObjDelete));
}
int CObjBaseTemplate::IsWeird() const
{
ADDTOCALLSTACK_INTENSIVE("CObjBaseTemplate::IsWeird");
if ( !GetParent() )
return 0x3101;
if ( !IsValidUID() )
return 0x3102;
return 0;
}
bool GetDeltaStr(CPointMap &pt, TCHAR *pszDir)
{
TCHAR *ppCmd[3];
size_t iArgQty = Str_ParseCmds(pszDir, ppCmd, COUNTOF(ppCmd));
if ( iArgQty <= 0 )
return false;
TCHAR chDir = static_cast<TCHAR>(toupper(ppCmd[0][0]));
int iTmp = Exp_GetVal(ppCmd[1]);
if ( IsDigit(chDir) || (chDir == '-') )
{
pt.m_x += static_cast<signed short>(Exp_GetVal(ppCmd[0]));
pt.m_y += static_cast<signed short>(iTmp);
pt.m_z += static_cast<signed char>(Exp_GetVal(ppCmd[2]));
}
else // a direction by name
{
if ( iTmp == 0 )
iTmp = 1;
DIR_TYPE eDir = GetDirStr(ppCmd[0]);
if ( eDir >= DIR_QTY )
return false;
pt.MoveN(eDir, iTmp);
}
return true;
}
///////////////////////////////////////////////////////////
// CObjBase
bool CObjBase::sm_fDeleteReal = false; // UID table.
CObjBase::CObjBase(bool fItem)
{
m_timeout.Init();
m_timestamp.Init();
m_wHue = HUE_DEFAULT;
m_RunningTrigger = NULL;
m_Can = 0;
m_ModMaxWeight = 0;
m_attackBase = 0;
m_attackRange = 0;
m_defenseBase = 0;
m_defenseRange = 0;
m_DamPhysical = 0;
m_DamFire = 0;
m_DamCold = 0;
m_DamPoison = 0;
m_DamEnergy = 0;
m_ResPhysical = 0;
m_ResPhysicalMax = 0;
m_ResFire = 0;
m_ResFireMax = 0;
m_ResCold = 0;
m_ResColdMax = 0;
m_ResPoison = 0;
m_ResPoisonMax = 0;
m_ResEnergy = 0;
m_ResEnergyMax = 0;
m_Luck = 0;
m_DamIncrease = 0;
m_SpellDamIncrease = 0;
m_HitLifeLeech = 0;
m_HitManaDrain = 0;
m_HitManaLeech = 0;
m_HitStaminaLeech = 0;
m_HitChanceIncrease = 0;
m_DefChanceIncrease = 0;
m_DefChanceIncreaseMax = 0;
m_SwingSpeedIncrease = 0;
m_FasterCasting = 0;
m_FasterCastRecovery = 0;
m_LowerManaCost = 0;
m_LowerReagentCost = 0;
m_EnhancePotions = 0;
m_NightSight = 0;
m_ReflectPhysicalDamage = 0;
m_uidSpawnItem = UID_UNUSED;
++sm_iCount;
m_ModAr = 0;
m_fStatusUpdate = 0;
m_PropertyList = NULL;
m_PropertyHash = 0;
m_PropertyRevision = 0;
if ( g_Serv.IsLoading() )
{
// Don't do this yet if we are loading, UID will be set later. Just check if this is an item
CObjBaseTemplate::SetUID(UID_O_DISCONNECT|UID_O_INDEX_MASK|(fItem ? UID_F_ITEM : 0));
}
else
{
// Find a free UID slot for this
SetUID(UID_CLEAR, fItem);
ASSERT(IsValidUID());
SetContainerFlags(UID_O_DISCONNECT); // it is no place for now
}
// Put in the idle list while this don't get moved to world
g_World.m_ObjNew.InsertHead(this);
}
CObjBase::~CObjBase()
{
FreePropertyList();
g_World.m_ObjStatusUpdates.RemovePtr(this);
--sm_iCount;
ASSERT(IsDisconnected());
// Free up the UID slot
SetUID(UID_UNUSED, false);
}
bool CObjBase::IsContainer() const
{
ADDTOCALLSTACK("CObjBase::IsContainer");
// Simple test if object is a container.
return (dynamic_cast<const CContainer *>(this) != NULL);
}
void CObjBase::SetHue(HUE_TYPE wHue, bool fSkipTrigger, CTextConsole *pSrc, CObjBase *pObj, SOUND_TYPE wSound)
{
ADDTOCALLSTACK("CObjBase::SetHue");
if ( g_Serv.IsLoading() ) // we do not want tons of @Dye being called during world load, just set the hue then continue...
{
m_wHue = wHue;
return;
}
CScriptTriggerArgs args;
args.m_iN1 = wHue;
args.m_iN2 = wSound;
/* @Dye is now more universal, it is called on EVERY CObjBase color change.
Sanity checks are recommended and if possible, avoid using it on universal events.
Trigger info to be added to intenal
LPCTSTR const CItem::sm_szTrigName //CItem.cpp
LPCTSTR const CChar::sm_szTrigName //CChar.cpp
enum ITRIG_TYPE //CObjBase.h
enum CTRIG_TYPE //CObjBase.h
ADD(DYE, "@Dye") //triggers.tbl
*/
if ( IsTrigUsed("@Dye") && !fSkipTrigger )
{
if ( pObj )
args.m_pO1 = pObj;
if ( OnTrigger("@Dye", pSrc, &args) == TRIGRET_RET_TRUE )
return;
}
m_wHue = static_cast<HUE_TYPE>(args.m_iN1);
if ( args.m_iN2 > 0 ) // no sound? no checks for who can hear, packets....
Sound(static_cast<SOUND_TYPE>(args.m_iN2));
if ( IsChar() )
{
// When changing body hue, check if face hue must be changed too
CItem *pFace = static_cast<CChar *>(this)->LayerFind(LAYER_FACE);
if ( pFace )
pFace->SetHue(m_wHue, fSkipTrigger, pSrc, pObj);
}
}
int CObjBase::IsWeird() const
{
ADDTOCALLSTACK_INTENSIVE("CObjBase::IsWeird");
int iResultCode = CObjBaseTemplate::IsWeird();
if ( iResultCode )
return iResultCode;
if ( !g_Serv.IsLoading() )
{
if ( GetUID().ObjFind() != this ) // make sure it's linked both ways correctly.
return 0x3201;
}
return 0;
}
void CObjBase::SetUID(DWORD dwIndex, bool fItem)
{
ADDTOCALLSTACK("CObjBase::SetUID");
// Move the serial number.
// This is possibly dangerous if conflict arrises.
dwIndex &= UID_O_INDEX_MASK; // make sure no flags in here
if ( IsValidUID() ) // I already have a uid?
{
if ( !dwIndex )
return; // the point was just to make sure it was located
g_World.FreeUID(static_cast<DWORD>(GetUID()) & UID_O_INDEX_MASK); // remove the old UID
}
if ( dwIndex != UID_O_INDEX_MASK ) // just wanted to remove it
dwIndex = g_World.AllocUID(dwIndex, this);
if ( fItem )
dwIndex |= UID_F_ITEM;
CObjBaseTemplate::SetUID(dwIndex);
}
bool CObjBase::SetNamePool(LPCTSTR pszName)
{
ADDTOCALLSTACK("CObjBase::SetNamePool");
ASSERT(pszName);
TCHAR szTemp[MAX_ITEM_NAME_SIZE];
if ( pszName[0] == '#' )
{
// Pick random name from the given #NAMES list
++pszName;
strncpy(szTemp, pszName, sizeof(szTemp) - 1);
TCHAR *ppArgs[2];
Str_ParseCmds(szTemp, ppArgs, COUNTOF(ppArgs));
CResourceLock s;
if ( !g_Cfg.ResourceLock(s, RES_NAMES, ppArgs[0]) || !s.ReadKey() )
return false;
int iCount = Calc_GetRandVal(ATOI(s.GetKey())) + 1;
while ( iCount-- )
{
if ( !s.ReadKey() )
{
DEBUG_ERR(("Name list '#%s' have invalid entries\n", ppArgs[0]));
return false;
}
}
strncpy(szTemp, s.GetKey(), sizeof(szTemp) - 1);
}
else
{
// Directly set the given name
strncpy(szTemp, pszName, sizeof(szTemp) - 1);
}
if ( !CObjBaseTemplate::SetName(szTemp) )
return false;
UpdatePropertyFlag();
return true;
}
bool CObjBase::MoveNearObj(const CObjBaseTemplate *pObj, WORD wSteps)
{
ADDTOCALLSTACK("CObjBase::MoveNearObj");
ASSERT(pObj);
if ( pObj->IsDisconnected() ) // nothing is "near" a disconnected item.
return false;
pObj = pObj->GetTopLevelObj();
return MoveNear(pObj->GetTopPoint(), wSteps);
}
void CObjBase::r_WriteSafe(CScript &s)
{
ADDTOCALLSTACK("CObjBase::r_WriteSafe");
// Write an object with some fault protection.
DWORD uid = 0;
try
{
uid = GetUID();
if ( m_TagDefs.GetKeyNum("NOSAVE") ) // objects with TAG.NOSAVE set are not saved
return;
if ( !g_Cfg.m_fSaveGarbageCollect && g_World.FixObj(this) )
return;
r_Write(s);
}
catch ( const CGrayError &e )
{
g_Log.CatchEvent(&e, "Write Object 0%" FMTDWORDH, uid);
CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1);
}
catch ( ... ) // catch all
{
g_Log.CatchEvent(NULL, "Write Object 0%" FMTDWORDH, uid);
CurrentProfileData.Count(PROFILE_STAT_FAULTS, 1);
}
}
void CObjBase::SetTimeout(INT64 iDelayInTicks)
{
ADDTOCALLSTACK("CObjBase::SetTimeout");
// Set delay in TICK_PER_SEC of a sec. -1 = never.
if ( iDelayInTicks < 0 )
m_timeout.Init();
else
m_timeout = CServTime::GetCurrentTime() + iDelayInTicks;
}
void CObjBase::Sound(SOUND_TYPE id, BYTE bRepeat) const
{
ADDTOCALLSTACK("CObjBase::Sound");
// Send sound to all nearby clients
if ( !g_Cfg.m_fGenericSounds || (id <= SOUND_NONE) )
return;
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
if ( !pClient->CanHear(this, TALKMODE_OBJ) )
continue;
pClient->addSound(id, this, bRepeat);
}
}
void CObjBase::Effect(EFFECT_TYPE motion, ITEMID_TYPE id, const CObjBaseTemplate *pSrc, BYTE bSpeed, BYTE bFrames, bool fExplode, DWORD dwColor, DWORD dwRender, WORD wEffectID, WORD wExplodeID, WORD wExplodeSound, DWORD dwItemUID, BYTE bLayer) const
{
ADDTOCALLSTACK("CObjBase::Effect");
// Object-based effect
if ( motion == EFFECT_FADE_SCREEN )
{
// This effect must be used only on client chars (and send it only to this client)
const CChar *pChar = dynamic_cast<const CChar *>(this);
if ( pChar && pChar->m_pClient )
pChar->m_pClient->addEffect(motion, NULL, NULL, NULL, NULL, id);
return;
}
CPointMap ptSrc = NULL;
CObjBaseTemplate *pDest = GetTopLevelObj();
CPointMap ptDest = pDest->GetTopPoint();
if ( motion == EFFECT_BOLT )
{
// Source should be a valid object when using moving effects
if ( !pSrc )
return;
pSrc = pSrc->GetTopLevelObj();
ptSrc = pSrc->GetTopPoint();
}
else
{
// Otherwise, source is not needed (set the same as dest just to fill the packet)
pSrc = pDest;
ptSrc = ptDest;
}
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
CChar *pChar = pClient->GetChar();
if ( !pChar || !pChar->CanSee(pDest) )
continue;
pClient->addEffect(motion, pSrc, ptSrc, pDest, ptDest, id, bSpeed, bFrames, fExplode, dwColor, dwRender, wEffectID, wExplodeID, wExplodeSound, dwItemUID, bLayer);
}
}
void CObjBase::Effect(EFFECT_TYPE motion, ITEMID_TYPE id, CPointMap ptSrc, CPointMap ptDest, BYTE bSpeed, BYTE bFrames, bool fExplode, DWORD dwColor, DWORD dwRender, WORD wEffectID, WORD wExplodeID, WORD wExplodeSound, DWORD dwItemUID, BYTE bLayer) const
{
ADDTOCALLSTACK("CObjBase::Effect(2)");
// Ground-based effect
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
CChar *pChar = pClient->GetChar();
if ( !pChar || (pChar->GetTopPoint().GetDist(ptDest) > pChar->GetSight()) )
continue;
pClient->addEffect(motion, NULL, ptSrc, NULL, ptDest, id, bSpeed, bFrames, fExplode, dwColor, dwRender, wEffectID, wExplodeID, wExplodeSound, dwItemUID, bLayer);
}
}
void CObjBase::Emote(LPCTSTR pszTextYou, LPCTSTR pszTextThem, CClient *pClientExclude)
{
ADDTOCALLSTACK("CObjBase::Emote");
// Show message as *emote*
// ARGS:
// pszTextYou = text to client itself
// pszTextThem = text to clients nearby (if null, inherit the same message from pszTextYou)
CObjBase *pObjTop = static_cast<CObjBase *>(GetTopLevelObj());
if ( !pObjTop )
return;
HUE_TYPE defaultHue = HUE_TEXT_DEF;
FONT_TYPE defaultFont = FONT_NORMAL;
bool defaultUnicode = false;
if ( pszTextYou && (*pszTextYou == '@') )
{
++pszTextYou;
const char *s = pszTextYou;
pszTextYou = strchr(s, ' ');
WORD wArgs[] = { static_cast<WORD>(defaultHue), static_cast<WORD>(defaultFont), static_cast<WORD>(defaultUnicode) };
if ( pszTextYou )
{
for ( int i = 0; (s < pszTextYou) && (i < 3); ++i, ++s )
{
if ( *s != ',' )
wArgs[i] = static_cast<WORD>(Exp_GetLLVal(s));
}
++pszTextYou;
}
defaultHue = static_cast<HUE_TYPE>(wArgs[0]);
defaultFont = static_cast<FONT_TYPE>(wArgs[1]);
defaultUnicode = static_cast<bool>(wArgs[2]);
}
if ( !pszTextThem )
pszTextThem = pszTextYou;
TCHAR *pszOthers = Str_GetTemp();
TCHAR *pszYou = Str_GetTemp();
if ( pObjTop->IsChar() )
{
if ( pObjTop != this )
{
// Equipped items
sprintf(pszOthers, g_Cfg.GetDefaultMsg(DEFMSG_MSG_EMOTE_1), pObjTop->GetName(), GetName(), pszTextThem);
sprintf(pszYou, g_Cfg.GetDefaultMsg(DEFMSG_MSG_EMOTE_2), GetName(), pszTextYou);
}
else
{
// Chars
sprintf(pszOthers, g_Cfg.GetDefaultMsg(DEFMSG_MSG_EMOTE_5), GetName(), pszTextThem);
sprintf(pszYou, g_Cfg.GetDefaultMsg(DEFMSG_MSG_EMOTE_6), pszTextYou);
}
}
else
{
// Items on ground or inside container
sprintf(pszOthers, g_Cfg.GetDefaultMsg(DEFMSG_MSG_EMOTE_7), GetName(), pszTextThem);
strcpy(pszYou, pszOthers);
}
pObjTop->UpdateObjMessage(pszOthers, pszYou, pClientExclude, defaultHue, TALKMODE_EMOTE, defaultFont, defaultUnicode);
}
void CObjBase::Speak(LPCTSTR pszText, HUE_TYPE wHue, TALKMODE_TYPE mode, FONT_TYPE font)
{
ADDTOCALLSTACK("CObjBase::Speak");
g_World.Speak(this, pszText, wHue, mode, font);
}
void CObjBase::SpeakUTF8(LPCTSTR pszText, HUE_TYPE wHue, TALKMODE_TYPE mode, FONT_TYPE font, CLanguageID lang)
{
ADDTOCALLSTACK("CObjBase::SpeakUTF8");
// convert UTF8 to UNICODE.
NCHAR szBuffer[MAX_TALK_BUFFER];
CvtSystemToNUNICODE(szBuffer, COUNTOF(szBuffer), pszText, -1);
g_World.SpeakUNICODE(this, szBuffer, wHue, mode, font, lang);
}
void CObjBase::SpeakUTF8Ex(const NWORD *pszText, HUE_TYPE wHue, TALKMODE_TYPE mode, FONT_TYPE font, CLanguageID lang)
{
ADDTOCALLSTACK("CObjBase::SpeakUTF8Ex");
g_World.SpeakUNICODE(this, pszText, wHue, mode, font, lang);
}
bool CObjBase::MoveNear(CPointMap pt, WORD wSteps)
{
ADDTOCALLSTACK("CObjBase::MoveNear");
// Move to nearby this other object.
// Actually move it within +/- iSteps
CChar *pChar = dynamic_cast<CChar *>(this);
CPointMap ptOld = pt;
for ( WORD i = 0; i < 20; ++i )
{
pt = ptOld;
pt.m_x += static_cast<signed short>(Calc_GetRandVal(-wSteps, wSteps));
pt.m_y += static_cast<signed short>(Calc_GetRandVal(-wSteps, wSteps));
if ( !MoveTo(pt) )
continue;
if ( pChar )
{
pChar->m_zClimbHeight = 0;
if ( !pChar->CanMoveWalkTo(pt, false) )
continue;
}
else
Update();
return true;
}
return false;
}
void CObjBase::UpdateObjMessage(LPCTSTR pszTextThem, LPCTSTR pszTextYou, CClient *pClientExclude, HUE_TYPE wHue, TALKMODE_TYPE mode, FONT_TYPE font, bool fUnicode) const
{
ADDTOCALLSTACK("CObjBase::UpdateObjMessage");
// Show everyone a msg coming from this object.
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
if ( pClient == pClientExclude )
continue;
if ( !pClient->CanSee(this) )
continue;
pClient->addBarkParse((pClient->GetChar() == this) ? pszTextYou : pszTextThem, this, wHue, mode, font, fUnicode);
}
}
void CObjBase::UpdateCanSee(PacketSend *packet, CClient *exclude) const
{
ADDTOCALLSTACK("CObjBase::UpdateCanSee");
// Send this update message to everyone who can see this.
// NOTE: Need not be a top level object. CanSee() will calc that.
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
if ( pClient == exclude )
continue;
if ( !pClient->CanSee(this) )
continue;
packet->send(pClient);
}
delete packet;
}
TRIGRET_TYPE CObjBase::OnHearTrigger(CResourceLock &s, LPCTSTR pszCmd, CChar *pSrc, TALKMODE_TYPE &mode, HUE_TYPE wHue)
{
ADDTOCALLSTACK("CObjBase::OnHearTrigger");
// Check all the keys in this script section.
// look for pattern or partial trigger matches.
// RETURN:
// TRIGRET_ENDIF = no match.
// TRIGRET_DEFAULT = found match but it had no RETURN
CScriptTriggerArgs Args(pszCmd);
Args.m_iN1 = mode;
Args.m_iN2 = wHue;
bool fMatch = false;
while ( s.ReadKeyParse() )
{
if ( s.IsKeyHead("ON", 2) )
{
// Look for some key word.
_strupr(s.GetArgStr());
if ( Str_Match(s.GetArgStr(), pszCmd) == MATCH_VALID )
fMatch = true;
continue;
}
if ( !fMatch )
continue; // look for the next "ON" section.
TRIGRET_TYPE tr = CObjBase::OnTriggerRunVal(s, TRIGRUN_SECTION_EXEC, pSrc, &Args);
if ( tr != TRIGRET_RET_FALSE )
return tr;
fMatch = false;
}
mode = static_cast<TALKMODE_TYPE>(Args.m_iN1);
return TRIGRET_ENDIF; // continue looking.
}
enum OBR_TYPE
{
OBR_DEF,
OBR_ROOM,
OBR_SECTOR,
OBR_SPAWNITEM,
OBR_TOPOBJ,
OBR_TYPEDEF,
OBR_QTY
};
LPCTSTR const CObjBase::sm_szRefKeys[OBR_QTY+1] =
{
"DEF",
"ROOM",
"SECTOR",
"SPAWNITEM",
"TOPOBJ",
"TYPEDEF",
NULL
};
bool CObjBase::r_GetRef(LPCTSTR &pszKey, CScriptObj *&pRef)
{
ADDTOCALLSTACK("CObjBase::r_GetRef");
int index = FindTableHeadSorted(pszKey, sm_szRefKeys, COUNTOF(sm_szRefKeys) - 1);
if ( index >= 0 )
{
pszKey += strlen(sm_szRefKeys[index]);
SKIP_SEPARATORS(pszKey);
switch ( index )
{
case OBR_ROOM:
pRef = GetTopLevelObj()->GetTopPoint().GetRegion(REGION_TYPE_ROOM);
return true;
case OBR_SECTOR:
pRef = GetTopLevelObj()->GetTopSector();
return true;
case OBR_SPAWNITEM:
if ( (m_uidSpawnItem != static_cast<CGrayUID>(UID_UNUSED)) && (pszKey[-1] != '.') )
break;
pRef = m_uidSpawnItem.ItemFind();
return true;
case OBR_TOPOBJ:
if ( pszKey[-1] != '.' ) // only used as a ref !
break;
pRef = dynamic_cast<CObjBase *>(GetTopLevelObj());
return true;
case OBR_DEF:
case OBR_TYPEDEF:
pRef = Base_GetDef();
return true;
}
}
return CScriptObj::r_GetRef(pszKey, pRef);
}
enum OBC_TYPE
{
#define ADD(a,b) OC_##a,
#include "../tables/CObjBase_props.tbl"
#undef ADD
OC_QTY
};
LPCTSTR const CObjBase::sm_szLoadKeys[OC_QTY+1] =
{
#define ADD(a,b) b,
#include "../tables/CObjBase_props.tbl"
#undef ADD
NULL
};
bool CObjBase::r_WriteVal(LPCTSTR pszKey, CGString &sVal, CTextConsole *pSrc, CScriptTriggerArgs* pArgs)
{
ADDTOCALLSTACK("CObjBase::r_WriteVal");
EXC_TRY("WriteVal");
int index = FindTableHeadSorted(pszKey, sm_szLoadKeys, COUNTOF(sm_szLoadKeys) - 1);
if ( index < 0 )
{
// RES_FUNCTION call
// Is it a function returning a value ? Parse args ?
LPCTSTR pszArgs = strchr(pszKey, '(');
if (pszArgs)
{
LPCTSTR pszArgsStart = pszArgs;
Str_SkipArgumentList(pszArgs);
TemporaryString sArgsTmp;
strncpy(sArgsTmp, pszArgsStart, pszArgs - pszArgsStart - 1);
sArgsTmp.setAt(pszArgs - pszArgsStart - 1, '\0');
pszArgs = sArgsTmp;
pszArgs++;
}
else
{
pszArgs = strchr(pszKey, ' ');
if (pszArgs)
SKIP_SEPARATORS(pszArgs);
}
CScriptTriggerArgs Args(pszArgs ? pszArgs : "");
if (pArgs)
Args.m_pO1 = pArgs->m_pO1;
if ( r_Call(pszKey, pSrc, &Args, &sVal) )
return true;
if ( Base_GetDef()->r_WriteVal(pszKey, sVal, pSrc, pArgs) )
return true;
return CScriptObj::r_WriteVal(pszKey, sVal, pSrc, pArgs);
}
bool fZero = false;
switch ( index )
{
//return as string or hex number or NULL if not set
//On these ones, check BaseDef if not found on dynamic
case OC_NAMELOC:
{
CVarDefCont *pVar = GetDefKey(pszKey, true);
sVal = pVar ? pVar->GetValStr() : "";
break;
}
//return as decimal number or 0 if not set
//On these ones, check BaseDef if not found on dynamic
case OC_DAMCHAOS:
case OC_DAMDIRECT:
case OC_EXPANSION:
case OC_REGENFOOD:
case OC_REGENHITS:
case OC_REGENMANA:
case OC_REGENSTAM:
case OC_REGENVALFOOD:
case OC_REGENVALHITS:
case OC_REGENVALMANA:
case OC_REGENVALSTAM:
case OC_COMBATBONUSSTAT:
case OC_COMBATBONUSPERCENT:
{
CVarDefCont *pVar = GetDefKey(pszKey, true);
sVal.FormatLLVal(pVar ? pVar->GetValNum() : 0);
break;
}
case OC_ARMOR:
{
const CChar *pChar = dynamic_cast<const CChar *>(this);
if ( pChar )
{
sVal.FormatVal(pChar->m_defense);
break;
}
pszKey += 5;
if ( *pszKey == '.' )
{
SKIP_SEPARATORS(pszKey);
if ( !strnicmp(pszKey, "LO", 2) )
sVal.Format("%d", m_defenseBase);
else if ( !strnicmp(pszKey, "HI", 2) )
sVal.Format("%d", m_defenseBase + m_defenseRange);
}
else
sVal.Format("%d,%d", m_defenseBase, m_defenseBase + m_defenseRange);
break;
}
case OC_DAM:
{
pszKey += 3;
if ( *pszKey == '.' )
{
SKIP_SEPARATORS(pszKey);
if ( !strnicmp(pszKey, "LO", 2) )
sVal.Format("%d", m_attackBase);
else if ( !strnicmp(pszKey, "HI", 2) )
sVal.Format("%d", m_attackBase + m_attackRange);
}
else
sVal.Format("%d,%d", m_attackBase, m_attackBase + m_attackRange);
break;
}
case OC_DAMCOLD:
sVal.FormatVal(m_DamCold);
break;
case OC_DAMENERGY:
sVal.FormatVal(m_DamEnergy);
break;
case OC_DAMFIRE:
sVal.FormatVal(m_DamFire);
break;
case OC_DAMPHYSICAL:
sVal.FormatVal(m_DamPhysical);
break;
case OC_DAMPOISON:
sVal.FormatVal(m_DamPoison);
break;
case OC_ID:
sVal = g_Cfg.ResourceGetName(Base_GetDef()->GetResourceID());
break;
case OC_INCREASEDAM:
sVal.FormatVal(m_DamIncrease);
break;
case OC_INCREASEDEFCHANCE:
sVal.FormatVal(m_DefChanceIncrease);
break;
case OC_INCREASEDEFCHANCEMAX:
sVal.FormatVal(m_DefChanceIncreaseMax);
break;
case OC_INCREASEHITCHANCE:
sVal.FormatVal(m_HitChanceIncrease);
break;
case OC_INCREASESPELLDAM:
sVal.FormatVal(m_SpellDamIncrease);
break;
case OC_INCREASESWINGSPEED:
sVal.FormatVal(m_SwingSpeedIncrease);
break;
case OC_FASTERCASTING:
sVal.FormatVal(m_FasterCasting);
break;
case OC_FASTERCASTRECOVERY:
sVal.FormatVal(m_FasterCastRecovery);
break;
case OC_HITLEECHLIFE:
sVal.FormatVal(m_HitLifeLeech);
break;
case OC_HITLEECHMANA:
sVal.FormatVal(m_HitManaLeech);
break;
case OC_HITLEECHSTAM:
sVal.FormatVal(m_HitStaminaLeech);
break;
case OC_HITMANADRAIN:
sVal.FormatVal(m_HitManaDrain);
break;
case OC_LOWERMANACOST:
sVal.FormatVal(m_LowerManaCost);
break;
case OC_LOWERREAGENTCOST:
sVal.FormatVal(m_LowerReagentCost);
break;
case OC_ENHANCEPOTIONS:
sVal.FormatVal(m_EnhancePotions);
break;
case OC_NIGHTSIGHT:
sVal.FormatVal(m_NightSight);
break;
case OC_REFLECTPHYSICALDAM:
sVal.FormatVal(m_ReflectPhysicalDamage);
break;
case OC_RANGE:
{
if ( RangeH() == 0 )
sVal.Format("%d", RangeL());
else
sVal.Format("%d,%d", RangeH(), RangeL());
break;
}
case OC_RANGEL:
sVal.FormatVal(RangeH());
break;
case OC_RANGEH:
sVal.FormatVal(RangeL());
break;
case OC_CAN:
sVal.FormatHex(m_Can);
break;
case OC_MODMAXWEIGHT:
sVal.FormatVal(m_ModMaxWeight);
return true;
case OC_CANSEE:
case OC_CANSEELOS:
case OC_SRCCANSEELOS:
case OC_CANSEELOSFLAG:
{
CChar *pChar = pSrc->GetChar();
bool fCanSee = (index == OC_CANSEE);
bool fUseFlags = (index == OC_CANSEELOSFLAG);
bool fSrcCanSee = (index == OC_SRCCANSEELOS);
WORD wFlags = 0;
if (fCanSee)
pszKey += 6;
else if (fUseFlags)
pszKey += 13;
else if (fSrcCanSee)
pszKey += 12;
else
pszKey += 9;
SKIP_SEPARATORS(pszKey);
GETNONWHITESPACE(pszKey);
if ( fUseFlags && *pszKey )
{
wFlags = static_cast<WORD>(Exp_GetVal(pszKey));
SKIP_ARGSEP(pszKey);
}
if ( *pszKey ) // has an argument - UID to see(los) or POS to los only
{
CPointMap pt;
CObjBase *pObj = NULL;
if ( !fCanSee )
pt = g_Cfg.GetRegionPoint(pszKey);
if ( fCanSee || !pt.IsValidPoint() )
{
pObj = static_cast<CGrayUID>(Exp_GetVal(pszKey)).ObjFind();
if ( !fCanSee && pObj )
pt = pObj->GetTopPoint();
}
pChar = GetUID().CharFind();
if ( pChar )
sVal.FormatVal(fCanSee ? pChar->CanSee(pObj) : pChar->CanSeeLOS(pt, NULL, pChar->GetSight(), wFlags));
else
sVal.FormatVal(0);
}
else
{
if ( pChar ) // standard way src TO current object
sVal.FormatVal(fCanSee ? pChar->CanSee(this) : pChar->CanSeeLOS(this, wFlags));
else
sVal.FormatVal(0);
}
break;
}
case OC_COLOR:
sVal.FormatHex(GetHue());
break;
case OC_COMPLEXITY:
{
if ( IsDisconnected() || !GetTopLevelObj()->GetTopPoint().IsValidPoint() )
return false;
return GetTopLevelObj()->GetTopSector()->r_WriteVal(pszKey, sVal, pSrc, pArgs);
}
case OC_CTAGCOUNT:
{
CChar *pChar = dynamic_cast<CChar *>(this);
sVal.FormatVal((pChar && pChar->m_pClient) ? pChar->m_pClient->m_TagDefs.GetCount() : 0);
break;
}
case OC_TEXTF:
{
TCHAR *pszFormat = const_cast<TCHAR *>(pszKey);
pszFormat += 5;
TCHAR *pszArg[4];
size_t iArgQty = Str_ParseCmds(pszFormat, pszArg, COUNTOF(pszArg));
if ( iArgQty < 2 )
{
g_Log.EventError("%s: function can't have less than 2 args\n", sm_szLoadKeys[index]);
return false;
}
if ( iArgQty > 4 )
{
g_Log.EventError("%s: function exceeded max args allowed (%" FMTSIZE_T "/%d)\n", sm_szLoadKeys[index], iArgQty, 4);
return false;
}
if ( *pszArg[0] == '"' ) // skip quotes
++pszArg[0];
BYTE bCount = 0;
for ( TCHAR *pszEnd = pszArg[0] + strlen(pszArg[0]) - 1; pszEnd >= pszArg[0]; --pszEnd )
{
if ( *pszEnd == '"' )
{
*pszEnd = '\0';
break;
}
++bCount;
}
sVal.Format(pszArg[0], pszArg[1], pszArg[2] ? pszArg[2] : 0, pszArg[3] ? pszArg[3] : 0);
return true;
}
case OC_DIALOGLIST:
{
pszKey += 10;
if ( *pszKey == '.' )
{
SKIP_SEPARATORS(pszKey);
GETNONWHITESPACE(pszKey);
CClient *pClient = (pSrc->GetChar() && pSrc->GetChar()->m_pClient) ? pSrc->GetChar()->m_pClient : NULL;
sVal.FormatVal(0);
if ( pClient )
{
if ( !strnicmp(pszKey, "COUNT", 5) )
sVal.FormatVal(pClient->m_mapOpenedGumps.size());
else
{
CClient::OpenedGumpsMap_t *pDialogList = &pClient->m_mapOpenedGumps;
size_t iDialogIndex = static_cast<size_t>(Exp_GetVal(pszKey));
SKIP_SEPARATORS(pszKey);
if ( iDialogIndex <= pDialogList->size() )
{
CClient::OpenedGumpsMap_t::iterator itDialogFound = pDialogList->begin();
while ( iDialogIndex-- )
++itDialogFound;
if ( !strnicmp(pszKey, "ID", 2) )
sVal.Format("%s", g_Cfg.ResourceGetName(RESOURCE_ID(RES_DIALOG, (*itDialogFound).first)));
else if ( !strnicmp(pszKey, "COUNT", 5) )
sVal.FormatVal((*itDialogFound).second);
}
}
}
else
DEBUG_ERR(("DIALOGLIST called on non-client object\n"));
return true;
}
return false;
}
case OC_DISTANCEFROM:
{
pszKey += 12;
CObjBase* pThis = IsTopLevel() ? this : static_cast<CObjBase*>(GetTopLevelObj());
CObjBase* pObj = pSrc->GetChar();
TemporaryString pszArg;
if (Str_ParseArgumentList(pszKey, pszArg))
{
CExpression expr(pArgs, pSrc, this);
pObj = static_cast<CGrayUID>(expr.GetVal(pszArg)).ObjFind();
}
if ( pObj && !pObj->IsTopLevel() )
pObj = dynamic_cast<CObjBase *>(pObj->GetTopLevelObj());
if ( !pObj )
return false;
sVal.FormatVal(pThis->GetDist(pObj));
break;
}
case OC_EVENTS:
m_OEvents.WriteResourceRefList(sVal);
break;
case OC_FACING:
{
pszKey += 6;
SKIP_SEPARATORS(pszKey);
GETNONWHITESPACE(pszKey);
CObjBase *pThis = IsTopLevel() ? this : static_cast<CObjBase *>(GetTopLevelObj());
CObjBase *pObj = pSrc->GetChar();
if ( *pszKey )
{
CPointMap pt = g_Cfg.GetRegionPoint(pszKey);
if ( pt.IsValidPoint() )
{
if ( !pThis->GetTopPoint().IsValidPoint() )
return false;
sVal.FormatVal(pThis->GetTopPoint().GetDir(pt));
return true;
}
pObj = static_cast<CGrayUID>(Exp_GetVal(pszKey)).ObjFind();
}
if ( !pObj )
return false;
if ( !pObj->IsTopLevel() )
pObj = static_cast<CObjBase *>(pObj->GetTopLevelObj());
sVal.FormatVal(pThis->GetDir(pObj));
break;
}
case OC_ISCHAR:
sVal.FormatVal(IsChar());
break;
case OC_ISEVENT:
{
if (pszKey[7] == '.' || pszKey[7] == ' ')
{
pszKey += 8;
sVal.FormatVal(m_OEvents.ContainsResourceName(RES_EVENTS, pszKey));
return true;
}
else if (pszKey[7] == '(')
{
pszKey += 8;
TemporaryString args;
Str_ParseArgumentList(pszKey, args);
Str_ParseArgumentEnd(pszKey, true);
sVal.FormatVal(m_OEvents.ContainsResourceName(RES_EVENTS, args));
return true;
}
return false;
}
case OC_ISTEVENT:
{
if ( pszKey[8] != '.' )
return false;
pszKey += 9;
sVal.FormatVal(Base_GetDef()->m_TEvents.ContainsResourceName(RES_EVENTS, pszKey));
return true;
}
case OC_ISITEM:
sVal.FormatVal(IsItem());
break;
case OC_ISCONT:
sVal.FormatVal(IsContainer());
break;
case OC_ISNEARTYPETOP:
case OC_ISNEARTYPE:
{
bool fReturnP = false;
pszKey += (index == OC_ISNEARTYPETOP) ? 13 : 10;
if ( !strnicmp(pszKey, ".P", 2) )
{
fReturnP = true;
pszKey += 2;
}
SKIP_SEPARATORS(pszKey);
SKIP_ARGSEP(pszKey);
if ( GetTopPoint().IsValidPoint() )
{
IT_TYPE iType = static_cast<IT_TYPE>(g_Cfg.ResourceGetIndexType(RES_TYPEDEF, pszKey));
SKIP_IDENTIFIERSTRING(pszKey);
SKIP_SEPARATORS(pszKey);
SKIP_ARGSEP(pszKey);
int iDistance = *pszKey ? Exp_GetVal(pszKey) : 0;
bool fCheckMulti = *pszKey ? (Exp_GetVal(pszKey) != 0) : false;
bool fLimitZ = *pszKey ? (Exp_GetVal(pszKey) != 0) : false;
if ( fReturnP )
{
CPointMap pt = (index == OC_ISNEARTYPETOP) ? g_World.FindTypeNear_Top(GetTopPoint(), iType, iDistance) : g_World.FindItemTypeNearby(GetTopPoint(), iType, iDistance, fCheckMulti, fLimitZ);
if ( pt.IsValidPoint() )
sVal = pt.WriteUsed();
else
sVal.FormatVal(0);
}
else
sVal.FormatVal((index == OC_ISNEARTYPETOP) ? g_World.IsTypeNear_Top(GetTopPoint(), iType, iDistance) : g_World.IsItemTypeNear(GetTopPoint(), iType, iDistance, fCheckMulti, fLimitZ));
}
else
sVal.FormatVal(0);
return true;
}
case OC_ISPLAYER:
{
CChar *pChar = dynamic_cast<CChar *>(this);
sVal.FormatVal((pChar && pChar->m_pPlayer) ? 1 : 0);
return true;
}
case OC_ISDIALOGOPEN:
{
pszKey += 12;
SKIP_SEPARATORS(pszKey);
GETNONWHITESPACE(pszKey);
CChar *pChar = dynamic_cast<CChar *>(this);
CClient *pClient = (pChar && pChar->m_pClient) ? pChar->m_pClient : NULL;
if ( pClient )
{
DWORD context = static_cast<DWORD>(g_Cfg.ResourceGetIDType(RES_DIALOG, pszKey));
if ( pClient->m_NetState->isClientKR() )
context = g_Cfg.GetKRDialog(context);
context &= 0xFFFFFF;
CClient::OpenedGumpsMap_t::iterator itGumpFound = pClient->m_mapOpenedGumps.find(static_cast<int>(context));
sVal.FormatVal((itGumpFound != pClient->m_mapOpenedGumps.end()) ? (*itGumpFound).second : 0);
}
else
sVal.FormatVal(0);
return true;
}
case OC_ISARMOR:
{
pszKey += 7;
SKIP_SEPARATORS(pszKey);
GETNONWHITESPACE(pszKey);
CItem *pItem = NULL;
if ( *pszKey )
{
TCHAR *pszArg = Str_GetTemp();
strcpylen(pszArg, pszKey, strlen(pszKey) + 1);
pItem = dynamic_cast<CItem *>(static_cast<CGrayUID>(Exp_GetVal(pszKey)).ObjFind());
if ( !pItem )
{
ITEMID_TYPE id = static_cast<ITEMID_TYPE>(g_Cfg.ResourceGetID(RES_ITEMDEF, const_cast<LPCTSTR &>(reinterpret_cast<LPTSTR &>(pszArg))).GetResIndex());
const CItemBase *pItemDef = CItemBase::FindItemBase(id);
if ( pItemDef )
{
sVal.FormatVal(CItemBase::IsTypeArmor(pItemDef->GetType()));
break;
}
}
sVal.FormatVal(pItem ? pItem->IsTypeArmor() : 0);
break;
}
pItem = dynamic_cast<CItem *>(this);
sVal.FormatVal(pItem ? pItem->IsTypeArmor() : 0);
break;
}
case OC_ISTIMERF:
{
if ( pszKey[8] != '.' )
return false;
pszKey += 9;
sVal.FormatVal(g_World.m_TimedFunctions.IsTimer(GetUID(), pszKey));
return true;
}
case OC_ISWEAPON:
{
pszKey += 8;
SKIP_SEPARATORS(pszKey);
GETNONWHITESPACE(pszKey);
CItem *pItem = NULL;
if ( *pszKey )
{
TCHAR *pszArg = Str_GetTemp();
strcpylen(pszArg, pszKey, strlen(pszKey) + 1);
pItem = dynamic_cast<CItem *>(static_cast<CGrayUID>(Exp_GetVal(pszKey)).ObjFind());
if ( !pItem )
{
ITEMID_TYPE id = static_cast<ITEMID_TYPE>(g_Cfg.ResourceGetID(RES_ITEMDEF, const_cast<LPCTSTR &>(reinterpret_cast<LPTSTR &>(pszArg))).GetResIndex());
const CItemBase *pItemDef = CItemBase::FindItemBase(id);
if ( pItemDef )
{
sVal.FormatVal(CItemBase::IsTypeWeapon(pItemDef->GetType()));
break;
}
}
sVal.FormatVal(pItem ? pItem->IsTypeWeapon() : 0);
break;
}
pItem = dynamic_cast<CItem *>(this);
sVal.FormatVal(pItem ? pItem->IsTypeWeapon() : 0);
break;
}
case OC_LUCK:
sVal.FormatVal(m_Luck);
break;
case OC_MAP:
case OC_MAPPLANE:
sVal.FormatVal(GetTopPoint().m_map);
break;
case OC_MODAR:
sVal.FormatVal(m_ModAr);
break;
case OC_NAME:
sVal = GetName();
break;
case OC_P_X:
sVal.FormatVal(GetTopPoint().m_x);
break;
case OC_P_Y:
sVal.FormatVal(GetTopPoint().m_y);
break;
case OC_P_Z:
sVal.FormatVal(GetTopPoint().m_z);
break;
case OC_P:
{
if ( pszKey[1] == '.' )
return GetTopPoint().r_WriteVal(pszKey + 2, sVal);
sVal = GetTopPoint().WriteUsed();
break;
}
case OC_RESCOLD:
sVal.FormatVal(m_ResCold);
break;
case OC_RESCOLDMAX:
sVal.FormatVal(m_ResColdMax);
break;
case OC_RESENERGY:
sVal.FormatVal(m_ResEnergy);
break;
case OC_RESENERGYMAX:
sVal.FormatVal(m_ResEnergyMax);
break;
case OC_RESFIRE:
sVal.FormatVal(m_ResFire);
break;
case OC_RESFIREMAX:
sVal.FormatVal(m_ResFireMax);
break;
case OC_RESPHYSICAL:
sVal.FormatVal(m_ResPhysical);
break;
case OC_RESPHYSICALMAX:
sVal.FormatVal(m_ResPhysicalMax);
break;
case OC_RESPOISON:
sVal.FormatVal(m_ResPoison);
break;
case OC_RESPOISONMAX:
sVal.FormatVal(m_ResPoisonMax);
break;
case OC_TAG0:
fZero = true;
++pszKey;
// fall through
case OC_TAG:
{
if ( pszKey[3] != '.' && pszKey[3] != '(' )
return false;
if (pszKey[3] == '.')
{
pszKey += 4;
TCHAR* pszTagName = Str_TrimWhitespace(const_cast<CHAR*>(pszKey));
pszTagName = Str_TrimEnd(pszTagName, ") \t");
CVarDefCont* pVarKey = m_TagDefs.GetKey(pszTagName);
if (!pVarKey)
sVal = Base_GetDef()->m_TagDefs.GetKeyStr(pszTagName, fZero, pArgs, pSrc, this);
else
sVal = pVarKey->GetValStr();
return true;
}
else
{
pszKey += 3;
if (Str_ParseArgumentStart(pszKey, true))
{
TemporaryString tagName;
if (Str_ParseVariableName(pszKey, tagName))
{
if (Str_ParseArgumentEnd(pszKey, true))
{
CVarDefCont* pVarKey = m_TagDefs.GetKey(tagName, pArgs, pSrc, this);
if (!pVarKey)
sVal = Base_GetDef()->m_TagDefs.GetKeyStr(tagName, fZero, pArgs, pSrc, this);
else
sVal = pVarKey->GetValStr();
return r_WriteValChained(pszKey, sVal, pSrc, pArgs);
}
}
}
}
}
case OC_TIMER:
sVal.FormatLLVal(GetTimerAdjusted());
break;
case OC_TIMERD:
sVal.FormatLLVal(GetTimerDAdjusted());
break;
case OC_TRIGGER:
{
pszKey += 7;
GETNONWHITESPACE(pszKey);
if ( *pszKey )
{
TRIGRET_TYPE tr;
bool fRet = CallPersonalTrigger(const_cast<TCHAR *>(pszKey), pSrc, tr, false);
if ( fRet )
sVal.FormatVal(tr);
return fRet;
}
return false;
}
case OC_TOPOBJ:
{
if ( pszKey[6] == '.' )
return CScriptObj::r_WriteVal(pszKey, sVal, pSrc, pArgs);
sVal.FormatHex(GetTopLevelObj()->GetUID());
break;
}
case OC_UID:
if ( pszKey[3] == '.' )
return CScriptObj::r_WriteVal(pszKey, sVal, pSrc, pArgs);
// fall through
case OC_SERIAL:
sVal.FormatUid(GetUID());
break;
case OC_SPAWNITEM:
{
if ( pszKey[9] == '.' )
return CScriptObj::r_WriteVal(pszKey, sVal, pSrc, pArgs);
sVal.FormatHex(m_uidSpawnItem);
break;
}
case OC_SEXTANTP:
{
pszKey += 8;
SKIP_SEPARATORS(pszKey);
GETNONWHITESPACE(pszKey);
CPointMap pt = *pszKey ? g_Cfg.GetRegionPoint(pszKey) : GetTopPoint();
if ( !pt.IsValidPoint() )
return false;
sVal = g_Cfg.Calc_MaptoSextant(pt);
break;
}
case OC_TIMESTAMP:
sVal.FormatLLVal(GetTimeStamp().GetTimeRaw());
break;
case OC_WEIGHT:
sVal.FormatVal(GetWeight());
break;
case OC_Z:
sVal.FormatVal(GetTopZ());
break;
case OC_TAGAT:
{
pszKey += 5;
if ( *pszKey == '.' ) // do we have an argument?
{
SKIP_SEPARATORS(pszKey);
size_t iQty = static_cast<size_t>(Exp_GetVal(pszKey));
if ( iQty >= m_TagDefs.GetCount() )
return false; // trying to get non-existant tag
const CVarDefCont *pTagAt = m_TagDefs.GetAt(iQty);
if ( !pTagAt )
return false; // trying to get non-existant tag
SKIP_SEPARATORS(pszKey);
if ( !*pszKey )
{
sVal.Format("%s=%s", pTagAt->GetKey(), pTagAt->GetValStr());
return true;
}
else if ( !strnicmp(pszKey, "KEY", 3) )
{
sVal = pTagAt->GetKey();
return true;
}
else if ( !strnicmp(pszKey, "VAL", 3) )
{
sVal = pTagAt->GetValStr();
return true;
}
}
return false;
}
case OC_TAGCOUNT:
sVal.FormatVal(m_TagDefs.GetCount());
break;
case OC_PROPSAT:
{
pszKey += 7; // eat the 'TAGAT'
if ( *pszKey == '.' ) // do we have an argument?
{
SKIP_SEPARATORS(pszKey);
size_t iQty = static_cast<size_t>(Exp_GetVal(pszKey));
if ( iQty >= m_BaseDefs.GetCount() )
return false; // trying to get non-existant tag
const CVarDefCont *pTagAt = m_BaseDefs.GetAt(iQty);
if ( !pTagAt )
return false; // trying to get non-existant tag
SKIP_SEPARATORS(pszKey);
if ( !*pszKey )
{
sVal.Format("%s=%s", pTagAt->GetKey(), pTagAt->GetValStr());
return true;
}
else if ( !strnicmp(pszKey, "KEY", 3) )
{
sVal = pTagAt->GetKey();
return true;
}
else if ( !strnicmp(pszKey, "VAL", 3) )
{
sVal = pTagAt->GetValStr();
return true;
}
}
return false;
}
case OC_PROPSCOUNT:
sVal.FormatVal(m_BaseDefs.GetCount());
break;
case OC_AGE:
case OC_CHANGER:
break;
default:
return false;
}
return true;
EXC_CATCH;
EXC_DEBUG_START;
EXC_ADD_KEYRET(pSrc);
EXC_DEBUG_END;
return false;
}
bool CObjBase::r_LoadVal(CScript &s, CScriptTriggerArgs* pArgs, CTextConsole* pSrc)
{
ADDTOCALLSTACK("CObjBase::r_LoadVal");
// load the basic stuff.
EXC_TRY("LoadVal");
// we're using FindTableSorted so we must do this here.
// Using FindTableHeadSorted instead would result in keywords
// starting with "P" not working, for instance :)
LPCTSTR pszKey = s.GetKey();
if ( s.IsKeyHead("TAG.", 4))
{
if (s.IsKeyHead("TAG.REMOVE",10))
{
LPCTSTR pszArgs = s.GetArgStr();
m_TagDefs.DeleteKey(pszArgs);
return true;
}
else
{
bool fQuoted = false;
TCHAR* arg2 = s.GetArgStr(&fQuoted);
if (*arg2 == '#')
{
LPCTSTR ppArg2 = arg2 + 1;
if (!IsStrNumeric(ppArg2))
{
LPCTSTR pszVarName = s.GetKey() + 4;
LPCTSTR sVal = m_TagDefs.GetKeyStr(pszVarName, false, pArgs, pSrc, this);
if (strlen(sVal) > 0)
{
TemporaryString pszBuffer;
strcpy(pszBuffer, sVal);
strcat(pszBuffer, arg2 + 1);
int iValue = Exp_GetVal(pszBuffer);
m_TagDefs.SetNum(pszVarName, iValue, false, pArgs, pSrc, this);
}
else
m_TagDefs.SetStr(s.GetKey() + 4, fQuoted, arg2, false, pArgs, pSrc, this);
}
else
{
m_TagDefs.SetStr(s.GetKey() + 4, fQuoted, arg2, false, pArgs, pSrc, this);
}
}
else
m_TagDefs.SetStr(s.GetKey() + 4, fQuoted, arg2, false, pArgs, pSrc, this);
return true;
}
}
else if ( s.IsKeyHead("TAG0.", 5) )
{
bool fQuoted = false;
m_TagDefs.SetStr(s.GetKey() + 5, fQuoted, s.GetArgStr(&fQuoted), true, pArgs, pSrc, this);
return true;
}
int index = FindTableSorted(s.GetKey(), sm_szLoadKeys, COUNTOF(sm_szLoadKeys) - 1);
if ( index < 0 )
return CScriptObj::r_LoadVal(s, pArgs, pSrc);
bool fSendUpdate = false;
switch ( index )
{
// Set as numeric
case OC_DAMCHAOS:
case OC_DAMDIRECT:
case OC_EXPANSION:
case OC_NAMELOC:
SetDefNum(s.GetKey(), s.GetArgVal(pArgs, pSrc, this), false);
fSendUpdate = true;
break;
case OC_REGENFOOD:
case OC_REGENHITS:
case OC_REGENSTAM:
case OC_REGENMANA:
case OC_REGENVALFOOD:
case OC_REGENVALHITS:
case OC_REGENVALSTAM:
case OC_REGENVALMANA:
case OC_COMBATBONUSSTAT:
case OC_COMBATBONUSPERCENT:
SetDefNum(s.GetKey(), s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_ARMOR:
{
if ( IsChar() )
return false;
INT64 piVal[2];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piVal, COUNTOF(piVal));
m_defenseBase = static_cast<WORD>(piVal[0]);
m_defenseRange = (iArgQty > 1) ? static_cast<WORD>(piVal[1]) - m_defenseBase : 0;
fSendUpdate = true;
break;
}
case OC_DAM:
{
INT64 piVal[2];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piVal, COUNTOF(piVal));
m_attackBase = static_cast<WORD>(piVal[0]);
m_attackRange = (iArgQty > 1) ? static_cast<WORD>(piVal[1]) - m_attackBase : 0;
fSendUpdate = true;
break;
}
case OC_DAMCOLD:
m_DamCold = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_DAMENERGY:
m_DamEnergy = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_DAMFIRE:
m_DamFire = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_DAMPHYSICAL:
m_DamPhysical = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_DAMPOISON:
m_DamPoison = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_INCREASEDAM:
m_DamIncrease = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_INCREASEDEFCHANCE:
m_DefChanceIncrease = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_INCREASEDEFCHANCEMAX:
m_DefChanceIncreaseMax = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_INCREASEHITCHANCE:
m_HitChanceIncrease = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_INCREASESPELLDAM:
m_SpellDamIncrease = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_INCREASESWINGSPEED:
m_SwingSpeedIncrease = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_FASTERCASTING:
m_FasterCasting = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_FASTERCASTRECOVERY:
m_FasterCastRecovery = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_HITLEECHLIFE:
m_HitLifeLeech = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_HITLEECHMANA:
m_HitManaLeech = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_HITLEECHSTAM:
m_HitStaminaLeech = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_HITMANADRAIN:
m_HitManaDrain = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_LOWERMANACOST:
m_LowerManaCost = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_LOWERREAGENTCOST:
m_LowerReagentCost = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_ENHANCEPOTIONS:
m_EnhancePotions = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_NIGHTSIGHT:
m_NightSight = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_REFLECTPHYSICALDAM:
m_ReflectPhysicalDamage = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RANGE:
{
INT64 piVal[2];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piVal, COUNTOF(piVal));
if ( iArgQty > 1 )
{
INT64 iRange = ((piVal[0] & 0xFF) << 8) & 0xFF00;
iRange |= (piVal[1] & 0xFF);
SetDefNum(s.GetKey(), iRange, false);
}
else
SetDefNum(s.GetKey(), piVal[0], false);
fSendUpdate = true;
break;
}
case OC_CAN:
m_Can = static_cast<DWORD>(s.GetArgVal(pArgs, pSrc, this));
break;
case OC_MODMAXWEIGHT:
m_ModMaxWeight = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_COLOR:
{
if ( !strcmpi(s.GetArgStr(), "match_shirt") || !strcmpi(s.GetArgStr(), "match_hair") )
{
const CChar *pChar = dynamic_cast<const CChar *>(GetTopLevelObj());
if ( pChar )
{
const CItem *pMatch = pChar->LayerFind(!strcmpi(s.GetArgStr() + 6, "shirt") ? LAYER_SHIRT : LAYER_HAIR);
if ( pMatch )
{
m_wHue = pMatch->GetHue();
break;
}
}
m_wHue = HUE_DEFAULT;
break;
}
SetHue(static_cast<HUE_TYPE>(s.GetArgVal(pArgs, pSrc, this)), false, &g_Serv); // @Dye is called from @Create/.xcolor/script command here. Since we can not receive pSrc on this r_LoadVal function ARGO/SRC will be null
Update();
break;
}
case OC_EVENTS:
return m_OEvents.r_LoadVal(s, RES_EVENTS);
case OC_LUCK:
m_Luck = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_MAP:
case OC_MAPPLANE:
{
// Move to another map
if ( !IsTopLevel() )
return false;
CPointMap pt = GetTopPoint();
pt.m_map = static_cast<BYTE>(s.GetArgVal(pArgs, pSrc, this));
// Is the desired mapplane allowed?
if ( !g_MapList.IsMapSupported(pt.m_map) )
return false;
MoveTo(pt);
if ( IsItem() )
Update();
break;
}
case OC_MODAR:
{
m_ModAr = s.GetArgVal(pArgs, pSrc, this);
CChar *pChar = dynamic_cast<CChar *>(this);
if ( pChar )
pChar->m_defense = pChar->CalcArmorDefense();
fSendUpdate = true;
break;
}
case OC_NAME:
SetName(static_cast<LPCTSTR>(s.GetArgStr()));
fSendUpdate = true;
break;
case OC_P_X:
case OC_P_Y:
case OC_P_Z:
case OC_P:
return false; // must set the point via the CItem or CChar methods
case OC_RESCOLD:
m_ResCold = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESCOLDMAX:
m_ResColdMax = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESENERGY:
m_ResEnergy = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESENERGYMAX:
m_ResEnergyMax = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESFIRE:
m_ResFire = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESFIREMAX:
m_ResFireMax = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESPHYSICAL:
m_ResPhysical = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESPHYSICALMAX:
m_ResPhysicalMax = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESPOISON:
m_ResPoison = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_RESPOISONMAX:
m_ResPoisonMax = static_cast<int>(s.GetArgVal(pArgs, pSrc, this));
fSendUpdate = true;
break;
case OC_TIMER:
SetTimeout(s.GetArgLLVal(pArgs, pSrc, this) * TICK_PER_SEC);
break;
case OC_TIMERD:
SetTimeout(s.GetArgLLVal(pArgs, pSrc, this));
break;
case OC_TIMESTAMP:
SetTimeStamp(s.GetArgLLVal(pArgs, pSrc, this));
break;
case OC_SPAWNITEM:
if ( !g_Serv.IsLoading() ) // SPAWNITEM is read-only
return false;
m_uidSpawnItem = static_cast<CGrayUID>(s.GetArgVal(pArgs, pSrc, this));
break;
case OC_UID:
case OC_SERIAL:
// Don't set container flags through this.
SetUID(s.GetArgVal(pArgs, pSrc, this), dynamic_cast<CItem *>(this) ? true : false);
break;
default:
return false;
}
if ( fSendUpdate )
{
if ( IsItem() )
UpdatePropertyFlag();
else
static_cast<CChar *>(this)->UpdateStatsFlag();
}
return true;
EXC_CATCH;
EXC_DEBUG_START;
EXC_ADD_SCRIPT;
EXC_DEBUG_END;
return false;
}
void CObjBase::r_Write(CScript &s)
{
ADDTOCALLSTACK_INTENSIVE("CObjBase::r_Write");
s.WriteKeyHex("SERIAL", GetUID());
if ( IsIndividualName() )
s.WriteKey("NAME", GetIndividualName());
if ( m_wHue != HUE_DEFAULT )
s.WriteKeyHex("COLOR", GetHue());
if ( m_timeout.IsTimeValid() )
s.WriteKeyVal("TIMER", GetTimerAdjusted());
if ( m_timestamp.IsTimeValid() )
s.WriteKeyVal("TIMESTAMP", GetTimeStamp().GetTimeRaw());
if ( m_uidSpawnItem.IsValidUID() )
s.WriteKeyHex("SPAWNITEM", m_uidSpawnItem);
if ( m_ModAr )
s.WriteKeyVal("MODAR", m_ModAr);
if ( m_ModMaxWeight )
s.WriteKeyVal("MODMAXWEIGHT", m_ModMaxWeight);
CBaseBaseDef *pBaseDef = Base_GetDef();
ASSERT(pBaseDef);
if ( m_DamPhysical != pBaseDef->m_DamPhysical )
s.WriteKeyVal("DAMPHYSICAL", m_DamPhysical);
if ( m_DamFire != pBaseDef->m_DamFire )
s.WriteKeyVal("DAMFIRE", m_DamFire);
if ( m_DamCold != pBaseDef->m_DamCold )
s.WriteKeyVal("DAMCOLD", m_DamCold);
if ( m_DamPoison != pBaseDef->m_DamPoison )
s.WriteKeyVal("DAMPOISON", m_DamPoison);
if ( m_DamEnergy != pBaseDef->m_DamEnergy )
s.WriteKeyVal("DAMENERGY", m_DamEnergy);
if ( m_ResPhysical != pBaseDef->m_ResPhysical )
s.WriteKeyVal("RESPHYSICAL", m_ResPhysical);
if ( m_ResPhysicalMax != pBaseDef->m_ResPhysicalMax )
s.WriteKeyVal("RESPHYSICALMAX", m_ResPhysicalMax);
if ( m_ResFire != pBaseDef->m_ResFire )
s.WriteKeyVal("RESFIRE", m_ResFire);
if ( m_ResFireMax != pBaseDef->m_ResFireMax )
s.WriteKeyVal("RESFIREMAX", m_ResFireMax);
if ( m_ResCold != pBaseDef->m_ResCold )
s.WriteKeyVal("RESCOLD", m_ResCold);
if ( m_ResColdMax != pBaseDef->m_ResColdMax )
s.WriteKeyVal("RESCOLDMAX", m_ResColdMax);
if ( m_ResPoison != pBaseDef->m_ResPoison )
s.WriteKeyVal("RESPOISON", m_ResPoison);
if ( m_ResPoisonMax != pBaseDef->m_ResPoisonMax )
s.WriteKeyVal("RESPOISONMAX", m_ResPoisonMax);
if ( m_ResEnergy != pBaseDef->m_ResEnergy )
s.WriteKeyVal("RESENERGY", m_ResEnergy);
if ( m_ResEnergyMax != pBaseDef->m_ResEnergyMax )
s.WriteKeyVal("RESENERGYMAX", m_ResEnergyMax);
if ( m_Luck != pBaseDef->m_Luck )
s.WriteKeyVal("LUCK", m_Luck);
if ( m_DamIncrease != pBaseDef->m_DamIncrease )
s.WriteKeyVal("INCREASEDAM", m_DamIncrease);
if ( m_SpellDamIncrease != pBaseDef->m_SpellDamIncrease )
s.WriteKeyVal("INCREASESPELLDAM", m_SpellDamIncrease);
if ( m_HitLifeLeech != pBaseDef->m_HitLifeLeech )
s.WriteKeyVal("HITLEECHLIFE", m_HitLifeLeech);
if ( m_HitManaLeech != pBaseDef->m_HitManaLeech )
s.WriteKeyVal("HITLEECHMANA", m_HitManaLeech);
if ( m_HitStaminaLeech != pBaseDef->m_HitStaminaLeech )
s.WriteKeyVal("HITLEECHSTAM", m_HitStaminaLeech);
if ( m_HitManaDrain != pBaseDef->m_HitManaDrain )
s.WriteKeyVal("HITMANADRAIN", m_HitManaDrain);
if ( m_HitChanceIncrease != pBaseDef->m_HitChanceIncrease )
s.WriteKeyVal("INCREASEHITCHANCE", m_HitChanceIncrease);
if ( m_DefChanceIncrease != pBaseDef->m_DefChanceIncrease )
s.WriteKeyVal("INCREASEDEFCHANCE", m_DefChanceIncrease);
if ( m_DefChanceIncreaseMax != pBaseDef->m_DefChanceIncreaseMax )
s.WriteKeyVal("INCREASEDEFCHANCEMAX", m_DefChanceIncreaseMax);
if ( m_SwingSpeedIncrease != pBaseDef->m_SwingSpeedIncrease )
s.WriteKeyVal("INCREASESWINGSPEED", m_SwingSpeedIncrease);
if ( m_FasterCasting != pBaseDef->m_FasterCasting )
s.WriteKeyVal("FASTERCASTING", m_FasterCasting);
if ( m_FasterCastRecovery != pBaseDef->m_FasterCastRecovery )
s.WriteKeyVal("FASTERCASTRECOVERY", m_FasterCastRecovery);
if ( m_LowerManaCost != pBaseDef->m_LowerManaCost )
s.WriteKeyVal("LOWERMANACOST", m_LowerManaCost);
if ( m_LowerReagentCost != pBaseDef->m_LowerReagentCost )
s.WriteKeyVal("LOWERREAGENTCOST", m_LowerReagentCost);
if ( m_EnhancePotions != pBaseDef->m_EnhancePotions )
s.WriteKeyVal("ENHANCEPOTIONS", m_EnhancePotions);
if ( m_NightSight != pBaseDef->m_NightSight )
s.WriteKeyVal("NIGHTSIGHT", m_NightSight);
if ( m_ReflectPhysicalDamage != pBaseDef->m_ReflectPhysicalDamage )
s.WriteKeyVal("REFLECTPHYSICALDAM", m_ReflectPhysicalDamage);
m_BaseDefs.r_WritePrefix(s); // new variable storage system
m_TagDefs.r_WritePrefix(s, "TAG");
m_OEvents.r_Write(s, "EVENTS");
}
enum OV_TYPE
{
#define ADD(a,b) OV_##a,
#include "../tables/CObjBase_functions.tbl"
#undef ADD
OV_QTY
};
LPCTSTR const CObjBase::sm_szVerbKeys[OV_QTY+1] =
{
#define ADD(a,b) b,
#include "../tables/CObjBase_functions.tbl"
#undef ADD
NULL
};
// Execute command from script
bool CObjBase::r_Verb(CScript &s, CTextConsole *pSrc, CScriptTriggerArgs* pArgs)
{
ADDTOCALLSTACK("CObjBase::r_Verb");
EXC_TRY("Verb");
ASSERT(pSrc);
LPCTSTR pszKey = s.GetKey();
if ( !strnicmp(pszKey, "CLEARTAGS", 9) )
{
pszKey = s.GetArgStr();
SKIP_SEPARATORS(pszKey);
m_TagDefs.ClearKeys(pszKey);
return true;
}
CGString sVal;
CScriptTriggerArgs Args(s.GetArgRaw());
if ( r_Call(pszKey, pSrc, &Args, &sVal) )
return true;
int index;
if ( !strnicmp(pszKey, "TARGET", 6) )
index = OV_TARGET;
else
{
index = FindTableSorted(pszKey, sm_szVerbKeys, COUNTOF(sm_szVerbKeys) - 1);
if (index < 0)
{
if (!stricmp(pszKey, "TAG"))
{
bool fQuoted = false;
TCHAR* ppArgs[2];
size_t iCount;
LPCTSTR pszRawArgs = s.GetArgRaw();
TemporaryString varArgList;
Str_ParseArgumentList(pszRawArgs, varArgList);
Str_ParseArgumentEnd(pszRawArgs, false);
iCount = Str_ParseCmds(varArgList, ppArgs, COUNTOF(ppArgs), ",", false);
TCHAR* pszVarName = Str_TrimWhitespace(ppArgs[0]);
if (iCount > 1)
{
TCHAR* pszValue = iCount == 1 ? s.GetArgStr(&fQuoted) : ppArgs[1];
if (*pszValue == '"')
{
pszValue++;
pszValue = Str_TrimEnd(pszValue, "\"");
fQuoted = true;
}
if (*ppArgs[1] == '#')
{
LPCTSTR ppArgs2 = ppArgs[1] + 1;
if (!IsStrNumeric(ppArgs2))
{
LPCTSTR sVal = m_TagDefs.GetKeyStr(pszVarName, false, pArgs, pSrc, this);
TemporaryString pszBuffer;
strcpy(pszBuffer, sVal);
strcat(pszBuffer, ppArgs[1] + 1);
int iValue = Exp_GetVal(pszBuffer);
m_TagDefs.SetNum(pszVarName, iValue, false, pArgs, pSrc);
}
else
{
m_TagDefs.SetStr(pszVarName, fQuoted, pszValue, false, pArgs, pSrc, this);
}
}
else
{
m_TagDefs.SetStr(pszVarName, fQuoted, pszValue, false, pArgs, pSrc, this);
}
}
else
{
if (*pszRawArgs == '.')
{
pszRawArgs++;
CObjBase* pObj = static_cast<CGrayUID>(m_TagDefs.GetKeyNum(varArgList)).ObjFind();
if (pObj)
{
CScript subS(pszRawArgs);
return pObj->r_Verb(subS, pSrc, pArgs);
}
}
}
return true;
}
return CScriptObj::r_Verb(s, pSrc, pArgs);
}
}
CChar *pCharSrc = pSrc->GetChar();
CClient *pClientSrc = (pCharSrc && pCharSrc->m_pClient) ? pCharSrc->m_pClient : NULL;
switch ( index )
{
case OV_DAMAGE: // "Dmg, SourceFlags, SourceCharUid, DmgPhysical(%), DmgFire(%), DmgCold(%), DmgPoison(%), DmgEnergy(%)" = do me some damage.
{
EXC_SET("DAMAGE");
INT64 piCmd[8];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piCmd, COUNTOF(piCmd));
if ( iArgQty < 1 )
return false;
if ( iArgQty > 2 ) // Give it a new source char UID
{
CObjBaseTemplate *pObj = CGrayUID(static_cast<DWORD>(piCmd[2])).ObjFind();
if ( pObj )
pObj = pObj->GetTopLevelObj();
pCharSrc = dynamic_cast<CChar *>(pObj);
}
CChar *pChar = dynamic_cast<CChar *>(this);
CItem *pItem = dynamic_cast<CItem *>(this);
if ( pChar )
pChar->OnTakeDamage(static_cast<int>(piCmd[0]),
pCharSrc,
(iArgQty >= 2) ? static_cast<DAMAGE_TYPE>(piCmd[1]) : DAMAGE_HIT_BLUNT|DAMAGE_GENERAL,
(iArgQty >= 4) ? static_cast<int>(piCmd[3]) : 0, // physical damage %
(iArgQty >= 5) ? static_cast<int>(piCmd[4]) : 0, // fire damage %
(iArgQty >= 6) ? static_cast<int>(piCmd[5]) : 0, // cold damage %
(iArgQty >= 7) ? static_cast<int>(piCmd[6]) : 0, // poison damage %
(iArgQty >= 8) ? static_cast<int>(piCmd[7]) : 0 // energy damage %
);
else if ( pItem )
pItem->OnTakeDamage(static_cast<int>(piCmd[0]),
pCharSrc,
(iArgQty >= 2) ? static_cast<DAMAGE_TYPE>(piCmd[1]) : DAMAGE_HIT_BLUNT|DAMAGE_GENERAL
);
break;
}
case OV_EDIT:
{
EXC_SET("EDIT");
// Put up a list of items in the container. (if it is a container)
if ( !pClientSrc )
return false;
pClientSrc->m_Targ_Text = s.GetArgStr();
pClientSrc->Cmd_EditItem(this, -1);
break;
}
case OV_EFFECT:
{
EXC_SET("EFFECT");
// Visual effect based on obj location
// Syntax: EFFECT motion, id, speed, frames, [explode, color, render, effectID, explodeID, explodeSound, itemUID, layer]
INT64 piCmd[12];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piCmd, COUNTOF(piCmd));
if ( iArgQty < 2 )
return true;
Effect(
static_cast<EFFECT_TYPE>(piCmd[0]), // Motion
static_cast<ITEMID_TYPE>(RES_GET_INDEX(piCmd[1])), // ID
pCharSrc, // Source
(iArgQty >= 3) ? static_cast<BYTE>(piCmd[2]) : 0, // Speed
(iArgQty >= 4) ? static_cast<BYTE>(piCmd[3]) : 0, // Frames
(iArgQty >= 5) ? (piCmd[4] != 0) : false, // Explode
(iArgQty >= 6) ? static_cast<DWORD>(piCmd[5]) : 0, // Color
(iArgQty >= 7) ? static_cast<DWORD>(piCmd[6]) : 0, // Render
(iArgQty >= 8) ? static_cast<WORD>(piCmd[7]) : 0, // EffectID
(iArgQty >= 9) ? static_cast<WORD>(piCmd[8]) : 0, // ExplodeID
(iArgQty >= 10) ? static_cast<WORD>(piCmd[9]) : 0, // ExplodeSound
(iArgQty >= 11) ? static_cast<DWORD>(piCmd[10]) : 0, // ItemUID
(iArgQty >= 12) ? static_cast<BYTE>(piCmd[11]) : 0 // Layer
);
break;
}
case OV_EFFECTP:
{
EXC_SET("EFFECTP");
// Visual effect based on P location
// Syntax: EFFECTLOC srcX, srcY, srcZ, srcM, destX, destY, destZ, destM, motion, id, speed, frames, [explode, color, render, effectID, explodeID, explodeSound, itemUID, layer]
INT64 piCmd[20];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piCmd, COUNTOF(piCmd));
if ( iArgQty < 10 )
return true;
Effect(
static_cast<EFFECT_TYPE>(piCmd[8]), // Motion
static_cast<ITEMID_TYPE>(RES_GET_INDEX(piCmd[9])), // ID
CPointMap(static_cast<signed short>(piCmd[0]), static_cast<signed short>(piCmd[1]), static_cast<signed char>(piCmd[2]), static_cast<BYTE>(piCmd[3])), // Source P
CPointMap(static_cast<signed short>(piCmd[4]), static_cast<signed short>(piCmd[5]), static_cast<signed char>(piCmd[6]), static_cast<BYTE>(piCmd[7])), // Dest P
(iArgQty >= 11) ? static_cast<BYTE>(piCmd[10]) : 0, // Speed
(iArgQty >= 12) ? static_cast<BYTE>(piCmd[11]) : 0, // Frames
(iArgQty >= 13) ? (piCmd[12] != 0) : false, // Explode
(iArgQty >= 14) ? static_cast<DWORD>(piCmd[13]) : 0, // Color
(iArgQty >= 15) ? static_cast<DWORD>(piCmd[14]) : 0, // Render
(iArgQty >= 16) ? static_cast<WORD>(piCmd[15]) : 0, // EffectID
(iArgQty >= 17) ? static_cast<WORD>(piCmd[16]) : 0, // ExplodeID
(iArgQty >= 18) ? static_cast<WORD>(piCmd[17]) : 0, // ExplodeSound
(iArgQty >= 19) ? static_cast<DWORD>(piCmd[18]) : 0, // ItemUID
(iArgQty >= 20) ? static_cast<BYTE>(piCmd[19]) : 0 // Layer
);
break;
}
case OV_EMOTE:
EXC_SET("EMOTE");
Emote(s.GetArgStr());
break;
case OV_FLIP:
EXC_SET("FLIP");
Flip();
break;
case OV_INPDLG:
{
// "INPDLG" verb maxchars
// else assume it was a property button
EXC_SET("INPDLG");
if ( !pClientSrc )
return false;
TCHAR *ppArgs[2]; // Maximum parameters in one line
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), ppArgs, COUNTOF(ppArgs));
CGString sOrgValue;
if ( !r_WriteVal(ppArgs[0], sOrgValue, pSrc, pArgs) )
sOrgValue = ".";
pClientSrc->m_Targ_Text = ppArgs[0]; // The attribute we want to edit.
int iMaxLength = (iArgQty > 1) ? ATOI(ppArgs[1]) : 1;
CGString sPrompt;
sPrompt.Format("%s (# = default)", static_cast<LPCTSTR>(ppArgs[0]));
pClientSrc->addGumpInpVal(true, INPVAL_Text, iMaxLength, sPrompt, sOrgValue, this);
break;
}
case OV_MENU:
{
EXC_SET("MENU");
if ( !pClientSrc )
return false;
pClientSrc->Menu_Setup(g_Cfg.ResourceGetIDType(RES_MENU, s.GetArgStr()), this);
break;
}
case OV_MESSAGE: //put info message (for pSrc client only) over item.
case OV_MSG:
{
EXC_SET("MESSAGE or MSG");
if ( !pCharSrc )
UpdateObjMessage(s.GetArgStr(), s.GetArgStr(), NULL, HUE_TEXT_DEF, TALKMODE_OBJ);
else
pCharSrc->ObjMessage(s.GetArgStr(), this);
break;
}
case OV_MESSAGEUA:
{
EXC_SET("MESSAGEUA");
if ( !pClientSrc )
return false;
TCHAR *ppArgs[5];
NCHAR ncBuffer[MAX_TALK_BUFFER];
size_t iArgQty = Str_ParseCmds(s.GetArgRaw(), ppArgs, COUNTOF(ppArgs));
if ( iArgQty < 5 )
break;
CvtSystemToNUNICODE(ncBuffer, COUNTOF(ncBuffer), ppArgs[4], -1);
pClientSrc->addBarkUNICODE(ncBuffer, this, static_cast<HUE_TYPE>(ppArgs[0][0] ? Exp_GetVal(ppArgs[0]) : HUE_TEXT_DEF), static_cast<TALKMODE_TYPE>(ppArgs[1][0] ? Exp_GetVal(ppArgs[1]) : TALKMODE_SAY), static_cast<FONT_TYPE>(ppArgs[2][0] ? Exp_GetVal(ppArgs[2]) : FONT_NORMAL), CLanguageID(ppArgs[3]));
break;
}
case OV_MOVE:
{
// move without restriction. east,west,etc. (?up,down,)
EXC_SET("MOVE");
if ( IsTopLevel() )
{
CPointMap pt = GetTopPoint();
if ( !GetDeltaStr(pt, s.GetArgStr()) )
return false;
MoveTo(pt);
CChar *pChar = dynamic_cast<CChar *>(this);
if ( pChar )
{
pChar->Update(true, pChar->m_pClient);
if ( pChar->m_pClient )
pChar->m_pClient->addPlayerUpdate();
break;
}
CItem *pItem = dynamic_cast<CItem *>(this);
if ( pItem )
{
pItem->Update();
break;
}
}
break;
}
case OV_MOVENEAR:
{
EXC_SET("MOVENEAR");
CObjBase *pObjNear;
INT64 piCmd[2];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piCmd, COUNTOF(piCmd));
if ( iArgQty <= 0 )
return false;
if ( iArgQty < 2 )
piCmd[1] = 1;
pObjNear = static_cast<CGrayUID>(piCmd[0]).ObjFind();
if ( !pObjNear )
return false;
MoveNearObj(pObjNear, static_cast<WORD>(piCmd[1]));
break;
}
case OV_NUDGEDOWN:
{
EXC_SET("NUDGEDOWN");
if ( IsTopLevel() )
{
signed char zDiff = static_cast<signed char>(s.GetArgVal());
SetTopZ(GetTopZ() - (zDiff ? zDiff : 1));
CChar *pChar = dynamic_cast<CChar *>(this);
if ( pChar )
{
pChar->Update(true, pChar->m_pClient);
if ( pChar->m_pClient )
pChar->m_pClient->addPlayerUpdate();
break;
}
CItem *pItem = dynamic_cast<CItem *>(this);
if ( pItem )
{
pItem->Update();
break;
}
}
break;
}
case OV_NUDGEUP:
{
EXC_SET("NUDGEUP");
if ( IsTopLevel() )
{
signed char zDiff = static_cast<signed char>(s.GetArgVal());
SetTopZ(GetTopZ() + (zDiff ? zDiff : 1));
CChar *pChar = dynamic_cast<CChar *>(this);
if ( pChar )
{
pChar->Update(true, pChar->m_pClient);
if ( pChar->m_pClient )
pChar->m_pClient->addPlayerUpdate();
break;
}
CItem *pItem = dynamic_cast<CItem *>(this);
if ( pItem )
{
pItem->Update();
break;
}
}
break;
}
case OV_MOVETO:
case OV_P:
{
EXC_SET("P or MOVETO");
MoveTo(g_Cfg.GetRegionPoint(s.GetArgStr()));
if ( IsItem() )
Update();
break;
}
case OV_PROMPTCONSOLE:
case OV_PROMPTCONSOLEU:
{
EXC_SET("PROMPTCONSOLE/U");
if ( !pClientSrc )
return false;
TCHAR *ppArgs[2];
int iArgQty = Str_ParseCmds(s.GetArgRaw(), ppArgs, COUNTOF(ppArgs));
if ( iArgQty == 0 )
break;
pClientSrc->addPromptConsoleFunction(ppArgs[0], ppArgs[1], (index == OV_PROMPTCONSOLEU));
break;
}
case OV_INFO:
EXC_SET("INFO");
if ( !pClientSrc )
return false;
return pClientSrc->addGumpDialogProps(this);
case OV_REMOVE:
EXC_SET("REMOVE");
Delete(); // remove this object now
return true;
case OV_REMOVEFROMVIEW:
EXC_SET("REMOVEFROMVIEW");
RemoveFromView(NULL, false); // remove this object from all clients
return true;
case OV_RESENDTOOLTIP:
{
EXC_SET("RESENDTOOLTIP");
INT64 piCmd[2];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piCmd, COUNTOF(piCmd));
bool fSendFull = (iArgQty >= 1) ? (piCmd[0] != 0) : false;
bool fUseCache = (iArgQty >= 2) ? (piCmd[1] != 0) : false;
ResendTooltip(fSendFull, fUseCache);
return true;
}
case OV_SAY: // speak so everyone can here
EXC_SET("SAY");
Speak(s.GetArgStr());
break;
case OV_SAYU: // speak in unicode from the UTF8 system format
EXC_SET("SAYU");
SpeakUTF8(s.GetArgStr(), HUE_TEXT_DEF, TALKMODE_SAY, FONT_NORMAL);
break;
case OV_SAYUA: // this can have full args. SAYUA Color, Mode, Font, Lang, Text
{
EXC_SET("SAYUA");
TCHAR *ppArgs[5];
size_t iArgQty = Str_ParseCmds(s.GetArgRaw(), ppArgs, COUNTOF(ppArgs));
if ( iArgQty < 5 )
break;
SpeakUTF8(ppArgs[4], static_cast<HUE_TYPE>(ppArgs[0][0] ? Exp_GetVal(ppArgs[0]) : HUE_TEXT_DEF), static_cast<TALKMODE_TYPE>(ppArgs[1][0] ? Exp_GetVal(ppArgs[1]) : TALKMODE_SAY), static_cast<FONT_TYPE>(ppArgs[2][0] ? Exp_GetVal(ppArgs[2]) : FONT_NORMAL), CLanguageID(ppArgs[3]));
break;
}
case OV_SOUND:
{
EXC_SET("SOUND");
INT64 piCmd[2];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piCmd, COUNTOF(piCmd));
Sound(static_cast<SOUND_TYPE>(piCmd[0]), (iArgQty > 1) ? static_cast<BYTE>(piCmd[1]) : 1);
break;
}
case OV_SPELLEFFECT: // spell, strength, noresist
{
EXC_SET("SPELLEFFECT");
INT64 piCmd[4];
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), piCmd, COUNTOF(piCmd));
CItem *pItemSrc = NULL;
switch ( iArgQty )
{
case 4:
pItemSrc = static_cast<CGrayUID>(piCmd[3]).ItemFind();
case 3:
pCharSrc = (piCmd[2] == -1) ? dynamic_cast<CChar *>(this) : static_cast<CGrayUID>(piCmd[2]).CharFind();
break;
default:
break;
}
OnSpellEffect(static_cast<SPELL_TYPE>(RES_GET_INDEX(piCmd[0])), pCharSrc, static_cast<int>(piCmd[1]), pItemSrc);
break;
}
case OV_TAGLIST:
{
EXC_SET("TAGLIST");
if ( !strcmpi(s.GetArgStr(), "log") )
pSrc = &g_Serv;
m_TagDefs.DumpKeys(pSrc, "TAG.");
break;
}
case OV_PROPSLIST:
{
EXC_SET("PROPSLIST");
if ( !strcmpi(s.GetArgStr(), "log") )
pSrc = &g_Serv;
m_BaseDefs.DumpKeys(pSrc, NULL);
break;
}
case OV_TARGET:
{
EXC_SET("TARGET");
if ( !pClientSrc )
return false;
pszKey += 6;
bool fAllowGround = false;
bool fCheckCrime = false;
bool fFunction = false;
bool fMulti = false;
TCHAR chLow = static_cast<TCHAR>(tolower(*pszKey));
while ( (chLow >= 'a') && (chLow <= 'z') )
{
if ( chLow == 'f' )
fFunction = true;
else if ( chLow == 'g' )
fAllowGround = true;
else if ( chLow == 'w' )
fCheckCrime = true;
else if ( chLow == 'm' )
fMulti = true;
chLow = static_cast<TCHAR>(tolower(*(++pszKey)));
}
pClientSrc->m_Targ_UID = GetUID();
pClientSrc->m_tmUseItem.m_pParent = GetParent(); // cheat verify
if ( fFunction )
{
if ( fMulti )
{
if ( IsStrEmpty(s.GetArgStr()) )
break;
char *ppArg[3];
Str_ParseCmds(s.GetArgStr(), ppArg, COUNTOF(ppArg), ",");
if ( !IsStrNumeric(ppArg[1]) )
DEBUG_ERR(("Invalid argument in Target Multi\n"));
ITEMID_TYPE itemid = static_cast<ITEMID_TYPE>(Exp_GetVal(ppArg[1]));
HUE_TYPE color = static_cast<HUE_TYPE>(Exp_GetVal(ppArg[2]));
pClientSrc->addTargetFunctionMulti(ppArg[0], itemid, color, fAllowGround);
}
else
pClientSrc->addTargetFunction(s.GetArgStr(), fAllowGround, fCheckCrime);
}
else
{
if ( fMulti )
{
char *ppArg[2];
Str_ParseCmds(s.GetArgStr(), ppArg, COUNTOF(ppArg), ",");
if ( !IsStrNumeric(ppArg[0]) )
DEBUG_ERR(("Invalid argument in Target Multi\n"));
ITEMID_TYPE itemid = static_cast<ITEMID_TYPE>(Exp_GetVal(ppArg[0]));
HUE_TYPE color = static_cast<HUE_TYPE>(Exp_GetVal(ppArg[1]));
pClientSrc->addTargetItems(CLIMODE_TARG_USE_ITEM, itemid, color, fAllowGround);
}
else
pClientSrc->addTarget(CLIMODE_TARG_USE_ITEM, s.GetArgStr(), fAllowGround, fCheckCrime);
}
break;
}
case OV_TIMERF:
{
EXC_SET("TIMERF");
if ( !strnicmp(s.GetArgStr(), "CLEAR", 5) )
{
g_World.m_TimedFunctions.Erase(GetUID());
break;
}
else if ( !strnicmp(s.GetArgStr(), "STOP", 4) )
{
g_World.m_TimedFunctions.Stop(GetUID(), s.GetArgStr() + 5);
break;
}
TCHAR *pszFuncName = s.GetArgRaw();
int iTimer = Exp_GetVal(pszFuncName);
if ( iTimer < 0 )
{
g_Log.EventError("%s: invalid timer '%d'\n", sm_szVerbKeys[index], iTimer);
return true;
}
SKIP_ARGSEP(pszFuncName);
if ( !pszFuncName )
{
g_Log.EventError("%s: args can't be empty\n", sm_szVerbKeys[index]);
return true;
}
else if ( strlen(pszFuncName) > 1024 )
{
g_Log.EventError("%s: args exceeded max length allowed (%" FMTSIZE_T "/%d)\n", sm_szVerbKeys[index], strlen(pszFuncName), 1024);
return true;
}
g_World.m_TimedFunctions.Add(GetUID(), iTimer, pszFuncName);
break;
}
case OV_TRIGGER:
{
if ( s.HasArgs() )
{
TRIGRET_TYPE tr;
CallPersonalTrigger(s.GetArgRaw(), pSrc, tr, false);
}
break;
}
case OV_DIALOG:
case OV_SDIALOG:
{
EXC_SET("DIALOG or SDIALOG");
if ( !pClientSrc )
return false;
TCHAR *ppArgs[1]; // maximum parameters in one line
LPCTSTR pszArgs = s.GetArgStr();
GETNONWHITESPACE(pszArgs);
TemporaryString args;
Str_ParseArgumentList(pszArgs, args);
if (!Str_Parse(args, ppArgs, ","))
ppArgs[0] = NULL;
pClientSrc->Dialog_Setup(CLIMODE_DIALOG, g_Cfg.ResourceGetIDType(RES_DIALOG, args), 0, this, ppArgs[0]);
break;
}
case OV_DIALOGCLOSE:
{
EXC_SET("DIALOGCLOSE");
if ( !pClientSrc )
return false;
TCHAR *ppArgs[2]; // maximum parameters in one line
size_t iArgQty = Str_ParseCmds(s.GetArgStr(), ppArgs, COUNTOF(ppArgs));
if ( iArgQty < 1 )
return false;
DWORD context = static_cast<DWORD>(g_Cfg.ResourceGetIDType(RES_DIALOG, ppArgs[0]));
if ( pClientSrc->m_NetState->isClientKR() )
context = g_Cfg.GetKRDialog(context);
pClientSrc->Dialog_Close(this, context, (iArgQty > 1) ? Exp_GetVal(ppArgs[1]) : 0);
break;
}
case OV_TRYP:
{
EXC_SET("TRYP");
int iMinPriv = s.GetArgVal();
if ( iMinPriv >= PLEVEL_QTY )
{
pSrc->SysMessagef("The %s property can't be changed.", static_cast<LPCTSTR>(s.GetArgStr()));
return false;
}
if ( pSrc->GetPrivLevel() < iMinPriv )
{
pSrc->SysMessagef("You lack the privilege to change the %s property.", static_cast<LPCTSTR>(s.GetArgStr()));
return false;
}
// do this verb only if we can touch it.
if ( pSrc->GetPrivLevel() <= PLEVEL_Counsel )
{
if ( !pCharSrc || !pCharSrc->CanTouch(this) )
{
pSrc->SysMessagef("Can't touch %s object %s", static_cast<LPCTSTR>(s.GetArgStr()), GetName());
return false;
}
}
// no break here, TRYP only does extra checks
}
case OV_TRY:
{
EXC_SET("TRY or TRYP");
LPCTSTR pszVerb = s.GetArgStr();
CScript script(pszVerb);
g_Log.Event(LOGM_NOCONTEXT | LOGL_EVENT, "'%s' commands uid=0%" FMTDWORDH " to '%s'\n", GetName(), static_cast<DWORD>(GetUID()), pszVerb);
if ( !r_Verb(script, pSrc, pArgs) )
{
DEBUG_ERR(("Can't try %s object %s (0%" FMTDWORDH ")\n", pszVerb, GetName(), static_cast<DWORD>(GetUID())));
return false;
}
return true;
}
case OV_TRYSRC:
case OV_TRYSRV:
{
EXC_SET("TRYSRC or TRYSRV");
CGrayUID uidNewSrc;
CTextConsole *pNewSrc = NULL;
if ( index == OV_TRYSRC )
uidNewSrc = s.GetArgVal();
LPCTSTR pszVerb = s.GetArgStr();
if ( index == OV_TRYSRC )
{
if ( uidNewSrc.IsValidUID() )
pNewSrc = uidNewSrc.CharFind();
}
else
pNewSrc = &g_Serv;
if ( !pNewSrc )
{
if ( index == OV_TRYSRC )
DEBUG_ERR(("Can't trysrc %s object %s (0%" FMTDWORDH "): invalid src UID=0%" FMTDWORDH "\n", pszVerb, GetName(), static_cast<DWORD>(GetUID()), static_cast<DWORD>(uidNewSrc)));
else
DEBUG_ERR(("Can't trysrv %s object %s (0%" FMTDWORDH ")\n", pszVerb, GetName(), static_cast<DWORD>(GetUID())));
return false;
}
CScript script(pszVerb);
if ( !r_Verb(script, pNewSrc, pArgs) )
{
if ( index == OV_TRYSRC )
DEBUG_ERR(("Can't trysrc %s object %s (0%" FMTDWORDH ") with src %s (0%" FMTDWORDH ")\n", pszVerb, GetName(), static_cast<DWORD>(GetUID()), pNewSrc->GetName(), static_cast<DWORD>(uidNewSrc)));
else
DEBUG_ERR(("Can't trysrv %s object %s (0%" FMTDWORDH ")\n", pszVerb, GetName(), static_cast<DWORD>(GetUID())));
return false;
}
return true;
}
case OV_UID:
EXC_SET("UID");
// block anyone from ever doing this.
if ( pSrc )
pSrc->SysMessage("Setting the UID this way is not allowed");
return false;
case OV_UPDATEX:
EXC_SET("UPDATEX");
RemoveFromView();
// no break here, UPDATEX just remove the object from view before update it
case OV_UPDATE:
{
EXC_SET("UPDATE");
CClient *pClientExclude = NULL;
CChar *pChar = dynamic_cast<CChar *>(this);
if ( pChar && pChar->m_pClient )
{
pChar->m_pClient->addReSync();
pClientExclude = pChar->m_pClient; // don't update this client again
}
Update(true, pClientExclude);
break;
}
case OV_CLICK:
{
EXC_SET("CLICK");
if ( !pCharSrc || !pCharSrc->m_pClient )
return false;
if ( s.HasArgs() )
{
CGrayUID uid = static_cast<CGrayUID>(s.GetArgVal());
if ( !uid.ObjFind() || !IsChar() )
return false;
pCharSrc->m_pClient->Event_SingleClick(uid);
}
else
pCharSrc->m_pClient->Event_SingleClick(GetUID());
return true;
}
case OV_DCLICK:
{
EXC_SET("DCLICK");
if ( !pCharSrc )
return false;
if ( s.HasArgs() )
{
CGrayUID uid = static_cast<CGrayUID>(s.GetArgVal());
if ( !uid.ObjFind() || !IsChar() )
return false;
CChar *pChar = static_cast<CChar *>(this);
return pChar->Use_Obj(uid.ObjFind(), true, true);
}
else
return pCharSrc->Use_Obj(this, true, true);
}
case OV_USEITEM:
{
EXC_SET("USEITEM");
if ( !pCharSrc )
return false;
if ( s.HasArgs() )
{
CGrayUID uid = static_cast<CGrayUID>(s.GetArgVal());
if ( !uid.ObjFind() || !IsChar() )
return false;
CChar *pChar = static_cast<CChar *>(this);
return pChar->Use_Obj(uid.ObjFind(), false, true);
}
else
return pCharSrc->Use_Obj(this, false, true);
}
case OV_FIX:
s.GetArgStr()[0] = '\0';
// fall through
case OV_Z:
{
EXC_SET("FIX or Z");
if ( IsItemEquipped() )
return false;
CChar *pChar = dynamic_cast<CChar *>(this);
if ( pChar )
{
SetTopZ(s.HasArgs() ? static_cast<signed char>(s.GetArgVal()) : pChar->GetFixZ(GetTopPoint()));
pChar->Update(true, pChar->m_pClient);
if ( pChar->m_pClient )
pChar->m_pClient->addPlayerUpdate();
break;
}
CItem *pItem = dynamic_cast<CItem *>(this);
if ( pItem )
{
SetTopZ(s.HasArgs() ? static_cast<signed char>(s.GetArgVal()) : pItem->GetFixZ(GetTopPoint()));
pItem->Update();
break;
}
return false;
}
default:
return false;
}
return true;
EXC_CATCH;
EXC_DEBUG_START;
EXC_ADD_SCRIPTSRC;
EXC_DEBUG_END;
return false;
}
void CObjBase::RemoveFromView(CClient *pClientExclude, bool fHardcoded)
{
ADDTOCALLSTACK("CObjBase::RemoveFromView");
// Remove this item from all clients.
// In a destructor this can do funny things.
if ( IsDisconnected() )
return; // not in the world.
CObjBaseTemplate *pObjTop = GetTopLevelObj();
CItem *pItem = fHardcoded ? dynamic_cast<CItem *>(this) : NULL;
CChar *pChar = NULL;
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
if ( pClientExclude == pClient )
continue;
pChar = pClient->GetChar();
if ( !pChar )
continue;
if ( pChar->GetTopDist(pObjTop) > pChar->GetSight() ) // client does not support removing of items which are farther (will be removed from the radar on the next step, cause the server won't resend it)
continue;
if ( pItem && pItem->IsItemEquipped() )
{
if ( (pItem->GetEquipLayer() > LAYER_HORSE) && (pItem->GetEquipLayer() != LAYER_BANKBOX) && (pItem->GetEquipLayer() != LAYER_DRAGGING) )
continue;
}
if ( GetEquipLayer() == LAYER_BANKBOX )
pClient->closeUIWindow(PacketCloseUIWindow::Container, this);
pClient->addObjectRemove(this);
}
}
void CObjBase::ResendOnEquip(bool fAllClients)
{
ADDTOCALLSTACK("CObjBase::RemoveFromView");
// Remove this item from all clients if fAllClients == true, from Enhanced Client only if not.
// Then resend it.
if ( IsDisconnected() )
return; // not in the world.
CObjBaseTemplate *pObjTop = GetTopLevelObj();
CItem *pItem = dynamic_cast<CItem *>(this);
CChar *pChar = NULL;
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
if ( !fAllClients && !pClient->m_NetState->isClientEnhanced() )
continue;
pChar = pClient->GetChar();
if ( !pChar )
continue;
if ( pChar->GetTopDist(pObjTop) > pChar->GetSight() ) // client does not support removing of items which are farther (will be removed from the radar on the next step, cause the server won't resend it)
continue;
if ( pItem )
{
if ( pItem->IsItemEquipped() && !pChar->IsPriv(PRIV_GM) )
{
if ( (pItem->GetEquipLayer() > LAYER_HORSE) && (pItem->GetEquipLayer() != LAYER_BANKBOX) && (pItem->GetEquipLayer() != LAYER_DRAGGING) )
continue;
}
if ( pItem->IsTypeSpellbook() && pItem->IsItemInContainer() ) // items must be removed from view before equipping in EC when on the floor, however spellbooks cannot be removed from view or client will crash
continue;
}
if ( GetEquipLayer() == LAYER_BANKBOX )
pClient->closeUIWindow(PacketCloseUIWindow::Container, this);
pClient->addObjectRemove(this);
pClient->addItem(pItem);
}
}
void CObjBase::SetPropertyList(PacketPropertyList *pPropertyList)
{
ADDTOCALLSTACK("CObjBase::SetPropertyList");
// set the property list for this object
if ( pPropertyList == GetPropertyList() )
return;
FreePropertyList();
m_PropertyList = pPropertyList;
}
void CObjBase::FreePropertyList()
{
ADDTOCALLSTACK("CObjBase::FreePropertyList");
// free m_PropertyList
if ( m_PropertyList == NULL )
return;
delete m_PropertyList;
m_PropertyList = NULL;
}
DWORD CObjBase::UpdatePropertyRevision(DWORD dwHash)
{
ADDTOCALLSTACK("CObjBase::UpdatePropertyRevision");
if ( m_PropertyHash != dwHash )
{
// Increment revision number when property hash get changed
m_PropertyHash = dwHash;
++m_PropertyRevision;
}
return m_PropertyRevision;
}
void CObjBase::UpdatePropertyFlag()
{
ADDTOCALLSTACK("CObjBase::UpdatePropertyFlag");
if ( (!(g_Cfg.m_iFeatureAOS & FEATURE_AOS_UPDATE_B)) || g_Serv.IsLoading() )
return;
m_fStatusUpdate |= SU_UPDATE_TOOLTIP;
// Items equipped, inside containers or with timer expired doesn't receive ticks and need to be added to a list of items to be processed separately
if ( (!IsTopLevel() || IsTimerExpired()) && !g_World.m_ObjStatusUpdates.ContainsPtr(this) )
g_World.m_ObjStatusUpdates.Add(this);
}
void CObjBase::OnTickStatusUpdate()
{
ADDTOCALLSTACK("CObjBase::OnTickStatusUpdate");
// Process m_fStatusUpdate flags
if ( m_fStatusUpdate & SU_UPDATE_TOOLTIP )
ResendTooltip();
}
void CObjBase::ResendTooltip(bool fSendFull, bool fUseCache)
{
ADDTOCALLSTACK("CObjBase::ResendTooltip");
// Send tooltip packet to all nearby clients
m_fStatusUpdate &= ~SU_UPDATE_TOOLTIP;
if ( IsDisconnected() || g_Serv.IsLoading() )
return; // not in the world.
if ( !fUseCache )
FreePropertyList();
CChar *pChar = NULL;
ClientIterator it;
for ( CClient *pClient = it.next(); pClient != NULL; pClient = it.next() )
{
if ( !pClient->m_TooltipEnabled )
continue;
pChar = pClient->GetChar();
if ( !pChar || !pChar->CanSee(this) )
continue;
pClient->addAOSTooltip(this, fSendFull);
}
}
void CObjBase::DeletePrepare()
{
ADDTOCALLSTACK("CObjBase::DeletePrepare");
// Prepare to delete.
RemoveFromView();
RemoveSelf(); // Must remove early or else virtuals will fail.
}
void CObjBase::Delete(bool fForce)
{
ADDTOCALLSTACK("CObjBase::Delete");
UNREFERENCED_PARAMETER(fForce); // CObjBase doesnt use it, but CItem and CChar does use it, do not remove
if ( m_uidSpawnItem.ItemFind() )
static_cast<CItemSpawn *>(m_uidSpawnItem.ItemFind())->DelObj(GetUID());
DeletePrepare();
g_World.m_TimedFunctions.Erase(GetUID());
g_World.m_ObjDelete.InsertHead(this);
}
void CObjBase::DeleteThis()
{
Delete();
}
bool CObjBase::IsTriggerActive(LPCTSTR pszTrig)
{
return (m_RunningTrigger == pszTrig);
}
LPCTSTR CObjBase::GetTriggerActive()
{
return m_RunningTrigger ? m_RunningTrigger : "none";
}
void CObjBase::SetTriggerActive(LPCTSTR pszTrig)
{
if ( pszTrig )
{
char *chText = Str_GetTemp();
sprintf(chText, "Trigger: %s", pszTrig);
ADDTOCALLSTACK(chText);
}
m_RunningTrigger = pszTrig ? pszTrig : NULL;
}
TRIGRET_TYPE CObjBase::Spell_OnTrigger(SPELL_TYPE spell, SPTRIG_TYPE stage, CChar *pSrc, CScriptTriggerArgs *pArgs)
{
ADDTOCALLSTACK("CObjBase::Spell_OnTrigger");
CSpellDef *pSpellDef = g_Cfg.GetSpellDef(spell);
if ( !pSpellDef )
return TRIGRET_RET_TRUE;
if ( pSpellDef->HasTrigger(stage) )
{
// RES_SKILL
CResourceLock s;
if ( pSpellDef->ResourceLock(s) )
return CScriptObj::OnTriggerScript(s, CSpellDef::sm_szTrigName[stage], pSrc, pArgs);
}
return TRIGRET_RET_DEFAULT;
}
inline bool CObjBase::CallPersonalTrigger(TCHAR *pszArgs, CTextConsole *pSrc, TRIGRET_TYPE &tr, bool fFull)
{
ADDTOCALLSTACK("CObjBase::CallPersonalTrigger");
UNREFERENCED_PARAMETER(fFull);
TCHAR *ppCmdTrigger[3];
size_t iArgQty = Str_ParseCmds(pszArgs, ppCmdTrigger, COUNTOF(ppCmdTrigger), ",");
if ( iArgQty > 0 )
{
LPCTSTR pszTrigger = ppCmdTrigger[0];
CScriptTriggerArgs csTriggerArgs;
if ( iArgQty == 3 )
{
int iTriggerArgType = ATOI(ppCmdTrigger[1]);
if ( iTriggerArgType == 1 ) // 3 ARGNs
{
INT64 Arg_piCmd[3];
iArgQty = Str_ParseCmds(ppCmdTrigger[2], Arg_piCmd, COUNTOF(Arg_piCmd), ",");
if ( iArgQty == 3 )
csTriggerArgs.m_iN3 = Arg_piCmd[2];
if ( iArgQty >= 2 )
csTriggerArgs.m_iN2 = Arg_piCmd[1];
if ( iArgQty >= 1 )
csTriggerArgs.m_iN1 = Arg_piCmd[0];
}
else if ( iTriggerArgType == 2 ) // ARGS
{
csTriggerArgs.m_s1 = ppCmdTrigger[2];
csTriggerArgs.m_s1_raw = ppCmdTrigger[2];
}
else if ( iTriggerArgType == 3 ) // ARGO
{
CObjBase *pTriggerArgObj = static_cast<CGrayUID>(Exp_GetVal(ppCmdTrigger[2])).ObjFind();
if ( pTriggerArgObj )
csTriggerArgs.m_pO1 = pTriggerArgObj;
}
else if ( iTriggerArgType == 4 ) // FULL TRIGGER
{
TCHAR *ppArgs[5];
iArgQty = Str_ParseCmds(ppCmdTrigger[2], ppArgs, COUNTOF(ppArgs), ",");
// ARGS
if ( iArgQty == 5 )
{
csTriggerArgs.m_s1 = ppArgs[4];
csTriggerArgs.m_s1_raw = ppArgs[4];
}
// ARGNs
if ( iArgQty >= 4 )
csTriggerArgs.m_iN3 = Exp_GetVal(ppArgs[3]);
if ( iArgQty >= 3 )
csTriggerArgs.m_iN2 = Exp_GetVal(ppArgs[2]);
if ( iArgQty >= 2 )
csTriggerArgs.m_iN1 = Exp_GetVal(ppArgs[1]);
// ARGO
if ( iArgQty >= 1 )
{
CObjBase *pTriggerArgObj = static_cast<CGrayUID>(Exp_GetVal(ppArgs[0])).ObjFind();
if ( pTriggerArgObj )
csTriggerArgs.m_pO1 = pTriggerArgObj;
}
}
}
tr = OnTrigger(pszTrigger, pSrc, &csTriggerArgs);
return true;
}
return false;
}
| 26.967899 | 303 | 0.660486 | [
"render",
"object"
] |
049ac44cda8db39983c6096e031793807d3ff1d8 | 10,853 | cpp | C++ | compiler/nnc/unittests/transformations/Switcher.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 1 | 2020-05-22T13:53:40.000Z | 2020-05-22T13:53:40.000Z | compiler/nnc/unittests/transformations/Switcher.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 1 | 2020-09-23T23:12:23.000Z | 2020-09-23T23:20:34.000Z | compiler/nnc/unittests/transformations/Switcher.cpp | periannath/ONE | 61e0bdf2bcd0bc146faef42b85d469440e162886 | [
"Apache-2.0"
] | 1 | 2021-07-22T11:02:43.000Z | 2021-07-22T11:02:43.000Z | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. 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 <gtest/gtest.h>
#include "passes/transformations/DataFormatSwitcher.h"
#include "mir/ops/AvgPool2DOp.h"
#include "mir/ops/Conv2DOp.h"
#include "mir/ops/Deconv2DOp.h"
#include "mir/ops/DepthwiseConv2DOp.h"
#include "mir/ops/MaxPool2DOp.h"
#include "mir/ops/TransposeOp.h"
TEST(TRANSFORMATIONS, Switcher_Conv2D_NCHW2NHWC)
{
mir::Graph g;
mir::TensorType input_type{mir::DataType::FLOAT32, {1, 3, 299, 299}};
auto *input = g.create<mir::ops::InputOp>(input_type);
mir::TensorType kernel_type{mir::DataType::FLOAT32, {3, 32, 3, 3}};
auto *kernel = g.create<mir::ops::InputOp>(kernel_type);
// Conv2DOp
mir::Conv2DOpAttributes attributes;
attributes.strides = {2, 5};
attributes.padding_before = {8, 1};
attributes.padding_after = {7, 9};
attributes.data_format = mir::DataFormat::NCHW;
auto *conv = g.create<mir::ops::Conv2DOp>(input->getOutput(0), kernel->getOutput(0), attributes);
auto *output = g.create<mir::ops::OutputOp>(conv->getOutput(0));
nnc::DataFormatSwitcher switcher(mir::DataFormat::NHWC);
switcher.run(&g);
auto *trans_out = output->getInput(0)->getNode();
auto *conv_ = trans_out->getInput(0)->getNode();
auto *trans_in = conv_->getInput(0)->getNode();
auto *input_ = trans_in->getInput(0)->getNode();
ASSERT_EQ(trans_out->getType(), mir::Operation::Type::transpose);
ASSERT_NE(conv_, conv);
ASSERT_EQ(trans_in->getType(), mir::Operation::Type::transpose);
ASSERT_EQ(input_, input);
auto &in_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_in)->getAxisOrder();
auto &out_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_out)->getAxisOrder();
ASSERT_EQ(in_axis_order.size(), 4);
ASSERT_EQ(in_axis_order, std::vector<size_t>({0, 2, 3, 1}));
ASSERT_EQ(out_axis_order.size(), 4);
ASSERT_EQ(out_axis_order, std::vector<size_t>({0, 3, 1, 2}));
// Check Conv2D params
auto *nhwc_conv = dynamic_cast<mir::ops::Conv2DOp *>(conv_);
ASSERT_EQ(nhwc_conv->getDataFormat(), mir::DataFormat::NHWC);
ASSERT_EQ(nhwc_conv->getStrides(), std::vector<int32_t>({2, 5}));
ASSERT_EQ(nhwc_conv->getPaddingBefore(), std::vector<int32_t>({8, 1}));
ASSERT_EQ(nhwc_conv->getPaddingAfter(), std::vector<int32_t>({7, 9}));
}
TEST(TRANSFORMATIONS, Switcher_DWConv2D_NHWC2NCHW)
{
mir::Graph g;
mir::TensorType input_type{mir::DataType::FLOAT32, {1, 112, 112, 32}};
auto *input = g.create<mir::ops::InputOp>(input_type);
mir::TensorType kernel_type{mir::DataType::FLOAT32, {3, 3, 32, 3}};
auto *kernel = g.create<mir::ops::InputOp>(kernel_type);
// DepthwiseConv2DOp
mir::Conv2DOpAttributes attributes;
attributes.strides = {3, 25};
attributes.padding_before = {67, 123};
attributes.padding_after = {32, 356};
auto *dw_conv =
g.create<mir::ops::DepthwiseConv2DOp>(input->getOutput(0), kernel->getOutput(0), attributes);
auto *output = g.create<mir::ops::OutputOp>(dw_conv->getOutput(0));
nnc::DataFormatSwitcher switcher(mir::DataFormat::NCHW);
switcher.run(&g);
auto *trans_out = output->getInput(0)->getNode();
auto *dw_conv_ = trans_out->getInput(0)->getNode();
auto *trans_in = dw_conv_->getInput(0)->getNode();
auto *input_ = trans_in->getInput(0)->getNode();
ASSERT_EQ(trans_out->getType(), mir::Operation::Type::transpose);
ASSERT_NE(dw_conv_, dw_conv);
ASSERT_EQ(trans_in->getType(), mir::Operation::Type::transpose);
ASSERT_EQ(input_, input);
auto &in_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_in)->getAxisOrder();
auto &out_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_out)->getAxisOrder();
ASSERT_EQ(in_axis_order.size(), 4);
ASSERT_EQ(in_axis_order, std::vector<size_t>({0, 3, 1, 2}));
ASSERT_EQ(out_axis_order.size(), 4);
ASSERT_EQ(out_axis_order, std::vector<size_t>({0, 2, 3, 1}));
// Check DepthwiseConv2D params
auto *nhwc_dw_conv = dynamic_cast<mir::ops::DepthwiseConv2DOp *>(dw_conv_);
ASSERT_EQ(nhwc_dw_conv->getDataFormat(), mir::DataFormat::NCHW);
ASSERT_EQ(nhwc_dw_conv->getStrides(), std::vector<int32_t>({3, 25}));
ASSERT_EQ(nhwc_dw_conv->getPaddingBefore(), std::vector<int32_t>({67, 123}));
ASSERT_EQ(nhwc_dw_conv->getPaddingAfter(), std::vector<int32_t>({32, 356}));
}
TEST(TRANSFORMATIONS, Switcher_DeConv2D_NHWC2NCHW)
{
mir::Graph g;
mir::TensorType input_type{mir::DataType::FLOAT32, {1, 112, 112, 32}};
auto *input = g.create<mir::ops::InputOp>(input_type);
mir::TensorType kernel_type{mir::DataType::FLOAT32, {3, 3, 3, 32}};
auto *kernel = g.create<mir::ops::InputOp>(kernel_type);
// DeConv2DOp
mir::Deconv2DOpAttributes attributes;
attributes.strides = {255, 54};
attributes.padding_before = {31, 72};
attributes.padding_after = {32, 71};
auto *deconv =
g.create<mir::ops::DeConv2DOp>(input->getOutput(0), kernel->getOutput(0), attributes);
auto *output = g.create<mir::ops::OutputOp>(deconv->getOutput(0));
nnc::DataFormatSwitcher switcher(mir::DataFormat::NCHW);
switcher.run(&g);
auto *trans_out = output->getInput(0)->getNode();
auto *deconv_ = trans_out->getInput(0)->getNode();
auto *trans_in = deconv_->getInput(0)->getNode();
auto *input_ = trans_in->getInput(0)->getNode();
ASSERT_EQ(trans_out->getType(), mir::Operation::Type::transpose);
ASSERT_NE(deconv_, deconv);
ASSERT_EQ(trans_in->getType(), mir::Operation::Type::transpose);
ASSERT_EQ(input_, input);
auto &in_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_in)->getAxisOrder();
auto &out_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_out)->getAxisOrder();
ASSERT_EQ(in_axis_order.size(), 4);
ASSERT_EQ(in_axis_order, std::vector<size_t>({0, 3, 1, 2}));
ASSERT_EQ(out_axis_order.size(), 4);
ASSERT_EQ(out_axis_order, std::vector<size_t>({0, 2, 3, 1}));
// Check DeConv2D params
auto *nhwc_deconv = dynamic_cast<mir::ops::DeConv2DOp *>(deconv_);
ASSERT_EQ(nhwc_deconv->getDataFormat(), mir::DataFormat::NCHW);
ASSERT_EQ(nhwc_deconv->getStrides(), std::vector<int32_t>({255, 54}));
ASSERT_EQ(nhwc_deconv->getPaddingBefore(), std::vector<int32_t>({31, 72}));
ASSERT_EQ(nhwc_deconv->getPaddingAfter(), std::vector<int32_t>({32, 71}));
}
TEST(TRANSFORMATIONS, Switcher_AvgPool2D_NHWC2NCHW)
{
mir::Graph g;
mir::TensorType input_type{mir::DataType::FLOAT32, {1, 112, 112, 32}};
auto *input = g.create<mir::ops::InputOp>(input_type);
// AvgPool2DOp
mir::AvgPool2DOpAttributes attributes;
attributes.window = {41, 54};
attributes.strides = {22, 53};
attributes.padding_before = {11, 36};
attributes.padding_after = {38, 45};
auto *avg_pool = g.create<mir::ops::AvgPool2DOp>(input->getOutput(0), attributes);
auto *output = g.create<mir::ops::OutputOp>(avg_pool->getOutput(0));
nnc::DataFormatSwitcher switcher(mir::DataFormat::NCHW);
switcher.run(&g);
auto *trans_out = output->getInput(0)->getNode();
auto *avg_pool_ = trans_out->getInput(0)->getNode();
auto *trans_in = avg_pool_->getInput(0)->getNode();
auto *input_ = trans_in->getInput(0)->getNode();
ASSERT_EQ(trans_out->getType(), mir::Operation::Type::transpose);
ASSERT_NE(avg_pool_, avg_pool);
ASSERT_EQ(trans_in->getType(), mir::Operation::Type::transpose);
ASSERT_EQ(input_, input);
auto &in_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_in)->getAxisOrder();
auto &out_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_out)->getAxisOrder();
ASSERT_EQ(in_axis_order.size(), 4);
ASSERT_EQ(in_axis_order, std::vector<size_t>({0, 3, 1, 2}));
ASSERT_EQ(out_axis_order.size(), 4);
ASSERT_EQ(out_axis_order, std::vector<size_t>({0, 2, 3, 1}));
// Check AvgPool2D params
auto *nhwc_avg_pool = dynamic_cast<mir::ops::AvgPool2DOp *>(avg_pool_);
ASSERT_EQ(nhwc_avg_pool->getDataFormat(), mir::DataFormat::NCHW);
ASSERT_EQ(nhwc_avg_pool->getWindowSize(), std::vector<int32_t>({41, 54}));
ASSERT_EQ(nhwc_avg_pool->getStrides(), std::vector<int32_t>({22, 53}));
ASSERT_EQ(nhwc_avg_pool->getPaddingBefore(), std::vector<int32_t>({11, 36}));
ASSERT_EQ(nhwc_avg_pool->getPaddingAfter(), std::vector<int32_t>({38, 45}));
ASSERT_EQ(nhwc_avg_pool->getIncludePad(), true);
}
TEST(TRANSFORMATIONS, Switcher_MaxPool2D_NCHW2NHWC)
{
mir::Graph g;
mir::TensorType input_type{mir::DataType::FLOAT32, {1, 3, 299, 299}};
auto *input = g.create<mir::ops::InputOp>(input_type);
mir::TensorType kernel_type{mir::DataType::FLOAT32, {3, 32, 3, 3}};
auto *kernel = g.create<mir::ops::InputOp>(kernel_type);
// MaxPool2DOp
mir::MaxPool2DOpAttributes attributes;
attributes.window = {41, 54};
attributes.strides = {22, 53};
attributes.padding_before = {11, 36};
attributes.padding_after = {38, 45};
attributes.data_format = mir::DataFormat::NCHW;
auto *max_pool = g.create<mir::ops::MaxPool2DOp>(input->getOutput(0), attributes);
auto *output = g.create<mir::ops::OutputOp>(max_pool->getOutput(0));
nnc::DataFormatSwitcher switcher(mir::DataFormat::NHWC);
switcher.run(&g);
auto *trans_out = output->getInput(0)->getNode();
auto *max_pool_ = trans_out->getInput(0)->getNode();
auto *trans_in = max_pool_->getInput(0)->getNode();
auto *input_ = trans_in->getInput(0)->getNode();
ASSERT_EQ(trans_out->getType(), mir::Operation::Type::transpose);
ASSERT_NE(max_pool_, max_pool);
ASSERT_EQ(trans_in->getType(), mir::Operation::Type::transpose);
ASSERT_EQ(input_, input);
auto &in_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_in)->getAxisOrder();
auto &out_axis_order = dynamic_cast<mir::ops::TransposeOp *>(trans_out)->getAxisOrder();
ASSERT_EQ(in_axis_order.size(), 4);
ASSERT_EQ(in_axis_order, std::vector<size_t>({0, 2, 3, 1}));
ASSERT_EQ(out_axis_order.size(), 4);
ASSERT_EQ(out_axis_order, std::vector<size_t>({0, 3, 1, 2}));
// Check MaxPool2D params
auto *nhwc_max_pool = dynamic_cast<mir::ops::MaxPool2DOp *>(max_pool_);
ASSERT_EQ(nhwc_max_pool->getDataFormat(), mir::DataFormat::NHWC);
ASSERT_EQ(nhwc_max_pool->getWindowSize(), std::vector<int32_t>({41, 54}));
ASSERT_EQ(nhwc_max_pool->getStrides(), std::vector<int32_t>({22, 53}));
ASSERT_EQ(nhwc_max_pool->getPaddingBefore(), std::vector<int32_t>({11, 36}));
ASSERT_EQ(nhwc_max_pool->getPaddingAfter(), std::vector<int32_t>({38, 45}));
}
| 39.754579 | 99 | 0.709389 | [
"vector"
] |
049bfea0f1128a115a006efae65a06c125bf3a09 | 696 | cpp | C++ | src/QRtMidiIn.cpp | dalfry/hairless-simicat | 76f7badfe09d1528addd304bb64c56c55acb766b | [
"BSD-2-Clause"
] | 1 | 2019-07-31T11:57:22.000Z | 2019-07-31T11:57:22.000Z | src/QRtMidiIn.cpp | dalfry/hairless-simicat | 76f7badfe09d1528addd304bb64c56c55acb766b | [
"BSD-2-Clause"
] | null | null | null | src/QRtMidiIn.cpp | dalfry/hairless-simicat | 76f7badfe09d1528addd304bb64c56c55acb766b | [
"BSD-2-Clause"
] | 1 | 2021-05-22T11:17:46.000Z | 2021-05-22T11:17:46.000Z | #include "QRtMidiIn.h"
static void midiCallbackOuter(double timeStamp, std::vector<unsigned char> *message, void *userData)
{
QRtMidiIn *midi =(QRtMidiIn *)userData;
midi->midiCallback(timeStamp, message);
}
QRtMidiIn::QRtMidiIn(const std::string clientName) :
QObject(0),
RtMidiIn(clientName)
{
this->ignoreTypes(false,false,false); // we want MIDI SysEx, time & sense messages
this->setCallback(midiCallbackOuter, this);
}
void QRtMidiIn::midiCallback(double timeStamp, std::vector<unsigned char> *message)
{
QByteArray messageCopy = QByteArray((const char *)message->data(), message->size());
emit messageReceived(timeStamp, messageCopy);
}
| 30.26087 | 100 | 0.712644 | [
"vector"
] |
04a0f9c385b64c3dde7468e00cc757576b1350ba | 4,714 | cc | C++ | libsrc/pylith/problems/SolverLinear.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | 1 | 2021-01-20T17:18:28.000Z | 2021-01-20T17:18:28.000Z | libsrc/pylith/problems/SolverLinear.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | null | null | null | libsrc/pylith/problems/SolverLinear.cc | joegeisz/pylith | f74060b7b19d7e90abf8597bbe9250c96593c0ad | [
"MIT"
] | null | null | null | // -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ======================================================================
//
#include <portinfo>
#include "SolverLinear.hh" // implementation of class methods
#include "Formulation.hh" // USES Formulation
#include "pylith/topology/Mesh.hh" // USES Mesh
#include "pylith/topology/Field.hh" // USES Field
#include "pylith/topology/SolutionFields.hh" // USES SolutionFields
#include "pylith/topology/Jacobian.hh" // USES Jacobian
#include "pylith/utils/EventLogger.hh" // USES EventLogger
#include <petscksp.h> // USES PetscKSP
#include "pylith/utils/error.h" // USES PYLITH_CHECK_ERROR
// ----------------------------------------------------------------------
// Constructor
pylith::problems::SolverLinear::SolverLinear(void) :
_ksp(0)
{ // constructor
} // constructor
// ----------------------------------------------------------------------
// Destructor
pylith::problems::SolverLinear::~SolverLinear(void)
{ // destructor
deallocate();
} // destructor
// ----------------------------------------------------------------------
// Deallocate data structures.
void
pylith::problems::SolverLinear::deallocate(void)
{ // deallocate
PYLITH_METHOD_BEGIN;
Solver::deallocate();
PetscErrorCode err = KSPDestroy(&_ksp);PYLITH_CHECK_ERROR(err);
PYLITH_METHOD_END;
} // deallocate
// ----------------------------------------------------------------------
// Initialize solver.
void
pylith::problems::SolverLinear::initialize(const topology::SolutionFields& fields,
const topology::Jacobian& jacobian,
Formulation* formulation)
{ // initialize
PYLITH_METHOD_BEGIN;
assert(formulation);
_initializeLogger();
Solver::initialize(fields, jacobian, formulation);
PetscErrorCode err = 0;
err = KSPDestroy(&_ksp);PYLITH_CHECK_ERROR(err);
err = KSPCreate(fields.mesh().comm(), &_ksp);PYLITH_CHECK_ERROR(err);
err = KSPSetInitialGuessNonzero(_ksp, PETSC_FALSE);PYLITH_CHECK_ERROR(err);
err = KSPSetFromOptions(_ksp);PYLITH_CHECK_ERROR(err);
if (formulation->splitFields()) {
PetscPC pc = 0;
err = KSPGetPC(_ksp, &pc);PYLITH_CHECK_ERROR(err);
_setupFieldSplit(&pc, formulation, jacobian, fields);
} // if
if (!_skipNullSpaceCreation) {
_createNullSpace(fields);
} // if
PYLITH_METHOD_END;
} // initialize
// ----------------------------------------------------------------------
// Solve the system.
void
pylith::problems::SolverLinear::solve(topology::Field* solution,
topology::Jacobian* jacobian,
const topology::Field& residual)
{ // solve
PYLITH_METHOD_BEGIN;
assert(solution);
assert(jacobian);
assert(_formulation);
const int setupEvent = _logger->eventId("SoLi setup");
const int solveEvent = _logger->eventId("SoLi solve");
const int scatterEvent = _logger->eventId("SoLi scatter");
_logger->eventBegin(scatterEvent);
// Update PetscVector view of field.
residual.scatterLocalToGlobal();
_logger->eventEnd(scatterEvent);
_logger->eventBegin(setupEvent);
PetscErrorCode err = 0;
const PetscMat jacobianMat = jacobian->matrix();
err = KSPSetOperators(_ksp, jacobianMat, jacobianMat);PYLITH_CHECK_ERROR(err);
jacobian->resetValuesChanged();
const PetscVec residualVec = residual.globalVector();
const PetscVec solutionVec = solution->globalVector();
_logger->eventEnd(setupEvent);
_logger->eventBegin(solveEvent);
err = KSPSolve(_ksp, residualVec, solutionVec); PYLITH_CHECK_ERROR(err);
_logger->eventEnd(solveEvent);
_logger->eventBegin(scatterEvent);
// Update section view of field.
solution->scatterGlobalToLocal();
_logger->eventEnd(scatterEvent);
// Update rate fields to be consistent with current solution.
_formulation->calcRateFields();
PYLITH_METHOD_END;
} // solve
// ----------------------------------------------------------------------
// Initialize logger.
void
pylith::problems::SolverLinear::_initializeLogger(void)
{ // initializeLogger
PYLITH_METHOD_BEGIN;
delete _logger; _logger = new utils::EventLogger;assert(_logger);
_logger->className("SolverLinear");
_logger->initialize();
_logger->registerEvent("SoLi setup");
_logger->registerEvent("SoLi solve");
_logger->registerEvent("SoLi scatter");
PYLITH_METHOD_END;
} // initializeLogger
// End of file
| 28.227545 | 82 | 0.63916 | [
"mesh"
] |
04a56dfdb676af279b8f6de0c4eda1163ed18514 | 11,516 | cpp | C++ | 3rdparty/wxWidgets/src/msw/dlmsw.cpp | mikiec84/winsparkle | e73db4ddb3be830b36b58e2f90f4bee6a0c684b7 | [
"MIT"
] | 2 | 2015-01-10T09:15:16.000Z | 2018-01-03T21:21:46.000Z | 3rdparty/wxWidgets/src/msw/dlmsw.cpp | mikiec84/winsparkle | e73db4ddb3be830b36b58e2f90f4bee6a0c684b7 | [
"MIT"
] | null | null | null | 3rdparty/wxWidgets/src/msw/dlmsw.cpp | mikiec84/winsparkle | e73db4ddb3be830b36b58e2f90f4bee6a0c684b7 | [
"MIT"
] | 1 | 2019-01-20T12:55:33.000Z | 2019-01-20T12:55:33.000Z | /////////////////////////////////////////////////////////////////////////////
// Name: msw/dlmsw.cpp
// Purpose: Win32-specific part of wxDynamicLibrary and related classes
// Author: Vadim Zeitlin
// Modified by:
// Created: 2005-01-10 (partly extracted from common/dynlib.cpp)
// RCS-ID: $Id: dlmsw.cpp 62801 2009-12-07 03:04:33Z VZ $
// Copyright: (c) 1998-2005 Vadim Zeitlin <vadim@wxwindows.org>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_DYNLIB_CLASS
#include "wx/msw/private.h"
#include "wx/msw/debughlp.h"
const wxString wxDynamicLibrary::ms_dllext(wxT(".dll"));
// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------
// wrap some functions from version.dll: load them dynamically and provide a
// clean interface
class wxVersionDLL
{
public:
// load version.dll and bind to its functions
wxVersionDLL();
// return the file version as string, e.g. "x.y.z.w"
wxString GetFileVersion(const wxString& filename) const;
private:
typedef DWORD (APIENTRY *GetFileVersionInfoSize_t)(PTSTR, PDWORD);
typedef BOOL (APIENTRY *GetFileVersionInfo_t)(PTSTR, DWORD, DWORD, PVOID);
typedef BOOL (APIENTRY *VerQueryValue_t)(const PVOID, PTSTR, PVOID *, PUINT);
#define DO_FOR_ALL_VER_FUNCS(what) \
what(GetFileVersionInfoSize); \
what(GetFileVersionInfo); \
what(VerQueryValue)
#define DECLARE_VER_FUNCTION(func) func ## _t m_pfn ## func
DO_FOR_ALL_VER_FUNCS(DECLARE_VER_FUNCTION);
#undef DECLARE_VER_FUNCTION
wxDynamicLibrary m_dll;
wxDECLARE_NO_COPY_CLASS(wxVersionDLL);
};
// class used to create wxDynamicLibraryDetails objects
class WXDLLIMPEXP_BASE wxDynamicLibraryDetailsCreator
{
public:
// type of parameters being passed to EnumModulesProc
struct EnumModulesProcParams
{
wxDynamicLibraryDetailsArray *dlls;
wxVersionDLL *verDLL;
};
// the declared type of the first EnumModulesProc() parameter changed in
// recent SDK versions and is no PCSTR instead of old PSTR, we know that
// it's const in version 11 and non-const in version 8 included with VC8
// (and earlier), suppose that it's only changed in version 11
#if defined(API_VERSION_NUMBER) && API_VERSION_NUMBER >= 11
typedef PCSTR NameStr_t;
#else
typedef PSTR NameStr_t;
#endif
// TODO: fix EnumerateLoadedModules() to use EnumerateLoadedModules64()
#ifdef __WIN64__
typedef DWORD64 DWORD_32_64;
#else
typedef DWORD DWORD_32_64;
#endif
static BOOL CALLBACK
EnumModulesProc(NameStr_t name, DWORD_32_64 base, ULONG size, void *data);
};
// ============================================================================
// wxVersionDLL implementation
// ============================================================================
// ----------------------------------------------------------------------------
// loading
// ----------------------------------------------------------------------------
wxVersionDLL::wxVersionDLL()
{
// don't give errors if DLL can't be loaded or used, we're prepared to
// handle it
wxLogNull noLog;
if ( m_dll.Load(wxT("version.dll"), wxDL_VERBATIM) )
{
// the functions we load have either 'A' or 'W' suffix depending on
// whether we're in ANSI or Unicode build
#ifdef UNICODE
#define SUFFIX L"W"
#else // ANSI
#define SUFFIX "A"
#endif // UNICODE/ANSI
#define LOAD_VER_FUNCTION(name) \
m_pfn ## name = (name ## _t)m_dll.GetSymbol(wxT(#name SUFFIX)); \
if ( !m_pfn ## name ) \
{ \
m_dll.Unload(); \
return; \
}
DO_FOR_ALL_VER_FUNCS(LOAD_VER_FUNCTION);
#undef LOAD_VER_FUNCTION
}
}
// ----------------------------------------------------------------------------
// wxVersionDLL operations
// ----------------------------------------------------------------------------
wxString wxVersionDLL::GetFileVersion(const wxString& filename) const
{
wxString ver;
if ( m_dll.IsLoaded() )
{
wxChar *pc = const_cast<wxChar *>((const wxChar*) filename.t_str());
DWORD dummy;
DWORD sizeVerInfo = m_pfnGetFileVersionInfoSize(pc, &dummy);
if ( sizeVerInfo )
{
wxCharBuffer buf(sizeVerInfo);
if ( m_pfnGetFileVersionInfo(pc, 0, sizeVerInfo, buf.data()) )
{
void *pVer;
UINT sizeInfo;
if ( m_pfnVerQueryValue(buf.data(),
const_cast<wxChar *>(wxT("\\")),
&pVer,
&sizeInfo) )
{
VS_FIXEDFILEINFO *info = (VS_FIXEDFILEINFO *)pVer;
ver.Printf(wxT("%d.%d.%d.%d"),
HIWORD(info->dwFileVersionMS),
LOWORD(info->dwFileVersionMS),
HIWORD(info->dwFileVersionLS),
LOWORD(info->dwFileVersionLS));
}
}
}
}
//else: we failed to load DLL, can't retrieve version info
return ver;
}
// ============================================================================
// wxDynamicLibraryDetailsCreator implementation
// ============================================================================
/* static */
BOOL CALLBACK
wxDynamicLibraryDetailsCreator::EnumModulesProc(NameStr_t name,
DWORD_32_64 base,
ULONG size,
void *data)
{
EnumModulesProcParams *params = (EnumModulesProcParams *)data;
wxDynamicLibraryDetails *details = new wxDynamicLibraryDetails;
// fill in simple properties
details->m_name = wxString::FromAscii(name);
details->m_address = wxUIntToPtr(base);
details->m_length = size;
// to get the version, we first need the full path
const HMODULE
hmod = wxDynamicLibrary::MSWGetModuleHandle(name, details->m_address);
if ( hmod )
{
wxString fullname = wxGetFullModuleName(hmod);
if ( !fullname.empty() )
{
details->m_path = fullname;
details->m_version = params->verDLL->GetFileVersion(fullname);
}
}
params->dlls->Add(details);
// continue enumeration (returning FALSE would have stopped it)
return TRUE;
}
// ============================================================================
// wxDynamicLibrary implementation
// ============================================================================
// ----------------------------------------------------------------------------
// misc functions
// ----------------------------------------------------------------------------
wxDllType wxDynamicLibrary::GetProgramHandle()
{
return (wxDllType)::GetModuleHandle(NULL);
}
// ----------------------------------------------------------------------------
// loading/unloading DLLs
// ----------------------------------------------------------------------------
/* static */
wxDllType
wxDynamicLibrary::RawLoad(const wxString& libname, int flags)
{
return flags & wxDL_GET_LOADED
? ::GetModuleHandle(libname.t_str())
: ::LoadLibrary(libname.t_str());
}
/* static */
void wxDynamicLibrary::Unload(wxDllType handle)
{
::FreeLibrary(handle);
}
/* static */
void *wxDynamicLibrary::RawGetSymbol(wxDllType handle, const wxString& name)
{
return (void *)::GetProcAddress(handle,
#ifdef __WXWINCE__
name.c_str()
#else
name.ToAscii()
#endif // __WXWINCE__
);
}
// ----------------------------------------------------------------------------
// enumerating loaded DLLs
// ----------------------------------------------------------------------------
/* static */
wxDynamicLibraryDetailsArray wxDynamicLibrary::ListLoaded()
{
wxDynamicLibraryDetailsArray dlls;
#if wxUSE_DBGHELP
if ( wxDbgHelpDLL::Init() )
{
// prepare to use functions for version info extraction
wxVersionDLL verDLL;
wxDynamicLibraryDetailsCreator::EnumModulesProcParams params;
params.dlls = &dlls;
params.verDLL = &verDLL;
if ( !wxDbgHelpDLL::EnumerateLoadedModules
(
::GetCurrentProcess(),
wxDynamicLibraryDetailsCreator::EnumModulesProc,
¶ms
) )
{
wxLogLastError(wxT("EnumerateLoadedModules"));
}
}
#endif // wxUSE_DBGHELP
return dlls;
}
/* static */
HMODULE wxDynamicLibrary::MSWGetModuleHandle(const char *name, void *addr)
{
// we want to use GetModuleHandleEx() instead of usual GetModuleHandle()
// because the former works correctly for comctl32.dll while the latter
// returns NULL when comctl32.dll version 6 is used under XP (note that
// GetModuleHandleEx() is only available under XP and later, coincidence?)
// check if we can use GetModuleHandleEx
typedef BOOL (WINAPI *GetModuleHandleEx_t)(DWORD, LPCSTR, HMODULE *);
static const GetModuleHandleEx_t INVALID_FUNC_PTR = (GetModuleHandleEx_t)-1;
static GetModuleHandleEx_t s_pfnGetModuleHandleEx = INVALID_FUNC_PTR;
if ( s_pfnGetModuleHandleEx == INVALID_FUNC_PTR )
{
wxDynamicLibrary dll(wxT("kernel32.dll"), wxDL_VERBATIM);
s_pfnGetModuleHandleEx =
(GetModuleHandleEx_t)dll.RawGetSymbol(wxT("GetModuleHandleExA"));
// dll object can be destroyed, kernel32.dll won't be unloaded anyhow
}
// get module handle from its address
if ( s_pfnGetModuleHandleEx )
{
// flags are GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
// GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
HMODULE hmod;
if ( s_pfnGetModuleHandleEx(6, (char *)addr, &hmod) && hmod )
return hmod;
}
// Windows CE only has Unicode API, so even we have an ANSI string here, we
// still need to use GetModuleHandleW() there
#ifdef __WXWINCE__
return ::GetModuleHandleW(wxConvLibc.cMB2WC(name).data());
#else
return ::GetModuleHandleA((char *)name);
#endif
}
#endif // wxUSE_DYNLIB_CLASS
| 33.672515 | 81 | 0.496179 | [
"object"
] |
04a662ec420020678596807f3ec52b7111a2a685 | 29,238 | cc | C++ | chrome/browser/ash/power/ml/adaptive_screen_brightness_manager_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/ash/power/ml/adaptive_screen_brightness_manager_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/ash/power/ml/adaptive_screen_brightness_manager_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ash/power/ml/adaptive_screen_brightness_manager.h"
#include <memory>
#include <vector>
#include "base/test/test_mock_time_task_runner.h"
#include "base/timer/timer.h"
#include "chrome/browser/ash/accessibility/accessibility_manager.h"
#include "chrome/browser/ash/accessibility/magnification_manager.h"
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/ash/power/ml/adaptive_screen_brightness_ukm_logger.h"
#include "chrome/browser/ash/power/ml/screen_brightness_event.pb.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/tabs/tab_activity_simulator.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "chrome/test/base/test_browser_window_aura.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/dbus/power/fake_power_manager_client.h"
#include "chromeos/dbus/power/power_manager_client.h"
#include "chromeos/dbus/power_manager/backlight.pb.h"
#include "chromeos/dbus/power_manager/power_supply_properties.pb.h"
#include "components/ukm/content/source_url_recorder.h"
#include "content/public/test/web_contents_tester.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/user_activity/user_activity_detector.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/gfx/geometry/point.h"
namespace ash {
namespace power {
namespace ml {
namespace {
struct LogActivityInfo {
ScreenBrightnessEvent screen_brightness_event;
ukm::SourceId tab_id;
bool has_form_entry;
};
const int kInactivityDurationSecs =
AdaptiveScreenBrightnessManager::kInactivityDuration.InSeconds();
const int kLoggingIntervalSecs =
AdaptiveScreenBrightnessManager::kLoggingInterval.InSeconds();
// Testing ukm logger.
class TestingAdaptiveScreenBrightnessUkmLogger
: public AdaptiveScreenBrightnessUkmLogger {
public:
TestingAdaptiveScreenBrightnessUkmLogger() = default;
~TestingAdaptiveScreenBrightnessUkmLogger() override = default;
const std::vector<LogActivityInfo>& log_activity_info() const {
return log_activity_info_;
}
// AdaptiveScreenBrightnessUkmLogger overrides:
void LogActivity(const ScreenBrightnessEvent& screen_brightness_event,
ukm::SourceId tab_id,
bool has_form_entry) override {
log_activity_info_.push_back(
LogActivityInfo{screen_brightness_event, tab_id, has_form_entry});
}
private:
std::vector<LogActivityInfo> log_activity_info_;
DISALLOW_COPY_AND_ASSIGN(TestingAdaptiveScreenBrightnessUkmLogger);
};
} // namespace
class AdaptiveScreenBrightnessManagerTest
: public ChromeRenderViewHostTestHarness {
public:
AdaptiveScreenBrightnessManagerTest()
: ChromeRenderViewHostTestHarness(
base::test::TaskEnvironment::MainThreadType::UI,
base::test::TaskEnvironment::TimeSource::MOCK_TIME,
base::test::TaskEnvironment::ThreadPoolExecutionMode::QUEUED) {}
~AdaptiveScreenBrightnessManagerTest() override = default;
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
PowerManagerClient::InitializeFake();
auto logger = std::make_unique<TestingAdaptiveScreenBrightnessUkmLogger>();
ukm_logger_ = logger.get();
mojo::PendingRemote<viz::mojom::VideoDetectorObserver> observer;
auto periodic_timer = std::make_unique<base::RepeatingTimer>();
periodic_timer->SetTaskRunner(
task_environment()->GetMainThreadTaskRunner());
screen_brightness_manager_ =
std::make_unique<AdaptiveScreenBrightnessManager>(
std::move(logger), &user_activity_detector_,
FakePowerManagerClient::Get(), nullptr, nullptr,
observer.InitWithNewPipeAndPassReceiver(),
std::move(periodic_timer));
}
void TearDown() override {
screen_brightness_manager_.reset();
PowerManagerClient::Shutdown();
ChromeRenderViewHostTestHarness::TearDown();
}
protected:
TestingAdaptiveScreenBrightnessUkmLogger* ukm_logger() { return ukm_logger_; }
void ReportUserActivity(const ui::Event* const event) {
screen_brightness_manager_->OnUserActivity(event);
}
void ReportPowerChangeEvent(
const power_manager::PowerSupplyProperties::ExternalPower power,
const float battery_percent) {
power_manager::PowerSupplyProperties proto;
proto.set_external_power(power);
proto.set_battery_percent(battery_percent);
FakePowerManagerClient::Get()->UpdatePowerProperties(proto);
}
void ReportLidEvent(const PowerManagerClient::LidState state) {
FakePowerManagerClient::Get()->SetLidState(state,
base::TimeTicks::UnixEpoch());
}
void ReportTabletModeEvent(const PowerManagerClient::TabletMode mode) {
FakePowerManagerClient::Get()->SetTabletMode(mode,
base::TimeTicks::UnixEpoch());
}
void ReportBrightnessChangeEvent(
const double level,
const power_manager::BacklightBrightnessChange_Cause cause) {
power_manager::BacklightBrightnessChange change;
change.set_percent(level);
change.set_cause(cause);
screen_brightness_manager_->ScreenBrightnessChanged(change);
}
void ReportVideoStart() {
screen_brightness_manager_->OnVideoActivityStarted();
}
void ReportVideoEnd() { screen_brightness_manager_->OnVideoActivityEnded(); }
void FireTimer() { screen_brightness_manager_->OnTimerFired(); }
void InitializeBrightness(const double level) {
screen_brightness_manager_->OnReceiveScreenBrightnessPercent(level);
}
void FastForwardTimeBySecs(const int seconds) {
task_environment()->FastForwardBy(base::TimeDelta::FromSeconds(seconds));
}
// Creates a test browser window and sets its visibility, activity and
// incognito status.
std::unique_ptr<Browser> CreateTestBrowser(bool is_visible,
bool is_focused,
bool is_incognito = false) {
Profile* const original_profile = profile();
Profile* const used_profile =
is_incognito
? original_profile->GetPrimaryOTRProfile(/*create_if_needed=*/true)
: original_profile;
Browser::CreateParams params(used_profile, true);
auto dummy_window = std::make_unique<aura::Window>(nullptr);
dummy_window->Init(ui::LAYER_SOLID_COLOR);
root_window()->AddChild(dummy_window.get());
dummy_window->SetBounds(gfx::Rect(root_window()->bounds().size()));
if (is_visible) {
dummy_window->Show();
} else {
dummy_window->Hide();
}
std::unique_ptr<Browser> browser =
chrome::CreateBrowserWithAuraTestWindowForParams(
std::move(dummy_window), ¶ms);
if (is_focused) {
browser->window()->Activate();
} else {
browser->window()->Deactivate();
}
return browser;
}
// Adds a tab with specified url to the tab strip model. Also optionally sets
// the tab to be the active one in the tab strip model.
// TODO(jiameng): there doesn't seem to be a way to set form entry (via
// page importance signal). Check if there's some other way to set it.
ukm::SourceId CreateTestWebContents(TabStripModel* const tab_strip_model,
const GURL& url,
bool is_active) {
DCHECK(tab_strip_model);
DCHECK(!url.is_empty());
content::WebContents* contents =
tab_activity_simulator_.AddWebContentsAndNavigate(tab_strip_model, url);
if (is_active) {
tab_strip_model->ActivateTabAt(tab_strip_model->count() - 1);
}
content::WebContentsTester::For(contents)->TestSetIsLoading(false);
return ukm::GetSourceIdForWebContentsDocument(contents);
}
const gfx::Point kEventLocation = gfx::Point(90, 90);
const ui::MouseEvent kMouseEvent = ui::MouseEvent(ui::ET_MOUSE_MOVED,
kEventLocation,
kEventLocation,
base::TimeTicks(),
0,
0);
TabActivitySimulator tab_activity_simulator_;
const GURL kUrl1 = GURL("https://example1.com/");
const GURL kUrl2 = GURL("https://example2.com/");
const GURL kUrl3 = GURL("https://example3.com/");
private:
FakeChromeUserManager fake_user_manager_;
ui::UserActivityDetector user_activity_detector_;
std::unique_ptr<AdaptiveScreenBrightnessManager> screen_brightness_manager_;
TestingAdaptiveScreenBrightnessUkmLogger* ukm_logger_;
DISALLOW_COPY_AND_ASSIGN(AdaptiveScreenBrightnessManagerTest);
};
TEST_F(AdaptiveScreenBrightnessManagerTest, PeriodicLogging) {
InitializeBrightness(75.0f);
ReportPowerChangeEvent(power_manager::PowerSupplyProperties::AC, 23.0f);
ReportVideoStart();
ReportLidEvent(PowerManagerClient::LidState::OPEN);
ReportTabletModeEvent(PowerManagerClient::TabletMode::UNSUPPORTED);
FastForwardTimeBySecs(kLoggingIntervalSecs);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_FLOAT_EQ(23.0, features.env_data().battery_percent());
EXPECT_FALSE(features.env_data().on_battery());
EXPECT_TRUE(features.activity_data().is_video_playing());
EXPECT_EQ(ScreenBrightnessEvent::Features::EnvData::LAPTOP,
features.env_data().device_mode());
EXPECT_EQ(75, features.env_data().previous_brightness());
const ScreenBrightnessEvent::Event& event =
info[0].screen_brightness_event.event();
EXPECT_EQ(75, event.brightness());
EXPECT_EQ(ScreenBrightnessEvent::Event::PERIODIC, event.reason());
EXPECT_FALSE(event.has_time_since_last_event_sec());
}
TEST_F(AdaptiveScreenBrightnessManagerTest,
PeriodicLoggingBrightnessUninitialized) {
ReportPowerChangeEvent(power_manager::PowerSupplyProperties::AC, 23.0f);
ReportVideoStart();
ReportLidEvent(PowerManagerClient::LidState::OPEN);
ReportTabletModeEvent(PowerManagerClient::TabletMode::UNSUPPORTED);
FastForwardTimeBySecs(kLoggingIntervalSecs);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
EXPECT_TRUE(info.empty());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, PeriodicTimerTest) {
ReportPowerChangeEvent(power_manager::PowerSupplyProperties::AC, 23.0f);
ReportVideoStart();
ReportLidEvent(PowerManagerClient::LidState::OPEN);
ReportTabletModeEvent(PowerManagerClient::TabletMode::UNSUPPORTED);
FastForwardTimeBySecs(kLoggingIntervalSecs - 10);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
EXPECT_TRUE(info.empty());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, BrightnessChange) {
ReportBrightnessChangeEvent(
30.0f, power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);
FastForwardTimeBySecs(2);
ReportBrightnessChangeEvent(
40.0f, power_manager::
BacklightBrightnessChange_Cause_EXTERNAL_POWER_DISCONNECTED);
FastForwardTimeBySecs(6);
ReportBrightnessChangeEvent(
20.0f, power_manager::BacklightBrightnessChange_Cause_USER_REQUEST);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(3U, info.size());
const ScreenBrightnessEvent::Event& event =
info[0].screen_brightness_event.event();
EXPECT_EQ(30, event.brightness());
EXPECT_EQ(ScreenBrightnessEvent::Event::OTHER, event.reason());
EXPECT_FALSE(event.has_time_since_last_event_sec());
// Brightness wasn't initialized so there's no previous brightness level.
EXPECT_FALSE(info[0]
.screen_brightness_event.features()
.env_data()
.has_previous_brightness());
const ScreenBrightnessEvent::Event& event1 =
info[1].screen_brightness_event.event();
EXPECT_EQ(40, event1.brightness());
EXPECT_EQ(ScreenBrightnessEvent::Event::EXTERNAL_POWER_DISCONNECTED,
event1.reason());
EXPECT_EQ(2, event1.time_since_last_event_sec());
EXPECT_EQ(30, info[1]
.screen_brightness_event.features()
.env_data()
.previous_brightness());
const ScreenBrightnessEvent::Event& event2 =
info[2].screen_brightness_event.event();
EXPECT_EQ(20, event2.brightness());
EXPECT_EQ(ScreenBrightnessEvent::Event::USER_DOWN, event2.reason());
EXPECT_EQ(6, event2.time_since_last_event_sec());
EXPECT_EQ(40, info[2]
.screen_brightness_event.features()
.env_data()
.previous_brightness());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, NoUserEvents) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(kLoggingIntervalSecs);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_FALSE(features.activity_data().has_last_activity_time_sec());
EXPECT_FALSE(features.activity_data().has_recent_time_active_sec());
EXPECT_EQ(75, features.env_data().previous_brightness());
const ScreenBrightnessEvent::Event& event =
info[0].screen_brightness_event.event();
EXPECT_EQ(75, event.brightness());
EXPECT_FALSE(event.has_time_since_last_event_sec());
EXPECT_EQ(ScreenBrightnessEvent::Event::PERIODIC, event.reason());
EXPECT_EQ(ukm::kInvalidSourceId, info[0].tab_id);
}
TEST_F(AdaptiveScreenBrightnessManagerTest, NullUserActivity) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(1);
ReportUserActivity(nullptr);
FastForwardTimeBySecs(kLoggingIntervalSecs);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_FALSE(features.activity_data().has_last_activity_time_sec());
EXPECT_FALSE(features.activity_data().has_recent_time_active_sec());
EXPECT_EQ(75, features.env_data().previous_brightness());
const ScreenBrightnessEvent::Event& event =
info[0].screen_brightness_event.event();
EXPECT_EQ(75, event.brightness());
EXPECT_FALSE(event.has_time_since_last_event_sec());
EXPECT_EQ(ScreenBrightnessEvent::Event::PERIODIC, event.reason());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, OneUserEvent) {
InitializeBrightness(75.0f);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(kLoggingIntervalSecs);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_EQ(kLoggingIntervalSecs,
features.activity_data().last_activity_time_sec());
EXPECT_EQ(0, features.activity_data().recent_time_active_sec());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, TwoUserEventsSameActivity) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(1);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(5);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(kLoggingIntervalSecs);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
// Timer starts from the beginning, so subtract 6 seconds.
EXPECT_EQ(kLoggingIntervalSecs - 6,
features.activity_data().last_activity_time_sec());
EXPECT_EQ(5, features.activity_data().recent_time_active_sec());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, TwoUserEventsDifferentActivities) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(1);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(kInactivityDurationSecs + 5);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(kLoggingIntervalSecs);
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_EQ(kLoggingIntervalSecs - kInactivityDurationSecs - 6,
features.activity_data().last_activity_time_sec());
EXPECT_EQ(0, features.activity_data().recent_time_active_sec());
}
TEST_F(AdaptiveScreenBrightnessManagerTest,
MultipleUserEventsMultipleActivities) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(1);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(5);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(kInactivityDurationSecs + 5);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(kInactivityDurationSecs + 10);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(2);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(2);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(2);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_EQ(2, features.activity_data().last_activity_time_sec());
EXPECT_EQ(4, features.activity_data().recent_time_active_sec());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, VideoStartStop) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(2);
ReportVideoStart();
FastForwardTimeBySecs(5);
FireTimer();
FastForwardTimeBySecs(kInactivityDurationSecs + 40);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(2U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_EQ(0, features.activity_data().last_activity_time_sec());
EXPECT_EQ(5, features.activity_data().recent_time_active_sec());
const ScreenBrightnessEvent::Features& features1 =
info[1].screen_brightness_event.features();
EXPECT_EQ(0, features1.activity_data().last_activity_time_sec());
EXPECT_EQ(kInactivityDurationSecs + 45,
features1.activity_data().recent_time_active_sec());
FastForwardTimeBySecs(10);
ReportVideoEnd();
FastForwardTimeBySecs(5);
FireTimer();
FastForwardTimeBySecs(kInactivityDurationSecs + 45);
FireTimer();
ASSERT_EQ(4U, info.size());
const ScreenBrightnessEvent::Features& features2 =
info[2].screen_brightness_event.features();
EXPECT_EQ(5, features2.activity_data().last_activity_time_sec());
EXPECT_EQ(kInactivityDurationSecs + 55,
features2.activity_data().recent_time_active_sec());
const ScreenBrightnessEvent::Features& features3 =
info[3].screen_brightness_event.features();
EXPECT_EQ(kInactivityDurationSecs + 50,
features3.activity_data().last_activity_time_sec());
EXPECT_EQ(kInactivityDurationSecs + 55,
features3.activity_data().recent_time_active_sec());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, VideoStartStopWithUserEvents) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(1);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(2);
ReportVideoStart();
FastForwardTimeBySecs(5);
FireTimer();
FastForwardTimeBySecs(kInactivityDurationSecs + 40);
FireTimer();
FastForwardTimeBySecs(4);
ReportUserActivity(&kMouseEvent);
FastForwardTimeBySecs(6);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(3U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_EQ(0, features.activity_data().last_activity_time_sec());
EXPECT_EQ(7, features.activity_data().recent_time_active_sec());
const ScreenBrightnessEvent::Features& features1 =
info[1].screen_brightness_event.features();
EXPECT_EQ(0, features1.activity_data().last_activity_time_sec());
EXPECT_EQ(kInactivityDurationSecs + 47,
features1.activity_data().recent_time_active_sec());
const ScreenBrightnessEvent::Features& features2 =
info[2].screen_brightness_event.features();
EXPECT_EQ(0, features2.activity_data().last_activity_time_sec());
EXPECT_EQ(kInactivityDurationSecs + 57,
features2.activity_data().recent_time_active_sec());
FastForwardTimeBySecs(10);
ReportVideoEnd();
FastForwardTimeBySecs(5);
FireTimer();
FastForwardTimeBySecs(kInactivityDurationSecs + 45);
FireTimer();
ASSERT_EQ(5U, info.size());
const ScreenBrightnessEvent::Features& features3 =
info[3].screen_brightness_event.features();
EXPECT_EQ(5, features3.activity_data().last_activity_time_sec());
EXPECT_EQ(kInactivityDurationSecs + 67,
features3.activity_data().recent_time_active_sec());
const ScreenBrightnessEvent::Features& features4 =
info[4].screen_brightness_event.features();
EXPECT_EQ(kInactivityDurationSecs + 50,
features4.activity_data().last_activity_time_sec());
EXPECT_EQ(kInactivityDurationSecs + 67,
features4.activity_data().recent_time_active_sec());
}
TEST_F(AdaptiveScreenBrightnessManagerTest, UserEventCounts) {
InitializeBrightness(75.0f);
FastForwardTimeBySecs(1);
ReportUserActivity(&kMouseEvent);
const ui::TouchEvent kTouchEvent(
ui::ET_TOUCH_PRESSED, kEventLocation, base::TimeTicks(),
ui::PointerDetails(ui::EventPointerType::kTouch, 0));
ReportUserActivity(&kTouchEvent);
ReportUserActivity(&kTouchEvent);
const ui::KeyEvent kKeyEvent(
ui::ET_KEY_PRESSED, ui::VKEY_A, ui::DomCode::US_A, 0,
ui::DomKey::FromCharacter('a'), base::TimeTicks());
ReportUserActivity(&kKeyEvent);
ReportUserActivity(&kKeyEvent);
ReportUserActivity(&kKeyEvent);
const ui::TouchEvent kStylusEvent(
ui::ET_TOUCH_MOVED, kEventLocation, base::TimeTicks(),
ui::PointerDetails(ui::EventPointerType::kPen, 0), ui::EF_NONE);
ReportUserActivity(&kStylusEvent);
ReportUserActivity(&kStylusEvent);
ReportUserActivity(&kStylusEvent);
ReportUserActivity(&kStylusEvent);
FastForwardTimeBySecs(2);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
const ScreenBrightnessEvent::Features& features =
info[0].screen_brightness_event.features();
EXPECT_EQ(1, features.activity_data().num_recent_mouse_events());
EXPECT_EQ(2, features.activity_data().num_recent_touch_events());
EXPECT_EQ(3, features.activity_data().num_recent_key_events());
EXPECT_EQ(4, features.activity_data().num_recent_stylus_events());
}
// Test is flaky. See https://crbug.com/938055.
TEST_F(AdaptiveScreenBrightnessManagerTest, DISABLED_SingleBrowser) {
std::unique_ptr<Browser> browser =
CreateTestBrowser(true /* is_visible */, true /* is_focused */);
BrowserList::GetInstance()->SetLastActive(browser.get());
TabStripModel* tab_strip_model = browser->tab_strip_model();
CreateTestWebContents(tab_strip_model, kUrl1, false /* is_active */);
const ukm::SourceId source_id2 =
CreateTestWebContents(tab_strip_model, kUrl2, true /* is_active */);
InitializeBrightness(75.0f);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
EXPECT_EQ(source_id2, info[0].tab_id);
EXPECT_EQ(false, info[0].has_form_entry);
// Browser DCHECKS that all tabs have been closed at destruction.
tab_strip_model->CloseAllTabs();
}
// Test is flaky. See https://crbug.com/944325.
TEST_F(AdaptiveScreenBrightnessManagerTest,
DISABLED_MultipleBrowsersWithActive) {
// Simulates three browsers:
// - browser1 is the last active but minimized, so not visible.
// - browser2 and browser3 are both visible but browser2 is the topmost.
std::unique_ptr<Browser> browser1 =
CreateTestBrowser(false /* is_visible */, false /* is_focused */);
std::unique_ptr<Browser> browser2 =
CreateTestBrowser(true /* is_visible */, true /* is_focused */);
std::unique_ptr<Browser> browser3 =
CreateTestBrowser(true /* is_visible */, false /* is_focused */);
BrowserList::GetInstance()->SetLastActive(browser3.get());
BrowserList::GetInstance()->SetLastActive(browser2.get());
BrowserList::GetInstance()->SetLastActive(browser1.get());
TabStripModel* tab_strip_model1 = browser1->tab_strip_model();
CreateTestWebContents(tab_strip_model1, kUrl1, true /* is_active */);
TabStripModel* tab_strip_model2 = browser2->tab_strip_model();
const ukm::SourceId source_id2 =
CreateTestWebContents(tab_strip_model2, kUrl2, true /* is_active */);
TabStripModel* tab_strip_model3 = browser3->tab_strip_model();
CreateTestWebContents(tab_strip_model3, kUrl3, true /* is_active */);
InitializeBrightness(75.0f);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
EXPECT_EQ(source_id2, info[0].tab_id);
EXPECT_EQ(false, info[0].has_form_entry);
// Browser DCHECKS that all tabs have been closed at destruction.
tab_strip_model1->CloseAllTabs();
tab_strip_model2->CloseAllTabs();
tab_strip_model3->CloseAllTabs();
}
TEST_F(AdaptiveScreenBrightnessManagerTest,
DISABLED_MultipleBrowsersNoneActive) {
// Simulates three browsers, none of which are active.
// - browser1 is the last active but minimized and so not visible.
// - browser2 and browser3 are both visible but not focused so not active.
// - browser2 is the topmost.
std::unique_ptr<Browser> browser1 =
CreateTestBrowser(false /* is_visible */, false /* is_focused */);
std::unique_ptr<Browser> browser2 =
CreateTestBrowser(true /* is_visible */, false /* is_focused */);
std::unique_ptr<Browser> browser3 =
CreateTestBrowser(true /* is_visible */, false /* is_focused */);
BrowserList::GetInstance()->SetLastActive(browser3.get());
BrowserList::GetInstance()->SetLastActive(browser2.get());
BrowserList::GetInstance()->SetLastActive(browser1.get());
TabStripModel* tab_strip_model1 = browser1->tab_strip_model();
CreateTestWebContents(tab_strip_model1, kUrl1, true /* is_active */);
TabStripModel* tab_strip_model2 = browser2->tab_strip_model();
const ukm::SourceId source_id2 =
CreateTestWebContents(tab_strip_model2, kUrl2, true /* is_active */);
TabStripModel* tab_strip_model3 = browser3->tab_strip_model();
CreateTestWebContents(tab_strip_model3, kUrl3, true /* is_active */);
InitializeBrightness(75.0f);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
EXPECT_EQ(source_id2, info[0].tab_id);
EXPECT_EQ(false, info[0].has_form_entry);
// Browser DCHECKS that all tabs have been closed at destruction.
tab_strip_model1->CloseAllTabs();
tab_strip_model2->CloseAllTabs();
tab_strip_model3->CloseAllTabs();
}
TEST_F(AdaptiveScreenBrightnessManagerTest, BrowsersWithIncognito) {
// Simulates three browsers:
// - browser1 is the last active but minimized and so not visible.
// - browser2 is visible but not focused so not active.
// - browser3 is visible and focused, but incognito.
std::unique_ptr<Browser> browser1 =
CreateTestBrowser(false /* is_visible */, false /* is_focused */);
std::unique_ptr<Browser> browser2 =
CreateTestBrowser(true /* is_visible */, false /* is_focused */);
std::unique_ptr<Browser> browser3 = CreateTestBrowser(
true /* is_visible */, true /* is_focused */, true /* is_incognito */);
BrowserList::GetInstance()->SetLastActive(browser3.get());
BrowserList::GetInstance()->SetLastActive(browser2.get());
BrowserList::GetInstance()->SetLastActive(browser1.get());
TabStripModel* tab_strip_model1 = browser1->tab_strip_model();
CreateTestWebContents(tab_strip_model1, kUrl1, true /* is_active */);
TabStripModel* tab_strip_model2 = browser2->tab_strip_model();
const ukm::SourceId source_id2 =
CreateTestWebContents(tab_strip_model2, kUrl2, true /* is_active */);
TabStripModel* tab_strip_model3 = browser3->tab_strip_model();
CreateTestWebContents(tab_strip_model3, kUrl3, true /* is_active */);
InitializeBrightness(75.0f);
FireTimer();
const std::vector<LogActivityInfo>& info = ukm_logger()->log_activity_info();
ASSERT_EQ(1U, info.size());
EXPECT_EQ(source_id2, info[0].tab_id);
EXPECT_EQ(false, info[0].has_form_entry);
// Browser DCHECKS that all tabs have been closed at destruction.
tab_strip_model1->CloseAllTabs();
tab_strip_model2->CloseAllTabs();
tab_strip_model3->CloseAllTabs();
}
} // namespace ml
} // namespace power
} // namespace ash
| 37.971429 | 80 | 0.740338 | [
"geometry",
"vector",
"model"
] |
04a7a2975b123bf6d0a632ab5968cc3cfab190cb | 11,392 | cc | C++ | goopdate/update_response_utils.cc | rocious/omaha | 44a58900e58979362ad18de6867d804bee0f1b91 | [
"Apache-2.0"
] | 4 | 2016-05-19T09:22:52.000Z | 2020-10-22T03:45:41.000Z | goopdate/update_response_utils.cc | rocious/omaha | 44a58900e58979362ad18de6867d804bee0f1b91 | [
"Apache-2.0"
] | 1 | 2015-06-15T06:26:34.000Z | 2015-06-15T06:26:34.000Z | goopdate/update_response_utils.cc | rocious/omaha | 44a58900e58979362ad18de6867d804bee0f1b91 | [
"Apache-2.0"
] | 1 | 2015-06-24T19:26:58.000Z | 2015-06-24T19:26:58.000Z | // Copyright 2010 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/goopdate/update_response_utils.h"
#include "omaha/base/debug.h"
#include "omaha/base/error.h"
#include "omaha/base/logging.h"
#include "omaha/common/lang.h"
#include "omaha/common/experiment_labels.h"
#include "omaha/goopdate/model.h"
#include "omaha/goopdate/server_resource.h"
#include "omaha/goopdate/string_formatter.h"
namespace omaha {
namespace update_response_utils {
// TODO(omaha): unit test the functions below.
// Returns a pointer to the app object corresponding to the appid in the
// response object. Returns NULL if the app is not found.
const xml::response::App* GetApp(const xml::response::Response& response,
const CString& appid) {
size_t app_index = 0;
for (; app_index < response.apps.size(); ++app_index) {
if (!appid.CompareNoCase(response.apps[app_index].appid)) {
return &response.apps[app_index];
}
}
return NULL;
}
HRESULT GetInstallData(const std::vector<xml::response::Data>& data,
const CString& install_data_index,
CString* install_data) {
ASSERT1(install_data);
if (install_data_index.IsEmpty()) {
return S_OK;
}
std::vector<xml::response::Data>::const_iterator it;
for (it = data.begin(); it != data.end(); ++it) {
if (install_data_index != it->install_data_index) {
continue;
}
if (it->status != kResponseStatusOkValue) {
ASSERT1(it->status == kResponseDataStatusNoData);
return GOOPDATE_E_INVALID_INSTALL_DATA_INDEX;
}
ASSERT1(!it->install_data.IsEmpty());
*install_data = it->install_data;
return S_OK;
}
return GOOPDATE_E_INVALID_INSTALL_DATA_INDEX;
}
// Check the outer elements first, then check any child elements only if the
// outer element was successful.
CString GetAppResponseStatus(const xml::response::App& app) {
if (_tcsicmp(kResponseStatusOkValue, app.status) != 0) {
ASSERT1(!app.status.IsEmpty());
return app.status;
}
if (!app.update_check.status.IsEmpty() &&
_tcsicmp(kResponseStatusOkValue, app.update_check.status) != 0) {
return app.update_check.status;
}
std::vector<xml::response::Data>::const_iterator data;
for (data = app.data.begin(); data != app.data.end(); ++data) {
if (!data->status.IsEmpty() &&
_tcsicmp(kResponseStatusOkValue, data->status) != 0) {
return data->status;
}
}
if (!app.ping.status.IsEmpty() &&
_tcsicmp(kResponseStatusOkValue, app.ping.status) != 0) {
return app.ping.status;
}
std::vector<xml::response::Event>::const_iterator it;
for (it = app.events.begin(); it != app.events.end(); ++it) {
if (!it->status.IsEmpty() &&
_tcsicmp(kResponseStatusOkValue, it->status) != 0) {
return it->status;
}
}
// TODO(omaha): verify that no other elements can report errors
// once we've finalized the protocol.
return app.status;
}
HRESULT BuildApp(const xml::UpdateResponse* update_response,
HRESULT code,
App* app) {
ASSERT1(update_response);
ASSERT1(SUCCEEDED(code) || code == GOOPDATE_E_NO_UPDATE_RESPONSE);
ASSERT1(app);
AppVersion* next_version = app->next_version();
const CString& app_id = app->app_guid_string();
const xml::response::App* response_app(GetApp(update_response->response(),
app_id));
ASSERT1(response_app);
const xml::response::UpdateCheck& update_check = response_app->update_check;
VERIFY1(SUCCEEDED(app->put_ttToken(CComBSTR(update_check.tt_token))));
if (code == GOOPDATE_E_NO_UPDATE_RESPONSE) {
return S_OK;
}
for (size_t i = 0; i < update_check.urls.size(); ++i) {
HRESULT hr = next_version->AddDownloadBaseUrl(update_check.urls[i]);
if (FAILED(hr)) {
return hr;
}
}
for (size_t i = 0; i < update_check.install_manifest.packages.size(); ++i) {
const xml::InstallPackage& package(
update_check.install_manifest.packages[i]);
HRESULT hr = next_version->AddPackage(package.name,
package.size,
package.hash);
if (FAILED(hr)) {
return hr;
}
}
CString server_install_data;
HRESULT hr = GetInstallData(response_app->data,
app->server_install_data_index(),
&server_install_data);
if (FAILED(hr)) {
return hr;
}
app->set_server_install_data(server_install_data);
ASSERT1(!next_version->install_manifest());
next_version->set_install_manifest(
new xml::InstallManifest(update_check.install_manifest));
// TODO(omaha): it appears the version_ below holds either the manifest
// version or the "pv" version, written by the installer. If this is the case,
// then it is confusing and perhaps we need to have two different members to
// hold these values.
ASSERT1(next_version->version().IsEmpty());
next_version->set_version(next_version->install_manifest()->version);
return S_OK;
}
// "noupdate" is an error for fresh installs, but a successful completion in
// the cases of silent and on demand updates. The caller is responsible for
// interpreting "noupdate" as it sees fit.
xml::UpdateResponseResult GetResult(const xml::UpdateResponse* update_response,
const CString& appid,
const CString& language) {
ASSERT1(update_response);
const xml::response::App* response_app(GetApp(update_response->response(),
appid));
StringFormatter formatter(language);
CString text;
if (!response_app) {
CORE_LOG(L1, (_T("[UpdateResponse::GetResult][app not found][%s]"), appid));
VERIFY1(SUCCEEDED(formatter.LoadString(IDS_UNKNOWN_APPLICATION, &text)));
return std::make_pair(GOOPDATE_E_NO_SERVER_RESPONSE, text);
}
const xml::response::UpdateCheck& update_check = response_app->update_check;
const CString& status = GetAppResponseStatus(*response_app);
const CString& display_name = update_check.install_manifest.name;
ASSERT1(!status.IsEmpty());
CORE_LOG(L1, (_T("[UpdateResponse::GetResult][%s][%s][%s]"),
appid, status, display_name));
// ok
if (_tcsicmp(kResponseStatusOkValue, status) == 0) {
return std::make_pair(S_OK, CString());
}
// noupdate
if (_tcsicmp(kResponseStatusNoUpdate, status) == 0) {
VERIFY1(SUCCEEDED(formatter.LoadString(IDS_NO_UPDATE_RESPONSE, &text)));
return std::make_pair(GOOPDATE_E_NO_UPDATE_RESPONSE, text);
}
// "restricted"
if (_tcsicmp(kResponseStatusRestrictedExportCountry, status) == 0) {
VERIFY1(SUCCEEDED(formatter.LoadString(IDS_RESTRICTED_RESPONSE_FROM_SERVER,
&text)));
return std::make_pair(GOOPDATE_E_RESTRICTED_SERVER_RESPONSE, text);
}
// "error-UnKnownApplication"
if (_tcsicmp(kResponseStatusUnKnownApplication, status) == 0) {
VERIFY1(SUCCEEDED(formatter.LoadString(IDS_UNKNOWN_APPLICATION, &text)));
return std::make_pair(GOOPDATE_E_UNKNOWN_APP_SERVER_RESPONSE, text);
}
// "error-OsNotSupported"
if (_tcsicmp(kResponseStatusOsNotSupported, status) == 0) {
const CString& error_url(update_check.error_url);
VERIFY1(SUCCEEDED(formatter.LoadString(IDS_OS_NOT_SUPPORTED, &text)));
if (!error_url.IsEmpty()) {
// TODO(omaha3): The error URL is no longer in the error string. Either
// we need to provide this URL to the client or we need to deprecate
// error_url and put this information in the Get Help redirect.
// Alternatively, we could have the COM server build error URLs in all
// cases. The current UI would still need to build an URL for the entire
// bundle, though, because it does not have per-app links.
}
return std::make_pair(GOOPDATE_E_OS_NOT_SUPPORTED, text);
}
// "error-internal"
if (_tcsicmp(kResponseStatusInternalError, status) == 0) {
VERIFY1(SUCCEEDED(formatter.FormatMessage(&text,
IDS_NON_OK_RESPONSE_FROM_SERVER,
status)));
return std::make_pair(GOOPDATE_E_INTERNAL_ERROR_SERVER_RESPONSE, text);
}
// "error-hash"
if (_tcsicmp(kResponseStatusHashError, status) == 0) {
VERIFY1(SUCCEEDED(formatter.FormatMessage(&text,
IDS_NON_OK_RESPONSE_FROM_SERVER,
status)));
return std::make_pair(GOOPDATE_E_SERVER_RESPONSE_NO_HASH, text);
}
// "error-unsupportedprotocol"
if (_tcsicmp(kResponseStatusUnsupportedProtocol, status) == 0) {
// TODO(omaha): Ideally, we would provide an app-specific URL instead of
// just the publisher name. If it was a link, we could use point to a
// redirect URL and provide the app GUID rather than somehow obtaining the
// app-specific URL.
VERIFY1(SUCCEEDED(formatter.FormatMessage(&text,
IDS_INSTALLER_OLD,
kShortCompanyName)));
return std::make_pair(GOOPDATE_E_SERVER_RESPONSE_UNSUPPORTED_PROTOCOL,
text);
}
VERIFY1(SUCCEEDED(formatter.FormatMessage(&text,
IDS_NON_OK_RESPONSE_FROM_SERVER,
status)));
return std::make_pair(GOOPDATE_E_UNKNOWN_SERVER_RESPONSE, text);
}
bool IsOmahaUpdateAvailable(const xml::UpdateResponse* update_response) {
ASSERT1(update_response);
xml::UpdateResponseResult update_response_result(
update_response_utils::GetResult(update_response,
kGoogleUpdateAppId,
lang::GetDefaultLanguage(true)));
return update_response_result.first == S_OK;
}
HRESULT ApplyExperimentLabelDeltas(bool is_machine,
const xml::UpdateResponse* update_response) {
ASSERT1(update_response);
for (size_t app_index = 0;
app_index < update_response->response().apps.size();
++app_index) {
const xml::response::App& app = update_response->response().apps[app_index];
if (!app.experiments.IsEmpty()) {
VERIFY1(IsGuid(app.appid));
ExperimentLabels labels;
VERIFY1(SUCCEEDED(labels.ReadFromRegistry(is_machine, app.appid)));
if (!labels.DeserializeAndApplyDelta(app.experiments)) {
return E_FAIL;
}
HRESULT hr = labels.WriteToRegistry(is_machine, app.appid);
if (FAILED(hr)) {
return hr;
}
}
}
return S_OK;
}
} // namespace update_response_utils
} // namespace omaha
| 35.936909 | 80 | 0.65309 | [
"object",
"vector",
"model"
] |
04a878b6bf1cee3b616e2db1a2c754f96c19d137 | 107,434 | hpp | C++ | include/DG/Tweening/DOTween.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/DG/Tweening/DOTween.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/DG/Tweening/DOTween.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include <initializer_list>
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: DG.Tweening.Core.Enums.NestedTweenFailureBehaviour
#include "DG/Tweening/Core/Enums/NestedTweenFailureBehaviour.hpp"
// Including type: DG.Tweening.Core.Enums.RewindCallbackMode
#include "DG/Tweening/Core/Enums/RewindCallbackMode.hpp"
// Including type: DG.Tweening.LogBehaviour
#include "DG/Tweening/LogBehaviour.hpp"
// Including type: UnityEngine.LogType
#include "UnityEngine/LogType.hpp"
// Including type: DG.Tweening.UpdateType
#include "DG/Tweening/UpdateType.hpp"
// Including type: DG.Tweening.AutoPlay
#include "DG/Tweening/AutoPlay.hpp"
// Including type: DG.Tweening.LoopType
#include "DG/Tweening/LoopType.hpp"
// Including type: DG.Tweening.Ease
#include "DG/Tweening/Ease.hpp"
// Including type: DG.Tweening.Core.SafeModeReport
#include "DG/Tweening/Core/SafeModeReport.hpp"
// Including type: DG.Tweening.Plugins.Options.FloatOptions
#include "DG/Tweening/Plugins/Options/FloatOptions.hpp"
// Including type: DG.Tweening.Plugins.Options.NoOptions
#include "DG/Tweening/Plugins/Options/NoOptions.hpp"
// Including type: DG.Tweening.Plugins.Options.UintOptions
#include "DG/Tweening/Plugins/Options/UintOptions.hpp"
// Including type: DG.Tweening.Plugins.Options.StringOptions
#include "DG/Tweening/Plugins/Options/StringOptions.hpp"
// Including type: UnityEngine.Vector2
#include "UnityEngine/Vector2.hpp"
// Including type: DG.Tweening.Plugins.Options.VectorOptions
#include "DG/Tweening/Plugins/Options/VectorOptions.hpp"
// Including type: UnityEngine.Vector3
#include "UnityEngine/Vector3.hpp"
// Including type: UnityEngine.Vector4
#include "UnityEngine/Vector4.hpp"
// Including type: UnityEngine.Quaternion
#include "UnityEngine/Quaternion.hpp"
// Including type: DG.Tweening.Plugins.Options.QuaternionOptions
#include "DG/Tweening/Plugins/Options/QuaternionOptions.hpp"
// Including type: UnityEngine.Color
#include "UnityEngine/Color.hpp"
// Including type: DG.Tweening.Plugins.Options.ColorOptions
#include "DG/Tweening/Plugins/Options/ColorOptions.hpp"
// Including type: UnityEngine.Rect
#include "UnityEngine/Rect.hpp"
// Including type: DG.Tweening.Plugins.Options.RectOptions
#include "DG/Tweening/Plugins/Options/RectOptions.hpp"
// Including type: DG.Tweening.Plugins.Options.Vector3ArrayOptions
#include "DG/Tweening/Plugins/Options/Vector3ArrayOptions.hpp"
// Including type: DG.Tweening.Color2
#include "DG/Tweening/Color2.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: DG::Tweening
namespace DG::Tweening {
// Forward declaring type: TweenCallback
class TweenCallback;
// Forward declaring type: IDOTweenInit
class IDOTweenInit;
// Forward declaring type: Tweener
class Tweener;
// Skipping declaration: AxisConstraint because it is already included!
// Forward declaring type: Sequence
class Sequence;
// Forward declaring type: Tween
class Tween;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`3<T1, T2, TResult>
template<typename T1, typename T2, typename TResult>
class Func_3;
// Forward declaring type: Nullable`1<T>
template<typename T>
struct Nullable_1;
// Skipping declaration: ValueType because it is already included!
}
// Forward declaring namespace: DG::Tweening::Core
namespace DG::Tweening::Core {
// Forward declaring type: DOTweenComponent
class DOTweenComponent;
// Forward declaring type: DOTweenSettings
class DOTweenSettings;
// Forward declaring type: TweenerCore`3<T1, T2, TPlugOptions>
template<typename T1, typename T2, typename TPlugOptions>
class TweenerCore_3;
// Forward declaring type: DOGetter`1<T>
template<typename T>
class DOGetter_1;
// Forward declaring type: DOSetter`1<T>
template<typename T>
class DOSetter_1;
}
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: RectOffset
class RectOffset;
}
// Forward declaring namespace: DG::Tweening::Plugins::Options
namespace DG::Tweening::Plugins::Options {
// Skipping declaration: IPlugOptions because it is already included!
}
// Forward declaring namespace: DG::Tweening::Plugins::Core
namespace DG::Tweening::Plugins::Core {
// Forward declaring type: ABSTweenPlugin`3<T1, T2, TPlugOptions>
template<typename T1, typename T2, typename TPlugOptions>
class ABSTweenPlugin_3;
}
// Completed forward declares
// Type namespace: DG.Tweening
namespace DG::Tweening {
// Forward declaring type: DOTween
class DOTween;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::DG::Tweening::DOTween);
DEFINE_IL2CPP_ARG_TYPE(::DG::Tweening::DOTween*, "DG.Tweening", "DOTween");
// Type namespace: DG.Tweening
namespace DG::Tweening {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: DG.Tweening.DOTween
// [TokenAttribute] Offset: FFFFFFFF
class DOTween : public ::Il2CppObject {
public:
// Nested type: ::DG::Tweening::DOTween::$$c__DisplayClass60_0
class $$c__DisplayClass60_0;
// Get static field: static public readonly System.String Version
static ::StringW _get_Version();
// Set static field: static public readonly System.String Version
static void _set_Version(::StringW value);
// Get static field: static public System.Boolean useSafeMode
static bool _get_useSafeMode();
// Set static field: static public System.Boolean useSafeMode
static void _set_useSafeMode(bool value);
// Get static field: static public DG.Tweening.Core.Enums.NestedTweenFailureBehaviour nestedTweenFailureBehaviour
static ::DG::Tweening::Core::Enums::NestedTweenFailureBehaviour _get_nestedTweenFailureBehaviour();
// Set static field: static public DG.Tweening.Core.Enums.NestedTweenFailureBehaviour nestedTweenFailureBehaviour
static void _set_nestedTweenFailureBehaviour(::DG::Tweening::Core::Enums::NestedTweenFailureBehaviour value);
// Get static field: static public System.Boolean showUnityEditorReport
static bool _get_showUnityEditorReport();
// Set static field: static public System.Boolean showUnityEditorReport
static void _set_showUnityEditorReport(bool value);
// Get static field: static public System.Single timeScale
static float _get_timeScale();
// Set static field: static public System.Single timeScale
static void _set_timeScale(float value);
// Get static field: static public System.Boolean useSmoothDeltaTime
static bool _get_useSmoothDeltaTime();
// Set static field: static public System.Boolean useSmoothDeltaTime
static void _set_useSmoothDeltaTime(bool value);
// Get static field: static public System.Single maxSmoothUnscaledTime
static float _get_maxSmoothUnscaledTime();
// Set static field: static public System.Single maxSmoothUnscaledTime
static void _set_maxSmoothUnscaledTime(float value);
// Get static field: static DG.Tweening.Core.Enums.RewindCallbackMode rewindCallbackMode
static ::DG::Tweening::Core::Enums::RewindCallbackMode _get_rewindCallbackMode();
// Set static field: static DG.Tweening.Core.Enums.RewindCallbackMode rewindCallbackMode
static void _set_rewindCallbackMode(::DG::Tweening::Core::Enums::RewindCallbackMode value);
// Get static field: static private DG.Tweening.LogBehaviour _logBehaviour
static ::DG::Tweening::LogBehaviour _get__logBehaviour();
// Set static field: static private DG.Tweening.LogBehaviour _logBehaviour
static void _set__logBehaviour(::DG::Tweening::LogBehaviour value);
// Get static field: static public System.Func`3<UnityEngine.LogType,System.Object,System.Boolean> onWillLog
static ::System::Func_3<::UnityEngine::LogType, ::Il2CppObject*, bool>* _get_onWillLog();
// Set static field: static public System.Func`3<UnityEngine.LogType,System.Object,System.Boolean> onWillLog
static void _set_onWillLog(::System::Func_3<::UnityEngine::LogType, ::Il2CppObject*, bool>* value);
// Get static field: static public System.Boolean drawGizmos
static bool _get_drawGizmos();
// Set static field: static public System.Boolean drawGizmos
static void _set_drawGizmos(bool value);
// Get static field: static public System.Boolean debugMode
static bool _get_debugMode();
// Set static field: static public System.Boolean debugMode
static void _set_debugMode(bool value);
// Get static field: static private System.Boolean _fooDebugStoreTargetId
static bool _get__fooDebugStoreTargetId();
// Set static field: static private System.Boolean _fooDebugStoreTargetId
static void _set__fooDebugStoreTargetId(bool value);
// Get static field: static public DG.Tweening.UpdateType defaultUpdateType
static ::DG::Tweening::UpdateType _get_defaultUpdateType();
// Set static field: static public DG.Tweening.UpdateType defaultUpdateType
static void _set_defaultUpdateType(::DG::Tweening::UpdateType value);
// Get static field: static public System.Boolean defaultTimeScaleIndependent
static bool _get_defaultTimeScaleIndependent();
// Set static field: static public System.Boolean defaultTimeScaleIndependent
static void _set_defaultTimeScaleIndependent(bool value);
// Get static field: static public DG.Tweening.AutoPlay defaultAutoPlay
static ::DG::Tweening::AutoPlay _get_defaultAutoPlay();
// Set static field: static public DG.Tweening.AutoPlay defaultAutoPlay
static void _set_defaultAutoPlay(::DG::Tweening::AutoPlay value);
// Get static field: static public System.Boolean defaultAutoKill
static bool _get_defaultAutoKill();
// Set static field: static public System.Boolean defaultAutoKill
static void _set_defaultAutoKill(bool value);
// Get static field: static public DG.Tweening.LoopType defaultLoopType
static ::DG::Tweening::LoopType _get_defaultLoopType();
// Set static field: static public DG.Tweening.LoopType defaultLoopType
static void _set_defaultLoopType(::DG::Tweening::LoopType value);
// Get static field: static public System.Boolean defaultRecyclable
static bool _get_defaultRecyclable();
// Set static field: static public System.Boolean defaultRecyclable
static void _set_defaultRecyclable(bool value);
// Get static field: static public DG.Tweening.Ease defaultEaseType
static ::DG::Tweening::Ease _get_defaultEaseType();
// Set static field: static public DG.Tweening.Ease defaultEaseType
static void _set_defaultEaseType(::DG::Tweening::Ease value);
// Get static field: static public System.Single defaultEaseOvershootOrAmplitude
static float _get_defaultEaseOvershootOrAmplitude();
// Set static field: static public System.Single defaultEaseOvershootOrAmplitude
static void _set_defaultEaseOvershootOrAmplitude(float value);
// Get static field: static public System.Single defaultEasePeriod
static float _get_defaultEasePeriod();
// Set static field: static public System.Single defaultEasePeriod
static void _set_defaultEasePeriod(float value);
// Get static field: static public DG.Tweening.Core.DOTweenComponent instance
static ::DG::Tweening::Core::DOTweenComponent* _get_instance();
// Set static field: static public DG.Tweening.Core.DOTweenComponent instance
static void _set_instance(::DG::Tweening::Core::DOTweenComponent* value);
// Get static field: static System.Int32 maxActiveTweenersReached
static int _get_maxActiveTweenersReached();
// Set static field: static System.Int32 maxActiveTweenersReached
static void _set_maxActiveTweenersReached(int value);
// Get static field: static System.Int32 maxActiveSequencesReached
static int _get_maxActiveSequencesReached();
// Set static field: static System.Int32 maxActiveSequencesReached
static void _set_maxActiveSequencesReached(int value);
// Get static field: static DG.Tweening.Core.SafeModeReport safeModeReport
static ::DG::Tweening::Core::SafeModeReport _get_safeModeReport();
// Set static field: static DG.Tweening.Core.SafeModeReport safeModeReport
static void _set_safeModeReport(::DG::Tweening::Core::SafeModeReport value);
// Get static field: static readonly System.Collections.Generic.List`1<DG.Tweening.TweenCallback> GizmosDelegates
static ::System::Collections::Generic::List_1<::DG::Tweening::TweenCallback*>* _get_GizmosDelegates();
// Set static field: static readonly System.Collections.Generic.List`1<DG.Tweening.TweenCallback> GizmosDelegates
static void _set_GizmosDelegates(::System::Collections::Generic::List_1<::DG::Tweening::TweenCallback*>* value);
// Get static field: static System.Boolean initialized
static bool _get_initialized();
// Set static field: static System.Boolean initialized
static void _set_initialized(bool value);
// Get static field: static System.Boolean isQuitting
static bool _get_isQuitting();
// Set static field: static System.Boolean isQuitting
static void _set_isQuitting(bool value);
// static public DG.Tweening.LogBehaviour get_logBehaviour()
// Offset: 0x10941C8
static ::DG::Tweening::LogBehaviour get_logBehaviour();
// static public System.Void set_logBehaviour(DG.Tweening.LogBehaviour value)
// Offset: 0x109422C
static void set_logBehaviour(::DG::Tweening::LogBehaviour value);
// static public System.Boolean get_debugStoreTargetId()
// Offset: 0x1094314
static bool get_debugStoreTargetId();
// static public System.Void set_debugStoreTargetId(System.Boolean value)
// Offset: 0x10943D0
static void set_debugStoreTargetId(bool value);
// static private System.Void .cctor()
// Offset: 0x1098A34
static void _cctor();
// static public DG.Tweening.IDOTweenInit Init(System.Nullable`1<System.Boolean> recycleAllByDefault, System.Nullable`1<System.Boolean> useSafeMode, System.Nullable`1<DG.Tweening.LogBehaviour> logBehaviour)
// Offset: 0x109443C
static ::DG::Tweening::IDOTweenInit* Init(::System::Nullable_1<bool> recycleAllByDefault, ::System::Nullable_1<bool> useSafeMode, ::System::Nullable_1<::DG::Tweening::LogBehaviour> logBehaviour);
// static private System.Void AutoInit()
// Offset: 0x1094D24
static void AutoInit();
// static private DG.Tweening.IDOTweenInit Init(DG.Tweening.Core.DOTweenSettings settings, System.Nullable`1<System.Boolean> recycleAllByDefault, System.Nullable`1<System.Boolean> useSafeMode, System.Nullable`1<DG.Tweening.LogBehaviour> logBehaviour)
// Offset: 0x10945C4
static ::DG::Tweening::IDOTweenInit* Init(::DG::Tweening::Core::DOTweenSettings* settings, ::System::Nullable_1<bool> recycleAllByDefault, ::System::Nullable_1<bool> useSafeMode, ::System::Nullable_1<::DG::Tweening::LogBehaviour> logBehaviour);
// static public System.Void SetTweensCapacity(System.Int32 tweenersCapacity, System.Int32 sequencesCapacity)
// Offset: 0x10950B4
static void SetTweensCapacity(int tweenersCapacity, int sequencesCapacity);
// static public System.Void Clear(System.Boolean destroy)
// Offset: 0x1095128
static void Clear(bool destroy);
// static public System.Void ClearCachedTweens()
// Offset: 0x10954A8
static void ClearCachedTweens();
// static public System.Int32 Validate()
// Offset: 0x1095504
static int Validate();
// static public System.Void ManualUpdate(System.Single deltaTime, System.Single unscaledDeltaTime)
// Offset: 0x1095560
static void ManualUpdate(float deltaTime, float unscaledDeltaTime);
// static public DG.Tweening.Core.TweenerCore`3<System.Single,System.Single,DG.Tweening.Plugins.Options.FloatOptions> To(DG.Tweening.Core.DOGetter`1<System.Single> getter, DG.Tweening.Core.DOSetter`1<System.Single> setter, System.Single endValue, System.Single duration)
// Offset: 0x1095730
static ::DG::Tweening::Core::TweenerCore_3<float, float, ::DG::Tweening::Plugins::Options::FloatOptions>* To(::DG::Tweening::Core::DOGetter_1<float>* getter, ::DG::Tweening::Core::DOSetter_1<float>* setter, float endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<System.Double,System.Double,DG.Tweening.Plugins.Options.NoOptions> To(DG.Tweening.Core.DOGetter`1<System.Double> getter, DG.Tweening.Core.DOSetter`1<System.Double> setter, System.Double endValue, System.Single duration)
// Offset: 0x10957D4
static ::DG::Tweening::Core::TweenerCore_3<double, double, ::DG::Tweening::Plugins::Options::NoOptions>* To(::DG::Tweening::Core::DOGetter_1<double>* getter, ::DG::Tweening::Core::DOSetter_1<double>* setter, double endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<System.Int32,System.Int32,DG.Tweening.Plugins.Options.NoOptions> To(DG.Tweening.Core.DOGetter`1<System.Int32> getter, DG.Tweening.Core.DOSetter`1<System.Int32> setter, System.Int32 endValue, System.Single duration)
// Offset: 0x1095878
static ::DG::Tweening::Core::TweenerCore_3<int, int, ::DG::Tweening::Plugins::Options::NoOptions>* To(::DG::Tweening::Core::DOGetter_1<int>* getter, ::DG::Tweening::Core::DOSetter_1<int>* setter, int endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<System.UInt32,System.UInt32,DG.Tweening.Plugins.Options.UintOptions> To(DG.Tweening.Core.DOGetter`1<System.UInt32> getter, DG.Tweening.Core.DOSetter`1<System.UInt32> setter, System.UInt32 endValue, System.Single duration)
// Offset: 0x109591C
static ::DG::Tweening::Core::TweenerCore_3<uint, uint, ::DG::Tweening::Plugins::Options::UintOptions>* To(::DG::Tweening::Core::DOGetter_1<uint>* getter, ::DG::Tweening::Core::DOSetter_1<uint>* setter, uint endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<System.Int64,System.Int64,DG.Tweening.Plugins.Options.NoOptions> To(DG.Tweening.Core.DOGetter`1<System.Int64> getter, DG.Tweening.Core.DOSetter`1<System.Int64> setter, System.Int64 endValue, System.Single duration)
// Offset: 0x10959C0
static ::DG::Tweening::Core::TweenerCore_3<int64_t, int64_t, ::DG::Tweening::Plugins::Options::NoOptions>* To(::DG::Tweening::Core::DOGetter_1<int64_t>* getter, ::DG::Tweening::Core::DOSetter_1<int64_t>* setter, int64_t endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<System.UInt64,System.UInt64,DG.Tweening.Plugins.Options.NoOptions> To(DG.Tweening.Core.DOGetter`1<System.UInt64> getter, DG.Tweening.Core.DOSetter`1<System.UInt64> setter, System.UInt64 endValue, System.Single duration)
// Offset: 0x1095A64
static ::DG::Tweening::Core::TweenerCore_3<uint64_t, uint64_t, ::DG::Tweening::Plugins::Options::NoOptions>* To(::DG::Tweening::Core::DOGetter_1<uint64_t>* getter, ::DG::Tweening::Core::DOSetter_1<uint64_t>* setter, uint64_t endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<System.String,System.String,DG.Tweening.Plugins.Options.StringOptions> To(DG.Tweening.Core.DOGetter`1<System.String> getter, DG.Tweening.Core.DOSetter`1<System.String> setter, System.String endValue, System.Single duration)
// Offset: 0x1095B08
static ::DG::Tweening::Core::TweenerCore_3<::StringW, ::StringW, ::DG::Tweening::Plugins::Options::StringOptions>* To(::DG::Tweening::Core::DOGetter_1<::StringW>* getter, ::DG::Tweening::Core::DOSetter_1<::StringW>* setter, ::StringW endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector2,UnityEngine.Vector2,DG.Tweening.Plugins.Options.VectorOptions> To(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector2> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector2> setter, UnityEngine.Vector2 endValue, System.Single duration)
// Offset: 0x1095BAC
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector2, ::UnityEngine::Vector2, ::DG::Tweening::Plugins::Options::VectorOptions>* To(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector2>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector2>* setter, ::UnityEngine::Vector2 endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,UnityEngine.Vector3,DG.Tweening.Plugins.Options.VectorOptions> To(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector3> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector3> setter, UnityEngine.Vector3 endValue, System.Single duration)
// Offset: 0x1095C60
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::UnityEngine::Vector3, ::DG::Tweening::Plugins::Options::VectorOptions>* To(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>* setter, ::UnityEngine::Vector3 endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector4,UnityEngine.Vector4,DG.Tweening.Plugins.Options.VectorOptions> To(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector4> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector4> setter, UnityEngine.Vector4 endValue, System.Single duration)
// Offset: 0x1095D1C
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector4, ::UnityEngine::Vector4, ::DG::Tweening::Plugins::Options::VectorOptions>* To(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector4>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector4>* setter, ::UnityEngine::Vector4 endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Quaternion,UnityEngine.Vector3,DG.Tweening.Plugins.Options.QuaternionOptions> To(DG.Tweening.Core.DOGetter`1<UnityEngine.Quaternion> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Quaternion> setter, UnityEngine.Vector3 endValue, System.Single duration)
// Offset: 0x1095DE8
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Quaternion, ::UnityEngine::Vector3, ::DG::Tweening::Plugins::Options::QuaternionOptions>* To(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Quaternion>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Quaternion>* setter, ::UnityEngine::Vector3 endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Color,UnityEngine.Color,DG.Tweening.Plugins.Options.ColorOptions> To(DG.Tweening.Core.DOGetter`1<UnityEngine.Color> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Color> setter, UnityEngine.Color endValue, System.Single duration)
// Offset: 0x1095EA4
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Color, ::UnityEngine::Color, ::DG::Tweening::Plugins::Options::ColorOptions>* To(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Color>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Color>* setter, ::UnityEngine::Color endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Rect,UnityEngine.Rect,DG.Tweening.Plugins.Options.RectOptions> To(DG.Tweening.Core.DOGetter`1<UnityEngine.Rect> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Rect> setter, UnityEngine.Rect endValue, System.Single duration)
// Offset: 0x1095F70
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Rect, ::UnityEngine::Rect, ::DG::Tweening::Plugins::Options::RectOptions>* To(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Rect>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Rect>* setter, ::UnityEngine::Rect endValue, float duration);
// static public DG.Tweening.Tweener To(DG.Tweening.Core.DOGetter`1<UnityEngine.RectOffset> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.RectOffset> setter, UnityEngine.RectOffset endValue, System.Single duration)
// Offset: 0x109603C
static ::DG::Tweening::Tweener* To(::DG::Tweening::Core::DOGetter_1<::UnityEngine::RectOffset*>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::RectOffset*>* setter, ::UnityEngine::RectOffset* endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<T1,T2,TPlugOptions> To(DG.Tweening.Plugins.Core.ABSTweenPlugin`3<T1,T2,TPlugOptions> plugin, DG.Tweening.Core.DOGetter`1<T1> getter, DG.Tweening.Core.DOSetter`1<T1> setter, T2 endValue, System.Single duration)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2, class TPlugOptions>
static ::DG::Tweening::Core::TweenerCore_3<T1, T2, TPlugOptions>* To(::DG::Tweening::Plugins::Core::ABSTweenPlugin_3<T1, T2, TPlugOptions>* plugin, ::DG::Tweening::Core::DOGetter_1<T1>* getter, ::DG::Tweening::Core::DOSetter_1<T1>* setter, T2 endValue, float duration) {
static_assert(std::is_convertible_v<std::remove_pointer_t<TPlugOptions>, ::DG::Tweening::Plugins::Options::IPlugOptions> && std::is_convertible_v<TPlugOptions, ::System::ValueType*>);
static auto ___internal__logger = ::Logger::get().WithContext("::DG::Tweening::DOTween::To");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("DG.Tweening", "DOTween", "To", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TPlugOptions>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(plugin), ::il2cpp_utils::ExtractType(getter), ::il2cpp_utils::ExtractType(setter), ::il2cpp_utils::ExtractType(endValue), ::il2cpp_utils::ExtractType(duration)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TPlugOptions>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::DG::Tweening::Core::TweenerCore_3<T1, T2, TPlugOptions>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, plugin, getter, setter, endValue, duration);
}
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,UnityEngine.Vector3,DG.Tweening.Plugins.Options.VectorOptions> ToAxis(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector3> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector3> setter, System.Single endValue, System.Single duration, DG.Tweening.AxisConstraint axisConstraint)
// Offset: 0x10960E0
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::UnityEngine::Vector3, ::DG::Tweening::Plugins::Options::VectorOptions>* ToAxis(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>* setter, float endValue, float duration, ::DG::Tweening::AxisConstraint axisConstraint);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Color,UnityEngine.Color,DG.Tweening.Plugins.Options.ColorOptions> ToAlpha(DG.Tweening.Core.DOGetter`1<UnityEngine.Color> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Color> setter, System.Single endValue, System.Single duration)
// Offset: 0x10961A0
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Color, ::UnityEngine::Color, ::DG::Tweening::Plugins::Options::ColorOptions>* ToAlpha(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Color>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Color>* setter, float endValue, float duration);
// static public DG.Tweening.Tweener To(DG.Tweening.Core.DOSetter`1<System.Single> setter, System.Single startValue, System.Single endValue, System.Single duration)
// Offset: 0x1096288
static ::DG::Tweening::Tweener* To(::DG::Tweening::Core::DOSetter_1<float>* setter, float startValue, float endValue, float duration);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,UnityEngine.Vector3[],DG.Tweening.Plugins.Options.Vector3ArrayOptions> Punch(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector3> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector3> setter, UnityEngine.Vector3 direction, System.Single duration, System.Int32 vibrato, System.Single elasticity)
// Offset: 0x109641C
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* Punch(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>* setter, ::UnityEngine::Vector3 direction, float duration, int vibrato, float elasticity);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,UnityEngine.Vector3[],DG.Tweening.Plugins.Options.Vector3ArrayOptions> Shake(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector3> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector3> setter, System.Single duration, System.Single strength, System.Int32 vibrato, System.Single randomness, System.Boolean ignoreZAxis, System.Boolean fadeOut)
// Offset: 0x109696C
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* Shake(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>* setter, float duration, float strength, int vibrato, float randomness, bool ignoreZAxis, bool fadeOut);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,UnityEngine.Vector3[],DG.Tweening.Plugins.Options.Vector3ArrayOptions> Shake(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector3> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector3> setter, System.Single duration, UnityEngine.Vector3 strength, System.Int32 vibrato, System.Single randomness, System.Boolean fadeOut)
// Offset: 0x1096F58
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* Shake(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>* setter, float duration, ::UnityEngine::Vector3 strength, int vibrato, float randomness, bool fadeOut);
// static private DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,UnityEngine.Vector3[],DG.Tweening.Plugins.Options.Vector3ArrayOptions> Shake(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector3> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector3> setter, System.Single duration, UnityEngine.Vector3 strength, System.Int32 vibrato, System.Single randomness, System.Boolean ignoreZAxis, System.Boolean vectorBased, System.Boolean fadeOut)
// Offset: 0x1096A30
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* Shake(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>* setter, float duration, ::UnityEngine::Vector3 strength, int vibrato, float randomness, bool ignoreZAxis, bool vectorBased, bool fadeOut);
// static public DG.Tweening.Core.TweenerCore`3<UnityEngine.Vector3,UnityEngine.Vector3[],DG.Tweening.Plugins.Options.Vector3ArrayOptions> ToArray(DG.Tweening.Core.DOGetter`1<UnityEngine.Vector3> getter, DG.Tweening.Core.DOSetter`1<UnityEngine.Vector3> setter, UnityEngine.Vector3[] endValues, System.Single[] durations)
// Offset: 0x109673C
static ::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* ToArray(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>* getter, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>* setter, ::ArrayW<::UnityEngine::Vector3> endValues, ::ArrayW<float> durations);
// static DG.Tweening.Core.TweenerCore`3<DG.Tweening.Color2,DG.Tweening.Color2,DG.Tweening.Plugins.Options.ColorOptions> To(DG.Tweening.Core.DOGetter`1<DG.Tweening.Color2> getter, DG.Tweening.Core.DOSetter`1<DG.Tweening.Color2> setter, DG.Tweening.Color2 endValue, System.Single duration)
// Offset: 0x1097174
static ::DG::Tweening::Core::TweenerCore_3<::DG::Tweening::Color2, ::DG::Tweening::Color2, ::DG::Tweening::Plugins::Options::ColorOptions>* To(::DG::Tweening::Core::DOGetter_1<::DG::Tweening::Color2>* getter, ::DG::Tweening::Core::DOSetter_1<::DG::Tweening::Color2>* setter, ::DG::Tweening::Color2 endValue, float duration);
// static public DG.Tweening.Sequence Sequence()
// Offset: 0x1097234
static ::DG::Tweening::Sequence* Sequence();
// static public System.Int32 CompleteAll(System.Boolean withCallbacks)
// Offset: 0x10973D8
static int CompleteAll(bool withCallbacks);
// static public System.Int32 Complete(System.Object targetOrId, System.Boolean withCallbacks)
// Offset: 0x109746C
static int Complete(::Il2CppObject* targetOrId, bool withCallbacks);
// static System.Int32 CompleteAndReturnKilledTot()
// Offset: 0x1097528
static int CompleteAndReturnKilledTot();
// static System.Int32 CompleteAndReturnKilledTot(System.Object targetOrId)
// Offset: 0x10975A0
static int CompleteAndReturnKilledTot(::Il2CppObject* targetOrId);
// static System.Int32 CompleteAndReturnKilledTotExceptFor(params System.Object[] excludeTargetsOrIds)
// Offset: 0x1097630
static int CompleteAndReturnKilledTotExceptFor(::ArrayW<::Il2CppObject*> excludeTargetsOrIds);
// static public System.Int32 FlipAll()
// Offset: 0x10976AC
static int FlipAll();
// static public System.Int32 Flip(System.Object targetOrId)
// Offset: 0x1097724
static int Flip(::Il2CppObject* targetOrId);
// static public System.Int32 GotoAll(System.Single to, System.Boolean andPlay)
// Offset: 0x10977B4
static int GotoAll(float to, bool andPlay);
// static public System.Int32 Goto(System.Object targetOrId, System.Single to, System.Boolean andPlay)
// Offset: 0x109783C
static int Goto(::Il2CppObject* targetOrId, float to, bool andPlay);
// static public System.Int32 KillAll(System.Boolean complete)
// Offset: 0x10978EC
static int KillAll(bool complete);
// static public System.Int32 KillAll(System.Boolean complete, params System.Object[] idsOrTargetsToExclude)
// Offset: 0x1097994
static int KillAll(bool complete, ::ArrayW<::Il2CppObject*> idsOrTargetsToExclude);
// static public System.Int32 Kill(System.Object targetOrId, System.Boolean complete)
// Offset: 0x1097AD0
static int Kill(::Il2CppObject* targetOrId, bool complete);
// static public System.Int32 PauseAll()
// Offset: 0x1097BB0
static int PauseAll();
// static public System.Int32 Pause(System.Object targetOrId)
// Offset: 0x1097C28
static int Pause(::Il2CppObject* targetOrId);
// static public System.Int32 PlayAll()
// Offset: 0x1097CB8
static int PlayAll();
// static public System.Int32 Play(System.Object targetOrId)
// Offset: 0x1097D30
static int Play(::Il2CppObject* targetOrId);
// static public System.Int32 Play(System.Object target, System.Object id)
// Offset: 0x1097DC0
static int Play(::Il2CppObject* target, ::Il2CppObject* id);
// static public System.Int32 PlayBackwardsAll()
// Offset: 0x1097E64
static int PlayBackwardsAll();
// static public System.Int32 PlayBackwards(System.Object targetOrId)
// Offset: 0x1097EDC
static int PlayBackwards(::Il2CppObject* targetOrId);
// static public System.Int32 PlayBackwards(System.Object target, System.Object id)
// Offset: 0x1097F6C
static int PlayBackwards(::Il2CppObject* target, ::Il2CppObject* id);
// static public System.Int32 PlayForwardAll()
// Offset: 0x1098010
static int PlayForwardAll();
// static public System.Int32 PlayForward(System.Object targetOrId)
// Offset: 0x1098088
static int PlayForward(::Il2CppObject* targetOrId);
// static public System.Int32 PlayForward(System.Object target, System.Object id)
// Offset: 0x1098118
static int PlayForward(::Il2CppObject* target, ::Il2CppObject* id);
// static public System.Int32 RestartAll(System.Boolean includeDelay)
// Offset: 0x10981BC
static int RestartAll(bool includeDelay);
// static public System.Int32 Restart(System.Object targetOrId, System.Boolean includeDelay, System.Single changeDelayTo)
// Offset: 0x1098238
static int Restart(::Il2CppObject* targetOrId, bool includeDelay, float changeDelayTo);
// static public System.Int32 Restart(System.Object target, System.Object id, System.Boolean includeDelay, System.Single changeDelayTo)
// Offset: 0x10982E8
static int Restart(::Il2CppObject* target, ::Il2CppObject* id, bool includeDelay, float changeDelayTo);
// static public System.Int32 RewindAll(System.Boolean includeDelay)
// Offset: 0x10983A0
static int RewindAll(bool includeDelay);
// static public System.Int32 Rewind(System.Object targetOrId, System.Boolean includeDelay)
// Offset: 0x109841C
static int Rewind(::Il2CppObject* targetOrId, bool includeDelay);
// static public System.Int32 SmoothRewindAll()
// Offset: 0x10984BC
static int SmoothRewindAll();
// static public System.Int32 SmoothRewind(System.Object targetOrId)
// Offset: 0x1098534
static int SmoothRewind(::Il2CppObject* targetOrId);
// static public System.Int32 TogglePauseAll()
// Offset: 0x10985C4
static int TogglePauseAll();
// static public System.Int32 TogglePause(System.Object targetOrId)
// Offset: 0x109863C
static int TogglePause(::Il2CppObject* targetOrId);
// static public System.Boolean IsTweening(System.Object targetOrId, System.Boolean alsoCheckIfIsPlaying)
// Offset: 0x10986CC
static bool IsTweening(::Il2CppObject* targetOrId, bool alsoCheckIfIsPlaying);
// static public System.Int32 TotalPlayingTweens()
// Offset: 0x1098760
static int TotalPlayingTweens();
// static public System.Collections.Generic.List`1<DG.Tweening.Tween> PlayingTweens(System.Collections.Generic.List`1<DG.Tweening.Tween> fillableList)
// Offset: 0x10987BC
static ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* PlayingTweens(::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* fillableList);
// static public System.Collections.Generic.List`1<DG.Tweening.Tween> PausedTweens(System.Collections.Generic.List`1<DG.Tweening.Tween> fillableList)
// Offset: 0x1098848
static ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* PausedTweens(::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* fillableList);
// static public System.Collections.Generic.List`1<DG.Tweening.Tween> TweensById(System.Object id, System.Boolean playingOnly, System.Collections.Generic.List`1<DG.Tweening.Tween> fillableList)
// Offset: 0x10988D4
static ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* TweensById(::Il2CppObject* id, bool playingOnly, ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* fillableList);
// static public System.Collections.Generic.List`1<DG.Tweening.Tween> TweensByTarget(System.Object target, System.Boolean playingOnly, System.Collections.Generic.List`1<DG.Tweening.Tween> fillableList)
// Offset: 0x109898C
static ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* TweensByTarget(::Il2CppObject* target, bool playingOnly, ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* fillableList);
// static private System.Void InitCheck()
// Offset: 0x1095674
static void InitCheck();
// static private DG.Tweening.Core.TweenerCore`3<T1,T2,TPlugOptions> ApplyTo(DG.Tweening.Core.DOGetter`1<T1> getter, DG.Tweening.Core.DOSetter`1<T1> setter, T2 endValue, System.Single duration, DG.Tweening.Plugins.Core.ABSTweenPlugin`3<T1,T2,TPlugOptions> plugin)
// Offset: 0xFFFFFFFFFFFFFFFF
template<class T1, class T2, class TPlugOptions>
static ::DG::Tweening::Core::TweenerCore_3<T1, T2, TPlugOptions>* ApplyTo(::DG::Tweening::Core::DOGetter_1<T1>* getter, ::DG::Tweening::Core::DOSetter_1<T1>* setter, T2 endValue, float duration, ::DG::Tweening::Plugins::Core::ABSTweenPlugin_3<T1, T2, TPlugOptions>* plugin) {
static_assert(std::is_convertible_v<std::remove_pointer_t<TPlugOptions>, ::DG::Tweening::Plugins::Options::IPlugOptions> && std::is_convertible_v<TPlugOptions, ::System::ValueType*>);
static auto ___internal__logger = ::Logger::get().WithContext("::DG::Tweening::DOTween::ApplyTo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("DG.Tweening", "DOTween", "ApplyTo", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TPlugOptions>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(getter), ::il2cpp_utils::ExtractType(setter), ::il2cpp_utils::ExtractType(endValue), ::il2cpp_utils::ExtractType(duration), ::il2cpp_utils::ExtractType(plugin)})));
static auto* ___generic__method = THROW_UNLESS((::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T1>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T2>::get(), ::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<TPlugOptions>::get()})));
return ::il2cpp_utils::RunMethodRethrow<::DG::Tweening::Core::TweenerCore_3<T1, T2, TPlugOptions>*, false>(static_cast<Il2CppObject*>(nullptr), ___generic__method, getter, setter, endValue, duration, plugin);
}
// public System.Void .ctor()
// Offset: 0x1098A2C
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static DOTween* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::DG::Tweening::DOTween::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<DOTween*, creationType>()));
}
}; // DG.Tweening.DOTween
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: DG::Tweening::DOTween::get_logBehaviour
// Il2CppName: get_logBehaviour
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::LogBehaviour (*)()>(&DG::Tweening::DOTween::get_logBehaviour)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "get_logBehaviour", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::set_logBehaviour
// Il2CppName: set_logBehaviour
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::DG::Tweening::LogBehaviour)>(&DG::Tweening::DOTween::set_logBehaviour)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("DG.Tweening", "LogBehaviour")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "set_logBehaviour", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::get_debugStoreTargetId
// Il2CppName: get_debugStoreTargetId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&DG::Tweening::DOTween::get_debugStoreTargetId)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "get_debugStoreTargetId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::set_debugStoreTargetId
// Il2CppName: set_debugStoreTargetId
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(bool)>(&DG::Tweening::DOTween::set_debugStoreTargetId)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "set_debugStoreTargetId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::_cctor
// Il2CppName: .cctor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&DG::Tweening::DOTween::_cctor)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::IDOTweenInit* (*)(::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<::DG::Tweening::LogBehaviour>)>(&DG::Tweening::DOTween::Init)> {
static const MethodInfo* get() {
static auto* recycleAllByDefault = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* useSafeMode = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* logBehaviour = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "LogBehaviour")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{recycleAllByDefault, useSafeMode, logBehaviour});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::AutoInit
// Il2CppName: AutoInit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&DG::Tweening::DOTween::AutoInit)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "AutoInit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Init
// Il2CppName: Init
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::IDOTweenInit* (*)(::DG::Tweening::Core::DOTweenSettings*, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<::DG::Tweening::LogBehaviour>)>(&DG::Tweening::DOTween::Init)> {
static const MethodInfo* get() {
static auto* settings = &::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOTweenSettings")->byval_arg;
static auto* recycleAllByDefault = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* useSafeMode = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg;
static auto* logBehaviour = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "LogBehaviour")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{settings, recycleAllByDefault, useSafeMode, logBehaviour});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::SetTweensCapacity
// Il2CppName: SetTweensCapacity
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(int, int)>(&DG::Tweening::DOTween::SetTweensCapacity)> {
static const MethodInfo* get() {
static auto* tweenersCapacity = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* sequencesCapacity = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "SetTweensCapacity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{tweenersCapacity, sequencesCapacity});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Clear
// Il2CppName: Clear
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(bool)>(&DG::Tweening::DOTween::Clear)> {
static const MethodInfo* get() {
static auto* destroy = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Clear", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{destroy});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::ClearCachedTweens
// Il2CppName: ClearCachedTweens
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&DG::Tweening::DOTween::ClearCachedTweens)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "ClearCachedTweens", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Validate
// Il2CppName: Validate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::Validate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Validate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::ManualUpdate
// Il2CppName: ManualUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(float, float)>(&DG::Tweening::DOTween::ManualUpdate)> {
static const MethodInfo* get() {
static auto* deltaTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* unscaledDeltaTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "ManualUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{deltaTime, unscaledDeltaTime});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<float, float, ::DG::Tweening::Plugins::Options::FloatOptions>* (*)(::DG::Tweening::Core::DOGetter_1<float>*, ::DG::Tweening::Core::DOSetter_1<float>*, float, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<double, double, ::DG::Tweening::Plugins::Options::NoOptions>* (*)(::DG::Tweening::Core::DOGetter_1<double>*, ::DG::Tweening::Core::DOSetter_1<double>*, double, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Double")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Double")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "Double")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<int, int, ::DG::Tweening::Plugins::Options::NoOptions>* (*)(::DG::Tweening::Core::DOGetter_1<int>*, ::DG::Tweening::Core::DOSetter_1<int>*, int, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int32")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int32")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<uint, uint, ::DG::Tweening::Plugins::Options::UintOptions>* (*)(::DG::Tweening::Core::DOGetter_1<uint>*, ::DG::Tweening::Core::DOSetter_1<uint>*, uint, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "UInt32")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "UInt32")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<int64_t, int64_t, ::DG::Tweening::Plugins::Options::NoOptions>* (*)(::DG::Tweening::Core::DOGetter_1<int64_t>*, ::DG::Tweening::Core::DOSetter_1<int64_t>*, int64_t, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int64")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Int64")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "Int64")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<uint64_t, uint64_t, ::DG::Tweening::Plugins::Options::NoOptions>* (*)(::DG::Tweening::Core::DOGetter_1<uint64_t>*, ::DG::Tweening::Core::DOSetter_1<uint64_t>*, uint64_t, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "UInt64")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "UInt64")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "UInt64")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::StringW, ::StringW, ::DG::Tweening::Plugins::Options::StringOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::StringW>*, ::DG::Tweening::Core::DOSetter_1<::StringW>*, ::StringW, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "String")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector2, ::UnityEngine::Vector2, ::DG::Tweening::Plugins::Options::VectorOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector2>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector2>*, ::UnityEngine::Vector2, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector2")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector2")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector2")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::UnityEngine::Vector3, ::DG::Tweening::Plugins::Options::VectorOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>*, ::UnityEngine::Vector3, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector4, ::UnityEngine::Vector4, ::DG::Tweening::Plugins::Options::VectorOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector4>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector4>*, ::UnityEngine::Vector4, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector4")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector4")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector4")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Quaternion, ::UnityEngine::Vector3, ::DG::Tweening::Plugins::Options::QuaternionOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Quaternion>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Quaternion>*, ::UnityEngine::Vector3, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Color, ::UnityEngine::Color, ::DG::Tweening::Plugins::Options::ColorOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Color>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Color>*, ::UnityEngine::Color, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Color")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Color")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("UnityEngine", "Color")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Rect, ::UnityEngine::Rect, ::DG::Tweening::Plugins::Options::RectOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Rect>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Rect>*, ::UnityEngine::Rect, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Rect")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Rect")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("UnityEngine", "Rect")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Tweener* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::RectOffset*>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::RectOffset*>*, ::UnityEngine::RectOffset*, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "RectOffset")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "RectOffset")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("UnityEngine", "RectOffset")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: DG::Tweening::DOTween::ToAxis
// Il2CppName: ToAxis
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::UnityEngine::Vector3, ::DG::Tweening::Plugins::Options::VectorOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>*, float, float, ::DG::Tweening::AxisConstraint)>(&DG::Tweening::DOTween::ToAxis)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* axisConstraint = &::il2cpp_utils::GetClassFromName("DG.Tweening", "AxisConstraint")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "ToAxis", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration, axisConstraint});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::ToAlpha
// Il2CppName: ToAlpha
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Color, ::UnityEngine::Color, ::DG::Tweening::Plugins::Options::ColorOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Color>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Color>*, float, float)>(&DG::Tweening::DOTween::ToAlpha)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Color")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Color")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "ToAlpha", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Tweener* (*)(::DG::Tweening::Core::DOSetter_1<float>*, float, float, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg;
static auto* startValue = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{setter, startValue, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Punch
// Il2CppName: Punch
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>*, ::UnityEngine::Vector3, float, int, float)>(&DG::Tweening::DOTween::Punch)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* direction = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* vibrato = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* elasticity = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Punch", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, direction, duration, vibrato, elasticity});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Shake
// Il2CppName: Shake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>*, float, float, int, float, bool, bool)>(&DG::Tweening::DOTween::Shake)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* strength = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* vibrato = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* randomness = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* ignoreZAxis = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* fadeOut = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Shake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, duration, strength, vibrato, randomness, ignoreZAxis, fadeOut});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Shake
// Il2CppName: Shake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>*, float, ::UnityEngine::Vector3, int, float, bool)>(&DG::Tweening::DOTween::Shake)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* strength = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
static auto* vibrato = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* randomness = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* fadeOut = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Shake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, duration, strength, vibrato, randomness, fadeOut});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Shake
// Il2CppName: Shake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>*, float, ::UnityEngine::Vector3, int, float, bool, bool, bool)>(&DG::Tweening::DOTween::Shake)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* strength = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg;
static auto* vibrato = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* randomness = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* ignoreZAxis = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* vectorBased = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* fadeOut = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Shake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, duration, strength, vibrato, randomness, ignoreZAxis, vectorBased, fadeOut});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::ToArray
// Il2CppName: ToArray
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::UnityEngine::Vector3, ::ArrayW<::UnityEngine::Vector3>, ::DG::Tweening::Plugins::Options::Vector3ArrayOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::UnityEngine::Vector3>*, ::DG::Tweening::Core::DOSetter_1<::UnityEngine::Vector3>*, ::ArrayW<::UnityEngine::Vector3>, ::ArrayW<float>)>(&DG::Tweening::DOTween::ToArray)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")})->byval_arg;
static auto* endValues = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3"), 1)->byval_arg;
static auto* durations = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Single"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "ToArray", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValues, durations});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::To
// Il2CppName: To
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Core::TweenerCore_3<::DG::Tweening::Color2, ::DG::Tweening::Color2, ::DG::Tweening::Plugins::Options::ColorOptions>* (*)(::DG::Tweening::Core::DOGetter_1<::DG::Tweening::Color2>*, ::DG::Tweening::Core::DOSetter_1<::DG::Tweening::Color2>*, ::DG::Tweening::Color2, float)>(&DG::Tweening::DOTween::To)> {
static const MethodInfo* get() {
static auto* getter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOGetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "Color2")})->byval_arg;
static auto* setter = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("DG.Tweening.Core", "DOSetter`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "Color2")})->byval_arg;
static auto* endValue = &::il2cpp_utils::GetClassFromName("DG.Tweening", "Color2")->byval_arg;
static auto* duration = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "To", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{getter, setter, endValue, duration});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Sequence
// Il2CppName: Sequence
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::DG::Tweening::Sequence* (*)()>(&DG::Tweening::DOTween::Sequence)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Sequence", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::CompleteAll
// Il2CppName: CompleteAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(bool)>(&DG::Tweening::DOTween::CompleteAll)> {
static const MethodInfo* get() {
static auto* withCallbacks = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "CompleteAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{withCallbacks});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Complete
// Il2CppName: Complete
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, bool)>(&DG::Tweening::DOTween::Complete)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* withCallbacks = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Complete", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId, withCallbacks});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::CompleteAndReturnKilledTot
// Il2CppName: CompleteAndReturnKilledTot
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::CompleteAndReturnKilledTot)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "CompleteAndReturnKilledTot", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::CompleteAndReturnKilledTot
// Il2CppName: CompleteAndReturnKilledTot
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::CompleteAndReturnKilledTot)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "CompleteAndReturnKilledTot", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::CompleteAndReturnKilledTotExceptFor
// Il2CppName: CompleteAndReturnKilledTotExceptFor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::ArrayW<::Il2CppObject*>)>(&DG::Tweening::DOTween::CompleteAndReturnKilledTotExceptFor)> {
static const MethodInfo* get() {
static auto* excludeTargetsOrIds = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "CompleteAndReturnKilledTotExceptFor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{excludeTargetsOrIds});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::FlipAll
// Il2CppName: FlipAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::FlipAll)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "FlipAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Flip
// Il2CppName: Flip
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::Flip)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Flip", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::GotoAll
// Il2CppName: GotoAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(float, bool)>(&DG::Tweening::DOTween::GotoAll)> {
static const MethodInfo* get() {
static auto* to = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* andPlay = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "GotoAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{to, andPlay});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Goto
// Il2CppName: Goto
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, float, bool)>(&DG::Tweening::DOTween::Goto)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* to = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
static auto* andPlay = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Goto", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId, to, andPlay});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::KillAll
// Il2CppName: KillAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(bool)>(&DG::Tweening::DOTween::KillAll)> {
static const MethodInfo* get() {
static auto* complete = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "KillAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{complete});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::KillAll
// Il2CppName: KillAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(bool, ::ArrayW<::Il2CppObject*>)>(&DG::Tweening::DOTween::KillAll)> {
static const MethodInfo* get() {
static auto* complete = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* idsOrTargetsToExclude = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Object"), 1)->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "KillAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{complete, idsOrTargetsToExclude});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Kill
// Il2CppName: Kill
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, bool)>(&DG::Tweening::DOTween::Kill)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* complete = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Kill", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId, complete});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PauseAll
// Il2CppName: PauseAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::PauseAll)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PauseAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Pause
// Il2CppName: Pause
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::Pause)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Pause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayAll
// Il2CppName: PlayAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::PlayAll)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Play
// Il2CppName: Play
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::Play)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Play", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Play
// Il2CppName: Play
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, ::Il2CppObject*)>(&DG::Tweening::DOTween::Play)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* id = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Play", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, id});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayBackwardsAll
// Il2CppName: PlayBackwardsAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::PlayBackwardsAll)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayBackwardsAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayBackwards
// Il2CppName: PlayBackwards
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::PlayBackwards)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayBackwards", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayBackwards
// Il2CppName: PlayBackwards
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, ::Il2CppObject*)>(&DG::Tweening::DOTween::PlayBackwards)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* id = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayBackwards", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, id});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayForwardAll
// Il2CppName: PlayForwardAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::PlayForwardAll)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayForwardAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayForward
// Il2CppName: PlayForward
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::PlayForward)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayForward", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayForward
// Il2CppName: PlayForward
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, ::Il2CppObject*)>(&DG::Tweening::DOTween::PlayForward)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* id = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayForward", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, id});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::RestartAll
// Il2CppName: RestartAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(bool)>(&DG::Tweening::DOTween::RestartAll)> {
static const MethodInfo* get() {
static auto* includeDelay = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "RestartAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{includeDelay});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Restart
// Il2CppName: Restart
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, bool, float)>(&DG::Tweening::DOTween::Restart)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* includeDelay = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* changeDelayTo = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Restart", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId, includeDelay, changeDelayTo});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Restart
// Il2CppName: Restart
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, ::Il2CppObject*, bool, float)>(&DG::Tweening::DOTween::Restart)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* id = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* includeDelay = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* changeDelayTo = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Restart", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, id, includeDelay, changeDelayTo});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::RewindAll
// Il2CppName: RewindAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(bool)>(&DG::Tweening::DOTween::RewindAll)> {
static const MethodInfo* get() {
static auto* includeDelay = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "RewindAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{includeDelay});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::Rewind
// Il2CppName: Rewind
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*, bool)>(&DG::Tweening::DOTween::Rewind)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* includeDelay = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "Rewind", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId, includeDelay});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::SmoothRewindAll
// Il2CppName: SmoothRewindAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::SmoothRewindAll)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "SmoothRewindAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::SmoothRewind
// Il2CppName: SmoothRewind
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::SmoothRewind)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "SmoothRewind", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::TogglePauseAll
// Il2CppName: TogglePauseAll
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::TogglePauseAll)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "TogglePauseAll", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::TogglePause
// Il2CppName: TogglePause
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)(::Il2CppObject*)>(&DG::Tweening::DOTween::TogglePause)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "TogglePause", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::IsTweening
// Il2CppName: IsTweening
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::Il2CppObject*, bool)>(&DG::Tweening::DOTween::IsTweening)> {
static const MethodInfo* get() {
static auto* targetOrId = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* alsoCheckIfIsPlaying = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "IsTweening", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{targetOrId, alsoCheckIfIsPlaying});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::TotalPlayingTweens
// Il2CppName: TotalPlayingTweens
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (*)()>(&DG::Tweening::DOTween::TotalPlayingTweens)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "TotalPlayingTweens", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PlayingTweens
// Il2CppName: PlayingTweens
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* (*)(::System::Collections::Generic::List_1<::DG::Tweening::Tween*>*)>(&DG::Tweening::DOTween::PlayingTweens)> {
static const MethodInfo* get() {
static auto* fillableList = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "Tween")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PlayingTweens", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{fillableList});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::PausedTweens
// Il2CppName: PausedTweens
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* (*)(::System::Collections::Generic::List_1<::DG::Tweening::Tween*>*)>(&DG::Tweening::DOTween::PausedTweens)> {
static const MethodInfo* get() {
static auto* fillableList = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "Tween")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "PausedTweens", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{fillableList});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::TweensById
// Il2CppName: TweensById
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* (*)(::Il2CppObject*, bool, ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>*)>(&DG::Tweening::DOTween::TweensById)> {
static const MethodInfo* get() {
static auto* id = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* playingOnly = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* fillableList = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "Tween")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "TweensById", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{id, playingOnly, fillableList});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::TweensByTarget
// Il2CppName: TweensByTarget
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::List_1<::DG::Tweening::Tween*>* (*)(::Il2CppObject*, bool, ::System::Collections::Generic::List_1<::DG::Tweening::Tween*>*)>(&DG::Tweening::DOTween::TweensByTarget)> {
static const MethodInfo* get() {
static auto* target = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
static auto* playingOnly = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* fillableList = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System.Collections.Generic", "List`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("DG.Tweening", "Tween")})->byval_arg;
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "TweensByTarget", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{target, playingOnly, fillableList});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::InitCheck
// Il2CppName: InitCheck
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&DG::Tweening::DOTween::InitCheck)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(DG::Tweening::DOTween*), "InitCheck", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: DG::Tweening::DOTween::ApplyTo
// Il2CppName: ApplyTo
// Cannot write MetadataGetter for generic methods!
// Writing MetadataGetter for method: DG::Tweening::DOTween::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 81.885671 | 582 | 0.742186 | [
"object",
"vector"
] |
04aa9c627623f0c5a06b8484924223387735d4fe | 7,642 | cpp | C++ | histogram_item.cpp | hsiaoairplane/3d-watermark-lsd | 168df211b579fafc77a9bccba6ed54ae30a0ee23 | [
"MIT"
] | 1 | 2018-07-20T02:44:11.000Z | 2018-07-20T02:44:11.000Z | histogram_item.cpp | hsiaoairplane/3d-watermark-lsd | 168df211b579fafc77a9bccba6ed54ae30a0ee23 | [
"MIT"
] | null | null | null | histogram_item.cpp | hsiaoairplane/3d-watermark-lsd | 168df211b579fafc77a9bccba6ed54ae30a0ee23 | [
"MIT"
] | null | null | null | #include "histogram_item.h"
#include <qstring.h>
#include <qpainter.h>
#include <qwt_plot.h>
#include <qwt_interval_data.h>
#include <qwt_painter.h>
#include <qwt_scale_map.h>
class HistogramItem::PrivateData
{
public:
int attributes;
QwtIntervalData data;
QColor color;
double reference;
};
HistogramItem::HistogramItem(const QwtText &title):
QwtPlotItem(title)
{
init();
}
HistogramItem::HistogramItem(const QString &title):
QwtPlotItem(QwtText(title))
{
init();
}
HistogramItem::~HistogramItem()
{
delete d_data;
}
void HistogramItem::init()
{
d_data = new PrivateData();
d_data->reference = 0.0;
d_data->attributes = HistogramItem::Auto;
setItemAttribute(QwtPlotItem::AutoScale, true);
setItemAttribute(QwtPlotItem::Legend, true);
setZ(20.0);
}
void HistogramItem::setBaseline(double reference)
{
if ( d_data->reference != reference )
{
d_data->reference = reference;
itemChanged();
}
}
double HistogramItem::baseline() const
{
return d_data->reference;
}
void HistogramItem::setData(const QwtIntervalData &data)
{
d_data->data = data;
itemChanged();
}
const QwtIntervalData &HistogramItem::data() const
{
return d_data->data;
}
void HistogramItem::setColor(const QColor &color)
{
if ( d_data->color != color )
{
d_data->color = color;
itemChanged();
}
}
QColor HistogramItem::color() const
{
return d_data->color;
}
QwtDoubleRect HistogramItem::boundingRect() const
{
QwtDoubleRect rect = d_data->data.boundingRect();
if ( !rect.isValid() )
return rect;
if ( d_data->attributes & Xfy )
{
rect = QwtDoubleRect( rect.y(), rect.x(),
rect.height(), rect.width() );
if ( rect.left() > d_data->reference )
rect.setLeft( d_data->reference );
else if ( rect.right() < d_data->reference )
rect.setRight( d_data->reference );
}
else
{
if ( rect.bottom() < d_data->reference )
rect.setBottom( d_data->reference );
else if ( rect.top() > d_data->reference )
rect.setTop( d_data->reference );
}
return rect;
}
int HistogramItem::rtti() const
{
return QwtPlotItem::Rtti_PlotHistogram;
}
void HistogramItem::setHistogramAttribute(HistogramAttribute attribute, bool on)
{
if ( bool(d_data->attributes & attribute) == on )
return;
if ( on )
d_data->attributes |= attribute;
else
d_data->attributes &= ~attribute;
itemChanged();
}
bool HistogramItem::testHistogramAttribute(HistogramAttribute attribute) const
{
return d_data->attributes & attribute;
}
void HistogramItem::draw(QPainter *painter, const QwtScaleMap &xMap,
const QwtScaleMap &yMap, const QRect &) const
{
const QwtIntervalData &iData = d_data->data;
painter->setPen(QPen(d_data->color));
const int x0 = xMap.transform(baseline());
const int y0 = yMap.transform(baseline());
for ( int i = 0; i < (int)iData.size(); i++ )
{
if ( d_data->attributes & HistogramItem::Xfy )
{
const int x2 = xMap.transform(iData.value(i));
if ( x2 == x0 )
continue;
int y1 = yMap.transform( iData.interval(i).minValue());
int y2 = yMap.transform( iData.interval(i).maxValue());
if ( y1 > y2 )
qSwap(y1, y2);
if ( i < (int)iData.size() - 2 )
{
const int yy1 = yMap.transform(iData.interval(i+1).minValue());
const int yy2 = yMap.transform(iData.interval(i+1).maxValue());
if ( y2 == qwtMin(yy1, yy2) )
{
const int xx2 = xMap.transform(
iData.interval(i+1).minValue());
if ( xx2 != x0 && ( (xx2 < x0 && x2 < x0) ||
(xx2 > x0 && x2 > x0) ) )
{
// One pixel distance between neighboured bars
y2++;
}
}
}
drawBar(painter, Qt::Horizontal,
QRect(x0, y1, x2 - x0, y2 - y1));
}
else
{
const int y2 = yMap.transform(iData.value(i));
if ( y2 == y0 )
continue;
int x1 = xMap.transform(iData.interval(i).minValue());
int x2 = xMap.transform(iData.interval(i).maxValue());
if ( x1 > x2 )
qSwap(x1, x2);
if ( i < (int)iData.size() - 2 )
{
const int xx1 = xMap.transform(iData.interval(i+1).minValue());
const int xx2 = xMap.transform(iData.interval(i+1).maxValue());
if ( x2 == qwtMin(xx1, xx2) )
{
const int yy2 = yMap.transform(iData.value(i+1));
if ( yy2 != y0 && ( (yy2 < y0 && y2 < y0) ||
(yy2 > y0 && y2 > y0) ) )
{
// One pixel distance between neighboured bars
x2--;
}
}
}
drawBar(painter, Qt::Vertical,
QRect(x1, y0, x2 - x1, y2 - y0) );
}
}
}
void HistogramItem::drawBar(QPainter *painter,
Qt::Orientation, const QRect& rect) const
{
painter->save();
const QColor color(painter->pen().color());
#if QT_VERSION >= 0x040000
const QRect r = rect.normalized();
#else
const QRect r = rect.normalize();
#endif
const int factor = 125;
const QColor light(color.light(factor));
const QColor dark(color.dark(factor));
painter->setBrush(color);
painter->setPen(Qt::NoPen);
QwtPainter::drawRect(painter, r.x() + 1, r.y() + 1,
r.width() - 2, r.height() - 2);
painter->setBrush(Qt::NoBrush);
painter->setPen(QPen(light, 2));
#if QT_VERSION >= 0x040000
QwtPainter::drawLine(painter,
r.left() + 1, r.top() + 2, r.right() + 1, r.top() + 2);
#else
QwtPainter::drawLine(painter,
r.left(), r.top() + 2, r.right() + 1, r.top() + 2);
#endif
painter->setPen(QPen(dark, 2));
#if QT_VERSION >= 0x040000
QwtPainter::drawLine(painter,
r.left() + 1, r.bottom(), r.right() + 1, r.bottom());
#else
QwtPainter::drawLine(painter,
r.left(), r.bottom(), r.right() + 1, r.bottom());
#endif
painter->setPen(QPen(light, 1));
#if QT_VERSION >= 0x040000
QwtPainter::drawLine(painter,
r.left(), r.top() + 1, r.left(), r.bottom());
QwtPainter::drawLine(painter,
r.left() + 1, r.top() + 2, r.left() + 1, r.bottom() - 1);
#else
QwtPainter::drawLine(painter,
r.left(), r.top() + 1, r.left(), r.bottom() + 1);
QwtPainter::drawLine(painter,
r.left() + 1, r.top() + 2, r.left() + 1, r.bottom());
#endif
painter->setPen(QPen(dark, 1));
#if QT_VERSION >= 0x040000
QwtPainter::drawLine(painter,
r.right() + 1, r.top() + 1, r.right() + 1, r.bottom());
QwtPainter::drawLine(painter,
r.right(), r.top() + 2, r.right(), r.bottom() - 1);
#else
QwtPainter::drawLine(painter,
r.right() + 1, r.top() + 1, r.right() + 1, r.bottom() + 1);
QwtPainter::drawLine(painter,
r.right(), r.top() + 2, r.right(), r.bottom());
#endif
painter->restore();
}
| 26.814035 | 81 | 0.528788 | [
"transform"
] |
04bd6cd96c57c65e4b52d91ba22e11e74cbb49f6 | 594 | cpp | C++ | src/solutions/47.cpp | bshankar/euler | c866a661a94d15d3744c74d85149534efac2ca23 | [
"MIT"
] | null | null | null | src/solutions/47.cpp | bshankar/euler | c866a661a94d15d3744c74d85149534efac2ca23 | [
"MIT"
] | null | null | null | src/solutions/47.cpp | bshankar/euler | c866a661a94d15d3744c74d85149534efac2ca23 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include "../lib/euler.hpp"
using namespace std;
typedef unsigned long ul;
int main() {
vector<bool> v = sieve(1000); // primes below 1000 ??
ul k = 650;
int seq = 0;
while (1) {
int dpd = 0;
for (int i = 0; i < v.size(); ++i) {
if (v[i]) continue;
ul p = i+2;
if (k % p == 0) ++dpd;
}
if (dpd == 4)
++seq;
else
seq = 0;
if (seq == 4) {
cout << k-3 << endl;
break;
}
++k;
}
}
| 19.8 | 57 | 0.388889 | [
"vector"
] |
04be00c6b0c5863c6e3967d6663461f43bafbbed | 37,320 | cc | C++ | agent/wptdriver/wpt_test.cc | AutomationConsultant/webpagetest | 37aff455ea1b99ba319f6558a676c0e72ba6e1eb | [
"BSD-3-Clause"
] | 1 | 2015-03-29T02:31:02.000Z | 2015-03-29T02:31:02.000Z | agent/wptdriver/wpt_test.cc | AutomationConsultant/webpagetest | 37aff455ea1b99ba319f6558a676c0e72ba6e1eb | [
"BSD-3-Clause"
] | null | null | null | agent/wptdriver/wpt_test.cc | AutomationConsultant/webpagetest | 37aff455ea1b99ba319f6558a676c0e72ba6e1eb | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
Copyright (c) 2010, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the <ORGANIZATION> nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include "StdAfx.h"
#include "wpt_test.h"
#include <ShlObj.h>
#include "util.h"
#include "../wpthook/shared_mem.h"
#include "wpt_settings.h"
static const DWORD SCRIPT_TIMEOUT_MULTIPLIER = 2;
static const BYTE JPEG_DEFAULT_QUALITY = 30;
static const DWORD MS_IN_SEC = 1000;
static const DWORD BROWSER_WIDTH = 1024;
static const DWORD BROWSER_HEIGHT = 768;
// Mobile emulation defaults (taken from a Droid RAZR).
// The height has 36 added pixels to allow for the debugging header.
static const TCHAR * DEFAULT_MOBILE_SCALE_FACTOR = _T("1.5");
static const DWORD DEFAULT_MOBILE_WIDTH = 540;
static const DWORD DEFAULT_MOBILE_HEIGHT = 900;
static const DWORD CHROME_PADDING_HEIGHT = 115;
static const DWORD CHROME_PADDING_WIDTH = 4;
static const char * DEFAULT_MOBILE_USER_AGENT =
"Mozilla/5.0 (Linux; Android 4.0.4; DROID RAZR "
"Build/6.7.2-180_DHD-16_M4-31) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/31.0.1631.1 Mobile Safari/537.36";
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
WptTest::WptTest(void):
_version(0)
,_test_timeout(DEFAULT_TEST_TIMEOUT * SECONDS_TO_MS)
,_activity_timeout(DEFAULT_ACTIVITY_TIMEOUT)
,_measurement_timeout(DEFAULT_TEST_TIMEOUT)
,has_gpu_(false)
,lock_count_(0) {
QueryPerformanceFrequency(&_perf_frequency);
// figure out what our working diriectory is
TCHAR path[MAX_PATH];
if( SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE,
NULL, SHGFP_TYPE_CURRENT, path)) ) {
PathAppend(path, _T("webpagetest"));
CreateDirectory(path, NULL);
_directory = path;
lstrcat(path, _T("_data"));
CreateDirectory(path, NULL);
_test_file = CString(path) + _T("\\test.dat");
}
InitializeCriticalSection(&cs_);
_tcp_port_override.InitHashTable(257);
Reset();
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
WptTest::~WptTest(void) {
DeleteCriticalSection(&cs_);
}
/*-----------------------------------------------------------------------------
Reset everything to their default values
-----------------------------------------------------------------------------*/
void WptTest::Reset(void) {
_id.Empty();
_url.Empty();
_runs = 1;
_discard = 0;
_fv_only = false;
_doc_complete = false;
_ignore_ssl = false;
_tcpdump = false;
_timeline = false;
_trace = false;
_netlog = false;
_video = false;
_spdy3 = false;
_noscript = false;
_clear_certs = false;
_emulate_mobile = false;
_force_software_render = false;
_test_type.Empty();
_block.Empty();
_bwIn = 0;
_bwOut = 0;
_latency = 0;
_plr = 0.0;
_browser.Empty();
_browser_url.Empty();
_browser_md5.Empty();
_basic_auth.Empty();
_script.Empty();
_run = 0;
_specific_run = 0;
_specific_index = 0;
_discard_test = false;
_index = 0;
_clear_cache = true;
_active = false;
_dom_element_check = false;
_log_data = true;
_sleep_end.QuadPart = 0;
_combine_steps = 0;
_image_quality = JPEG_DEFAULT_QUALITY;
_png_screen_shot = false;
_minimum_duration = 0;
_upload_incremental_results = true;
_user_agent.Empty();
_add_headers.RemoveAll();
_set_headers.RemoveAll();
_override_hosts.RemoveAll();
_dns_override.RemoveAll();
_dns_name_override.RemoveAll();
_block_requests.RemoveAll();
_save_response_bodies = false;
_save_html_body = false;
_preserve_user_agent = false;
_browser_width = BROWSER_WIDTH;
_browser_height = BROWSER_HEIGHT;
_viewport_width = 0;
_viewport_height = 0;
_no_run = 0;
_custom_rules.RemoveAll();
_client.Empty();
_continuous_video = false;
_browser_command_line.Empty();
_browser_additional_command_line.Empty();
_run_error.Empty();
_test_error.Empty();
}
/*-----------------------------------------------------------------------------
Parse the test settings from a string
-----------------------------------------------------------------------------*/
bool WptTest::Load(CString& test) {
bool ret = false;
WptTrace(loglevel::kFunction, _T("WptTest::Load()\n"));
Reset();
bool done = false;
int linePos = 0;
CString line = test.Tokenize(_T("\r\n"), linePos);
while (!done && linePos >= 0) {
int keyEnd = line.Find('=');
if (keyEnd > 0) {
CString key = line.Left(keyEnd).Trim();
CString value = line.Mid(keyEnd + 1);
if (key.GetLength()) {
// check against all of the known options
if (!key.CompareNoCase(_T("Test ID")))
_id = value.Trim();
else if (!key.CompareNoCase(_T("url")))
_url = value.Trim();
else if (!key.CompareNoCase(_T("fvonly")) && _ttoi(value.Trim()))
_fv_only = true;
else if (!key.CompareNoCase(_T("run")))
_specific_run = _ttoi(value.Trim());
else if (!key.CompareNoCase(_T("index")))
_specific_index = _ttoi(value.Trim());
else if (!key.CompareNoCase(_T("discardTest")) && _ttoi(value.Trim()))
_discard_test = true;
else if (!key.CompareNoCase(_T("runs")))
_runs = _ttoi(value.Trim());
else if (!key.CompareNoCase(_T("discard")) && !_specific_run)
_discard = _ttoi(value.Trim());
else if (!key.CompareNoCase(_T("web10")) && _ttoi(value.Trim()))
_doc_complete = true;
else if (!key.CompareNoCase(_T("ignoreSSL")) && _ttoi(value.Trim()))
_ignore_ssl = true;
else if (!key.CompareNoCase(_T("tcpdump")) && _ttoi(value.Trim()))
_tcpdump = true;
else if (!key.CompareNoCase(_T("timeline")) && _ttoi(value.Trim()))
_timeline = true;
else if (!key.CompareNoCase(_T("trace")) && _ttoi(value.Trim()))
_trace = true;
else if (!key.CompareNoCase(_T("netlog")) && _ttoi(value.Trim()))
_netlog = true;
else if (!key.CompareNoCase(_T("spdy3")) && _ttoi(value.Trim()))
_spdy3 = true;
else if (!key.CompareNoCase(_T("noscript")) && _ttoi(value.Trim()))
_noscript = true;
else if (!key.CompareNoCase(_T("Capture Video")) &&_ttoi(value.Trim()))
_video = true;
else if (!key.CompareNoCase(_T("clearcerts")) &&_ttoi(value.Trim()))
_clear_certs = true;
else if (!key.CompareNoCase(_T("mobile")) &&_ttoi(value.Trim()))
_emulate_mobile = true;
else if (!key.CompareNoCase(_T("swRender")) &&_ttoi(value.Trim()))
_force_software_render = true;
else if (!key.CompareNoCase(_T("type")))
_test_type = value.Trim();
else if (!key.CompareNoCase(_T("block")))
_block = value.Trim();
else if (!key.CompareNoCase(_T("bwIn")))
_bwIn = _ttoi(value.Trim());
else if (!key.CompareNoCase(_T("bwOut")))
_bwOut = _ttoi(value.Trim());
else if (!key.CompareNoCase(_T("latency")))
_latency = _ttoi(value.Trim());
else if (!key.CompareNoCase(_T("plr")))
_plr = _ttof(value.Trim());
else if (!key.CompareNoCase(_T("browser")))
_browser = value.Trim();
else if (!key.CompareNoCase(_T("customBrowserUrl")))
_browser_url = value.Trim();
else if (!key.CompareNoCase(_T("customBrowserMD5")))
_browser_md5 = value.Trim();
else if (!key.CompareNoCase(_T("Basic Auth")))
_basic_auth = value.Trim();
else if (!key.CompareNoCase(_T("imageQuality")))
_image_quality = (BYTE)max(_image_quality,
min(100, _ttoi(value.Trim())));
else if (!key.CompareNoCase(_T("pngScreenShot")) &&_ttoi(value.Trim()))
_png_screen_shot = true;
else if (!key.CompareNoCase(_T("time")))
_minimum_duration = MS_IN_SEC * max(_minimum_duration,
min(DEFAULT_TEST_TIMEOUT, _ttoi(value.Trim())));
else if (!key.CompareNoCase(_T("bodies")) && _ttoi(value.Trim()))
_save_response_bodies = true;
else if (!key.CompareNoCase(_T("htmlbody")) && _ttoi(value.Trim()))
_save_html_body = true;
else if (!key.CompareNoCase(_T("keepua")) && _ttoi(value.Trim()))
_preserve_user_agent = true;
else if (!key.CompareNoCase(_T("client")))
_client = value.Trim();
else if (!key.CompareNoCase(_T("customRule"))) {
int separator = value.Find(_T('='));
if (separator > 0) {
CString name = value.Left(separator).Trim();
CString rule = value.Mid(separator + 1).Trim();
separator = rule.Find(_T('\t'));
if (separator > 0) {
CString mime = rule.Left(separator).Trim();
rule = rule.Mid(separator + 1).Trim();
if (name.GetLength() && mime.GetLength() && rule.GetLength()) {
CustomRule new_rule;
new_rule._name = name;
new_rule._mime = mime;
new_rule._regex = rule;
_custom_rules.AddTail(new_rule);
}
}
}
} else if (!key.CompareNoCase(_T("cmdLine")))
_browser_command_line = value;
else if (!key.CompareNoCase(_T("addCmdLine")))
_browser_additional_command_line = value;
else if (!key.CompareNoCase(_T("continuousVideo")) &&
_ttoi(value.Trim()))
_continuous_video = true;
}
} else if (!line.Trim().CompareNoCase(_T("[Script]"))) {
// grab the rest of the response as the script
_script = test.Mid(linePos).Trim();
done = true;
}
line = test.Tokenize(_T("\r\n"), linePos);
}
if (_specific_run) {
_discard = 0;
}
if (_script.GetLength())
_test_timeout *= SCRIPT_TIMEOUT_MULTIPLIER;
WptTrace(loglevel::kFunction, _T("WptTest::Load() - Loaded test %s\n"),
(LPCTSTR)_id);
if( _id.GetLength() )
ret = true;
return ret;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool WptTest::GetNextTask(CStringA& task, bool& record) {
bool ret = false;
EnterCriticalSection(&cs_);
WptTrace(loglevel::kFunction, _T("[wpthook] - WptTest::GetNextTask\n"));
if (!_active && !IsLocked()){
Lock();
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
if( !_sleep_end.QuadPart || now.QuadPart >= _sleep_end.QuadPart) {
bool keep_processing = true;
while (keep_processing && !_script_commands.IsEmpty()) {
ScriptCommand command = _script_commands.RemoveHead();
bool consumed = false;
keep_processing = ProcessCommand(command, consumed);
if (!consumed) {
FixURL(command);
task = EncodeTask(command);
record = command.record;
if (record) {
_active = true;
if (_combine_steps > 0)
_combine_steps--;
}
ret = true;
}
}
}
Unlock();
}
LeaveCriticalSection(&cs_);
return ret;
}
/*-----------------------------------------------------------------------------
Create a JSON-encoded version of the task
-----------------------------------------------------------------------------*/
CStringA WptTest::EncodeTask(ScriptCommand& command) {
CStringA json = "{";
CStringA buff;
if (command.command.GetLength()) {
CString cmd(command.command);
cmd.MakeLower();
buff.Format("\"action\":\"%s\"", (LPCSTR)JSONEscape(cmd));
json += buff;
}
if (command.target.GetLength()) {
buff.Format(",\"target\":\"%s\"", (LPCSTR)JSONEscape(command.target));
json += buff;
}
if (command.value.GetLength()) {
buff.Format(",\"value\":\"%s\"", (LPCSTR)JSONEscape(command.value));
json += buff;
}
if (command.record)
json += ",\"record\":true";
else
json += ",\"record\":false";
json += _T("}");
return json;
}
/*-----------------------------------------------------------------------------
The last measurement completed, is it time to exit?
-----------------------------------------------------------------------------*/
bool WptTest::Done() {
WptTrace(loglevel::kFunction, _T("[wpthook] - WptTest::Done()\n"));
bool ret = false;
_active = false;
if (_script_commands.IsEmpty())
ret = true;
return ret;
}
/*-----------------------------------------------------------------------------
Parse the loaded script for commands (or create a default script if we
are just loading an url)
-----------------------------------------------------------------------------*/
void WptTest::BuildScript() {
_script_commands.RemoveAll();
if (_script.GetLength()) {
bool has_measurement = false;
bool in_comment = false;
int pos = 0;
CString line = _script.Tokenize(_T("\r\n"), pos).Trim();
while (pos >= 0) {
if (in_comment) {
if (line.Left(2) == _T("*/"))
in_comment = false;
} else {
if (line.Left(2) == _T("/*"))
in_comment = true;
else if(line.GetAt(0) != _T('/')) {
// break the command into it's component parts
int command_pos = 0;
CString command = line.Tokenize(_T("\t"), command_pos).Trim();
if (command.GetLength()) {
ScriptCommand script_command;
script_command.record = NavigationCommand(command);
script_command.command = command;
script_command.target = line.Tokenize(_T("\t"),command_pos).Trim();
if (!_no_run && command_pos > 0 &&
script_command.target.GetLength()) {
if (script_command.command == _T("block")) {
ParseBlockCommand(script_command.target, false);
}
else {
script_command.value =
line.Tokenize(_T("\t"),command_pos).Trim();
}
}
// Don't process the block commands again
if (script_command.command != _T("block")) {
if (script_command.record)
has_measurement = true;
if (!PreProcessScriptCommand(script_command))
_script_commands.AddTail(script_command);
}
}
}
}
line = _script.Tokenize(_T("\r\n"), pos).Trim();
}
if (!has_measurement)
_script_commands.RemoveAll();
}
if (_script_commands.IsEmpty() && _url.GetLength()) {
ScriptCommand command;
command.command = _T("navigate");
command.target = _url;
command.record = true;
_script_commands.AddTail(command);
}
if (_block.GetLength() ) {
ParseBlockCommand(_block, true);
}
if (_timeline) {
ScriptCommand command;
command.command = _T("captureTimeline");
command.record = false;
_script_commands.AddHead(command);
}
if (_trace) {
ScriptCommand command;
command.command = _T("captureTrace");
command.record = false;
_script_commands.AddHead(command);
}
if (_noscript) {
ScriptCommand command;
command.command = _T("noscript");
command.record = false;
_script_commands.AddHead(command);
}
if (_emulate_mobile) {
if (_device_scale_factor.IsEmpty())
_device_scale_factor = DEFAULT_MOBILE_SCALE_FACTOR;
if (!_viewport_width && !_viewport_height) {
DWORD padding_width = CHROME_PADDING_WIDTH;
DWORD padding_height = CHROME_PADDING_HEIGHT;
double scale = _ttof(_device_scale_factor);
if (scale >= 0.5 && scale <= 10.0) {
padding_width = (int)((double)padding_width * scale);
padding_height = (int)((double)padding_height * scale);
}
_browser_width = DEFAULT_MOBILE_WIDTH + padding_width;
_browser_height = DEFAULT_MOBILE_HEIGHT + padding_height;
}
if (_user_agent.IsEmpty())
_user_agent = DEFAULT_MOBILE_USER_AGENT;
}
// Scale the viewport or browser size by the scale factor.
// Once the viewport scaling is ACTUALLY working in Chrome then we can ues it
// but as of right now it isn't.
if (!has_gpu_ && _device_scale_factor.GetLength()) {
double scale = _ttof(_device_scale_factor);
_device_scale_factor.Empty();
if (scale >= 0.5 && scale <= 10.0) {
_browser_width = (int)((double)_browser_width / scale);
_browser_height = (int)((double)_browser_height / scale);
if (_viewport_width)
_viewport_width = (int)((double)_viewport_width / scale);
if (_viewport_height)
_viewport_height = (int)((double)_viewport_height / scale);
}
}
}
/*-----------------------------------------------------------------------------
See if the supplied command is one that initiates a measurement
(even if that measurement needs to be ignored)
-----------------------------------------------------------------------------*/
bool WptTest::NavigationCommand(CString& command) {
bool ret = false;
command.MakeLower();
if (command == _T("navigate") ||
command == _T("startmeasurement") ||
command == _T("waitforcomplete") ||
command == _T("submitform")) {
ret = true;
} else {
int index = command.Find(_T("andwait"));
if (index > 0) {
command = command.Left(index);
ret = true;
}
}
return ret;
}
/*-----------------------------------------------------------------------------
Make sure the URL has a protocol for navigation commands
-----------------------------------------------------------------------------*/
void WptTest::FixURL(ScriptCommand& command) {
if (!command.command.CompareNoCase(_T("navigate")) &&
command.target.GetLength()) {
if (!command.target.CompareNoCase(_T("about:blank"))) {
command.target = _T("http://127.0.0.1:8888/blank.html");
} else if (command.target.Left(4) != _T("http")) {
command.target = CString(_T("http://")) + command.target;
}
}
}
/*-----------------------------------------------------------------------------
Process the commands that we know about and that can be processed outside of
the browser (setting state, etc)
-----------------------------------------------------------------------------*/
bool WptTest::ProcessCommand(ScriptCommand& command, bool &consumed) {
bool continue_processing = true;
consumed = true;
WptTrace(loglevel::kFunction, _T("[wpthook] Processing Command '%s'\n"),
command.command);
CString cmd = command.command;
cmd.MakeLower();
if (cmd == _T("combinesteps")) {
_combine_steps = -1;
int count = _ttoi(command.target);
if (count > 0)
_combine_steps = count;
} else if (cmd == _T("logdata")) {
if (_ttoi(command.target))
_log_data = true;
else
_log_data = false;
} else if (cmd == _T("navigate")) {
_navigated_url = command.target;
continue_processing = false;
consumed = false;
} else if (cmd == _T("sleep")) {
int seconds = _ttoi(command.target);
if (seconds > 0) {
QueryPerformanceCounter(&_sleep_end);
_sleep_end.QuadPart += seconds * _perf_frequency.QuadPart;
continue_processing = false;
}
} else if (cmd == _T("settimeout")) {
int seconds = _ttoi(command.target);
if (seconds > 0 && seconds < 600)
_measurement_timeout = seconds * 1000;
} else if (cmd == _T("setactivitytimeout")) {
_activity_timeout = __min(__max(_ttoi(command.target), 0), 30000);
} else if (cmd == _T("setuseragent")) {
_user_agent = CT2A(command.target);
} else if (cmd == _T("addheader")) {
int pos = command.target.Find(_T(':'));
if (pos > 0) {
CStringA tag = CT2A(command.target.Left(pos).Trim());
CStringA value = CT2A(command.target.Mid(pos + 1).Trim());
HttpHeaderValue header(tag, value, (LPCSTR)CT2A(command.value.Trim()));
_add_headers.AddTail(header);
}
continue_processing = false;
consumed = false;
} else if (cmd == _T("setheader")) {
int pos = command.target.Find(_T(':'));
if (pos > 0) {
CStringA tag = CT2A(command.target.Left(pos).Trim());
CStringA value = CT2A(command.target.Mid(pos + 1).Trim());
CStringA filter = CT2A(command.value.Trim());
bool repeat = false;
if (!_set_headers.IsEmpty()) {
POSITION pos = _set_headers.GetHeadPosition();
while (pos && !repeat) {
HttpHeaderValue &header = _set_headers.GetNext(pos);
if (!header._tag.CompareNoCase(tag) &&
header._filter == filter) {
repeat = true;
header._value = value;
}
}
}
if (!repeat) {
HttpHeaderValue header(tag, value, filter);
_set_headers.AddTail(header);
}
}
continue_processing = false;
consumed = false;
} else if (cmd == _T("resetheaders")) {
_add_headers.RemoveAll();
_set_headers.RemoveAll();
continue_processing = false;
consumed = false;
} else if (cmd == _T("overridehost")) {
CStringA host = CT2A(command.target.Trim());
CStringA new_host = CT2A(command.value.Trim());
if (host.GetLength() && new_host.GetLength()) {
POSITION pos = _override_hosts.GetHeadPosition();
bool duplicate = false;
while (pos && !duplicate) {
HttpHeaderValue &existing = _override_hosts.GetNext(pos);
if (!existing._tag.CompareNoCase(host)) {
duplicate = true;
}
}
if (!duplicate) {
HttpHeaderValue host_override(host, new_host, "");
_override_hosts.AddTail(host_override);
}
}
// pass the host override command on to the browser extension as well
// (needed for SSL override on Chrome)
// include a bail-out if we have more than 3 hosts in the list
// because we were causing aborts to Chrome's navigations with long lists
if (_override_hosts.GetCount() <= 3) {
continue_processing = false;
consumed = false;
}
} else if (cmd == _T("block")) {
_block_requests.AddTail(command.target);
continue_processing = false;
consumed = false;
} else if (cmd == _T("setdomelement")) {
if (command.target.Trim().GetLength()) {
_dom_element_check = true;
WptTrace(loglevel::kFrequentEvent,
_T("[wpthook] - WptTest::BuildScript() Setting dom element check."));
}
continue_processing = false;
consumed = false;
} else if(cmd == _T("addcustomrule")) {
int separator = command.target.Find(_T('='));
if (separator > 0) {
CustomRule new_rule;
new_rule._name = command.target.Left(separator).Trim();
new_rule._mime = command.target.Mid(separator + 1).Trim();
new_rule._regex = command.value.Trim();
_custom_rules.AddTail(new_rule);
}
} else if(cmd == _T("reportdata")) {
ReportData();
continue_processing = false;
consumed = false;
} else {
continue_processing = false;
consumed = false;
}
return continue_processing;
}
/*-----------------------------------------------------------------------------
Process any commands that we need to handle right at startup
This is primarily for DNS overrides because of Chrome's pre-fetching
-----------------------------------------------------------------------------*/
bool WptTest::PreProcessScriptCommand(ScriptCommand& command) {
bool processed = true;
CString cmd = command.command;
cmd.MakeLower();
if (_no_run > 0) {
if (cmd == _T("if")) {
_no_run++;
} else if (cmd == _T("else")) {
if (_no_run == 1) {
_no_run = 0;
}
} else if (cmd == _T("endif")) {
_no_run = max(0, _no_run - 1);
}
} else {
if (cmd == _T("if")) {
if (!ConditionMatches(command)) {
_no_run = 1;
}
} else if (cmd == _T("else")) {
_no_run = 1;
} else if (cmd == _T("endif")) {
} else if (cmd == _T("setdns")) {
CDNSEntry entry(command.target, command.value);
_dns_override.AddTail(entry);
} else if (cmd == _T("setport")) {
USHORT original = (USHORT)_ttoi(command.target);
USHORT replacement = (USHORT)_ttoi(command.value);
if (original && replacement)
_tcp_port_override.SetAt(original, replacement);
} else if (cmd == _T("setdnsname")) {
CDNSName entry(command.target, command.value);
if (entry.name.GetLength() && entry.realName.GetLength())
_dns_name_override.AddTail(entry);
} else if (cmd == _T("setbrowsersize")) {
int width = _ttoi(command.target);
int height = _ttoi(command.value);
if (width > 0 && height > 0) {
_browser_width = (DWORD)width;
_browser_height = (DWORD)height;
}
} else if (cmd == _T("setviewportsize")) {
int width = _ttoi(command.target);
int height = _ttoi(command.value);
if (width > 0 && height > 0) {
_viewport_width = (DWORD)width;
_viewport_height = (DWORD)height;
}
} else if (cmd == _T("setdevicescalefactor")) {
_device_scale_factor = _T("");
for (int i = 0; i < command.target.GetLength(); i++) {
TCHAR ch = command.target.GetAt(i);
if (ch == _T('0') || ch == _T('1') || ch == _T('2') || ch == _T('3') ||
ch == _T('4') || ch == _T('5') || ch == _T('6') || ch == _T('7') ||
ch == _T('8') || ch == _T('9') || ch == _T('.'))
_device_scale_factor += ch;
else
break;
}
if (!_device_scale_factor.GetLength())
_device_scale_factor.Empty();
} else {
processed = false;
}
}
return processed;
}
/*-----------------------------------------------------------------------------
See if we need to override the DNS name
-----------------------------------------------------------------------------*/
void WptTest::OverrideDNSName(CString& name) {
POSITION pos = _dns_name_override.GetHeadPosition();
while (pos) {
CDNSName entry = _dns_name_override.GetNext(pos);
if (!name.CompareNoCase(entry.name))
name = entry.realName;
else if (entry.name.Left(1) == _T('*')) {
CString sub_string = entry.name.Mid(1).Trim();
if (!sub_string.GetLength() ||
!name.Right(sub_string.GetLength()).CompareNoCase(sub_string))
name = entry.realName;
}
}
}
/*-----------------------------------------------------------------------------
See if we need to override the DNS address
-----------------------------------------------------------------------------*/
ULONG WptTest::OverrideDNSAddress(CString& name) {
ULONG addr = 0;
POSITION pos = _dns_override.GetHeadPosition();
while (pos) {
CDNSEntry entry = _dns_override.GetNext(pos);
if (!name.CompareNoCase(entry.name))
addr = entry.addr;
else if (entry.name.Left(1) == _T('*')) {
CString sub_string = entry.name.Mid(1).Trim();
if (!sub_string.GetLength() ||
!name.Right(sub_string.GetLength()).CompareNoCase(sub_string))
addr = entry.addr;
}
}
return addr;
}
/*-----------------------------------------------------------------------------
See if we need to override the Port
-----------------------------------------------------------------------------*/
void WptTest::OverridePort(const struct sockaddr FAR * name, int namelen) {
if (!_tcp_port_override.IsEmpty() &&
name &&
namelen >= sizeof(struct sockaddr_in) &&
name->sa_family == AF_INET) {
struct sockaddr_in* ip_name = (struct sockaddr_in *)name;
USHORT current_port = htons(ip_name->sin_port);
USHORT new_port = 0;
if (_tcp_port_override.Lookup(current_port, new_port) && new_port) {
new_port = htons(new_port);
ip_name->sin_port = new_port;
}
}
}
/*-----------------------------------------------------------------------------
Modify an outbound request header. The modifications can include:
- Including PTST in the user agent string
- Adding new headers
- Overriding existing headers
- Overriding the host header for a specific host
-----------------------------------------------------------------------------*/
bool WptTest::ModifyRequestHeader(CStringA& header) const {
bool modified = true;
int pos = header.Find(':');
CStringA tag = header.Left(pos);
CStringA value = header.Mid(pos + 1).Trim();
if( !tag.CompareNoCase("User-Agent") ) {
if (_user_agent.GetLength()) {
header = CStringA("User-Agent: ") + _user_agent;
} else if(!_preserve_user_agent) {
CStringA user_agent;
user_agent.Format(" PTST/%d", _version);
header += user_agent;
}
} else if (!tag.CompareNoCase("Host")) {
CStringA new_headers;
// Add new headers after the host header.
POSITION pos = _add_headers.GetHeadPosition();
while (pos) {
HttpHeaderValue new_header = _add_headers.GetNext(pos);
if (RegexMatch(value, new_header._filter)) {
new_headers += CStringA("\r\n") + new_header._tag + CStringA(": ") +
new_header._value;
}
}
// Override existing headers (they are added here and the original
// version is removed below when it is processed)
pos = _set_headers.GetHeadPosition();
while (pos) {
HttpHeaderValue new_header = _set_headers.GetNext(pos);
if (RegexMatch(value, new_header._filter)) {
new_headers += CStringA("\r\n") + new_header._tag + CStringA(": ") +
new_header._value;
if (!new_header._tag.CompareNoCase("Host")) {
header.Empty();
new_headers.TrimLeft();
}
}
}
// Override the Host header for specified hosts
// The original value is added in a x-Host header.
pos = _override_hosts.GetHeadPosition();
while (pos) {
HttpHeaderValue host_override = _override_hosts.GetNext(pos);
if (!host_override._tag.CompareNoCase(value) ||
!host_override._tag.Compare("*")) {
header = CStringA("Host: ") + host_override._value;
new_headers += CStringA("\r\nx-Host: ") + value;
break;
}
}
if (new_headers.GetLength()) {
header += new_headers;
} else {
modified = false;
}
} else {
modified = false;
// Delete headers that were being overriden
POSITION pos = _set_headers.GetHeadPosition();
while (pos && !modified) {
HttpHeaderValue new_header = _set_headers.GetNext(pos);
if (!new_header._tag.CompareNoCase(tag)) {
header.Empty();
modified = true;
}
}
}
return modified;
}
/*-----------------------------------------------------------------------------
See if the outbound request needs to be blocked
-----------------------------------------------------------------------------*/
bool WptTest::BlockRequest(CString host, CString object) {
bool block = false;
CString request = host + object;
POSITION pos = _block_requests.GetHeadPosition();
while (!block && pos) {
CString block_pattern = _block_requests.GetNext(pos);
if (request.Find(block_pattern) >= 0)
block = true;
}
return block;
}
/*-----------------------------------------------------------------------------
See if the specified condition is a match
-----------------------------------------------------------------------------*/
bool WptTest::ConditionMatches(ScriptCommand& command) {
bool match = false;
int cached = 1;
if (_clear_cache)
cached = 0;
if (!command.target.CompareNoCase(_T("run"))) {
if (_run == _ttoi(command.value)) {
match = true;
}
} else if (!command.target.CompareNoCase(_T("cached"))) {
if (cached == _ttoi(command.value)) {
match = true;
}
}
return match;
}
/*-----------------------------------------------------------------------------
Parse the list of block strings into individual commands
-----------------------------------------------------------------------------*/
void WptTest::ParseBlockCommand(CString block_list, bool add_head) {
int pattern_pos = 0;
while (pattern_pos < block_list.GetLength()) {
CString pattern = block_list.Tokenize(_T(" "), pattern_pos).Trim();
if (pattern.GetLength()) {
// For each pattern, add a new script command.
ScriptCommand block_script_command;
block_script_command.command = _T("block");
block_script_command.target = pattern;
if (add_head) {
_script_commands.AddHead(block_script_command);
} else {
_script_commands.AddTail(block_script_command);
}
}
}
}
/*-----------------------------------------------------------------------------
The test is finished, insert the 2 dummy commands into the top of the
script to collect data
-----------------------------------------------------------------------------*/
void WptTest::CollectData() {
ScriptCommand cmd;
cmd.command = _T("reportdata");
_script_commands.AddHead(cmd);
cmd.command = _T("collectstats");
_script_commands.AddHead(cmd);
}
/*-----------------------------------------------------------------------------
Overridden in the hook-version to actually report the test data
-----------------------------------------------------------------------------*/
void WptTest::ReportData() {
}
/*-----------------------------------------------------------------------------
Remove any of our fake data collection commands if they are at the head of
the script command queue;
-----------------------------------------------------------------------------*/
void WptTest::CollectDataDone() {
bool removed = false;
do {
removed = false;
if (!_script_commands.IsEmpty()) {
ScriptCommand &cmd = _script_commands.GetHead();
if (cmd.command == _T("reportdata") ||
cmd.command == _T("collectstats")) {
_script_commands.RemoveHead();
removed = true;
}
}
} while(removed);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void WptTest::Lock() {
lock_count_++;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void WptTest::Unlock() {
lock_count_--;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool WptTest::IsLocked() {
return lock_count_ != 0;
}
| 36.696165 | 80 | 0.537031 | [
"object"
] |
04bfc9ee94036e6feef47b51d277802f1a94148b | 1,172 | cpp | C++ | android-28/android/graphics/drawable/shapes/OvalShape.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/graphics/drawable/shapes/OvalShape.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/graphics/drawable/shapes/OvalShape.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../Canvas.hpp"
#include "../../Outline.hpp"
#include "../../Paint.hpp"
#include "./RectShape.hpp"
#include "./Shape.hpp"
#include "../../../../JObject.hpp"
#include "./OvalShape.hpp"
namespace android::graphics::drawable::shapes
{
// Fields
// QJniObject forward
OvalShape::OvalShape(QJniObject obj) : android::graphics::drawable::shapes::RectShape(obj) {}
// Constructors
OvalShape::OvalShape()
: android::graphics::drawable::shapes::RectShape(
"android.graphics.drawable.shapes.OvalShape",
"()V"
) {}
// Methods
android::graphics::drawable::shapes::OvalShape OvalShape::clone() const
{
return callObjectMethod(
"clone",
"()Landroid/graphics/drawable/shapes/OvalShape;"
);
}
void OvalShape::draw(android::graphics::Canvas arg0, android::graphics::Paint arg1) const
{
callMethod<void>(
"draw",
"(Landroid/graphics/Canvas;Landroid/graphics/Paint;)V",
arg0.object(),
arg1.object()
);
}
void OvalShape::getOutline(android::graphics::Outline arg0) const
{
callMethod<void>(
"getOutline",
"(Landroid/graphics/Outline;)V",
arg0.object()
);
}
} // namespace android::graphics::drawable::shapes
| 23.44 | 94 | 0.674915 | [
"object",
"shape"
] |
04c123881f4bcbf5d4016e0bd3b63237387ec592 | 6,468 | cxx | C++ | Modules/IO/TransformBase/src/itkCompositeTransformIOHelper.cxx | ltmakela/ITK | 21f48c6d98e21ecece09be16a747221d7094d8a9 | [
"Apache-2.0"
] | 4 | 2015-05-22T03:47:43.000Z | 2016-06-16T20:57:21.000Z | Modules/IO/TransformBase/src/itkCompositeTransformIOHelper.cxx | ltmakela/ITK | 21f48c6d98e21ecece09be16a747221d7094d8a9 | [
"Apache-2.0"
] | null | null | null | Modules/IO/TransformBase/src/itkCompositeTransformIOHelper.cxx | ltmakela/ITK | 21f48c6d98e21ecece09be16a747221d7094d8a9 | [
"Apache-2.0"
] | 9 | 2016-06-23T16:03:12.000Z | 2022-03-31T09:25:08.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkCompositeTransformIOHelper.h"
#include "itkCompositeTransform.h"
namespace itk
{
/** build transform list from CompositeTransform */
template <typename TScalar,unsigned TDim>
int
CompositeTransformIOHelper
::BuildTransformList(const TransformType *transform)
{
//
// see if we've found the right type
typedef CompositeTransform<TScalar,TDim> CompositeType;
const CompositeType *composite = dynamic_cast<const CompositeType *>(transform);
if(composite == 0)
{
//
// if not, return zero
return 0;
}
//
// push the composite on the list first, as per the convention for
// the TransformFileReader
this->m_TransformList.push_back(const_cast<TransformType *>(transform));
const typename CompositeType::TransformQueueType &transforms =
composite->GetTransformQueue();
for(typename CompositeType::TransformQueueType::const_iterator it =
transforms.begin(); it != transforms.end(); ++it)
{
const TransformType *curTransform = dynamic_cast<const TransformType *>((*it).GetPointer());
if(curTransform == 0)
{
itkGenericExceptionMacro(<< "Failure to convert transform of type "
<< (*it)->GetTransformTypeAsString()
<< " to itk::TransformBase");
}
ConstTransformPointer curPtr = curTransform;
this->m_TransformList.push_back(curPtr);
}
return 1;
}
/** fill transform queue for a CompositeTransform */
template <typename TScalar,unsigned TDim>
int
CompositeTransformIOHelper
::InternalSetTransformList(TransformType *transform,TransformListType &transformList)
{
//
// local composite transform type
typedef CompositeTransform<TScalar,TDim> CompositeType;
typedef typename CompositeType::TransformType ComponentTransformType;
//
// see if we've found the right type
CompositeType *composite = dynamic_cast<CompositeType *>(transform);
if(composite == 0)
{
//
// if not, we'll try then next dim down
return 0;
}
//
// iterate thru transform list and assign into Composite
TransformListType::iterator it = transformList.begin();
++it; // skip the composite transform
for(; it != transformList.end(); ++it)
{
ComponentTransformType *component =
dynamic_cast<ComponentTransformType *>((*it).GetPointer());
if(component == 0)
{
itkGenericExceptionMacro(<< "Can't assign transform of type "
<< (*it)->GetTransformTypeAsString()
<< " to a Composite Transform of type "
<< composite->GetTransformTypeAsString());
}
composite->AddTransform(component);
}
return 1;
}
CompositeTransformIOHelper::ConstTransformListType &
CompositeTransformIOHelper
::GetTransformList(const TransformType *transform)
{
this->m_TransformList.clear();
// try each CompositeTransform Type, starting with
// most common
if(this->BuildTransformList<double,3>(transform) == 0 &&
this->BuildTransformList<float,3>(transform) == 0 &&
this->BuildTransformList<double,2>(transform) == 0 &&
this->BuildTransformList<float,2>(transform) == 0 &&
this->BuildTransformList<double,4>(transform) == 0 &&
this->BuildTransformList<double,5>(transform) == 0 &&
this->BuildTransformList<double,6>(transform) == 0 &&
this->BuildTransformList<double,7>(transform) == 0 &&
this->BuildTransformList<double,8>(transform) == 0 &&
this->BuildTransformList<double,9>(transform) == 0 &&
this->BuildTransformList<float,4>(transform) == 0 &&
this->BuildTransformList<float,5>(transform) == 0 &&
this->BuildTransformList<float,6>(transform) == 0 &&
this->BuildTransformList<float,7>(transform) == 0 &&
this->BuildTransformList<float,8>(transform) == 0 &&
this->BuildTransformList<float,9>(transform) == 0)
{
itkGenericExceptionMacro(<< "Unsupported Composite Transform Type "
<< transform->GetTransformTypeAsString());
}
return m_TransformList;
}
void
CompositeTransformIOHelper
::SetTransformList(TransformType *transform,TransformListType &transformList)
{
// try each CompositeTransform Type, starting with
// most common
if(this->InternalSetTransformList<double,3>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,3>(transform,transformList) == 0 &&
this->InternalSetTransformList<double,2>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,2>(transform,transformList) == 0 &&
this->InternalSetTransformList<double,4>(transform,transformList) == 0 &&
this->InternalSetTransformList<double,5>(transform,transformList) == 0 &&
this->InternalSetTransformList<double,6>(transform,transformList) == 0 &&
this->InternalSetTransformList<double,7>(transform,transformList) == 0 &&
this->InternalSetTransformList<double,8>(transform,transformList) == 0 &&
this->InternalSetTransformList<double,9>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,4>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,5>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,6>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,7>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,8>(transform,transformList) == 0 &&
this->InternalSetTransformList<float,9>(transform,transformList) == 0)
{
itkGenericExceptionMacro(<< "Unsupported Composite Transform Type "
<< transform->GetTransformTypeAsString());
}
}
}
| 39.2 | 96 | 0.673315 | [
"transform"
] |
04c45eee232793d1a1a0d646d49e1329249095a9 | 10,926 | cpp | C++ | activity_recognition_server/src/vector_encoding.cpp | kazuto1011/fps-activity-recognition | e937ec5722b16fea6bb704b455894c2f113384bb | [
"MIT"
] | null | null | null | activity_recognition_server/src/vector_encoding.cpp | kazuto1011/fps-activity-recognition | e937ec5722b16fea6bb704b455894c2f113384bb | [
"MIT"
] | null | null | null | activity_recognition_server/src/vector_encoding.cpp | kazuto1011/fps-activity-recognition | e937ec5722b16fea6bb704b455894c2f113384bb | [
"MIT"
] | null | null | null | /*
* vector_encoding.cpp
*
* Created on: Dec 8, 2014
* Author: kazuto
*/
#include "common.h"
#include "vector_encoding.h"
//----------------------------------------------------------------------------------
// Fisher Vector encoding
//----------------------------------------------------------------------------------
// create a new FisherVector instance
// with a gmm that clustering given data
//----------------------------------------------------------------------------------
FisherVector::FisherVector()
{
data_type = VL_TYPE_FLOAT;
}
void FisherVector::GmmCluster(cv::Mat &data, int num_visualwords)
{
this->num_clusters = num_visualwords;
this->dimension = data.cols;
this->fv_dimension = 2 * dimension * num_clusters;
this->gmm = vl_gmm_new(data_type, dimension, num_clusters);
// to get means, covariances and priors of the estimated mixture
vl_gmm_cluster(gmm, data.data, data.rows);
this->means = (float*)vl_gmm_get_means(gmm);
this->covariances = (float*)vl_gmm_get_covariances(gmm);
this->priors = (float*)vl_gmm_get_priors(gmm);
}
// create a new FisherVector instance
// with a gmm loading external params
//----------------------------------------------------------------------------------
FisherVector::FisherVector(const char* file_dir)
{
std::ifstream ifs(file_dir, std::ios_base::binary);
if (!ifs)
{
ROS_ERROR("Failed to open the file");
abort();
}
ifs.read((char*)&data_type, sizeof(vl_type));
ifs.read((char*)&num_clusters, sizeof(vl_size));
ifs.read((char*)&dimension, sizeof(vl_size));
this->fv_dimension = 2 * dimension * num_clusters;
this->means = (float*)vl_malloc(sizeof(float) * num_clusters * dimension);
this->covariances = (float*)vl_malloc(sizeof(float) * num_clusters * dimension);
this->priors = (float*)vl_malloc(sizeof(float) * num_clusters);
for (unsigned int i = 0; i < num_clusters; i++)
{
for (unsigned int j = 0; j < dimension; j++)
{
ifs.read((char*)&means[i * dimension + j], sizeof(float));
ifs.read((char*)&covariances[i * dimension + j], sizeof(float));
}
ifs.read((char*)&priors[i], sizeof(float));
}
ifs.close();
// intialize the gmm object and set the params
this->gmm = vl_gmm_new(data_type, dimension, num_clusters);
vl_gmm_set_covariances(gmm, covariances);
vl_gmm_set_priors(gmm, priors);
vl_gmm_set_means(gmm, means);
}
// fisher vector encoding
//----------------------------------------------------------------------------------
cv::Mat FisherVector::FvEncode(cv::Mat &data)
{
cv::Mat encoded_vec = cv::Mat_<float>(1, (int)fv_dimension);
/**
* VL_FISHER_FLAG_IMPROVED
* - Square root
* - L2 normalization
*/
vl_fisher_encode(encoded_vec.data, data_type, means, dimension, num_clusters, covariances, priors, data.data,
data.rows,
VL_FISHER_FLAG_IMPROVED);
return encoded_vec;
}
// save the gmm parameters into external file
//----------------------------------------------------------------------------------
void FisherVector::SaveGMM(const char* file_dir)
{
std::ofstream ofs(file_dir, std::ios_base::out | std::ios_base::binary);
if (!ofs)
{
ROS_ERROR("Failed to open the file");
abort();
}
ofs.write((char*)&data_type, sizeof(vl_type));
ofs.write((char*)&num_clusters, sizeof(vl_size));
ofs.write((char*)&dimension, sizeof(vl_size));
for (unsigned int i = 0; i < num_clusters; i++)
{
for (unsigned int j = 0; j < dimension; j++)
{
ofs.write((char*)&means[i * dimension + j], sizeof(float));
ofs.write((char*)&covariances[i * dimension + j], sizeof(float));
}
ofs.write((char*)&priors[i], sizeof(float));
}
ofs.close();
}
// destructor
//----------------------------------------------------------------------------------
FisherVector::~FisherVector()
{
vl_gmm_delete(this->gmm);
}
//----------------------------------------------------------------------------------
// VLAD encoding
//----------------------------------------------------------------------------------
// create a new VLAD instance
// with a k-means that clustering given data
//----------------------------------------------------------------------------------
VLAD::VLAD()
{
this->data_type = VL_TYPE_FLOAT;
this->distance_type = VlDistanceL2;
}
void VLAD::KmeansCluster(cv::Mat& data, int num_visualwords)
{
this->kmeans = vl_kmeans_new(data_type, distance_type);
this->num_centers = num_visualwords;
this->dimension = data.cols;
this->vlad_dimension = dimension * num_centers;
vl_kmeans_cluster(kmeans, data.data, dimension, data.rows, num_centers);
this->means = (float*)vl_kmeans_get_centers(kmeans);
}
// create a new VLAD instance
// with a k-means loading external params
//----------------------------------------------------------------------------------
VLAD::VLAD(const char* file_dir)
{
std::ifstream ifs(file_dir, std::ios_base::binary);
if (!ifs)
{
ROS_ERROR("Failed to open the file");
abort();
}
ifs.read((char*)&data_type, sizeof(vl_type));
ifs.read((char*)&distance_type, sizeof(VlVectorComparisonType));
ifs.read((char*)&dimension, sizeof(vl_size));
ifs.read((char*)&num_centers, sizeof(vl_size));
this->vlad_dimension = dimension * num_centers;
this->means = (float*)vl_malloc(sizeof(float) * num_centers * dimension);
for (unsigned int i = 0; i < dimension * num_centers; i++)
{
ifs.read((char*)&means[i], sizeof(float));
}
ifs.close();
// intialize the kmeans object and set the params
this->kmeans = vl_kmeans_new(data_type, distance_type);
vl_kmeans_set_centers(kmeans, means, dimension, num_centers);
}
// vlad encoding
//----------------------------------------------------------------------------------
cv::Mat VLAD::VladEncode(cv::Mat& data)
{
// stores the indice of k-means center that given data is assigned
cv::Mat indexes = cv::Mat_<unsigned int>(1, data.rows);
vl_kmeans_quantize(kmeans, (vl_uint32*)indexes.data, NULL, data.data, data.rows);
// hard assignment
cv::Mat assignments = cv::Mat::zeros(cv::Size(data.rows * num_centers, 1), CV_32F);
for (int i = 0; i < data.rows; i++)
assignments.at<float>(0, i * num_centers + indexes.at<int>(0, i)) = 1.;
/**
* VL_VLAD_FLAG_SQUARE_ROOT
* VL_VLAD_FLAG_NORMALIZE_COMPONENTS
*/
cv::Mat encoded_vec = cv::Mat_<float>(1, (int)vlad_dimension);
vl_vlad_encode(encoded_vec.data, data_type, means, dimension, num_centers, data.data, data.rows, assignments.data,
VL_VLAD_FLAG_SQUARE_ROOT | VL_VLAD_FLAG_NORMALIZE_MASS);
return encoded_vec;
}
// save the kmeans parameters into external file
//----------------------------------------------------------------------------------
void VLAD::SaveKmeans(const char* file_dir)
{
std::ofstream ofs(file_dir, std::ios_base::out | std::ios_base::binary);
if (!ofs)
{
ROS_ERROR("Failed to open the file");
abort();
}
ofs.write((char*)&data_type, sizeof(vl_type));
ofs.write((char*)&distance_type, sizeof(VlVectorComparisonType));
ofs.write((char*)&dimension, sizeof(vl_size));
ofs.write((char*)&num_centers, sizeof(vl_size));
for (unsigned int i = 0; i < dimension * num_centers; i++)
{
ofs.write((char*)&means[i], sizeof(float));
}
ofs.close();
}
// destructor
//----------------------------------------------------------------------------------
VLAD::~VLAD()
{
vl_kmeans_delete(this->kmeans);
}
//----------------------------------------------------------------------------------
// Bag of Visual Words
//----------------------------------------------------------------------------------
// create a new BoVW instance
// with a k-means that clustering given data
//----------------------------------------------------------------------------------
BoVW::BoVW()
{
this->data_type = VL_TYPE_FLOAT;
this->distance_type = VlDistanceL2;
}
void BoVW::KmeansCluster(cv::Mat& data, int num_visualwords)
{
this->kmeans = vl_kmeans_new(data_type, distance_type);
this->num_centers = num_visualwords;
this->dimension = data.cols;
this->bovw_dimension = num_centers;
// k-means
vl_kmeans_cluster(kmeans, data.data, dimension, data.rows, num_centers);
this->means = (float*)vl_kmeans_get_centers(kmeans);
}
// create a new BoVW instance
// with a k-means loading external params
//----------------------------------------------------------------------------------
BoVW::BoVW(const char* file_dir)
{
std::ifstream ifs(file_dir, std::ios_base::binary);
if (!ifs)
std::cout << "Failed to open the file" << std::endl;
ifs.read((char*)&data_type, sizeof(vl_type));
ifs.read((char*)&distance_type, sizeof(VlVectorComparisonType));
ifs.read((char*)&dimension, sizeof(vl_size));
ifs.read((char*)&num_centers, sizeof(vl_size));
this->bovw_dimension = num_centers;
this->means = (float*)vl_malloc(sizeof(float) * num_centers * dimension);
for (unsigned int i = 0; i < dimension * num_centers; i++)
{
ifs.read((char*)&means[i], sizeof(float));
}
ifs.close();
// intialize the kmeans object and set the params
kmeans = vl_kmeans_new(data_type, distance_type);
vl_kmeans_set_centers(kmeans, means, dimension, num_centers);
}
// build histogram
//----------------------------------------------------------------------------------
cv::Mat BoVW::BuidHistogram(cv::Mat& data)
{
cv::Mat indexes = cv::Mat_<int>(1, data.rows);
cv::Mat builtHist = cv::Mat::zeros(1, (int)bovw_dimension, CV_32F);
vl_kmeans_quantize(kmeans, (vl_uint32*)indexes.data, NULL, data.data, data.rows);
//L2 norm
float tmp, l2_sum = 0.;
float* builtHist_row = builtHist.ptr<float>(0);
const unsigned int* indexes_row = indexes.ptr<unsigned int>(0);
for (int i = 0; i < data.rows; i++)
builtHist_row[indexes_row[i]]++;
for (int i = 0; i < data.rows; i++)
{
tmp = builtHist_row[i];
l2_sum += tmp*tmp;
}
l2_sum = vl_sqrt_f(l2_sum);
l2_sum = VL_MAX(l2_sum, 1e-12);
for (unsigned int i = 0; i < bovw_dimension; i++)
{
builtHist.at<float>(0, i) /= l2_sum;
}
return builtHist;
}
// save the kmeans parameters into external file
//----------------------------------------------------------------------------------
void BoVW::SaveKmeans(const char* file_dir)
{
std::ofstream ofs(file_dir, std::ios_base::out | std::ios_base::binary);
if (!ofs)
{
ROS_ERROR("Failed to open the file");
abort();
}
ofs.write((char*)&data_type, sizeof(vl_type));
ofs.write((char*)&distance_type, sizeof(VlVectorComparisonType));
ofs.write((char*)&dimension, sizeof(vl_size));
ofs.write((char*)&num_centers, sizeof(vl_size));
for (unsigned int i = 0; i < dimension * num_centers; i++)
{
ofs.write((char*)&means[i], sizeof(float));
}
ofs.close();
}
// destructor
//----------------------------------------------------------------------------------
BoVW::~BoVW()
{
vl_kmeans_delete(this->kmeans);
}
| 30.18232 | 116 | 0.569376 | [
"object",
"vector"
] |
04c52a58b657f488021bf6c37c71b8bb05cb3b61 | 1,449 | cpp | C++ | src/modules/filter/benchmark/threshold_benchmark.cpp | mangosroom/mvk-nodes | 0ec3a7853e949d192ee54daeaf25875cd3cb6d18 | [
"Apache-2.0"
] | 5 | 2021-12-24T10:18:46.000Z | 2022-03-15T14:11:04.000Z | src/modules/filter/benchmark/threshold_benchmark.cpp | mangosroom/mvk-nodes | 0ec3a7853e949d192ee54daeaf25875cd3cb6d18 | [
"Apache-2.0"
] | null | null | null | src/modules/filter/benchmark/threshold_benchmark.cpp | mangosroom/mvk-nodes | 0ec3a7853e949d192ee54daeaf25875cd3cb6d18 | [
"Apache-2.0"
] | null | null | null | /**
* @file threshold_benchmark.cpp
* @author mango (2321544362@qq.com)
* @brief
* @version 0.1
* @date 2022-04-15
*
* @copyright Copyright (c) 2022
*
*/
#include "filter/threshold.hpp"
#include <chrono>
#include <iostream>
#include <vector>
#include <tuple>
#include <fstream>
using namespace mvk;
int main(int argc, char** argv)
{
std::vector<std::tuple<size_t, size_t>> img_sizes = {{640, 480}, {1280, 720}, {1280, 960}, {1920, 1080}, {1600, 1200}, {2048, 1536}, {2592, 1944}, {3264, 2448}, {3840, 2160}, {4224, 3168}, {5344, 4106}};
std::ofstream out_csv;
out_csv.open("mvk-threshold-benchmark.csv", std::ios::out);
std::cout << "-------------mvk-nodes filter threshold benchenmark------------------\n";
for(auto&& [len, wid]: img_sizes)
{
Image src(len, wid, 100);
Image dst;
auto t0 = std::chrono::system_clock::now();
for(int i = 0; i < 10; i++)
{
Threshold(src, dst, 128, THRESHOLD_TYPE::THRESH_BINARY);
}
auto t1 = std::chrono::system_clock::now();
std::cout <<std::to_string(len) + "x" + std::to_string(wid) + " cost "<< std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count() / 10000.0 << " ms." << std::endl;
out_csv <<std::to_string(len) + "x" + std::to_string(wid) + ","<< std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count() / 10000.0 << std::endl;
}
return 0;
}
| 32.2 | 207 | 0.5804 | [
"vector"
] |
04c81f482505249205b84d6f7c5b48bf1cf79303 | 1,105 | cpp | C++ | Closet/VisualWardrobe/CSceneNodeBoxyScalar.cpp | ducis/pile-of-cpp | af5a123ec67cff589f27bf20d435b2db29a0a7c8 | [
"MIT"
] | null | null | null | Closet/VisualWardrobe/CSceneNodeBoxyScalar.cpp | ducis/pile-of-cpp | af5a123ec67cff589f27bf20d435b2db29a0a7c8 | [
"MIT"
] | null | null | null | Closet/VisualWardrobe/CSceneNodeBoxyScalar.cpp | ducis/pile-of-cpp | af5a123ec67cff589f27bf20d435b2db29a0a7c8 | [
"MIT"
] | null | null | null | #include "CSceneNodeBoxyScalar.h"
namespace CSceneNodeBoxyScalar_impl{
const matrix44 GetTransform(const AABB &aabb){
return TranslateMatrix44( GetCenter(aabb) )*ScaleMatrix44( GetDim(aabb) );
}
}
using namespace CSceneNodeBoxyScalar_impl;
CSceneNodeBoxyScalar::CSceneNodeBoxyScalar( ISceneNode *pSN, const AABB &aabb ):m_pSN(pSN),m_aabb(aabb){
}
void CSceneNodeBoxyScalar::Render() const{
glPushMatrix();
const vector3 center(GetCenter(m_aabb)), dim(GetDim(m_aabb));
glTranslatef(center.x,center.y,center.z);
glScalef(dim.x,dim.y,dim.z);
m_pSN->Render();
//glutSolidCube(0.8f);
glPopMatrix();
}
void CSceneNodeBoxyScalar::OnInsertion(){
m_pSN->OnInsertion();
}
void CSceneNodeBoxyScalar::UpdateTransform(const matrix44 &parentTransform){
m_parentTransform = parentTransform;
m_pSN->UpdateTransform(m_parentTransform*GetTransform(m_aabb));
}
void CSceneNodeBoxyScalar::SetAABB(const AABB &aabb){
m_aabb = aabb;
UpdateTransform(m_parentTransform);
}
const AABB CSceneNodeBoxyScalar::GetAABB() const{
return m_aabb;
}
| 20.849057 | 105 | 0.734842 | [
"render"
] |
04d582dc4c036abfbbbf4b20c268178e833fc94a | 20,665 | cpp | C++ | solutions/predict_min.cpp | kborozdin/palindromic-length | 2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2 | [
"MIT"
] | null | null | null | solutions/predict_min.cpp | kborozdin/palindromic-length | 2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2 | [
"MIT"
] | null | null | null | solutions/predict_min.cpp | kborozdin/palindromic-length | 2fad58e82b5cc079bfceb9e782b7e2a8ee4306d2 | [
"MIT"
] | null | null | null | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <ctime>
using namespace std;
#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define eprintf(...) (void)0
#endif
#ifdef LOCAL
#define STRESS
#endif
typedef unsigned int uint;
const int INF = (int)1e9;
int PREDICT_STEP = 4;
const int S = 4;
const int MS = 2 * S;
#ifndef LOCAL
const int N = 1000500;
#else
const int N = 105;
#endif
const int DN = 2 * N;
bool get_bit(uint mask, int p)
{
return (mask & (1U << p)) != 0;
}
uint set_bit(uint mask, int p, bool x)
{
if (x)
return mask | (1U << p);
return mask & ~(1U << p);
}
int get_trit(uint mask, int p)
{
return 2 * get_bit(mask, 2 * p + 1) + get_bit(mask, 2 * p) - 1;
}
uint set_trit(uint mask, int p, int x)
{
return set_bit(set_bit(mask, 2 * p, (x + 1) % 2 != 0), 2 * p + 1, (x + 1) / 2 != 0);
}
uint bit_rev[1 << MS];
int bit_sum[S + 1][1 << MS];
uint bit_left_shift[S][1 << MS];
uint bit_right_shift[S][1 << MS];
uint bit_min[2 * S][1 << MS][1 << MS];
uint bit_iter[S + 1][S + 1][1 << MS];
void init_table()
{
for (uint mask = 0; mask < (1U << MS); mask++)
{
uint new_mask = set_trit(0, 0, 0);
int bal = 0;
for (int i = 0; i < S; i++)
{
int t = get_trit(mask, i);
bal += t;
bit_sum[i + 1][mask] = bal;
if (i > 0)
new_mask = set_trit(new_mask, S - i, -t);
}
bit_rev[mask] = new_mask;
}
for (uint mask = 0; mask < (1U << MS); mask++)
for (int i = 0; i < S; i++)
{
uint new_mask = mask >> (2 * i);
new_mask = set_trit(new_mask, 0, 0);
for (int j = S - i; j < S; j++)
new_mask = set_trit(new_mask, j, 1);
bit_left_shift[i][mask] = new_mask;
new_mask = (mask << (2 * i)) & ((1 << (2 * S)) - 1);
new_mask = set_trit(new_mask, 0, 0);
for (int j = 1; j <= i; j++)
new_mask = set_trit(new_mask, j, -1);
bit_right_shift[i][mask] = new_mask;
}
for (uint mask1 = 0; mask1 < (1U << MS); mask1++)
for (uint mask2 = 0; mask2 < (1U << MS); mask2++)
for (int bal = 0; bal < 2 * S; bal++)
{
uint new_mask = 0;
int sum1 = bal, sum2 = 0;
int prv = 0;
for (int i = 0; i < S; i++)
{
sum1 += get_trit(mask1, i);
sum2 += get_trit(mask2, i);
int nxt = min(sum1, sum2);
new_mask = set_trit(new_mask, i, nxt - prv);
prv = nxt;
}
bit_min[bal][mask1][mask2] = new_mask;
}
for (int len = 1; len <= S; len++)
for (int cnt = 1; len * cnt <= S; cnt++)
for (uint mask = 0; mask < (1U << MS); mask++)
{
int vals[S] = {};
for (int i = 1; i < len * cnt; i++)
vals[i] = vals[i - 1] + get_trit(mask, i % len);
for (int i = len * cnt; i < S; i++)
vals[i] = vals[i - 1] + 1;
for (int i = 1; i < S; i++)
vals[i] = min(vals[i], vals[i - 1] + 1);
for (int i = S - 2; i >= 0; i--)
vals[i] = min(vals[i], vals[i + 1] + 1);
uint new_mask = set_trit(0, 0, 0);
for (int i = 1; i < S; i++)
new_mask = set_trit(new_mask, i, vals[i] - vals[i - 1]);
bit_iter[len][cnt][mask] = new_mask;
}
}
struct BlockMin
{
int val;
uint mask;
BlockMin() : val(INF), mask()
{
for (int i = 0; i < S; i++)
mask = set_trit(mask, i, 0);
}
BlockMin(int _val, uint _mask) : val(_val), mask(_mask) {}
int get(int p)
{
return val + bit_sum[p + 1][mask];
}
BlockMin reverse()
{
return BlockMin(val + bit_sum[S][mask], bit_rev[mask]);
}
BlockMin left_shift(int len)
{
return BlockMin(val + bit_sum[len + 1][mask], bit_left_shift[len][mask]);
}
BlockMin right_shift(int len)
{
return BlockMin(val + len, bit_right_shift[len][mask]);
}
BlockMin apply(BlockMin o, int a, int b, int len, bool rev, bool inc)
{
if (rev)
{
o = o.reverse();
b = S - 1 - (b + len - 1);
}
o = o.right_shift(S - 1 - (b + len - 1)).left_shift(S - len).right_shift(a);
if (inc)
o.val++;
int bal = val - o.val;
if (bal <= -2 * S)
return *this;
if (bal >= 2 * S)
return o;
int new_val = min(val, o.val);
if (bal < 0)
return BlockMin(new_val, bit_min[-bal][o.mask][mask]);
return BlockMin(new_val, bit_min[bal][mask][o.mask]);
}
BlockMin reset_suf(int a)
{
return right_shift(S - a).left_shift(S - a);
}
BlockMin iterate_pref(int len, int cnt)
{
return BlockMin(val, bit_iter[len][cnt][mask]);
}
void eprint()
{
eprintf("val = %d; mask = { ", val);
for (int i = 0; i < S; i++)
eprintf("%d ", get_trit(mask, i));
eprintf("}\n");
}
};
struct GappedVector;
struct DPVector
{
int _size;
vector<BlockMin> v;
DPVector() : _size() {}
bool empty()
{
return _size == 0;
}
BlockMin &operator[](int p)
{
return v[p];
}
int get(int p)
{
return v[p / S].get(p % S);
}
void extend()
{
while ((int)v.size() * S < _size)
v.push_back(BlockMin());
}
int size()
{
return _size;
}
void swap(DPVector &other)
{
::swap(_size, other._size);
v.swap(other.v);
}
void resize(int new_len)
{
_size = new_len;
extend();
}
DPVector substr(int start, int len)
{
if (len <= 0)
return DPVector();
DPVector res;
res.resize(len);
res.apply_seg(0, len - 1, *this, start, start + len - 1, false, false, false);
return res;
}
DPVector iterate(int cnt)
{
DPVector res;
if (size() * cnt <= S)
{
res.resize(size() * cnt);
res[0] = v[0].iterate_pref(size(), cnt);
}
else
{
for (int i = 0; i < cnt; i++)
res = res.concat(*this);
}
return res;
}
DPVector concat(DPVector o)
{
if (o.empty())
return *this;
auto res = *this;
res.resize(res.size() + o.size());
res.reset_seg(size(), res.size() - 1, false);
res.apply_seg(size(), res.size() - 1, o, 0, o.size() - 1, false, false, false);
return res;
}
void apply_seg(int l, int r, DPVector &from, int c, int d, bool rev, bool inc, bool history);
void apply_seg(int l, int r, GappedVector &from, int c, int d, bool history);
void reset_seg(int l, int r, bool history);
};
enum HistoricEventType
{
HE_UNDEF, HE_SET, HE_SET_VEC, HE_SWAP_VEC, HE_RESIZE_VEC
};
struct HistoricEvent
{
HistoricEventType type;
void *ptr;
int arg1;
BlockMin arg2;
void *ptr1;
HistoricEvent(HistoricEventType _type, void *_ptr, int _arg1 = 0, BlockMin _arg2 = BlockMin(),
void *_ptr1 = nullptr) : type(_type), ptr(_ptr), arg1(_arg1), arg2(_arg2), ptr1(_ptr1) {}
};
struct HistoryManager
{
vector<HistoricEvent> events;
void set(int *ptr, int val)
{
events.push_back(HistoricEvent(HE_SET, ptr, *ptr));
*ptr = val;
}
void set_vec(DPVector *ptr, int id, BlockMin val)
{
events.push_back(HistoricEvent(HE_SET_VEC, ptr, id, (*ptr)[id]));
(*ptr)[id] = val;
}
void swap_vec(DPVector *ptr1, DPVector *ptr2)
{
events.push_back(HistoricEvent(HE_SWAP_VEC, ptr1, 0, BlockMin(), ptr2));
ptr1->swap(*ptr2);
}
void resize_vec(DPVector *ptr, int new_size)
{
events.push_back(HistoricEvent(HE_RESIZE_VEC, ptr, ptr->size()));
ptr->resize(new_size);
}
void undo()
{
while (!events.empty())
{
auto ev = events.back();
events.pop_back();
if (ev.type == HE_SET)
{
*(int*)ev.ptr = ev.arg1;
continue;
}
DPVector *ptr = (DPVector*)ev.ptr;
if (ev.type == HE_SET_VEC)
(*ptr)[ev.arg1] = ev.arg2;
else if (ev.type == HE_SWAP_VEC)
ptr->swap(*(DPVector*)ev.ptr1);
else if (ev.type == HE_RESIZE_VEC)
ptr->resize(ev.arg1);
else
throw;
}
}
void forget()
{
events.clear();
}
}
hist;
void DPVector::apply_seg(int l, int r, DPVector &from, int c, int d, bool rev, bool inc, bool history)
{
for (int i = c; i <= d; )
{
int j = rev ? r - (i - c) : l + (i - c);
int p1 = i / S;
int p2 = j / S;
int len1 = min(d - i + 1, S - i % S);
int len2 = rev ? min(j - l + 1, j % S + 1) : min(r - j + 1, S - j % S);
int len = min(len1, len2);
BlockMin res = v[p2].apply(from[p1], rev ? j % S - len + 1 : j % S, i % S, len, rev, inc);
if (history)
hist.set_vec(this, p2, res);
else
v[p2] = res;
i += len;
}
}
void DPVector::reset_seg(int l, int r, bool history)
{
int p1 = l / S;
int p2 = r / S;
if (l % S != 0)
{
BlockMin res = v[p1].reset_suf(l % S);
if (history)
hist.set_vec(this, p1, res);
else
v[p1] = res;
p1++;
}
for (int p = p1; p <= p2; p++)
{
if (history)
hist.set_vec(this, p, BlockMin());
else
v[p] = BlockMin();
}
}
struct GappedVector
{
DPVector a, b;
int apos, per;
GappedVector() : apos(), per() {}
GappedVector(int _per) : apos(), per(_per) {}
int suf()
{
return per - b.size();
}
void apply_seg(int l, int r, DPVector &from, int c, int d, bool history)
{
if (a.empty())
apos = l;
int old_size = a.size();
if (history)
hist.resize_vec(&a, old_size + (r - l + 1));
else
a.resize(old_size + (r - l + 1));
int al = old_size;
int ar = al + (r - l);
a.reset_seg(al, ar, history);
a.apply_seg(al, ar, from, c, d, true, true, history);
if (r >= suf())
a.apply_seg(al + max(0, suf() - l), ar, b, max(0, l - suf()), r - suf(), false, false, history);
if (r == per - 1)
{
if (history)
{
hist.swap_vec(&a, &b);
hist.resize_vec(&a, 0);
}
else
{
a.swap(b);
a.resize(0);
}
}
}
DPVector substr(int start, int len)
{
int end = start + len - 1;
DPVector res;
res.resize(len);
int left = max(start, apos);
int right = min(end, apos + a.size() - 1);
res.apply_seg(left - start, right - start, a, left - apos, right - apos, false, false, false);
int bstart = max(suf(), apos + a.size());
left = max(start, bstart);
right = min(end, per - 1);
res.apply_seg(left - start, right - start, b, left - suf(), right - suf(), false, false, false);
return res;
}
void clear()
{
a.resize(0);
b.resize(0);
apos = 0;
}
};
void DPVector::apply_seg(int l, int r, GappedVector &from, int c, int d, bool history)
{
int last = min(from.apos + from.a.size() - 1, d);
apply_seg(l, l + (last - c), from.a, c - from.apos, last - from.apos, false, false, history);
int suf = from.suf();
if (d >= suf)
{
int start = max(suf, c);
apply_seg(l + (start - c), r, from.b, start - suf, d - suf, false, false, history);
}
}
int n, dn;
char s[N];
char scan_s[N];
int l[DN], r[DN];
int rad[DN];
vector<int> starting[N];
int head, tail;
DPVector dp;
GappedVector per_dp[N];
int left_side[N];
bool dead_center[DN];
int lpos(int v)
{
return (v - 1) / 2;
}
int rpos(int v)
{
return v / 2;
}
int cent(int i)
{
return 2 * i + 1;
}
void init()
{
head = 0;
tail = dn;
r[head] = tail;
l[tail] = head;
}
int get_len(int v, int i)
{
if (v == tail)
return 0;
return 2 * (i + 1) - v;
}
int get_center(int len, int i)
{
if (len == 0)
return tail;
return 2 * (i + 1) - len;
}
int reflect(int v, int o)
{
return o + (o - v);
}
int get_period(int v, int i)
{
return get_len(v, i) - get_len(r[v], i);
}
void link(int a, int b)
{
r[a] = b;
l[b] = a;
}
int get_rad(int v, int i, bool prediction = false)
{
int c = r[head];
int can = i - rpos(v) + 1;
if (v == c && prediction)
return can;
if (v > c)
v = reflect(v, c);
return min((rad[v] + 1) / 2, can);
}
char imag_s(int i)
{
int c = r[head];
if (cent(i) > c)
i = rpos(reflect(cent(i), c));
return s[i];
}
int get_left_side(int v, int i)
{
int per = get_period(v, i);
int len = get_len(v, i);
int plen = len % per;
if (plen == 0)
plen = per;
int start = i - len + 1;
int center_v = cent(start) - 1 + plen;
int cur_rad = get_rad(center_v, i);
int left_side = lpos(center_v) - cur_rad + 1;
if (left_side > 0 && s[left_side - 1] == s[left_side - 1 + per])
throw;
return left_side;
}
void check_left_side(int v, int i)
{
int per = get_period(v, i);
int cur_left_side = get_left_side(v, i);
if (left_side[per] != cur_left_side)
{
per_dp[per].clear();
left_side[per] = cur_left_side;
}
}
void append_len(int len, int i, vector<pair<int, int>> &to_check)
{
int v = get_center(len, i);
rad[v] = len;
link(l[tail], v);
link(v, tail);
to_check.push_back(make_pair(v, i));
if (l[v] != head)
to_check.push_back(make_pair(l[v], i));
}
void remove(int v, int i, vector<pair<int, int>> &to_check)
{
dead_center[v] = true;
link(l[v], r[v]);
if (l[v] != head)
to_check.push_back(make_pair(l[v], i));
}
int jump_over(int v, int i)
{
int len = get_len(v, i);
int per = get_period(v, i);
int to = get_center(len % per + per, i);
if (v < to && get_period(to, i) < per)
return to;
return get_center(len % per, i);
}
bool is_leading(int v, int i)
{
return l[v] == head || get_period(l[v], i) != get_period(v, i);
}
void add_char(int i)
{
vector<pair<int, int>> to_check;
int old_c, c;
for (old_c = c = r[head]; ; c++)
{
int suf = get_len(c, i - 1);
if (suf == 0)
break;
rad[c] = min(rad[reflect(c, old_c)], suf);
if (rad[c] == suf && i - suf - 1 >= 0 && s[i - suf - 1] == s[i])
{
rad[c] += 2;
break;
}
if (rad[c] > 0)
{
if (rad[c] == suf)
remove(c, i, to_check);
starting[lpos(c) - get_rad(c, i) + 1].push_back(c);
}
}
auto &to_del = starting[i - get_len(c, i - 1)];
for (int j = 0; j < (int)to_del.size(); j++)
{
int v = to_del[j];
remove(reflect(v, c), i, to_check);
}
if (i - 1 >= 0 && s[i - 1] == s[i])
append_len(2, i, to_check);
append_len(1, i, to_check);
for (int j = 0; j < (int)to_check.size(); j++)
{
int v = to_check[j].first;
int p = to_check[j].second;
if (v == head || dead_center[v] || !is_leading(v, p))
continue;
check_left_side(v, p);
}
}
void calc_dp(int v, int i)
{
int per = get_period(v, i);
int jmp = jump_over(v, i);
int baby_len = get_len(jmp, i) + per;
int idx = per - 1 - (i - baby_len + 1 - left_side[per]) % per;
per_dp[per].apply_seg(idx, idx, dp, i - baby_len + 1, i - baby_len + 1, false);
dp.apply_seg(i + 1, i + 1, per_dp[per], idx, idx, false);
}
void calc_all_dp(int i)
{
for (int v = r[head]; v != tail; v = jump_over(v, i))
calc_dp(v, i);
}
int mod_sub(int a, int b, int mod)
{
return ((a - b) % mod + mod) % mod;
}
void predict_dp(int v, int start, int until)
{
int per = get_period(v, start - 1);
int jmp = jump_over(v, start - 1);
int baby = l[jmp];
int baby_len = get_len(baby, start - 1);
int pos_serend = 0;
int baby_rad = get_rad(baby, until - 1, true);
int ls = get_left_side(v, start - 1);
if (ls < lpos(baby) - baby_rad + 1)
pos_serend = rpos(baby) + baby_rad;
else
pos_serend = rpos(baby) + (lpos(baby) - ls) + 1;
int len_of_periodicity = pos_serend - left_side[per];
int big_center = left_side[per] + pos_serend;
int big_rad = get_rad(big_center, until - 1, true);
int big_diam = big_rad * 2 - big_center % 2;
int pos_big_death = pos_serend;
if (big_diam > len_of_periodicity)
pos_big_death = rpos(big_center) + big_rad;
int coef = 2 * start - 1 - left_side[per] - baby_len;
if (start < pos_serend)
{
int dp_coef = coef + left_side[per];
int can = min(pos_serend - start, mod_sub(coef, start, per) + 1);
int from = per - 1 - mod_sub(coef, start, per);
int to = per - 1 - mod_sub(coef, start + can - 1, per);
per_dp[per].apply_seg(from, to, dp, dp_coef - (start + can - 1), dp_coef - start, true);
if (start + can < pos_serend)
per_dp[per].apply_seg(0, 0, dp, dp_coef - (start + can), dp_coef - (start + can), true);
}
int full = pos_serend - start;
int prefix = min(full, mod_sub(coef, start, per) + 1);
int mid_cnt = (full - prefix) / per;
int suffix = full - prefix - mid_cnt * per;
auto prefix_vec = per_dp[per].substr(per - 1 - mod_sub(coef, start, per), prefix);
auto mid_vec = mid_cnt == 0 ? DPVector() : per_dp[per].substr(0, per).iterate(mid_cnt);
auto suffix_vec = per_dp[per].substr(per - 1 - mod_sub(coef, start + prefix + mid_cnt * per, per), suffix);
auto sub = prefix_vec.concat(mid_vec).concat(suffix_vec);
dp.apply_seg(start + 1, start + full, sub, 0, sub.size() - 1, false, false, true);
int left = pos_serend;
int right = pos_big_death - 1;
if (left <= right)
{
dp.apply_seg(left + 1, right + 1, dp,
rpos(reflect(cent(right), big_center)), rpos(reflect(cent(left), big_center)), true, true, true);
}
}
void predict(int start, int until)
{
if (start == until)
return;
for (int v = r[head]; v != tail; v = jump_over(v, start - 1))
predict_dp(v, start, until);
}
void predict_small_pals(int i, int until)
{
int cur_r = get_rad(cent(i), until - 1);
dp.apply_seg(i + 1, i + cur_r, dp, i - cur_r + 1, i, true, true, true);
cur_r = get_rad(cent(i) - 1, until - 1);
dp.apply_seg(i + 1, i + cur_r, dp, i - cur_r, i - 1, true, true, true);
}
void finalize_predict(int start, int until)
{
hist.undo();
//TODO
}
void finalize_predict_slow(int start, int until)
{
hist.undo();
//TODO
}
#ifdef STRESS
int slow_dp[N];
bool is_pal(string p)
{
string t = p;
reverse(t.begin(), t.end());
return p == t;
}
void calc_slow()
{
string ss = scan_s;
fill(slow_dp, slow_dp + n + 1, INF);
slow_dp[0] = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j <= n; j++)
if (is_pal(ss.substr(i, j - i)))
slow_dp[j] = min(slow_dp[j], slow_dp[i] + 1);
}
#endif
void print_ans(int i)
{
#ifndef STRESS
printf("%d\n", dp.get(i + 1));
#else
if (dp.get(i + 1) != slow_dp[i + 1])
{
eprintf("failed at %s\n", scan_s);
throw;
}
#endif
}
void solve()
{
#ifndef STRESS
scanf("%s", scan_s);
n = strlen(scan_s);
dn = 2 * n;
#else
dn = 2 * n;
fill(l, l + dn, 0);
fill(r, r + dn, 0);
fill(rad, rad + dn, 0);
fill(left_side, left_side + n + 1, 0);
fill(dead_center, dead_center + dn, false);
for (int i = 0; i <= n; i++)
{
starting[i] = vector<int>();
per_dp[i] = GappedVector();
}
dp = DPVector();
calc_slow();
#endif
init();
for (int i = 0; i <= n; i++)
per_dp[i] = GappedVector(i);
dp.resize(n + 1);
dp[0].val = 0;
for (int i = 1; i < S; i++)
dp[0].mask = set_trit(dp[0].mask, i, 1);
for (int i = 0; i < n; i++)
left_side[i] = -INF;
for (int start = 0; start < n; )
{
int until = min(min(n, start + PREDICT_STEP),
start + start - get_len(r[head], start - 1));
predict(start, until);
int i;
for (i = start; i < until; i++)
{
s[i] = scan_s[i];
if (s[i] != imag_s(i))
{
hist.undo();
predict(start, i);
for (int j = start; j < i; j++)
predict_small_pals(j, i);
break;
}
predict_small_pals(i, until);
print_ans(i);
}
if (start + PREDICT_STEP != i)
{
finalize_predict_slow(start, i - 1);
for (int j = start; j < i; j++)
{
add_char(j);
calc_all_dp(j);
}
}
else
{
finalize_predict(start, i - 1);
for (int j = start; j < i; j++)
{
add_char(j);
calc_all_dp(j);
}
}
if (i < n)
{
s[i] = scan_s[i];
add_char(i);
calc_all_dp(i);
print_ans(i);
}
start = i + 1;
}
}
#ifdef STRESS
void test_all_strings(int pos, int len, int alpha)
{
if (pos == len)
{
n = len;
scan_s[n] = 0;
solve();
return;
}
for (char c = 'a'; c < 'a' + alpha; c++)
{
scan_s[pos] = c;
test_all_strings(pos + 1, len, alpha);
}
}
void test_random_strings(int iters, int len, int alpha)
{
n = len;
scan_s[n] = 0;
for (int i = 0; i < iters; i++)
{
for (int j = 0; j < n; j++)
scan_s[j] = 'a' + rand() % alpha;
solve();
}
}
#endif
int main()
{
#ifdef LOCAL
freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
#else
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
#endif
init_table();
#ifndef STRESS
solve();
#else
srand(31415);
for (int alpha = 2; alpha <= 3; alpha++)
for (int len = alpha; len <= 30; len++)
for (PREDICT_STEP = 1; PREDICT_STEP <= 4; PREDICT_STEP++)
{
eprintf("step = %d alpha = %d, len = %d\n", PREDICT_STEP, alpha, len);
if (pow(alpha + 0., len + 0.) < 2e5)
test_all_strings(0, len, alpha);
else
test_random_strings((int)1e5, len, alpha);
}
#endif
eprintf("\n\ntime: %.3lf\n", (double)clock() / CLOCKS_PER_SEC);
return 0;
} | 22.054429 | 109 | 0.549722 | [
"vector"
] |
3e20ee075ac42a07751e30d270ef00d4fa00ad7d | 3,788 | hh | C++ | src/mem/cache/replacement_policies/ship_rp.hh | tanvisharma/gem5_565 | c093eef0befde08ca852c6709dff34e5190a134b | [
"BSD-3-Clause"
] | 6 | 2021-12-03T22:57:45.000Z | 2021-12-20T04:42:14.000Z | src/mem/cache/replacement_policies/ship_rp.hh | tanvisharma/gem5_565 | c093eef0befde08ca852c6709dff34e5190a134b | [
"BSD-3-Clause"
] | null | null | null | src/mem/cache/replacement_policies/ship_rp.hh | tanvisharma/gem5_565 | c093eef0befde08ca852c6709dff34e5190a134b | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2018 Inria
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* Declaration of a Signature-based Hit Predictor (SHiP) on
* top of Re-Reference Interval Prediction replacement policy.
*
* Re-Reference Interval Prediction (RRIP) is uses a
* re-reference prediction value to determine if entries are going to be re-
* used in the near future or not.
*
* The higher the value of the RRPV, the more distant the entry is from its
* next access.
*
* SHiP sets the RRPV based on the Signature History Counter Table (SHCT),
* which updates the counter on hits and misses.
* The signature can be memory-address based or instruction PC based.
*
*/
#ifndef __MEM_CACHE_REPLACEMENT_POLICIES_SHIP_RP_HH__
#define __MEM_CACHE_REPLACEMENT_POLICIES_SHIP_RP_HH__
#include "base/sat_counter.hh"
#include "mem/cache/replacement_policies/brrip_rp.hh"
struct SHIPRPParams;
class SHIPRP : public BRRIPRP
{
public:
/**
* Declaration of SHCT
*/
mutable std::vector<SatCounter> SHCT;
/** Convenience typedef. */
typedef SHIPRPParams Params;
/**
* Construct and initiliaze this replacement policy.
*/
SHIPRP(Params *p);
/**
* Destructor.
*/
~SHIPRP() {}
/**
* Touch an entry to update its replacement data.
*
* @param replacement_data Replacement data to be touched.
*/
void touch(const std::shared_ptr<ReplacementData>& replacement_data) const
override;
/**
* Reset replacement data. Used when an entry is inserted.
* Set RRPV according to the insertion policy used.
*
* @param replacement_data Replacement data to be reset.
*/
void reset(const std::shared_ptr<ReplacementData>& replacement_data) const
override;
/**
* Find replacement victim using rrpv.
*
* @param cands Replacement candidates, selected by indexing policy.
* @return Replacement entry to be replaced.
*/
ReplaceableEntry* getVictim(const ReplacementCandidates& candidates) const
override;
};
#endif // __MEM_CACHE_REPLACEMENT_POLICIES_SHIP_RP_HH__
| 35.074074 | 78 | 0.692978 | [
"vector"
] |
3e2158e545195ce3fe1ce46aa21f815b1e895a98 | 154 | cpp | C++ | main1.cpp | acmorrow/msvc-pch-vs-zi | 1cae7eba68cb9f230e027ca28e9f3dd13b07a796 | [
"MIT"
] | null | null | null | main1.cpp | acmorrow/msvc-pch-vs-zi | 1cae7eba68cb9f230e027ca28e9f3dd13b07a796 | [
"MIT"
] | null | null | null | main1.cpp | acmorrow/msvc-pch-vs-zi | 1cae7eba68cb9f230e027ca28e9f3dd13b07a796 | [
"MIT"
] | null | null | null | #include "common.hpp"
#ifndef PCH_INCLUDED
#include <vector>
#endif
int main() {
std::vector<int> xs = { 1, 2, 3 };
return common(xs.size());
}
| 14 | 38 | 0.61039 | [
"vector"
] |
3e28d96616e64364e2d84dc91ea3cf558613738b | 3,334 | cpp | C++ | test/median-filter-test.cpp | ademuri/arduino-input-filter | 856109442c81fec36f614c79a5273313f02046af | [
"Apache-2.0"
] | null | null | null | test/median-filter-test.cpp | ademuri/arduino-input-filter | 856109442c81fec36f614c79a5273313f02046af | [
"Apache-2.0"
] | null | null | null | test/median-filter-test.cpp | ademuri/arduino-input-filter | 856109442c81fec36f614c79a5273313f02046af | [
"Apache-2.0"
] | null | null | null | #include "gtest/gtest.h"
#include <cstdio>
#include "../src/median-filter.h"
#include "run-data-test.h"
namespace median_filter_input_test {
TEST(MedianFilter, loading_in_order) {
MedianFilter<uint32_t, uint32_t, 5> *input = new MedianFilter<uint32_t, uint32_t, 5>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{100, 1, 100},
{200, 1, 100},
{300, 1, 200},
{400, 1, 200},
{500, 1, 300},
};
RunDataTest(input, data, setAnalogRead);
}
TEST(MedianFilter, loading_reverse_order) {
MedianFilter<uint32_t, uint32_t, 5> *input = new MedianFilter<uint32_t, uint32_t, 5>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{500, 1, 500},
{400, 1, 400},
{300, 1, 400},
{200, 1, 300},
{100, 1, 300},
};
RunDataTest(input, data, setAnalogRead);
}
TEST(MedianFilter, loading_random_order) {
MedianFilter<uint32_t, uint32_t, 5> *input = new MedianFilter<uint32_t, uint32_t, 5>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{500, 1, 500},
{100, 1, 100},
{400, 1, 400},
{300, 1, 300},
{200, 1, 300},
};
RunDataTest(input, data, setAnalogRead);
}
TEST(MedianFilter, steady_state_step_function) {
MedianFilter<uint32_t, uint32_t, 5> *input = new MedianFilter<uint32_t, uint32_t, 5>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{100, 5, 100},
{200, 2, 100},
{200, 10, 200},
};
RunDataTest(input, data, setAnalogRead);
}
TEST(MedianFilter, steady_state_impulse) {
MedianFilter<uint32_t, uint32_t, 5> *input = new MedianFilter<uint32_t, uint32_t, 5>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{100, 10, 100},
{200, 2, 100},
{100, 10, 100},
{200, 2, 100},
{200, 1, 200},
{100, 2, 200},
{100, 10, 100},
};
RunDataTest(input, data, setAnalogRead);
}
// Not a reasonable size, but behavior should be consistent
TEST(MedianFilter, size_2) {
MedianFilter<uint32_t, uint32_t, 2> *input = new MedianFilter<uint32_t, uint32_t, 2>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{100, 1, 100},
{200, 1, 100},
{200, 2, 200},
{100, 5, 100},
};
RunDataTest(input, data, setAnalogRead);
}
TEST(MedianFilter, size_3) {
MedianFilter<uint32_t, uint32_t, 3> *input = new MedianFilter<uint32_t, uint32_t, 3>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{100, 2, 100},
{200, 1, 100},
{200, 2, 200},
{100, 1, 200},
{100, 5, 100},
};
RunDataTest(input, data, setAnalogRead);
}
TEST(MedianFilter, size_255) {
MedianFilter<uint32_t, uint32_t, 255> *input = new MedianFilter<uint32_t, uint32_t, 255>(analog_read_function);
std::vector<InputOutput<uint32_t, uint32_t>> data = {
{100, 255, 100},
{200, 127, 100},
{200, 1, 200},
{100, 127, 200},
{100, 1, 100},
};
RunDataTest(input, data, setAnalogRead);
}
TEST(MedianFilter, float) {
MedianFilter<float, float, 255> *input = new MedianFilter<float, float, 255>(float_read_function);
std::vector<InputOutput<float, float>> data = {
{1.0, 255, 1.0},
{2.0, 127, 1.0},
{2.0, 1, 2.0},
{1.0, 127, 2.0},
{1.0, 1, 1.0},
};
RunDataTest(input, data, setFloatRead);
}
}
| 28.254237 | 113 | 0.647271 | [
"vector"
] |
3e2e4a184e90dc2433f590a022531f69d261ec46 | 513 | cpp | C++ | Problems/Dynamic_Programming/minimizeCutSegments.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | Problems/Dynamic_Programming/minimizeCutSegments.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | Problems/Dynamic_Programming/minimizeCutSegments.cpp | vishwajeet-hogale/LearnSTL | 0cbfc12b66ba844de23d7966d18cadc7b2d5a77f | [
"MIT"
] | null | null | null | #include<iostream>
#include<math.h>
#include<bits/stdc++.h>
using namespace std;
int minimizeCuts(vector<int> &nums,int target){
vector<int> dp(target+1,target+1);
dp[0] = 0;
for(int i=1;i<=target;i++){
for(int j=0;j<nums.size();j++){
if(i>=nums[j]){
dp[i] = min(dp[i],1+dp[i-nums[j]]);
}
}
}
return dp[target];
}
int main(){
vector<int> nums({2,4,7});
cout<<minimizeCuts(nums,8)<<endl;
return 0;
} | 21.375 | 51 | 0.497076 | [
"vector"
] |
3e31c8774bde517efb3a74e7dac0cd6f546dfa52 | 8,474 | cpp | C++ | src/Router/EtcdHost.cpp | langio/DCache | 80006bb25f30c12337b4600a4791aefccc9aab03 | [
"BSD-3-Clause"
] | 1 | 2019-10-21T09:34:21.000Z | 2019-10-21T09:34:21.000Z | src/Router/EtcdHost.cpp | langio/DCache | 80006bb25f30c12337b4600a4791aefccc9aab03 | [
"BSD-3-Clause"
] | null | null | null | src/Router/EtcdHost.cpp | langio/DCache | 80006bb25f30c12337b4600a4791aefccc9aab03 | [
"BSD-3-Clause"
] | null | null | null | /**
* Tencent is pleased to support the open source community by making DCache available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 "EtcdHost.h"
#include <stdlib.h>
#include "EtcdHttp.h"
#include "global.h"
#include "util/tc_clientsocket.h"
#include "util/tc_timeprovider.h"
#define TEST_KEY string("healthcheck/key_" + ServerConfig::LocalIp + "_" + ServerConfig::ServerName)
#define TEST_VALUE_PREFIX string("healthcheckvalue")
// EtcdHost线程循环执行的时间间隔(单位:毫秒)
const int REPEAT_INTERVAL = 1000;
// 测试Key的超时时间(单位:秒)
const int TEST_KEY_TTL = 100;
tars::TC_ThreadRWLocker EtcdHost::_activeHostsLock;
using namespace tars;
EtcdHost::~EtcdHost()
{
_terminate = true;
if (isAlive())
{
getThreadControl().join();
}
TC_ThreadLock::Lock lock(*this);
notifyAll();
}
int EtcdHost::init(const RouterServerConfig &conf)
{
try
{
_appName = conf.getAppName("");
if (_appName == "")
{
TLOGERROR(FILE_FUN << "read AppName config error!" << endl);
return -1;
}
std::string defaultHost = "127.0.0.1:2379";
std::vector<std::string> hosts = conf.getEtcdHosts(defaultHost);
if (loadHostsInfo(hosts) != 0)
{
TLOGERROR(FILE_FUN << "load etcd Host Info error!" << endl);
return -1;
}
checkHostHealth();
if (_activeHosts.empty())
{
TLOGERROR(FILE_FUN << "All etcd host have been dead" << endl);
return -1;
}
TLOGDEBUG(FILE_FUN << "EtcdHost initiliaze succ" << endl);
return 0;
}
catch (TC_Exception &ex)
{
TLOGERROR(FILE_FUN << "get etcd host error: " << ex.what() << endl);
return -1;
}
}
void EtcdHost::terminate()
{
_terminate = true;
TC_ThreadLock::Lock sync(*this);
notifyAll();
}
std::string EtcdHost::choseHost()
{
tars::TC_ThreadRLock readLock(_activeHostsLock);
return _activeHosts[_count++ % _activeHosts.size()];
}
bool EtcdHost::checkHostWritable(const std::string &url,
const std::string &key,
const std::string &val)
{
try
{
auto req = makeEtcdHttpRequest(url, HTTP_PUT);
req->setDefaultHeader();
req->setKey(key);
req->setKeyTTL(TEST_KEY_TTL);
req->setValue(val);
std::string resp;
int rc = req->doRequest(DEFAULT_HTTP_REQUEST_TIMEOUT, &resp);
if (rc != 0)
{
TLOGERROR(FILE_FUN << "etcd request " << req->dumpURL() << " | "
<< "ret code = " << rc << endl);
return false;
}
TLOGDEBUG(FILE_FUN << "etcd response " << resp << endl);
return true;
}
catch (const std::exception &ex)
{
TLOGERROR(FILE_FUN << " exception:" << ex.what() << endl);
}
catch (...)
{
TLOGERROR(FILE_FUN << " unknow exception:" << endl);
}
return false;
}
bool EtcdHost::checkHostReadable(const std::string &url,
const std::string &key,
const std::string &val,
bool checkValue)
{
try
{
auto req = makeEtcdHttpRequest(url, HTTP_GET);
req->setKey(key);
std::string resp;
if (req->doRequest(DEFAULT_HTTP_REQUEST_TIMEOUT, &resp) != TC_ClientSocket::EM_SUCCESS)
{
TLOGERROR(FILE_FUN << "etcd request " << req->dumpURL() << "| FAILED" << endl);
return false;
}
EtcdHttpParser parser;
if (parser.parseContent(resp) != 0)
{
TLOGERROR(FILE_FUN << "parse http resp error: " << resp << endl);
return false;
}
int errCode;
std::string errMsg;
if (parser.getEtcdError(&errCode, &errMsg) != 0)
{
TLOGERROR(FILE_FUN << "etcd error. errCode : " << errCode << " errMsg : " << errMsg);
return false;
}
std::string v;
if (parser.getCurrentNodeValue(&v) != 0)
{
TLOGERROR(FILE_FUN << "get etcd value error" << endl);
return false;
}
if (checkValue && v != val)
{
return false;
}
// 如果不需要检查查询到的value,就返回true
return true;
}
catch (const std::exception &ex)
{
TLOGERROR(FILE_FUN << " exception:" << ex.what() << endl);
}
catch (...)
{
TLOGERROR(FILE_FUN << " unknow exception:" << endl);
}
return false;
}
std::string EtcdHost::createRandomTestValue() const
{
return std::string(TEST_VALUE_PREFIX + "_" + TC_Common::tostr(rand() % TNOWMS));
}
std::string EtcdHost::getRouterHost()
{
std::string s;
{
TC_ThreadRLock readLock(_activeHostsLock);
s = _activeHosts[_count++ % _activeHosts.size()];
}
return s + "/" + _appName + "/router/router_endpoint";
}
void EtcdHost::timeWait()
{
TC_ThreadLock::Lock lock(*this);
timedWait(REPEAT_INTERVAL);
}
void EtcdHost::run()
{
while (!_terminate)
{
timeWait();
try
{
checkHostHealth();
}
catch (const std::exception &ex)
{
TLOGERROR(FILE_FUN << " exception:" << ex.what() << endl);
}
catch (...)
{
TLOGERROR(FILE_FUN << " unknow exception:" << endl);
}
}
}
void EtcdHost::checkHostHealth()
{
::srand(TNOWMS);
HostMap::const_iterator it = _configHosts.begin();
std::vector<std::string> activeHostsURL;
for (; it != _configHosts.end(); ++it)
{
try
{
const HostInfo &host = it->second;
bool writeHealth = false, readHealth = false;
std::string testVal = createRandomTestValue();
writeHealth = checkHostWritable(host._url, TEST_KEY, testVal);
// 读写ETCD之间间隔1s
::sleep(1);
readHealth = checkHostReadable(host._url, TEST_KEY, testVal, writeHealth);
if (writeHealth || readHealth)
{
activeHostsURL.push_back(host._url);
}
if (!writeHealth || !readHealth)
{
std::string s = readHealth ? "readonly" : "dead";
std::string errMsg = "etcd host " + host._ip + ":" + host._port + " is " + s;
TLOGERROR(FILE_FUN << host._url << "|" << errMsg << endl);
}
}
catch (const std::exception &ex)
{
TLOGERROR(FILE_FUN << " exception:" << ex.what() << endl);
}
catch (...)
{
TLOGERROR(FILE_FUN << " unknow exception:" << endl);
}
}
if (activeHostsURL.empty())
{
TLOGERROR(FILE_FUN << "All etcd host have been dead" << endl);
}
else
{
TC_ThreadWLock writeLock(_activeHostsLock);
_activeHosts.swap(activeHostsURL);
}
}
int EtcdHost::loadHostsInfo(const std::vector<std::string> &hosts)
{
if (hosts.empty())
{
TLOGERROR(FILE_FUN << "load etcd Host Info error, has no etcd host!" << endl);
return -1;
}
std::vector<std::string>::const_iterator it = hosts.begin();
for (; it != hosts.end(); ++it)
{
std::string etcdHostUrl = "http://" + *it + "/v2/keys/";
TC_URL url;
if (!url.parseURL(etcdHostUrl))
{
TLOGERROR(FILE_FUN << "get etcd host error: " << etcdHostUrl << endl);
return -1;
}
std::string addr = url.getDomain() + ":" + url.getPort();
HostInfo h(url.getDomain(), url.getPort());
_configHosts[addr] = h;
TLOGDEBUG(FILE_FUN << "get a ETCD host. URL : " << h._url << "|IP : " << h._ip << ":"
<< h._port << endl);
}
assert(!_configHosts.empty());
return 0;
}
| 26.987261 | 100 | 0.549799 | [
"vector"
] |
3e33ca0fdbc6d48e2138d7fde515038d51cb9e1d | 132,555 | cpp | C++ | test/cl/ScanTest/ScanTest.cpp | jayavanth/Bolt | ea1045126efc060c56f43eef926d65490bca7375 | [
"BSL-1.0"
] | 1 | 2016-11-29T21:03:54.000Z | 2016-11-29T21:03:54.000Z | test/cl/ScanTest/ScanTest.cpp | jayavanth/Bolt | ea1045126efc060c56f43eef926d65490bca7375 | [
"BSL-1.0"
] | null | null | null | test/cl/ScanTest/ScanTest.cpp | jayavanth/Bolt | ea1045126efc060c56f43eef926d65490bca7375 | [
"BSL-1.0"
] | null | null | null | /***************************************************************************
* Copyright 2012 - 2013 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
#include "common/stdafx.h"
#include "common/myocl.h"
#include <vector>
#include <array>
#include "bolt/cl/scan.h"
#include "bolt/unicode.h"
#include "bolt/miniDump.h"
#include <bolt/cl/iterator/counting_iterator.h>
#include <gtest/gtest.h>
#include <boost/shared_array.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#define TEST_DOUBLE 1
#define SERIAL_TBB_OFFSET 0
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Below are helper routines to compare the results of two arrays for googletest
// They return an assertion object that googletest knows how to track
#if 1
/******************************************************************************
* Double x4
*****************************************************************************/
BOLT_FUNCTOR(uddtD4,
struct uddtD4
{
double a;
double b;
double c;
double d;
bool operator==(const uddtD4& rhs) const
{
bool equal = true;
double th = 0.0000000001;
if (rhs.a < th && rhs.a > -th)
equal = ( (1.0*a - rhs.a) < th && (1.0*a - rhs.a) > -th) ? equal : false;
else
equal = ( (1.0*a - rhs.a)/rhs.a < th && (1.0*a - rhs.a)/rhs.a > -th) ? equal : false;
if (rhs.b < th && rhs.b > -th)
equal = ( (1.0*b - rhs.b) < th && (1.0*b - rhs.b) > -th) ? equal : false;
else
equal = ( (1.0*b - rhs.b)/rhs.b < th && (1.0*b - rhs.b)/rhs.b > -th) ? equal : false;
if (rhs.c < th && rhs.c > -th)
equal = ( (1.0*c - rhs.c) < th && (1.0*c - rhs.c) > -th) ? equal : false;
else
equal = ( (1.0*c - rhs.c)/rhs.c < th && (1.0*c - rhs.c)/rhs.c > -th) ? equal : false;
if (rhs.d < th && rhs.d > -th)
equal = ( (1.0*d - rhs.d) < th && (1.0*d - rhs.d) > -th) ? equal : false;
else
equal = ( (1.0*d - rhs.d)/rhs.d < th && (1.0*d - rhs.d)/rhs.d > -th) ? equal : false;
return equal;
}
};
);
BOLT_CREATE_TYPENAME( bolt::cl::device_vector< uddtD4 >::iterator );
BOLT_CREATE_CLCODE( bolt::cl::device_vector< uddtD4 >::iterator, bolt::cl::deviceVectorIteratorTemplate );
BOLT_FUNCTOR(MultD4,
struct MultD4
{
uddtD4 operator()(const uddtD4 &lhs, const uddtD4 &rhs) const
{
uddtD4 _result;
_result.a = lhs.a*rhs.a;
_result.b = lhs.b*rhs.b;
_result.c = lhs.c*rhs.c;
_result.d = lhs.d*rhs.d;
return _result;
};
};
);
uddtD4 identityMultD4 = { 1.0, 1.0, 1.0, 1.0 };
uddtD4 initialMultD4 = { 1.00001, 1.000003, 1.0000005, 1.00000007 };
/******************************************************************************
* Integer x2
*****************************************************************************/
BOLT_FUNCTOR(uddtI2,
struct uddtI2
{
int a;
int b;
bool operator==(const uddtI2& rhs) const
{
bool equal = true;
equal = ( a == rhs.a ) ? equal : false;
equal = ( b == rhs.b ) ? equal : false;
return equal;
}
};
);
BOLT_CREATE_TYPENAME( bolt::cl::device_vector< uddtI2 >::iterator );
BOLT_CREATE_CLCODE( bolt::cl::device_vector< uddtI2 >::iterator, bolt::cl::deviceVectorIteratorTemplate );
BOLT_FUNCTOR(AddI2,
struct AddI2
{
uddtI2 operator()(const uddtI2 &lhs, const uddtI2 &rhs) const
{
uddtI2 _result;
_result.a = lhs.a+rhs.a;
_result.b = lhs.b+rhs.b;
return _result;
};
};
);
uddtI2 identityAddI2 = { 0, 0 };
uddtI2 initialAddI2 = { -1, 2 };
/******************************************************************************
* Mixed float and int
*****************************************************************************/
BOLT_FUNCTOR(uddtM3,
struct uddtM3
{
unsigned int a;
float b;
double c;
bool operator==(const uddtM3& rhs) const
{
bool equal = true;
float ths = 0.00001f;
double thd = 0.0000000001;
equal = ( a == rhs.a ) ? equal : false;
if (rhs.b < ths && rhs.b > -ths)
equal = ( (1.0*b - rhs.b) < ths && (1.0*b - rhs.b) > -ths) ? equal : false;
else
equal = ( (1.0*b - rhs.b)/rhs.b < ths && (1.0*b - rhs.b)/rhs.b > -ths) ? equal : false;
if (rhs.c < thd && rhs.c > -thd)
equal = ( (1.0*c - rhs.c) < thd && (1.0*c - rhs.c) > -thd) ? equal : false;
else
equal = ( (1.0*c - rhs.c)/rhs.c < thd && (1.0*c - rhs.c)/rhs.c > -thd) ? equal : false;
return equal;
}
};
);
BOLT_CREATE_TYPENAME( bolt::cl::device_vector< uddtM3 >::iterator );
BOLT_CREATE_CLCODE( bolt::cl::device_vector< uddtM3 >::iterator, bolt::cl::deviceVectorIteratorTemplate );
BOLT_FUNCTOR(MixM3,
struct MixM3
{
uddtM3 operator()(const uddtM3 &lhs, const uddtM3 &rhs) const
{
uddtM3 _result;
_result.a = lhs.a^rhs.a;
_result.b = lhs.b+rhs.b;
_result.c = lhs.c*rhs.c;
return _result;
};
};
);
uddtM3 identityMixM3 = { 0, 0.f, 1.0 };
uddtM3 initialMixM3 = { 1, 1.f, 1.000001 };
#endif
#if 0
template< typename T >
::testing::AssertionResult cmpArrays( const T ref, const T calc, size_t N )
{
for( size_t i = 0; i < N; ++i )
{
EXPECT_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
template< typename T, size_t N >
::testing::AssertionResult cmpArrays( const T (&ref)[N], const T (&calc)[N] )
{
for( size_t i = 0; i < N; ++i )
{
EXPECT_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
// Primary class template for std::array types
// The struct wrapper is necessary to partially specialize the member function
template< typename T, size_t N >
struct cmpStdArray
{
static ::testing::AssertionResult cmpArrays( const std::array< T, N >& ref, const std::array< T, N >& calc )
{
for( size_t i = 0; i < N; ++i )
{
EXPECT_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
};
// Partial template specialization for float types
// Partial template specializations only works for objects, not functions
template< size_t N >
struct cmpStdArray< float, N >
{
static ::testing::AssertionResult cmpArrays( const std::array< float, N >& ref, const std::array< float, N >& calc)
{
for( size_t i = 0; i < N; ++i )
{
EXPECT_FLOAT_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
};
#if TEST_DOUBLE
// Partial template specialization for float types
// Partial template specializations only works for objects, not functions
template< size_t N >
struct cmpStdArray< double, N >
{
static ::testing::AssertionResult cmpArrays( const std::array< double, N >& ref, const std::array< double,N >&calc)
{
for( size_t i = 0; i < N; ++i )
{
EXPECT_DOUBLE_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
};
#endif
// The following cmpArrays verify the correctness of std::vectors's
template< typename T >
::testing::AssertionResult cmpArrays( const std::vector< T >& ref, const std::vector< T >& calc )
{
for( size_t i = 0; i < ref.size( ); ++i )
{
EXPECT_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
::testing::AssertionResult cmpArrays( const std::vector< float >& ref, const std::vector< float >& calc )
{
for( size_t i = 0; i < ref.size( ); ++i )
{
EXPECT_FLOAT_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
#if TEST_DOUBLE
::testing::AssertionResult cmpArrays( const std::vector< double >& ref, const std::vector< double >& calc )
{
for( size_t i = 0; i < ref.size( ); ++i )
{
EXPECT_DOUBLE_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
#endif
// A very generic template that takes two container, and compares their values assuming a vector interface
template< typename S, typename B >
::testing::AssertionResult cmpArrays( const S& ref, const B& calc )
{
for( size_t i = 0; i < ref.size( ); ++i )
{
EXPECT_EQ( ref[ i ], calc[ i ] ) << _T( "Where i = " ) << i;
}
return ::testing::AssertionSuccess( );
}
#endif
#include "test_common.h"
/******************************************************************************
* Scan with User Defined Data Types and Operators
*****************************************************************************/
TEST(InclusiveScan, normalArrayTest)
{
const int length=10000;
float input[length] ;
float refInput[length];
for(int i=0; i<length; i++) {
input[i] = 1.f + rand()%3;
refInput[i] = input[i];
}
// call scan
bolt::cl::plus<float> ai2;
bolt::cl::inclusive_scan( input, input + length, input, ai2 );
::std::partial_sum(refInput, refInput + length, refInput, ai2);
// compare results
cmpArrays<float,length>(input, refInput);
}
TEST(InclusiveScan, SerialnormalArrayTest)
{
const int length=10000;
float input[length] ;
float refInput[length];
for(int i=0; i<length; i++) {
input[i] = 1.f + rand()%3;
refInput[i] = input[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
bolt::cl::plus<float> ai2;
bolt::cl::inclusive_scan( ctl, input, input + length, input, ai2 );
::std::partial_sum(refInput, refInput + length, refInput, ai2);
// compare results
cmpArrays<float,length>(input, refInput);
}
TEST(InclusiveScan, MulticorenormalArrayTest)
{
const int length=10000;
float input[length] ;
float refInput[length];
for(int i=0; i<length; i++) {
input[i] = 1.f + rand()%3;
refInput[i] = input[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
bolt::cl::plus<float> ai2;
bolt::cl::inclusive_scan( ctl, input, input + length, input, ai2 );
::std::partial_sum(refInput, refInput + length, refInput, ai2);
// compare results
cmpArrays<float,length>(input, refInput);
}
TEST(InclusiveScan, DeviceVectorInclFloat)
{
int length = 1<<10;
//bolt::cl::device_vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
refInput[i] = 1.f + rand()%3;
}
bolt::cl::device_vector< float > input( refInput.begin(), refInput.end());
// call scan
bolt::cl::plus<float> ai2;
//Out of Place Scan
//bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//Inplace Scan
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
//cmpArrays(refOutput, output);
cmpArrays(refInput, input);
}
TEST(InclusiveScan, SerialDeviceVectorInclFloat)
{
int length = 1<<10;
//bolt::cl::device_vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
refInput[i] = 1.f + rand()%3;
}
bolt::cl::device_vector< float > input( refInput.begin(), refInput.end());
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
bolt::cl::plus<float> ai2;
/*bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);*/
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
//cmpArrays(refOutput, output);
cmpArrays(refInput, input);
}
TEST(InclusiveScan, MulticoreDeviceVectorInclFloat)
{
int length = 1<<10;
bolt::cl::device_vector< float > output( length);
std::vector< float > refInput( length);
std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
refInput[i] = 1.f + rand()%3;
}
bolt::cl::device_vector< float > input( refInput.begin(), refInput.end());
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
bolt::cl::plus<float> ai2;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
//cmpArrays(refOutput, output);
cmpArrays(refInput, input);
}
#if (TEST_DOUBLE == 1)
TEST(InclusiveScan, DeviceVectorIncluddtM3)
{
//setup containers
int length = 1<<10;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3 );
//bolt::cl::device_vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length);
// call scan
MixM3 M3;
/*bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);*/
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
//cmpArrays(refOutput, output);
cmpArrays(refInput, input);
}
TEST(InclusiveScan, SerialDeviceVectorIncluddtM3)
{
//setup containers
int length = 1<<10;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3 );
//bolt::cl::device_vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
MixM3 M3;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), M3 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
//cmpArrays(refOutput, output);
cmpArrays(refInput, input);
}
TEST(InclusiveScan, MulticoreDeviceVectorIncluddtM3)
{
//setup containers
int length = 1<<10;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3 );
//bolt::cl::device_vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
MixM3 M3;
/*bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
#endif
TEST(ExclusiveScan, DeviceVectorExclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > stdinput( length);
//bolt::cl::device_vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
stdinput[i] = 1.f + rand()%3;
if(i != length-1)
refInput[i+1] = stdinput[i];
//refInput[i] = 2.0f;
}
refInput[0] = 3.0f;
bolt::cl::device_vector< float > input( stdinput.begin(), stdinput.end());
// call scan
bolt::cl::plus<float> ai2;
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), 3.0f, ai2 );
//// compare results
//cmpArrays(refOutput, output);
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, SerialDeviceVectorExclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > stdinput( length);
//bolt::cl::device_vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
stdinput[i] = 1.f + rand()%3;
if(i != length-1)
refInput[i+1] = stdinput[i];
//refInput[i] = 2.0f;
}
refInput[0] = 3.0f;
bolt::cl::device_vector< float > input( stdinput.begin(), stdinput.end());
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
bolt::cl::plus<float> ai2;
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), 3.0f, ai2 );
//// compare results
//cmpArrays(refOutput, output);
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, MulticoreDeviceVectorExclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > stdinput( length);
//bolt::cl::device_vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
stdinput[i] = 1.f + rand()%3;
if(i != length-1)
refInput[i+1] = stdinput[i];
//refInput[i] = 2.0f;
}
refInput[0] = 3.0f;
bolt::cl::device_vector< float > input( stdinput.begin(), stdinput.end());
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
bolt::cl::plus<float> ai2;
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), 3.0f, ai2 );
//// compare results
//cmpArrays(refOutput, output);
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
#if (TEST_DOUBLE == 1)
TEST(ExclusiveScan, DeviceVectorExcluddtM3)
{
//setup containers
int length = 1<<10;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3 );
//bolt::cl::device_vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = initialMixM3;
//std::vector< uddtM3 > refOutput( length);
// call scan
MixM3 M3;
/* bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, SerialDeviceVectorExcluddtM3)
{
//setup containers
int length = 1<<10;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3 );
//bolt::cl::device_vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = initialMixM3;
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
MixM3 M3;
/* bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, MulticoreDeviceVectorExcluddtM3)
{
//setup containers
int length = 1<<10;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3 );
//bolt::cl::device_vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = initialMixM3;
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
MixM3 M3;
/*bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
#endif
TEST(InclusiveScan, InclUdd)
{
//setup containers
int length = 1<<10;
std::vector< uddtI2 > input( length, initialAddI2 );
//std::vector< uddtI2 > output( length);
std::vector< uddtI2 > refInput( length, initialAddI2 );
//std::vector< uddtI2 > refOutput( length);
// call scan
AddI2 ai2;
//bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(InclusiveScan, SerialInclUdd)
{
//setup containers
int length = 1<<10;
std::vector< uddtI2 > input( length, initialAddI2 );
//std::vector< uddtI2 > output( length);
std::vector< uddtI2 > refInput( length, initialAddI2 );
//std::vector< uddtI2 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu); // tested with serial also
// call scan
AddI2 ai2;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(InclusiveScan, MulticoreInclUdd)
{
//setup containers
int length = 1<<10;
std::vector< uddtI2 > input( length, initialAddI2 );
//std::vector< uddtI2 > output( length);
std::vector< uddtI2 > refInput( length, initialAddI2 );
//std::vector< uddtI2 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
AddI2 ai2;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(InclusiveScan, InclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > input( length);
//std::vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
input[i] = 1.0f + rand()%3;
refInput[i] = input[i];
}
// call scan
bolt::cl::plus<float> ai2;
//bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(InclusiveScan, SerialInclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > input( length);
//std::vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
input[i] = 1.0f + rand()%3;
refInput[i] = input[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
bolt::cl::plus<float> ai2;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(InclusiveScan, MulticoreInclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > input( length);
//std::vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
input[i] = 1.0f + rand()%3;
refInput[i] = input[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
bolt::cl::plus<float> ai2;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
#if(TEST_DOUBLE == 1)
TEST(InclusiveScan, IncluddtM3)
{
//setup containers
int length = 1<<10;
std::vector< uddtM3 > input( length, initialMixM3 );
//std::vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length);
// call scan
MixM3 M3;
/*bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
TEST(InclusiveScan, SerialIncluddtM3)
{
//setup containers
int length = 1<<10;
std::vector< uddtM3 > input( length, initialMixM3 );
//std::vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
MixM3 M3;
/* bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
TEST(InclusiveScan, MulticoreIncluddtM3)
{
//setup containers
int length = 1<<10;
std::vector< uddtM3 > input( length, initialMixM3 );
//std::vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
MixM3 M3;
/*bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
#endif
TEST(ExclusiveScan, ExclUdd)
{
//setup containers
int length = 1<<10;
std::vector< uddtI2 > input( length, initialAddI2 );
//std::vector< uddtI2 > output( length);
std::vector< uddtI2 > refInput( length, initialAddI2 ); refInput[0] = initialAddI2;
//std::vector< uddtI2 > refOutput( length);
// call scan
AddI2 ai2;
//bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), initialAddI2, ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), initialAddI2, ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(ExclusiveScan,SerialExclUdd)
{
//setup containers
int length = 1<<10;
std::vector< uddtI2 > input( length, initialAddI2 );
//std::vector< uddtI2 > output( length);
std::vector< uddtI2 > refInput( length, initialAddI2 ); refInput[0] = initialAddI2;
//std::vector< uddtI2 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
AddI2 ai2;
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), initialAddI2, ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), initialAddI2, ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, MulticoreExclUdd)
{
//setup containers
int length = 1<<10;
std::vector< uddtI2 > input( length, initialAddI2 );
//std::vector< uddtI2 > output( length);
std::vector< uddtI2 > refInput( length, initialAddI2 ); refInput[0] = initialAddI2;
//std::vector< uddtI2 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
AddI2 ai2;
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), initialAddI2, ai2 );
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), initialAddI2, ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, ExclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > input( length);
//std::vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
input[i] = 1.0f + rand()%3;
if(i != length-1)
refInput[i+1] = input[i];
//refInput[i] = 2.0f;
}
refInput[0] = 3.0f;
// call scan
bolt::cl::plus<float> ai2;
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), 3.0f, ai2 );
//// compare results
//cmpArrays(refOutput, output);
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, SerialExclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > input( length);
//std::vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
input[i] = 1.0f + rand()%3;
if(i != length-1)
refInput[i+1] = input[i];
//refInput[i] = 2.0f;
}
refInput[0] = 3.0f;
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
bolt::cl::plus<float> ai2;
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), 3.0f, ai2 );
//// compare results
//cmpArrays(refOutput, output);
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, MulticoreExclFloat)
{
//setup containers
int length = 1<<10;
std::vector< float > input( length);
//std::vector< float > output( length);
std::vector< float > refInput( length);
//std::vector< float > refOutput( length);
for(int i=0; i<length; i++) {
input[i] = 1.0f + rand()%3;
if(i != length-1)
refInput[i+1] = input[i];
//refInput[i] = 2.0f;
}
refInput[0] = 3.0f;
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
bolt::cl::plus<float> ai2;
//::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), 3.0f, ai2 );
//// compare results
//cmpArrays(refOutput, output);
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
#if(TEST_DOUBLE == 1)
TEST(ExclusiveScan, ExcluddtM3)
{
//setup containers
int length = 1<<10;
std::vector< uddtM3 > input( length, initialMixM3 );
//std::vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = initialMixM3;
//std::vector< uddtM3 > refOutput( length);
// call scan
MixM3 M3;
/* bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
TEST(ExclusiveScan,SerialExcluddtM3)
{
//setup containers
int length = 1<<10;
std::vector< uddtM3 > input( length, initialMixM3 );
//std::vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = initialMixM3;
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
MixM3 M3;
/* bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
TEST(ExclusiveScan, MulticoreExcluddtM3)
{
//setup containers
int length = 1<<24;
std::vector< uddtM3 > input( length, initialMixM3 );
//std::vector< uddtM3 > output( length);
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = initialMixM3;
//std::vector< uddtM3 > refOutput( length);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
MixM3 M3;
/* bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refOutput.begin(), M3);
cmpArrays(refOutput, output); */
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), initialMixM3, M3 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), M3);
cmpArrays(refInput, input);
}
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(ScanUserDefined, IncAddInt2)
{
//setup containers
int length = (1<<16)+23;
bolt::cl::device_vector< uddtI2 > input( length, initialAddI2); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtI2 > output( length, identityAddI2); //, CL_MEM_READ_WRITE, false );
std::vector< uddtI2 > refInput( length, initialAddI2 );
//std::vector< uddtI2 > refOutput( length );
// call scan
AddI2 ai2;
//bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, SerialIncAddInt2)
{
//setup containers
int length = (1<<16)+23;
bolt::cl::device_vector< uddtI2 > input( length, initialAddI2); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtI2 > output( length, identityAddI2); //, CL_MEM_READ_WRITE, false );
std::vector< uddtI2 > refInput( length, initialAddI2 );
//std::vector< uddtI2 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
AddI2 ai2;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, MulticoreIncAddInt2)
{
//setup containers
int length = (1<<16)+23;
bolt::cl::device_vector< uddtI2 > input( length, initialAddI2); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtI2 > output( length, identityAddI2); //, CL_MEM_READ_WRITE, false );
std::vector< uddtI2 > refInput( length, initialAddI2 );
//std::vector< uddtI2 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
AddI2 ai2;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), ai2 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
#if(TEST_DOUBLE == 1)
TEST(ScanUserDefined, IncMultiplyDouble4)
{
//setup containers
int length = (1<<16)+11;
bolt::cl::device_vector< uddtD4 > input( length, initialMultD4); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtD4 > output( length, identityMultD4); //, CL_MEM_READ_WRITE, false );
std::vector< uddtD4 > refInput( length, initialMultD4 );
//std::vector< uddtD4 > refOutput( length );
// call scan
MultD4 md4;
//bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), md4 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), md4);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), md4 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), md4);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, SerialIncMultiplyDouble4)
{
//setup containers
int length = (1<<16)+11;
bolt::cl::device_vector< uddtD4 > input( length, initialMultD4); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtD4 > output( length, identityMultD4); //, CL_MEM_READ_WRITE, false );
std::vector< uddtD4 > refInput( length, initialMultD4 );
//std::vector< uddtD4 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
MultD4 md4;
//bolt::cl::inclusive_scan(ctl, input.begin(), input.end(), output.begin(), md4 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), md4);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan(ctl, input.begin(), input.end(), input.begin(), md4 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), md4);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, MulticoreIncMultiplyDouble4)
{
//setup containers
int length = (1<<16)+11;
bolt::cl::device_vector< uddtD4 > input( length, initialMultD4); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtD4 > output( length, identityMultD4); //, CL_MEM_READ_WRITE, false );
std::vector< uddtD4 > refInput( length, initialMultD4 );
//std::vector< uddtD4 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
MultD4 md4;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), md4 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), md4);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), md4 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), md4);
// compare results
cmpArrays(refInput, input);
}
#endif
#if(TEST_DOUBLE == 1)
TEST(ScanUserDefined, IncMixedM3)
{
//setup containers
int length = (1<<16)+57;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtM3 > output( length, identityMixM3); //, CL_MEM_READ_WRITE, false );
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length );
// call scan
MixM3 mm3;
//bolt::cl::inclusive_scan( input.begin(), input.end(), output.begin(), mm3 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), mm3);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), mm3 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), mm3);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, SerialIncMixedM3)
{
//setup containers
int length = (1<<16)+57;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtM3 > output( length, identityMixM3); //, CL_MEM_READ_WRITE, false );
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
MixM3 mm3;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), mm3 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), mm3);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), mm3 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), mm3);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, MulticoreIncMixedM3)
{
//setup containers
int length = (1<<16)+57;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtM3 > output( length, identityMixM3); //, CL_MEM_READ_WRITE, false );
std::vector< uddtM3 > refInput( length, initialMixM3 );
//std::vector< uddtM3 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
MixM3 mm3;
//bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), output.begin(), mm3 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), mm3);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::inclusive_scan( ctl, input.begin(), input.end(), input.begin(), mm3 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), mm3);
// compare results
cmpArrays(refInput, input);
}
#endif
///////////////////////////////////////////////// Exclusive ///////////////////////////
TEST(ScanUserDefined, ExclAddInt2)
{
//setup containers
int length = (1<<16)+23;
bolt::cl::device_vector< uddtI2 > input( length, initialAddI2); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtI2 > output( length, identityAddI2); //, CL_MEM_READ_WRITE, false );
std::vector< uddtI2 > refInput( length, initialAddI2 ); refInput[0] = identityAddI2;
//std::vector< uddtI2 > refOutput( length );
// call scan
AddI2 ai2;
//bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), identityAddI2, ai2 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), identityAddI2, ai2 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, SerialExclAddInt2)
{
//setup containers
int length = (1<<16)+23;
bolt::cl::device_vector< uddtI2 > input( length, initialAddI2); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtI2 > output( length, identityAddI2); //, CL_MEM_READ_WRITE, false );
std::vector< uddtI2 > refInput( length, initialAddI2 ); refInput[0] = identityAddI2;
//std::vector< uddtI2 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
AddI2 ai2;
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), identityAddI2, ai2 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), identityAddI2, ai2 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, MulticoreExclAddInt2)
{
//setup containers
int length = (1<<16)+23;
bolt::cl::device_vector< uddtI2 > input( length, initialAddI2); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtI2 > output( length, identityAddI2); //, CL_MEM_READ_WRITE, false );
std::vector< uddtI2 > refInput( length, initialAddI2 ); refInput[0] = identityAddI2;
//std::vector< uddtI2 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
AddI2 ai2;
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), identityAddI2, ai2 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), ai2);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), identityAddI2, ai2 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), ai2);
// compare results
cmpArrays(refInput, input);
}
#if(TEST_DOUBLE == 1)
TEST(ScanUserDefined, ExclMultiplyDouble4)
{
//setup containers
int length = (1<<16)+11;
bolt::cl::device_vector< uddtD4 > input( length, initialMultD4); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtD4 > output( length, identityMultD4); //, CL_MEM_READ_WRITE, false );
std::vector< uddtD4 > refInput( length, initialMultD4 ); refInput[0] = identityMultD4;
//std::vector< uddtD4 > refOutput( length );
// call scan
MultD4 md4;
//bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), identityMultD4, md4 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), md4);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), identityMultD4, md4 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), md4);
//compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, SerialExclMultiplyDouble4)
{
//setup containers
int length = (1<<16)+11;
bolt::cl::device_vector< uddtD4 > input( length, initialMultD4); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtD4 > output( length, identityMultD4); //, CL_MEM_READ_WRITE, false );
std::vector< uddtD4 > refInput( length, initialMultD4 ); refInput[0] = identityMultD4;
//std::vector< uddtD4 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
MultD4 md4;
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), identityMultD4, md4 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), md4);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), identityMultD4, md4 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), md4);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, MulticoreExclMultiplyDouble4)
{
//setup containers
int length = (1<<16)+11;
bolt::cl::device_vector< uddtD4 > input( length, initialMultD4); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtD4 > output( length, identityMultD4); //, CL_MEM_READ_WRITE, false );
std::vector< uddtD4 > refInput( length, initialMultD4 ); refInput[0] = identityMultD4;
//std::vector< uddtD4 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
MultD4 md4;
//bolt::cl::exclusive_scan(ctl, input.begin(), input.end(), output.begin(), identityMultD4, md4 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), md4);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan(ctl, input.begin(), input.end(), input.begin(), identityMultD4, md4 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), md4);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, ExclMixedM3)
{
//setup containers
int length = (1<<16)+57;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtM3 > output( length, identityMixM3); //, CL_MEM_READ_WRITE, false );
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = identityMixM3;
//std::vector< uddtM3 > refOutput( length );
// call scan
MixM3 mm3;
//bolt::cl::exclusive_scan( input.begin(), input.end(), output.begin(), identityMixM3, mm3 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), mm3);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), identityMixM3, mm3 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), mm3);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, SerialExclMixedM3)
{
//setup containers
int length = (1<<16)+57;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtM3 > output( length, identityMixM3); //, CL_MEM_READ_WRITE, false );
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = identityMixM3;
//std::vector< uddtM3 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
MixM3 mm3;
//bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), output.begin(), identityMixM3, mm3 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), mm3);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan( ctl, input.begin(), input.end(), input.begin(), identityMixM3, mm3 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), mm3);
// compare results
cmpArrays(refInput, input);
}
TEST(ScanUserDefined, MulticoreExclMixedM3)
{
//setup containers
int length = (1<<16)+57;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
//bolt::cl::device_vector< uddtM3 > output( length, identityMixM3); //, CL_MEM_READ_WRITE, false );
std::vector< uddtM3 > refInput( length, initialMixM3 ); refInput[0] = identityMixM3;
//std::vector< uddtM3 > refOutput( length );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
MixM3 mm3;
//bolt::cl::exclusive_scan(ctl, input.begin(), input.end(), output.begin(), identityMixM3, mm3 );
//::std::partial_sum( refInput.begin(), refInput.end(), refOutput.begin(), mm3);
//// compare results
//cmpArrays(refOutput, output);
bolt::cl::exclusive_scan(ctl, input.begin(), input.end(), input.begin(), identityMixM3, mm3 );
::std::partial_sum( refInput.begin(), refInput.end(), refInput.begin(), mm3);
// compare results
cmpArrays(refInput, input);
}
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fixture classes are now defined to enable googletest to process type parameterized tests
// This class creates a C++ 'TYPE' out of a size_t value
template< size_t N >
class TypeValue
{
public:
static const size_t value = N;
};
// Test fixture class, used for the Type-parameterized tests
// Namely, the tests that use std::array and TYPED_TEST_P macros
template< typename ArrayTuple >
class ScanArrayTest: public ::testing::Test
{
public:
ScanArrayTest( ): m_Errors( 0 )
{}
virtual void SetUp( )
{
for( int i=0; i < ArraySize; i++ )
{
stdInput[ i ] = 1;
boltInput[ i ] = 1;
}
};
virtual void TearDown( )
{};
virtual ~ScanArrayTest( )
{}
protected:
typedef typename std::tuple_element< 0, ArrayTuple >::type ArrayType;
// typedef typename std::tuple_element< 0, ArrayTuple >::type::value ArraySize;
static const size_t ArraySize = std::tuple_element< 1, ArrayTuple >::type::value;
typename std::array< ArrayType, ArraySize > stdInput, boltInput;
int m_Errors;
};
TYPED_TEST_CASE_P( ScanArrayTest );
TYPED_TEST_P( ScanArrayTest, InPlace )
{
typedef typename ScanArrayTest< gtest_TypeParam_ >::ArrayType ArrayType;
typedef std::array< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize > ArrayCont;
// Calling the actual functions under test
typename ArrayCont::iterator stdEnd = std::partial_sum( ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::stdInput.end( ), ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ) );
typename ArrayCont::iterator boltEnd = bolt::cl::inclusive_scan( ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::boltInput.end( ), ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ) );
typename ArrayCont::iterator istdEnd = ScanArrayTest< gtest_TypeParam_ >::stdInput.end( );
typename ArrayCont::iterator iboltEnd = ScanArrayTest< gtest_TypeParam_ >::boltInput.end( );
// The returned iterator should be at the end of the result range
EXPECT_EQ( istdEnd, stdEnd );
EXPECT_EQ( iboltEnd, boltEnd );
typename ArrayCont::difference_type stdNumElements = std::distance( ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), stdEnd );
typename ArrayCont::difference_type boltNumElements = std::distance( ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpStdArray< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize >::cmpArrays( ScanArrayTest< gtest_TypeParam_ >::stdInput, ScanArrayTest< gtest_TypeParam_ >::boltInput );
}
TYPED_TEST_P( ScanArrayTest, InPlacePlusFunction )
{
typedef typename ScanArrayTest< gtest_TypeParam_ >::ArrayType ArrayType;
typedef std::array< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize > ArrayCont;
// Calling the actual functions under test
typename ArrayCont::iterator stdEnd = std::partial_sum( ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::stdInput.end( ), ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), std::plus< ArrayType >( ) );
typename ArrayCont::iterator boltEnd = bolt::cl::inclusive_scan( ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::boltInput.end( ), ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), bolt::cl::plus< ArrayType >( ) );
typename ArrayCont::iterator istdEnd = ScanArrayTest< gtest_TypeParam_ >::stdInput.end( );
typename ArrayCont::iterator iboltEnd = ScanArrayTest< gtest_TypeParam_ >::boltInput.end( );
// The returned iterator should be at the end of the result range
EXPECT_EQ( istdEnd, stdEnd );
EXPECT_EQ( iboltEnd, boltEnd );
typename ArrayCont::difference_type stdNumElements = std::distance( ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), stdEnd );
typename ArrayCont::difference_type boltNumElements = std::distance( ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpStdArray< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize >::cmpArrays( ScanArrayTest< gtest_TypeParam_ >::stdInput, ScanArrayTest< gtest_TypeParam_ >::boltInput );
}
TYPED_TEST_P( ScanArrayTest, InPlaceMaxFunction )
{
typedef typename ScanArrayTest< gtest_TypeParam_ >::ArrayType ArrayType;
typedef std::array< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize > ArrayCont;
// Calling the actual functions under test
typename ArrayCont::iterator stdEnd = std::partial_sum( ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::stdInput.end( ), ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), bolt::cl::maximum< ArrayType >( ) );
typename ArrayCont::iterator boltEnd = bolt::cl::inclusive_scan( ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::boltInput.end( ), ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), bolt::cl::maximum< ArrayType >( ) );
typename ArrayCont::iterator istdEnd = ScanArrayTest< gtest_TypeParam_ >::stdInput.end( );
typename ArrayCont::iterator iboltEnd = ScanArrayTest< gtest_TypeParam_ >::boltInput.end( );
// The returned iterator should be at the end of the result range
EXPECT_EQ( istdEnd, stdEnd );
EXPECT_EQ( iboltEnd, boltEnd );
typename ArrayCont::difference_type stdNumElements = std::distance( ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), stdEnd );
typename ArrayCont::difference_type boltNumElements = std::distance( ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpStdArray< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize >::cmpArrays( ScanArrayTest< gtest_TypeParam_ >::stdInput, ScanArrayTest< gtest_TypeParam_ >::boltInput );
}
TYPED_TEST_P( ScanArrayTest, OutofPlace )
{
typedef typename ScanArrayTest< gtest_TypeParam_ >::ArrayType ArrayType;
typedef std::array< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize > ArrayCont;
// Declare temporary arrays to store results for out of place computation
ArrayCont stdResult, boltResult;
// Calling the actual functions under test, out of place semantics
typename ArrayCont::iterator stdEnd = std::partial_sum( ScanArrayTest< gtest_TypeParam_ >::stdInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::stdInput.end( ), stdResult.begin( ) );
typename ArrayCont::iterator boltEnd = bolt::cl::inclusive_scan( ScanArrayTest< gtest_TypeParam_ >::boltInput.begin( ), ScanArrayTest< gtest_TypeParam_ >::boltInput.end( ), boltResult.begin( ) );
// The returned iterator should be one past the end of the result array
EXPECT_EQ( stdResult.end( ), stdEnd );
EXPECT_EQ( boltResult.end( ), boltEnd );
typename ArrayCont::difference_type stdNumElements = std::distance( stdResult.begin( ), stdEnd );
typename ArrayCont::difference_type boltNumElements = std::distance( boltResult.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpStdArray< ArrayType, ScanArrayTest< gtest_TypeParam_ >::ArraySize >::cmpArrays( stdResult, boltResult );
}
REGISTER_TYPED_TEST_CASE_P( ScanArrayTest, InPlace, InPlacePlusFunction, InPlaceMaxFunction, OutofPlace );
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fixture classes are now defined to enable googletest to process value parameterized tests
// ::testing::TestWithParam< int > means that GetParam( ) returns int values, which i use for array size
class ScanIntegerVector: public ::testing::TestWithParam< int >
{
public:
// Create an std and a bolt vector of requested size, and initialize all the elements to 1
ScanIntegerVector( ): stdInput( GetParam( ), 1 ), boltInput( GetParam( ), 1 )
{}
protected:
std::vector< int > stdInput, boltInput;
};
// ::testing::TestWithParam< int > means that GetParam( ) returns int values, which i use for array size
class ScanFloatVector: public ::testing::TestWithParam< int >
{
public:
// Create an std and a bolt vector of requested size, and initialize all the elements to 1
ScanFloatVector( ): stdInput( GetParam( ), 1.0f ), boltInput( GetParam( ), 1.0f )
{}
protected:
std::vector< float > stdInput, boltInput;
};
// ::testing::TestWithParam< int > means that GetParam( ) returns int values, which i use for array size
class ScanDoubleVector: public ::testing::TestWithParam< int >
{
public:
// Create an std and a bolt vector of requested size, and initialize all the elements to 1
ScanDoubleVector( ): stdInput( GetParam( ), 0.0 ), boltInput( GetParam( ), 0.0 )
{}
protected:
std::vector< double > stdInput, boltInput;
};
// ::testing::TestWithParam< int > means that GetParam( ) returns int values, which i use for array size
class ScanIntegerDeviceVector: public ::testing::TestWithParam< int >
{
public:
// Create an std and a bolt vector of requested size, and initialize all the elements to 1
ScanIntegerDeviceVector( ): stdInput( GetParam( ), 1 ), boltInput( static_cast<size_t>( GetParam( ) ), 1 )
{}
protected:
std::vector< int > stdInput;
bolt::cl::device_vector< int > boltInput;
};
// ::testing::TestWithParam< int > means that GetParam( ) returns int values, which i use for array size
class ScanIntegerNakedPointer: public ::testing::TestWithParam< int >
{
public:
// Create an std and a bolt vector of requested size, and initialize all the elements to 1
ScanIntegerNakedPointer( ): stdInput( new int[ GetParam( ) ] ), boltInput( new int[ GetParam( ) ] )
{}
virtual void SetUp( )
{
size_t size = GetParam( );
for( size_t i=0; i < size; i++ )
{
stdInput[ i ] = 1;
boltInput[ i ] = 1;
}
};
virtual void TearDown( )
{
delete [] stdInput;
delete [] boltInput;
};
protected:
//boost::shared_array< int > stdInput;
//boost::shared_array< int > boltInput;
int* stdInput;
int* boltInput;
};
class scanStdVectorWithIters:public ::testing::TestWithParam<int>
{
protected:
int myStdVectSize;
public:
scanStdVectorWithIters():myStdVectSize(GetParam()){
}
};
typedef scanStdVectorWithIters ScanOffsetTest;
typedef scanStdVectorWithIters ScanCLtypeTest;
class StdVectCountingIterator :public ::testing::TestWithParam<int>{
protected:
int mySize;
public:
StdVectCountingIterator():mySize(GetParam()){
}
};
TEST_P (ScanCLtypeTest, InclTestLong)
{
std::vector< cl_long > refInput(myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
refInput[i] = 1 + rand()%3;
}
bolt::cl::device_vector< cl_long> input( refInput.begin(), refInput.end());
//bolt::cl::device_vector< cl_long > input( myStdVectSize, 1+rand()%3);
//std::vector< cl_long > refInput( input.begin(), input.end());
// call scan
bolt::cl::plus<cl_long> ai2;
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
cmpArrays(input, refInput);
}
TEST_P (ScanCLtypeTest, ExclTestLong)
{
std::vector< cl_long > stdinput( myStdVectSize);
std::vector< cl_long > refInput( myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
stdinput[i] = 1 + rand()%3;
if(i != myStdVectSize-1)
refInput[i+1] = stdinput[i];
}
refInput[0] = 3;
bolt::cl::device_vector< cl_long > input( stdinput.begin(), stdinput.end());
// call scan
bolt::cl::plus<cl_long> ai2;
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
TEST_P (ScanCLtypeTest, InclTestULong)
{
std::vector< cl_ulong > refInput(myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
refInput[i] = 1 + rand()%3;
}
bolt::cl::device_vector< cl_ulong> input( refInput.begin(), refInput.end());
// call scan
bolt::cl::plus<cl_ulong> ai2;
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
cmpArrays(input, refInput);
}
TEST_P (ScanCLtypeTest, ExclTestULong)
{
std::vector< cl_ulong > stdinput( myStdVectSize);
std::vector< cl_ulong > refInput( myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
stdinput[i] = 1 + rand()%3;
if(i != myStdVectSize-1)
refInput[i+1] = stdinput[i];
}
refInput[0] = 3;
bolt::cl::device_vector< cl_ulong > input( stdinput.begin(), stdinput.end());
// call scan
bolt::cl::plus<cl_ulong> ai2;
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
TEST_P (ScanCLtypeTest, InclTestShort)
{
std::vector< cl_short > refInput(myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
refInput[i] = 1 + rand()%3;
}
bolt::cl::device_vector< cl_short> input( refInput.begin(), refInput.end());
// call scan
bolt::cl::plus<cl_short> ai2;
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
cmpArrays(input, refInput);
}
TEST_P (ScanCLtypeTest, ExclTestShort)
{
std::vector< cl_short > stdinput( myStdVectSize);
std::vector< cl_short > refInput( myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
stdinput[i] = 1 + rand()%3;
if(i != myStdVectSize-1)
refInput[i+1] = stdinput[i];
}
refInput[0] = 3;
bolt::cl::device_vector< cl_short > input( stdinput.begin(), stdinput.end());
// call scan
bolt::cl::plus<cl_short> ai2;
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
TEST_P (ScanCLtypeTest, InclTestUShort)
{
std::vector< cl_ushort > refInput(myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
refInput[i] = 1 + rand()%3;
}
bolt::cl::device_vector< cl_ushort> input( refInput.begin(), refInput.end());
// call scan
bolt::cl::plus<cl_ushort> ai2;
bolt::cl::inclusive_scan( input.begin(), input.end(), input.begin(), ai2 );
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
cmpArrays(input, refInput);
}
TEST_P (ScanCLtypeTest, ExclTestUShort)
{
std::vector< cl_ushort > stdinput( myStdVectSize);
std::vector< cl_ushort > refInput( myStdVectSize);
for(int i=0; i<myStdVectSize; i++) {
stdinput[i] = 1 + rand()%3;
if(i != myStdVectSize-1)
refInput[i+1] = stdinput[i];
}
refInput[0] = 3;
bolt::cl::device_vector< cl_ushort > input( stdinput.begin(), stdinput.end());
// call scan
bolt::cl::plus<cl_ushort> ai2;
::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), refInput[0], ai2 );
// compare results
cmpArrays(refInput, input);
}
/*
//Scan With Fancy iterator as destination results in Compilation Error!
TEST_P( StdVectCountingIterator, withCountingIterator)
{
bolt::cl::counting_iterator<int> first(1);
bolt::cl::counting_iterator<int> last = first + mySize;
std::vector<int> stdInput( mySize);
std::vector<int> boltInput( mySize);
for (int i = 0; i < mySize; ++i){
stdInput[i] = i + 1;
boltInput[i] = i + 1;
}
//This is logically incorrect!
bolt::cl::counting_iterator<int> boltEnd = bolt::cl::inclusive_scan( boltInput.begin(), boltInput.end() , first);
std::vector<int>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
//Scan With Fancy iterator as input results in Compilation Error! -- NEED TO DEBUG
TEST_P( StdVectCountingIterator, withCountingIteratorInput)
{
bolt::cl::counting_iterator<int> first(1);
bolt::cl::counting_iterator<int> last = first + mySize;
std::vector<int> stdInput(mySize);
std::vector<int> boltOutput(mySize);
for (int i = 0; i < mySize; ++i){
stdInput[i] = i + 1;
}
std::vector<int>::iterator boltEnd = bolt::cl::inclusive_scan( first, / , boltOutput.begin());
std::vector<int>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P( StdVectCountingIterator, SerialwithCountingIteratorInput)
{
bolt::cl::counting_iterator<int> first(1);
bolt::cl::counting_iterator<int> last = first + mySize;
std::vector<int> stdInput( mySize);
std::vector<int> boltOutput( mySize);
for (int i = 0; i < mySize; ++i){
stdInput[i] = i + 1;
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
std::vector<int>::iterator boltEnd = bolt::cl::inclusive_scan( ctl, first, last , boltOutput.begin());
std::vector<int>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P( StdVectCountingIterator, MultiCorewithCountingIteratorInput)
{
bolt::cl::counting_iterator<int> first(1);
bolt::cl::counting_iterator<int> last = first + mySize;
std::vector<int> stdInput( mySize);
std::vector<int> boltOutput( mySize);
for (int i = 0; i < mySize; ++i){
stdInput[i] = i + 1;
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
std::vector<int>::iterator boltEnd = bolt::cl::inclusive_scan( ctl, first, last , boltOutput.begin());
std::vector<int>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
*/
TEST_P (scanStdVectorWithIters, intDefiniteValues){
std::vector<int> stdInput( myStdVectSize);
std::vector<int> boltInput( myStdVectSize);
for (int i = 0; i < myStdVectSize; ++i){
boltInput[i] = i + 1;
}
for (int i = 0; i < myStdVectSize; ++i){
stdInput[i] = i + 1;
}
std::vector<int>::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
std::vector<int>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P (scanStdVectorWithIters, SerialintDefiniteValues){
std::vector<int> stdInput( myStdVectSize);
std::vector<int> boltInput( myStdVectSize);
for (int i = 0; i < myStdVectSize; ++i){
boltInput[i] = i + 1;
}
for (int i = 0; i < myStdVectSize; ++i){
stdInput[i] = i + 1;
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
std::vector<int>::iterator boltEnd = bolt::cl::inclusive_scan(ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
std::vector<int>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P (scanStdVectorWithIters, MulticoreintDefiniteValues){
std::vector<int> stdInput( myStdVectSize);
std::vector<int> boltInput( myStdVectSize);
for (int i = 0; i < myStdVectSize; ++i){
boltInput[i] = i + 1;
}
for (int i = 0; i < myStdVectSize; ++i){
stdInput[i] = i + 1;
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
std::vector<int>::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
std::vector<int>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P (scanStdVectorWithIters, floatDefiniteValues){
std::vector<float> boltInput( myStdVectSize);
std::vector<float> stdInput( myStdVectSize);
for (int i = 0; i < myStdVectSize; ++i){
//stdInput[i] = 1.0f + ( static_cast<float>( rand( ) ) / RAND_MAX );
stdInput[i] = 1.f + rand()%3;
boltInput[i] = stdInput[i];
}
std::vector<float>::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
std::vector<float>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_FLOAT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P (scanStdVectorWithIters, SerialfloatDefiniteValues){
std::vector<float> boltInput( myStdVectSize);
std::vector<float> stdInput( myStdVectSize);
for (int i = 0; i < myStdVectSize; ++i){
//stdInput[i] = 1.0f + ( static_cast<float>( rand( ) ) / RAND_MAX );
stdInput[i] = 1.f + rand()%3;
boltInput[i] = stdInput[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
std::vector<float>::iterator boltEnd = bolt::cl::inclusive_scan(ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
std::vector<float>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_FLOAT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P (scanStdVectorWithIters, MulticorefloatDefiniteValues){
std::vector<float> boltInput( myStdVectSize);
std::vector<float> stdInput( myStdVectSize);
for (int i = 0; i < myStdVectSize; ++i){
//stdInput[i] = 1.0f + ( static_cast<float>( rand( ) ) / RAND_MAX );
stdInput[i] = 1.f + rand()%3;
boltInput[i] = stdInput[i];
}
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
std::vector<float>::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
std::vector<float>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_FLOAT_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
TEST_P (ScanOffsetTest, InclOffsetTestFloat)
{
float n = 1.f + rand()%3;
bolt::cl::device_vector< float > input( myStdVectSize, n);
std::vector< float > refInput( myStdVectSize, n);
// call scan
bolt::cl::plus<float> ai2;
bolt::cl::inclusive_scan( input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , ai2 );
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/2);
}
TEST_P (ScanOffsetTest, ExclOffsetTestFloat)
{
float n = 1.f + rand()%3;
bolt::cl::device_vector< float > input( myStdVectSize,n);
std::vector< float > refInput( myStdVectSize,n);
refInput[myStdVectSize/4] = 3.0f;
// call scan
bolt::cl::plus<float> ai2;
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
bolt::cl::exclusive_scan(input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , 3.0f, ai2 );
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/4);
}
#if (SERIAL_TBB_OFFSET == 1)
TEST_P (ScanOffsetTest, InclOffsetTestFloatSerial)
{
float n = 1.f + rand()%3;
bolt::cl::device_vector< float > input( myStdVectSize, n);
std::vector< float > refInput( myStdVectSize, n);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
bolt::cl::plus<float> ai2;
bolt::cl::inclusive_scan( ctl, input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , ai2 );
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/4);
}
TEST_P (ScanOffsetTest, ExclOffsetTestFloatSerial)
{
float n = 1.f + rand()%3;
bolt::cl::device_vector< float > input( myStdVectSize,n);
std::vector< float > refInput( myStdVectSize,n);
//refInput[myStdVectSize/4] = 3.0f;
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// call scan
bolt::cl::plus<float> ai2;
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
bolt::cl::exclusive_scan(ctl, input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , refInput[myStdVectSize/4], ai2 );
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/4);
}
TEST_P (ScanOffsetTest, InclOffsetTestFloatMultiCore)
{
float n = 1.f + rand()%3;
bolt::cl::device_vector< float > input( myStdVectSize, n);
std::vector< float > refInput( myStdVectSize, n);
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
bolt::cl::plus<float> ai2;
bolt::cl::inclusive_scan( ctl, input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , ai2 );
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/4);
}
TEST_P (ScanOffsetTest, ExclOffsetTestFloatMultiCore)
{
float n = 1.f + rand()%3;
bolt::cl::device_vector< float > input( myStdVectSize,n);
std::vector< float > refInput( myStdVectSize,n);
refInput[myStdVectSize/4] = 3.0f;
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// call scan
bolt::cl::plus<float> ai2;
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
bolt::cl::exclusive_scan(ctl, input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , 3.f, ai2 );
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/4);
}
#endif
#if (TEST_DOUBLE == 1)
TEST_P (ScanOffsetTest, InclOffsetTestDouble)
{
double n = 1.0 + rand()%3;
bolt::cl::device_vector< double > input( myStdVectSize, n);
std::vector< double > refInput( myStdVectSize, n);
// call scan
bolt::cl::plus<double> ai2;
bolt::cl::inclusive_scan( input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , ai2 );
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/4);
}
TEST_P (ScanOffsetTest, ExclOffsetTestDouble)
{
double n = 1.0 + rand()%3;
bolt::cl::device_vector< double > input( myStdVectSize,n);
std::vector< double > refInput( myStdVectSize,n);
refInput[myStdVectSize/4] = 3.0f;
// call scan
bolt::cl::plus<double> ai2;
::std::partial_sum(refInput.begin()+ (myStdVectSize/4) , refInput.end()- (myStdVectSize/4), refInput.begin()+ (myStdVectSize/4) , ai2);
bolt::cl::exclusive_scan(input.begin() + (myStdVectSize/4), input.end() - (myStdVectSize/4), input.begin()+ (myStdVectSize/4) , 3.0f, ai2 );
// ::std::partial_sum(refInput.begin(), refInput.end(), refInput.begin(), ai2);
// bolt::cl::exclusive_scan( input.begin(), input.end(), input.begin(), 3.0f, ai2 );
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",myStdVectSize, myStdVectSize/4);
}
TEST (ScanOffsetTest, InclOffsetTestUDD)
{
int length = 1<<16;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
std::vector< uddtM3 > refInput( length, initialMixM3 );
// call scan
MixM3 ai2;
bolt::cl::inclusive_scan( input.begin() + (length/4), input.end() - (length/4), input.begin()+ (length/4) , ai2 );
::std::partial_sum(refInput.begin()+ (length/4) , refInput.end()- (length/4), refInput.begin()+ (length/4) , ai2);
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",length, length/4);
}
TEST (ScanOffsetTest, ExclOffsetTestUDD)
{
int length = 1<<16;
bolt::cl::device_vector< uddtM3 > input( length, initialMixM3); //, CL_MEM_READ_WRITE, true );
std::vector< uddtM3 > refInput( length, initialMixM3 );
refInput[length/4] = initialMixM3;
// call scan
MixM3 ai2;
// call scan
::std::partial_sum(refInput.begin()+ (length/4) , refInput.end()- (length/4), refInput.begin()+ (length/4) , ai2);
bolt::cl::exclusive_scan(input.begin() + (length/4), input.end() - (length/4), input.begin()+ (length/4) , initialMixM3, ai2 );
cmpArrays(input, refInput);
printf("\nPass for size=%d Offset=%d\n",length, length/4);
}
TEST_P (scanStdVectorWithIters, doubleDefiniteValues){
std::vector<double> boltInput( myStdVectSize);
std::vector<double> stdInput( myStdVectSize);
for (int i = 0; i < myStdVectSize; ++i){
//stdInput[i] = 1.0f + ( static_cast<double>( rand( ) ) / RAND_MAX );
stdInput[i] = 1.0 + rand()%3;
boltInput[i] = stdInput[i];
}
std::vector<double>::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
std::vector<double>::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
EXPECT_DOUBLE_EQ((*(boltEnd-1)), (*(stdEnd-1)))<<std::endl;
}
#endif
////INSTANTIATE_TEST_CASE_P(inclusiveScanIter, scanStdVectorWithIters, ::testing::Range(1, 1025, 1));
//INSTANTIATE_TEST_CASE_P(inclusiveScanIterIntLimit, ScanCLtypeTest, ::testing::Range(1025, 25535, 1000));
INSTANTIATE_TEST_CASE_P(inclusiveScanIterIntLimit, ScanCLtypeTest, ::testing::Range( 1, 1024, 47 ));
INSTANTIATE_TEST_CASE_P(inclusiveScanIterIntLimit, ScanOffsetTest, ::testing::Range(1025, 65535, 5111));
INSTANTIATE_TEST_CASE_P(inclusiveScanIterIntLimit, scanStdVectorWithIters, ::testing::Range(1025, 65535, 5111));
INSTANTIATE_TEST_CASE_P(withCountingIterator, StdVectCountingIterator, ::testing::Range(1025, 65535, 5111));
TEST_P( ScanIntegerVector, InclusiveInplace )
{
//cl_int err = CL_SUCCESS;
//std::string strDeviceName = bolt::cl::control::getDefault( ).device( ).getInfo< CL_DEVICE_NAME >( &err );
//bolt::cl::V_OPENCL( err, "Device::getInfo< CL_DEVICE_NAME > failed" );
//std::cout << "Device under test : " << strDeviceName << std::endl;
// Calling the actual functions under test
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
std::vector< int >::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanIntegerVector, SerialInclusiveInplace )
{
//cl_int err = CL_SUCCESS;
//std::string strDeviceName = bolt::cl::control::getDefault( ).device( ).getInfo< CL_DEVICE_NAME >( &err );
//bolt::cl::V_OPENCL( err, "Device::getInfo< CL_DEVICE_NAME > failed" );
//std::cout << "Device under test : " << strDeviceName << std::endl;
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// Calling the actual functions under test
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
std::vector< int >::iterator boltEnd = bolt::cl::inclusive_scan( ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanIntegerVector, MulticoreInclusiveInplace )
{
//cl_int err = CL_SUCCESS;
//std::string strDeviceName = bolt::cl::control::getDefault( ).device( ).getInfo< CL_DEVICE_NAME >( &err );
//bolt::cl::V_OPENCL( err, "Device::getInfo< CL_DEVICE_NAME > failed" );
//std::cout << "Device under test : " << strDeviceName << std::endl;
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// Calling the actual functions under test
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
std::vector< int >::iterator boltEnd = bolt::cl::inclusive_scan(ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanFloatVector, InclusiveInplace )
{
// Calling the actual functions under test
std::vector< float >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
std::vector< float >::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< float >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< float >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanFloatVector, SerialInclusiveInplace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// Calling the actual functions under test
std::vector< float >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
std::vector< float >::iterator boltEnd = bolt::cl::inclusive_scan( ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< float >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< float >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanFloatVector, MulticoreInclusiveInplace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// Calling the actual functions under test
std::vector< float >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
std::vector< float >::iterator boltEnd = bolt::cl::inclusive_scan(ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< float >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< float >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
#if (TEST_DOUBLE == 1)
TEST_P( ScanDoubleVector, InclusiveInplace )
{
// Calling the actual functions under test
std::vector< double >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ),stdInput.begin( ));
std::vector< double >::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< double >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< double >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanDoubleVector, SerialInclusiveInplace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// Calling the actual functions under test
std::vector< double >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ),stdInput.begin( ));
std::vector< double >::iterator boltEnd = bolt::cl::inclusive_scan( ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< double >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< double >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanDoubleVector, MulticoreInclusiveInplace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// Calling the actual functions under test
std::vector< double >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ),stdInput.begin( ));
std::vector< double >::iterator boltEnd = bolt::cl::inclusive_scan( ctl, boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< double >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< double >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
#endif
TEST_P( ScanIntegerDeviceVector, InclusiveInplace )
{
// Calling the actual functions under test
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
bolt::cl::device_vector< int >::iterator boltEnd = bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ),
boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanIntegerDeviceVector, SerialInclusiveInplace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// Calling the actual functions under test
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
bolt::cl::device_vector< int >::iterator boltEnd = bolt::cl::inclusive_scan(ctl, boltInput.begin( ),
boltInput.end( ), boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
TEST_P( ScanIntegerDeviceVector, MulticoreInclusiveInplace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// Calling the actual functions under test
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
bolt::cl::device_vector< int >::iterator boltEnd = bolt::cl::inclusive_scan(ctl, boltInput.begin( ),
boltInput.end( ), boltInput.begin( ) );
// The returned iterator should be one past the
EXPECT_EQ( stdInput.end( ), stdEnd );
EXPECT_EQ( boltInput.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdInput.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltInput.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput );
}
#if defined(_WIN32)
TEST_P( ScanIntegerNakedPointer, InclusiveInplace )
{
size_t endIndex = GetParam( );
// Calling the actual functions under test
stdext::checked_array_iterator< int* > wrapStdInput( stdInput, endIndex );
stdext::checked_array_iterator< int* > stdEnd = std::partial_sum( wrapStdInput, wrapStdInput + endIndex,
wrapStdInput );
//int* stdEnd = std::partial_sum( stdInput, stdInput + endIndex, stdInput );
stdext::checked_array_iterator< int* > wrapBoltInput( boltInput, endIndex );
stdext::checked_array_iterator< int* > boltEnd = bolt::cl::inclusive_scan( wrapBoltInput,
wrapBoltInput + endIndex, wrapBoltInput );
//int* boltEnd = bolt::cl::inclusive_scan( boltInput, boltInput + endIndex, boltInput );
// The returned iterator should be one past the
EXPECT_EQ( wrapStdInput + endIndex, stdEnd );
EXPECT_EQ( wrapBoltInput + endIndex, boltEnd );
size_t stdNumElements = std::distance( wrapStdInput, stdEnd );
size_t boltNumElements = std::distance( wrapBoltInput, boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput, endIndex );
}
TEST_P( ScanIntegerNakedPointer, SerialInclusiveInplace )
{
size_t endIndex = GetParam( );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// Calling the actual functions under test
stdext::checked_array_iterator< int* > wrapStdInput( stdInput, endIndex );
stdext::checked_array_iterator< int* > stdEnd = std::partial_sum( wrapStdInput, wrapStdInput +
endIndex, wrapStdInput );
//int* stdEnd = std::partial_sum( stdInput, stdInput + endIndex, stdInput );
stdext::checked_array_iterator< int* > wrapBoltInput( boltInput, endIndex );
stdext::checked_array_iterator< int* > boltEnd = bolt::cl::inclusive_scan( ctl, wrapBoltInput,
wrapBoltInput + endIndex, wrapBoltInput );
//int* boltEnd = bolt::cl::inclusive_scan( boltInput, boltInput + endIndex, boltInput );
// The returned iterator should be one past the
EXPECT_EQ( wrapStdInput + endIndex, stdEnd );
EXPECT_EQ( wrapBoltInput + endIndex, boltEnd );
size_t stdNumElements = std::distance( wrapStdInput, stdEnd );
size_t boltNumElements = std::distance( wrapBoltInput, boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput, endIndex );
}
TEST_P( ScanIntegerNakedPointer, MultiCoreInclusiveInplace )
{
size_t endIndex = GetParam( );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// Calling the actual functions under test
stdext::checked_array_iterator< int* > wrapStdInput( stdInput, endIndex );
stdext::checked_array_iterator< int* > stdEnd = std::partial_sum( wrapStdInput, wrapStdInput +
endIndex, wrapStdInput );
//int* stdEnd = std::partial_sum( stdInput, stdInput + endIndex, stdInput );
stdext::checked_array_iterator< int* > wrapBoltInput( boltInput, endIndex );
stdext::checked_array_iterator< int* > boltEnd = bolt::cl::inclusive_scan( ctl, wrapBoltInput,
wrapBoltInput + endIndex, wrapBoltInput );
//int* boltEnd = bolt::cl::inclusive_scan( boltInput, boltInput + endIndex, boltInput );
// The returned iterator should be one past the
EXPECT_EQ( wrapStdInput + endIndex, stdEnd );
EXPECT_EQ( wrapBoltInput + endIndex, boltEnd );
size_t stdNumElements = std::distance( wrapStdInput, stdEnd );
size_t boltNumElements = std::distance( wrapBoltInput, boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, boltInput, endIndex );
}
#endif
TEST_P( ScanIntegerVector, ExclusiveOutOfPlace )
{
// Declare temporary arrays to store results for out of place computation
std::vector< int > stdResult( GetParam( ) ), boltResult( GetParam( ) );
int init = 3;
// Emulating a std exclusive scan
if( stdInput.size( ) )
stdInput[ 0 ] += init;
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdResult.begin( ) );
if( stdInput.size( ) )
stdInput[ 0 ] -= init;
stdEnd = std::transform( stdResult.begin( ), stdResult.end( ), stdInput.begin( ), stdResult.begin( ),
std::minus< int >( ) );
// Calling Bolt exclusive scan
std::vector< int >::iterator boltEnd = bolt::cl::exclusive_scan( boltInput.begin( ), boltInput.end( ),
boltResult.begin( ), init );
// The returned iterator should be one past the
EXPECT_EQ( stdResult.end( ), stdEnd );
EXPECT_EQ( boltResult.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdResult.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltResult.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdResult, boltResult );
}
TEST_P( ScanIntegerVector, SerialExclusiveOutOfPlace )
{
// Declare temporary arrays to store results for out of place computation
std::vector< int > stdResult( GetParam( ) ), boltResult( GetParam( ) );
int init = 3;
// Emulating a std exclusive scan
if( stdInput.size( ) )
stdInput[ 0 ] += init;
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdResult.begin( ) );
if( stdInput.size( ) )
stdInput[ 0 ] -= init;
stdEnd = std::transform( stdResult.begin( ), stdResult.end( ), stdInput.begin( ), stdResult.begin( ),
std::minus< int >( ) );
::cl::Context myContext = bolt::cl::control::getDefault( ).getContext( );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
// Calling Bolt exclusive scan
std::vector< int >::iterator boltEnd = bolt::cl::exclusive_scan(ctl, boltInput.begin( ), boltInput.end( ),
boltResult.begin( ), init );
// The returned iterator should be one past the
EXPECT_EQ( stdResult.end( ), stdEnd );
EXPECT_EQ( boltResult.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdResult.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltResult.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdResult, boltResult );
}
TEST_P( ScanIntegerVector, MultiCoreExclusiveOutOfPlace )
{
// Declare temporary arrays to store results for out of place computation
std::vector< int > stdResult( GetParam( ) ), boltResult( GetParam( ) );
int init = 3;
// Emulating a std exclusive scan
if( stdInput.size( ) )
stdInput[ 0 ] += init;
std::vector< int >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ), stdResult.begin( ) );
if( stdInput.size( ) )
stdInput[ 0 ] -= init;
stdEnd = std::transform( stdResult.begin( ), stdResult.end( ), stdInput.begin( ), stdResult.begin( ),
std::minus< int >( ) );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
// Calling Bolt exclusive scan
std::vector< int >::iterator boltEnd = bolt::cl::exclusive_scan(ctl, boltInput.begin( ), boltInput.end( ),
boltResult.begin( ), init );
// The returned iterator should be one past the
EXPECT_EQ( stdResult.end( ), stdEnd );
EXPECT_EQ( boltResult.end( ), boltEnd );
std::vector< int >::iterator::difference_type stdNumElements = std::distance( stdResult.begin( ), stdEnd );
std::vector< int >::iterator::difference_type boltNumElements = std::distance( boltResult.begin( ), boltEnd );
// Both collections should have the same number of elements
EXPECT_EQ( stdNumElements, boltNumElements );
// Loop through the array and compare all the values with each other
cmpArrays( stdResult, boltResult );
}
//tring to call out-place scan
TEST_P( ScanFloatVector, intSameValuesSerialOutPlace )
{
bolt::cl::device_vector< float > boltInput( GetParam( ), 1.0f );
bolt::cl::device_vector< float > boltOutput( GetParam( ), 1.0f );
bolt::cl::device_vector< float >::iterator boltEnd = bolt::cl::exclusive_scan(boltInput.begin( ),boltInput.end( ),
boltOutput.begin() );
std::vector< float > stdOutput( GetParam( ), 1.0f );
std::vector< float >::iterator stdEnd = bolt::cl::exclusive_scan( stdInput.begin( ), stdInput.end( ),
stdOutput.begin( ) );
// Loop through the array and compare all the values with each other
cmpArrays( stdOutput, boltOutput );
}
TEST_P( ScanFloatVector, SerialintSameValuesSerialOutPlace )
{
bolt::cl::device_vector< float > boltInput( GetParam( ), 1.0f );
bolt::cl::device_vector< float > boltOutput( GetParam( ), 1.0f );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
bolt::cl::device_vector< float >::iterator boltEnd = bolt::cl::exclusive_scan( ctl,
boltInput.begin( ),
boltInput.end( ),
boltOutput.begin() );
std::vector< float > stdOutput( GetParam( ), 1.0f );
std::vector< float >::iterator stdEnd = bolt::cl::exclusive_scan(ctl, stdInput.begin( ), stdInput.end( ),
stdOutput.begin( ) );
// Loop through the array and compare all the values with each other
cmpArrays( stdOutput, boltOutput );
}
TEST_P( ScanFloatVector, MulticoreintSameValuesSerialOutPlace )
{
bolt::cl::device_vector< float > boltInput( GetParam( ), 1.0f );
bolt::cl::device_vector< float > boltOutput( GetParam( ), 1.0f );
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
bolt::cl::device_vector< float >::iterator boltEnd = bolt::cl::exclusive_scan( ctl,
boltInput.begin( ),
boltInput.end( ),
boltOutput.begin( ) );
std::vector< float > stdOutput( GetParam( ), 1.0f );
std::vector< float >::iterator stdEnd = bolt::cl::exclusive_scan(ctl, stdInput.begin( ), stdInput.end( ),
stdOutput.begin( ) );
// Loop through the array and compare all the values with each other
cmpArrays( stdOutput, boltOutput );
}
//tring to call in-place scan
TEST_P( ScanFloatVector, intSameValuesSerialInPlace )
{
bolt::cl::device_vector< float > dvBoltInput( GetParam( ), 1.0f );
bolt::cl::device_vector< float >::iterator boltEnd = bolt::cl::exclusive_scan( dvBoltInput.begin( ),
dvBoltInput.end( ), dvBoltInput.begin() );
{
bolt::cl::device_vector< float >::pointer inPlaceData = dvBoltInput.data( );
}
//std::vector< float > stdInput( 1024, 1 );
std::vector< float >::iterator stdEnd = bolt::cl::exclusive_scan( stdInput.begin( ), stdInput.end( ),
stdInput.begin( ) );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, dvBoltInput );
}
TEST_P( ScanFloatVector, SerialintSameValuesSerialInPlace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::SerialCpu);
bolt::cl::device_vector< float > dvBoltInput( GetParam( ), 1.0f );
bolt::cl::device_vector< float >::iterator boltEnd = bolt::cl::exclusive_scan(ctl, dvBoltInput.begin( ),
dvBoltInput.end( ), dvBoltInput.begin() );
{
bolt::cl::device_vector< float >::pointer inPlaceData = dvBoltInput.data( );
}
//std::vector< float > stdInput( 1024, 1 );
std::vector< float >::iterator stdEnd = bolt::cl::exclusive_scan(ctl, stdInput.begin( ), stdInput.end( ),
stdInput.begin( ) );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, dvBoltInput );
}
TEST_P( ScanFloatVector, MulticoreintSameValuesSerialInPlace )
{
bolt::cl::control ctl = bolt::cl::control::getDefault( );
ctl.setForceRunMode(bolt::cl::control::MultiCoreCpu);
bolt::cl::device_vector< float > dvBoltInput( GetParam( ), 1.0f );
bolt::cl::device_vector< float >::iterator boltEnd = bolt::cl::exclusive_scan(ctl, dvBoltInput.begin( ),
dvBoltInput.end( ), dvBoltInput.begin() );
{
bolt::cl::device_vector< float >::pointer inPlaceData = dvBoltInput.data( );
}
//std::vector< float > stdInput( 1024, 1 );
std::vector< float >::iterator stdEnd = bolt::cl::exclusive_scan(ctl, stdInput.begin( ), stdInput.end( ),
stdInput.begin( ) );
// Loop through the array and compare all the values with each other
cmpArrays( stdInput, dvBoltInput );
}
// Test lots of consecutive numbers, but small range, suitable for integers because they overflow easier
INSTANTIATE_TEST_CASE_P( Inclusive, ScanIntegerVector, ::testing::Range( 0, 1024, 23 ) );
INSTANTIATE_TEST_CASE_P( Inclusive, ScanIntegerDeviceVector, ::testing::Range( 0, 1024, 23 ) );
INSTANTIATE_TEST_CASE_P( Inclusive, ScanIntegerNakedPointer, ::testing::Range( 0, 1024, 23) );
INSTANTIATE_TEST_CASE_P( Exclusive, ScanFloatVector, ::testing::Range( 1, 1024, 23 ) );
// Test a huge range, suitable for floating point as they are less prone to overflow
// (but floating point loses granularity at large values)
//INSTANTIATE_TEST_CASE_P( Inclusive, ScanFloatVector, ::testing::Range( 4096, 1048576, 4096 ) );
// above test takes a long time; >2hrs - DT
INSTANTIATE_TEST_CASE_P( Inclusive, ScanDoubleVector, ::testing::Range( 4096, 1048576, 4096 ) );
typedef ::testing::Types<
std::tuple< int, TypeValue< 1 > >,
//std::tuple< int, TypeValue< bolt::cl::scanMultiCpuThreshold - 1 > >,
//std::tuple< int, TypeValue< bolt::cl::scanGpuThreshold - 1 > >,
std::tuple< int, TypeValue< 31 > >,
std::tuple< int, TypeValue< 32 > >,
std::tuple< int, TypeValue< 63 > >,
std::tuple< int, TypeValue< 64 > >,
std::tuple< int, TypeValue< 127 > >,
std::tuple< int, TypeValue< 128 > >,
std::tuple< int, TypeValue< 129 > >,
std::tuple< int, TypeValue< 1000 > >,
std::tuple< int, TypeValue< 1053 > >,
std::tuple< int, TypeValue< 4096 > >,
std::tuple< int, TypeValue< 4097 > >,
std::tuple< int, TypeValue< 65535 > >,
//std::tuple< int, TypeValue< 131032 > >, // uncomment these to generate failures; stack overflow
//std::tuple< int, TypeValue< 262154 > >,
std::tuple< int, TypeValue< 65536 > >
> IntegerTests;
typedef ::testing::Types<
std::tuple< float, TypeValue< 1 > >,
//std::tuple< float, TypeValue< bolt::cl::scanMultiCpuThreshold - 1 > >,
//std::tuple< float, TypeValue< bolt::cl::scanGpuThreshold - 1 > >,
std::tuple< float, TypeValue< 31 > >,
std::tuple< float, TypeValue< 32 > >,
std::tuple< float, TypeValue< 63 > >,
std::tuple< float, TypeValue< 64 > >,
std::tuple< float, TypeValue< 127 > >,
std::tuple< float, TypeValue< 128 > >,
std::tuple< float, TypeValue< 129 > >,
std::tuple< float, TypeValue< 1000 > >,
std::tuple< float, TypeValue< 1053 > >,
std::tuple< float, TypeValue< 4096 > >,
std::tuple< float, TypeValue< 4097 > >,
std::tuple< float, TypeValue< 65535 > >,
std::tuple< float, TypeValue< 65536 > >
> FloatTests;
INSTANTIATE_TYPED_TEST_CASE_P( Integer, ScanArrayTest, IntegerTests );
INSTANTIATE_TYPED_TEST_CASE_P( Float, ScanArrayTest, FloatTests );
//here
/* TEST(Scan, cpuQueue)
{
MyOclContext ocl = initOcl(CL_DEVICE_TYPE_CPU, 0);
bolt::cl::control c(ocl._queue); // construct control structure from the queue.
std::vector< float > boltInput( 1024, 1.0f );
std::vector< float > boltOutput( 1024, 1.0f );
std::vector< float > stdInput( 1024, 1.0f );
std::vector< float > stdOutput( 1024, 1.0f );
std::cout << "Doing BOLT scan\n";
std::vector< float >::iterator boltEnd = bolt::cl::inclusive_scan( c, boltInput.begin( ), boltInput.end( ),
boltOutput.begin( ) );
std::cout << "Doing STD scan\n";
std::vector< float >::iterator stdEnd = std::partial_sum( stdInput.begin( ), stdInput.end( ),stdOutput.begin( ));
cmpArrays( stdInput, boltInput );
} */
/*
// std::deque's iteartor is not allowed in the bolt'routines because
// unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations
TEST (sanity_exclusive_scan__stdDeque, intSameValuesSerialRange_EP377072)
{
int size = 10;
std::deque<int> boltInput( size, 1 );
std::deque<int> stdInput( size, 1 );
//std::vector<int> boltInput( size, 1 );
//std::vector<int> stdInput( size, 1 );
std::cout<<"before exclusive_scan:\nstd input\tboltinput \n";
for (int i = 0; i < size; i++)
{
std::cout<<" "<<stdInput[i]<<" ";
std::cout<<" "<<boltInput[i]<<" \n";
}
//TAKE_THIS_CONTROL_PATH
bolt::cl::inclusive_scan( boltInput.begin( ), boltInput.end( ), boltInput.begin( ));
std::partial_sum( stdInput.begin( ), stdInput.end( ), stdInput.begin( ) );
std::cout<<"\n\nafter exclusive_scan:\nstd input\tboltinput \n";
for (int i = 0; i < size; i++)
{
std::cout<<" "<<stdInput[i]<<" ";
std::cout<<" "<<boltInput[i]<<" \n";
}
for (int i = 0; i < size; i++){
EXPECT_EQ(stdInput[i], boltInput[i]);
}
}
*/
int _tmain(int argc, _TCHAR* argv[])
{
// Register our minidump generating logic
// bolt::miniDumpSingleton::enableMiniDumps( );
// Initialize googletest; this removes googletest specific flags from command line
::testing::InitGoogleTest( &argc, &argv[ 0 ] );
bool print_clInfo = false;
cl_uint userPlatform = 0;
cl_uint userDevice = 0;
cl_device_type deviceType = CL_DEVICE_TYPE_DEFAULT;
try
{
// Declare supported options below, describe what they do
po::options_description desc( "Scan GoogleTest command line options" );
desc.add_options()
( "help,h", "produces this help message" )
( "queryOpenCL,q", "Print queryable platform and device info and return" )
( "platform,p", po::value< cl_uint >( &userPlatform )->default_value( 0 ),
"Specify the platform under test" )
( "device,d", po::value< cl_uint >( &userDevice )->default_value( 0 ),
"Specify the device under test" )
//( "gpu,g", "Force instantiation of all OpenCL GPU device" )
//( "cpu,c", "Force instantiation of all OpenCL CPU device" )
//( "all,a", "Force instantiation of all OpenCL devices" )
;
//// All positional options (un-named) should be interpreted as kernelFiles
//po::positional_options_description p;
//p.add("kernelFiles", -1);
//po::variables_map vm;
//po::store( po::command_line_parser( argc, argv ).options( desc ).positional( p ).run( ), vm );
//po::notify( vm );
po::variables_map vm;
po::store( po::parse_command_line( argc, argv, desc ), vm );
po::notify( vm );
if( vm.count( "help" ) )
{
// This needs to be 'cout' as program-options does not support wcout yet
std::cout << desc << std::endl;
return 0;
}
if( vm.count( "queryOpenCL" ) )
{
print_clInfo = true;
}
// The following 3 options are not implemented yet; they are meant to be used with ::clCreateContextFromType()
if( vm.count( "gpu" ) )
{
deviceType = CL_DEVICE_TYPE_GPU;
}
if( vm.count( "cpu" ) )
{
deviceType = CL_DEVICE_TYPE_CPU;
}
if( vm.count( "all" ) )
{
deviceType = CL_DEVICE_TYPE_ALL;
}
}
catch( std::exception& e )
{
std::cout << _T( "Scan GoogleTest error condition reported:" ) << std::endl << e.what() << std::endl;
return 1;
}
// Query OpenCL for available platforms
cl_int err = CL_SUCCESS;
// Platform vector contains all available platforms on system
std::vector< cl::Platform > platforms;
//std::cout << "HelloCL!\nGetting Platform Information\n";
bolt::cl::V_OPENCL( cl::Platform::get( &platforms ), "Platform::get() failed" );
if( print_clInfo )
{
bolt::cl::control::printPlatforms( );
return 0;
}
// Do stuff with the platforms
std::vector<cl::Platform>::iterator i;
if(platforms.size() > 0)
{
for(i = platforms.begin(); i != platforms.end(); ++i)
{
if(!strcmp((*i).getInfo<CL_PLATFORM_VENDOR>(&err).c_str(), "Advanced Micro Devices, Inc."))
{
break;
}
}
}
bolt::cl::V_OPENCL( err, "Platform::getInfo() failed" );
// Device info
std::vector< cl::Device > devices;
bolt::cl::V_OPENCL( platforms.front( ).getDevices( CL_DEVICE_TYPE_ALL, &devices ),"Platform::getDevices() failed");
cl::Context myContext( devices.at( userDevice ) );
cl::CommandQueue myQueue( myContext, devices.at( userDevice ) );
bolt::cl::control::getDefault( ).setCommandQueue( myQueue );
std::string strDeviceName = bolt::cl::control::getDefault( ).getDevice( ).getInfo< CL_DEVICE_NAME >( &err );
bolt::cl::V_OPENCL( err, "Device::getInfo< CL_DEVICE_NAME > failed" );
std::cout << "Device under test : " << strDeviceName << std::endl;
int retVal = RUN_ALL_TESTS( );
// Reflection code to inspect how many tests failed in gTest
::testing::UnitTest& unitTest = *::testing::UnitTest::GetInstance( );
unsigned int failedTests = 0;
for( int i = 0; i < unitTest.total_test_case_count( ); ++i )
{
const ::testing::TestCase& testCase = *unitTest.GetTestCase( i );
for( int j = 0; j < testCase.total_test_count( ); ++j )
{
const ::testing::TestInfo& testInfo = *testCase.GetTestInfo( j );
if( testInfo.result( )->Failed( ) )
++failedTests;
}
}
// Print helpful message at termination if we detect errors, to help users figure out what to do next
if( failedTests )
{
bolt::tout << _T( "\nFailed tests detected in test pass; please run test again with:" ) << std::endl;
bolt::tout << _T( "\t--gtest_filter=<XXX> to select a specific failing test of interest" ) << std::endl;
bolt::tout << _T( "\t--gtest_catch_exceptions=0 to generate minidump of failing test, or" ) << std::endl;
bolt::tout << _T( "\t--gtest_break_on_failure to debug interactively with debugger" ) << std::endl;
bolt::tout << _T( "\t (only on googletest assertion failures, not SEH exceptions)" ) << std::endl;
}
return retVal;
}
| 39.194264 | 268 | 0.617615 | [
"object",
"vector",
"transform"
] |
3e3718336ca39977cd5c2c3ac36e882b942a24be | 322 | cpp | C++ | Dataset/Leetcode/train/53/283.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/53/283.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/53/283.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
int XXX(vector<int>& nums) {
int max = nums[0], temp = 0;
for(int i = 0; i < nums.size(); i++){
temp = temp + nums[i];
if(temp > max)
max = temp;
if(temp < 0)
temp = 0;
}
return max;
}
};
| 20.125 | 45 | 0.378882 | [
"vector"
] |
3e3ab29b0e8545e926619e5af35dda4bf6c5daf3 | 12,492 | cpp | C++ | src/datatypes/attributes.cpp | EmanuelHerrendorf/mapping-core | d28d85547e8ed08df37dad1da142594d3f07a366 | [
"MIT"
] | null | null | null | src/datatypes/attributes.cpp | EmanuelHerrendorf/mapping-core | d28d85547e8ed08df37dad1da142594d3f07a366 | [
"MIT"
] | 10 | 2018-03-02T13:58:32.000Z | 2020-06-05T11:12:42.000Z | src/datatypes/attributes.cpp | EmanuelHerrendorf/mapping-core | d28d85547e8ed08df37dad1da142594d3f07a366 | [
"MIT"
] | 3 | 2018-02-26T14:01:43.000Z | 2019-12-09T10:03:17.000Z |
#include "util/exceptions.h"
#include "datatypes/attributes.h"
#include "util/binarystream.h"
#include <limits>
AttributeMaps::AttributeMaps() {
}
AttributeMaps::~AttributeMaps() {
}
AttributeMaps::AttributeMaps(BinaryReadBuffer &buffer) {
deserialize(buffer);
}
void AttributeMaps::deserialize(BinaryReadBuffer &buffer) {
_numeric.empty();
_textual.empty();
auto count = buffer.read<size_t>();
for (size_t i=0;i<count;i++) {
auto key = buffer.read<std::string>();
auto value = buffer.read<double>();
_numeric[key] = value;
}
buffer.read(&count);
for (size_t i=0;i<count;i++) {
auto key = buffer.read<std::string>();
auto value = buffer.read<std::string>();
_textual[key] = value;
}
}
void AttributeMaps::serialize(BinaryWriteBuffer &buffer, bool) const {
size_t count = _numeric.size();
buffer.write(count);
for (auto &e : _numeric) {
buffer.write(e.first);
buffer.write(e.second);
}
count = _textual.size();
buffer.write(count);
for (auto &e : _textual) {
buffer.write(e.first);
buffer.write(e.second);
}
}
void AttributeMaps::setNumeric(const std::string &key, double value) {
if (_numeric.count(key) > 0)
throw AttributeException(concat("Cannot set numeric attribute ", key, " because it's already set."));
if (_textual.count(key) > 0)
throw AttributeException(concat("Cannot set numeric attribute ", key, " because a textual attribute with the same name exists"));
_numeric[key] = value;
}
void AttributeMaps::setTextual(const std::string &key, const std::string &value) {
if (_textual.count(key) > 0)
throw AttributeException(concat("Cannot set textual attribute ", key, " because it's already set."));
if (_numeric.count(key) > 0)
throw AttributeException(concat("Cannot set textual attribute ", key, " because a numeric attribute with the same name exists"));
_textual[key] = value;
}
double AttributeMaps::getNumeric(const std::string &key) const {
auto it = _numeric.find(key);
if (it == _numeric.end())
throw AttributeException(concat("Cannot get numeric attribute ", key, " because it does not exist"));
return it->second;
}
const std::string &AttributeMaps::getTextual(const std::string &key) const {
auto it = _textual.find(key);
if (it == _textual.end())
throw AttributeException(concat("Cannot get textual attribute ", key, " because it does not exist"));
return it->second;
}
double AttributeMaps::getNumeric(const std::string &key, double defaultvalue) const {
auto it = _numeric.find(key);
if (it == _numeric.end()) {
if (_textual.count("key"))
throw AttributeException(concat("Cannot get numeric attribute ", key, " when a textual attribute with the same name exists"));
return defaultvalue;
}
return it->second;
}
const std::string &AttributeMaps::getTextual(const std::string &key, const std::string &defaultvalue) const {
auto it = _textual.find(key);
if (it == _textual.end()) {
if (_numeric.count("key"))
throw AttributeException(concat("Cannot get textual attribute ", key, " when a numeric attribute with the same name exists"));
return defaultvalue;
}
return it->second;
}
/**
* AttributeArrays
*
* for SimpleFeatureCollections
*/
template <typename T>
void AttributeArrays::AttributeArray<T>::set(size_t idx, const T &value) {
if (idx == array.size()) {
array.push_back(value);
return;
}
if (array.size() < idx+1)
resize(idx+1);
array[idx] = value;
}
template <typename T>
AttributeArrays::AttributeArray<T>::AttributeArray(BinaryReadBuffer &buffer) : unit(Unit::UNINITIALIZED) {
deserialize(buffer);
}
template <typename T>
void AttributeArrays::AttributeArray<T>::deserialize(BinaryReadBuffer &buffer) {
auto unit_json = buffer.read<std::string>();
unit = Unit(unit_json);
buffer.read(&array);
}
template <typename T>
void AttributeArrays::AttributeArray<T>::serialize(BinaryWriteBuffer &buffer, bool is_persistent_memory) const {
buffer << unit.toJson();
buffer.write(array, is_persistent_memory);
}
template<typename T> struct defaultvalue {
static const T value;
};
template<>
const double defaultvalue<double>::value = std::numeric_limits<double>::quiet_NaN();
template<>
const std::string defaultvalue<std::string>::value = "";
template <typename T>
void AttributeArrays::AttributeArray<T>::resize(size_t size) {
array.resize(size, defaultvalue<T>::value);
}
template<typename T>
size_t AttributeArrays::AttributeArray<T>::get_byte_size() const {
return unit.get_byte_size() + SizeUtil::get_byte_size(array);
}
template<typename T>
AttributeArrays::AttributeArray<T> AttributeArrays::AttributeArray<T>::copy() const {
AttributeArray<T> res(unit);
res.array = array;
return res;
}
AttributeArrays::AttributeArrays() {
}
AttributeArrays::AttributeArrays(BinaryReadBuffer &buffer) {
deserialize(buffer);
}
AttributeArrays::~AttributeArrays() {
}
void AttributeArrays::deserialize(BinaryReadBuffer &buffer) {
auto keycount = buffer.read<size_t>();
for (size_t i=0;i<keycount;i++) {
auto key = buffer.read<std::string>();
auto res = _numeric.emplace(key, buffer);
if (res.second != true)
throw AttributeException("Cannot deserialize AttributeArrays");
}
buffer.read(&keycount);
for (size_t i=0;i<keycount;i++) {
auto key = buffer.read<std::string>();
auto res = _textual.emplace(key, buffer);
if (res.second != true)
throw AttributeException("Cannot deserialize AttributeArrays");
}
}
void AttributeArrays::serialize(BinaryWriteBuffer &buffer, bool is_persistent_memory) const {
size_t keycount = _numeric.size();
buffer << keycount;
for (const auto &e : _numeric) {
buffer << e.first << e.second;
}
keycount = _textual.size();
buffer << keycount;
for (const auto &e : _textual) {
buffer << e.first << e.second;
}
}
AttributeArrays AttributeArrays::clone() const {
AttributeArrays copy;
// The Array's copy constructor is neither callable from std::pair nor std::map.
// Thus, we need to make sure the copying takes place right here, because we're friends.
for (auto &pair : _numeric) {
auto arraycopy = pair.second;
copy._numeric.emplace(pair.first, std::move(arraycopy));
}
for (auto &pair : _textual) {
auto arraycopy = pair.second;
copy._textual.emplace(pair.first, std::move(arraycopy));
}
return copy;
}
void AttributeArrays::checkIfAttributeDoesNotExist(const std::string &key) {
if (_numeric.count(key) > 0)
throw AttributeException(concat("Cannot add attribute ", key, " because a numeric attribute with the same name exists."));
if (_textual.count(key) > 0)
throw AttributeException(concat("Cannot add attribute ", key, " because a textual attribute with the same name exists."));
}
AttributeArrays::AttributeArray<double> &AttributeArrays::addNumericAttribute(const std::string &key, const Unit &unit) {
checkIfAttributeDoesNotExist(key);
auto res = _numeric.emplace(key, unit);
if (res.second != true)
throw AttributeException(concat("Cannot add numeric attribute ", key, " because it exists already."));
return (res.first)->second;
}
AttributeArrays::AttributeArray<double> &AttributeArrays::addNumericAttribute(const std::string &key, const Unit &unit, std::vector<double> &&values) {
checkIfAttributeDoesNotExist(key);
auto res = _numeric.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(unit, std::move(values)));
if (res.second != true)
throw AttributeException(concat("Cannot add numeric attribute ", key, " because it exists already."));
return (res.first)->second;
}
AttributeArrays::AttributeArray<std::string> &AttributeArrays::addTextualAttribute(const std::string &key, const Unit &unit) {
checkIfAttributeDoesNotExist(key);
auto res = _textual.emplace(key, unit);
if (res.second != true)
throw AttributeException(concat("Cannot add textual attribute ", key, " because it exists already."));
return (res.first)->second;
}
AttributeArrays::AttributeArray<std::string> &AttributeArrays::addTextualAttribute(const std::string &key, const Unit &unit, std::vector<std::string> &&values) {
checkIfAttributeDoesNotExist(key);
auto res = _textual.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(unit, std::move(values)));
if (res.second != true)
throw AttributeException(concat("Cannot add textual attribute ", key, " because it exists already."));
return (res.first)->second;
}
std::vector<std::string> AttributeArrays::getNumericKeys() const {
std::vector<std::string> keys;
for (auto &p : _numeric) {
keys.push_back(p.first);
}
return keys;
}
std::vector<std::string> AttributeArrays::getTextualKeys() const {
std::vector<std::string> keys;
for (auto &p : _textual) {
keys.push_back(p.first);
}
return keys;
}
template<typename T>
AttributeArrays AttributeArrays::filter_impl(const std::vector<T> &keep, size_t kept_count) const {
// If the kept_count wasn't provided, start counting
if (kept_count == 0) {
for (auto b : keep) {
if (b)
kept_count++;
}
}
AttributeArrays out;
for (auto &p : _numeric) {
const auto &in_array = p.second;
if (in_array.array.size() != keep.size())
throw AttributeException("Cannot filter Attributes when the keep vector has a different size than the attribute vectors");
auto &out_array = out.addNumericAttribute(p.first, in_array.unit);
out_array.array.reserve(kept_count);
for (size_t in_idx = 0; in_idx < keep.size(); in_idx++) {
if (keep[in_idx])
out_array.array.push_back(in_array.array[in_idx]);
}
}
for (auto &p : _textual) {
const auto &in_array = p.second;
if (in_array.array.size() != keep.size())
throw AttributeException("Cannot filter Attributes when the keep vector has a different size than the attribute vectors");
auto &out_array = out.addTextualAttribute(p.first, in_array.unit);
out_array.array.reserve(kept_count);
for (size_t in_idx = 0; in_idx < keep.size(); in_idx++) {
if (keep[in_idx])
out_array.array.push_back(in_array.array[in_idx]);
}
}
return out;
}
AttributeArrays AttributeArrays::filter(const std::vector<bool> &keep, size_t kept_count) const {
return filter_impl<bool>(keep, kept_count);
}
AttributeArrays AttributeArrays::filter(const std::vector<char> &keep, size_t kept_count) const {
return filter_impl<char>(keep, kept_count);
}
void AttributeArrays::validate(size_t expected_values) const {
for (auto &n : _numeric) {
if (n.second.array.size() != expected_values)
throw AttributeException(concat("Numeric attribute array ", n.first, " does not contain the expected amount of values (expected: ", expected_values, " actual: ", n.second.array.size(), ")"));
}
for (auto &n : _textual) {
if (n.second.array.size() != expected_values)
throw AttributeException(concat("Textual attribute array ", n.first, " does not contain the expected amount of values (expected: ", expected_values, " actual: ", n.second.array.size(), ")"));
}
}
size_t AttributeArrays::get_byte_size() const {
return SizeUtil::get_byte_size(_textual) + SizeUtil::get_byte_size(_numeric);
}
AttributeArrays AttributeArrays::copy() const {
AttributeArrays res;
for ( auto &e : _numeric )
res._numeric.emplace(e.first,e.second.copy());
for ( auto &e : _textual )
res._textual.emplace(e.first,e.second.copy());
return res;
}
// Instantiate as required
template class AttributeArrays::AttributeArray<double>;
template class AttributeArrays::AttributeArray<std::string>;
void AttributeArrays::resize(size_t size) {
for(std::string key : getTextualKeys()) {
textual(key).resize(size);
}
for(std::string key : getNumericKeys()) {
numeric(key).resize(size);
}
}
void AttributeArrays::renameNumericAttribute(const std::string &oldKey, const std::string &newKey) {
if (_numeric.count(oldKey) < 1)
throw ArgumentException("AttributeArray::rename oldKey does not exist");
if (_numeric.count(newKey) > 0)
throw ArgumentException("AttributeArray::rename newKey already exist");
AttributeArray<double> &temp = _numeric.at(oldKey);
_numeric.insert(std::make_pair(newKey, std::move(temp)));
_numeric.erase(oldKey);
}
void AttributeArrays::renameTextualAttribute(const std::string &oldKey, const std::string &newKey) {
if (_textual.count(oldKey) < 1)
throw ArgumentException("AttributeArray::rename oldKey does not exist");
if (_textual.count(newKey) > 0)
throw ArgumentException("AttributeArray::rename newKey already exist");
AttributeArray<std::string> &temp = _textual.at(oldKey);
_textual.insert(std::make_pair(newKey, std::move(temp)));
_textual.erase(oldKey);
}
| 31.867347 | 194 | 0.725504 | [
"vector"
] |
3e3edc8f8179dcc1cf3f42998f7955e2e4068e73 | 21,756 | cpp | C++ | libgramtools/tests/genotype/quasimap/coverage/test_allele_base.cpp | bricoletc/gramtools | 1ce06178b7b26f42d72e47d3d7b8a7a606e6f256 | [
"MIT"
] | null | null | null | libgramtools/tests/genotype/quasimap/coverage/test_allele_base.cpp | bricoletc/gramtools | 1ce06178b7b26f42d72e47d3d7b8a7a606e6f256 | [
"MIT"
] | null | null | null | libgramtools/tests/genotype/quasimap/coverage/test_allele_base.cpp | bricoletc/gramtools | 1ce06178b7b26f42d72e47d3d7b8a7a606e6f256 | [
"MIT"
] | null | null | null | #include <cctype>
#include "gtest/gtest.h"
#include "genotype/quasimap/coverage/allele_base.hpp"
#include "submod_resources.hpp"
#include "test_resources.hpp"
using namespace gram::submods;
using namespace gram::coverage::per_base;
TEST(AlleleBaseCoverageDump, GivenPopulatedAlleleBaseCoverage_CorrectJsonDump) {
SitesAlleleBaseCoverage allele_base_coverage = {
SitePbCoverage{
PerBaseCoverage{1, 12},
PerBaseCoverage{0, 3, 0},
},
SitePbCoverage{
PerBaseCoverage{0},
PerBaseCoverage{0, 19, 0},
},
};
auto result = dump_allele_base_coverage(allele_base_coverage);
std::string expected =
"{\"allele_base_counts\":[[[1,12],[0,3,0]],[[0],[0,19,0]]]}";
EXPECT_EQ(result, expected);
}
TEST(AlleleBaseCoverageDump,
GivenSingleSiteAlleleBaseCoverage_CorrectJsonDump) {
SitesAlleleBaseCoverage allele_base_coverage = {SitePbCoverage{
PerBaseCoverage{1, 12},
PerBaseCoverage{0, 3, 0},
}};
auto result = dump_allele_base_coverage(allele_base_coverage);
std::string expected = "{\"allele_base_counts\":[[[1,12],[0,3,0]]]}";
EXPECT_EQ(result, expected);
}
TEST(AlleleBaseCoverageDump, GivenEmptyAlleleBaseCoverage_CorrectJsonDump) {
SitesAlleleBaseCoverage allele_base_coverage = {};
auto result = dump_allele_base_coverage(allele_base_coverage);
std::string expected = "{\"allele_base_counts\":[]}";
EXPECT_EQ(result, expected);
}
TEST(AlleleBaseCoverageStructure, GivenNestedCovGraph_EmptyStructure) {
auto prg_raw = prg_string_to_ints("[AC[TG,CC]T,T]A");
auto prg_info = generate_prg_info(prg_raw);
SitesAlleleBaseCoverage expected{};
auto actual = coverage::generate::allele_base_non_nested(prg_info);
EXPECT_EQ(actual, expected);
}
TEST(AlleleBaseCoverageStructure,
GivenNonNestedCovGraphOneSite_CorrectStructure) {
auto prg_raw = encode_prg("ac5gg6ga6ccc6c6aaa");
auto prg_info = generate_prg_info(prg_raw);
SitesAlleleBaseCoverage expected{
SitePbCoverage{PerBaseCoverage{0, 0}, PerBaseCoverage{0, 0},
PerBaseCoverage{0, 0, 0}, PerBaseCoverage{0}}};
auto actual = coverage::generate::allele_base_non_nested(prg_info);
EXPECT_EQ(actual, expected);
}
TEST(AlleleBaseCoverageStructure,
GivenNonNestedCovGraphTwoSitesAndOneEmptyAllele_CorrectStructure) {
auto prg_raw = prg_string_to_ints("ac[a,c,tt]atg[gggg,,a]cc");
auto prg_info = generate_prg_info(prg_raw);
SitesAlleleBaseCoverage expected{SitePbCoverage{{0}, {0}, {0, 0}},
SitePbCoverage{{0, 0, 0, 0}, {}, {0}}};
auto actual = coverage::generate::allele_base_non_nested(prg_info);
EXPECT_EQ(actual, expected);
}
TEST(DummyCovNode, BuildWithSizeSmallerThanEndCoord_ThrowsException) {
EXPECT_THROW(DummyCovNode(0, 5, 3), InconsistentCovNodeCoordinates);
}
TEST(DummyCovNode, BuildWithStartGreaterThanEnd_ThrowsException) {
EXPECT_THROW(DummyCovNode(2, 1, 3), InconsistentCovNodeCoordinates);
}
TEST(DummyCovNode, ExtendWithEndPosGreaterThanNodeSize_ThrowsException) {
auto d = DummyCovNode(1, 5, 6);
EXPECT_THROW(d.extend_coordinates({0, 6}), InconsistentCovNodeCoordinates);
}
TEST(DummyCovNode, ExtendNoStartAndNoEnd_CorrectUnchangesCoordinates) {
auto d = DummyCovNode(1, 5, 6);
d.extend_coordinates({2, 5});
node_coordinates expected_coords{1, 5};
EXPECT_EQ(expected_coords, d.get_coordinates());
}
TEST(DummyCovNode, ExtendStartAndEnd_CorrectExtendedCoordinates) {
auto d = DummyCovNode(3, 3, 6);
d.extend_coordinates({0, 5});
node_coordinates expected_coords{0, 5};
EXPECT_EQ(expected_coords, d.get_coordinates());
}
TEST(Traverser, StartOutOfSiteEndInSite_correctObjectState) {
auto prg_raw = encode_prg("CT5gg6AAGa6cc");
auto prg_info = generate_prg_info(prg_raw);
std::size_t read_size = 5;
VariantSitePath traversed_path{VariantLocus{5, FIRST_ALLELE + 1}};
auto start_point = prg_info.coverage_graph.random_access[0];
Traverser t{start_point, traversed_path, read_size};
auto variant_node = t.next_Node().value();
EXPECT_EQ(variant_node->get_site_ID(), 5);
EXPECT_EQ(variant_node->get_allele_ID(), FIRST_ALLELE + 1);
std::pair<uint32_t, uint32_t> expected_coordinates{0, 2};
EXPECT_EQ(expected_coordinates, t.get_node_coordinates());
EXPECT_EQ(false, t.next_Node().has_value());
}
TEST(Traverser, StartAndEndInSite_CorrectNodeInterval) {
auto prg_raw = encode_prg("ct5g6aaAAAAAAaga6cc");
auto prg_info = generate_prg_info(prg_raw);
std::size_t read_size = 6;
// Empty because the fact we are in VariantLocus{5, 2} is recorded in
// traversing_path container
VariantSitePath traversed_path{};
auto start_point = prg_info.coverage_graph.random_access[7];
Traverser t{start_point, traversed_path, read_size};
auto variant_node = t.next_Node().value();
std::pair<uint32_t, uint32_t> expected_coordinates{2, 7};
EXPECT_EQ(expected_coordinates, t.get_node_coordinates());
}
TEST(Traverser, StartInSiteAndTraverseToAnotherSite_CorrectObjectState) {
auto prg_raw = encode_prg("ct5g6aAA6CC7gc8ga8AAAAa8");
auto prg_info = generate_prg_info(prg_raw);
std::size_t read_size = 8;
VariantSitePath traversed_path{VariantLocus{7, FIRST_ALLELE + 2}};
auto start_point = prg_info.coverage_graph.random_access[6];
Traverser t{start_point, traversed_path, read_size};
auto cur_Node = t.next_Node();
auto variant_node = cur_Node;
while (cur_Node.has_value()) {
variant_node = cur_Node;
cur_Node = t.next_Node();
}
std::pair<uint32_t, uint32_t> expected_coordinates{0, 3};
EXPECT_EQ(expected_coordinates, t.get_node_coordinates());
EXPECT_EQ(0, t.get_remaining_bases());
}
// Helper function to get all the loci that were traversed. Modifies the
// traversal in place
VariantSitePath collect_traversal(Traverser& t) {
VariantSitePath traversal;
VariantLocus site_and_allele;
auto cur_Node = t.next_Node();
while (bool(cur_Node)) {
site_and_allele = {cur_Node.value()->get_site_ID(),
cur_Node.value()->get_allele_ID()};
traversal.push_back(site_and_allele);
cur_Node = t.next_Node();
}
return traversal;
}
TEST(Traverser_Nested,
StartOutOfSiteEndOutOfSite_CorrectChosenSitesAndEndState) {
std::string raw_prg = "A[ctt,G[AAA,a]T]CCccc";
marker_vec v = prg_string_to_ints(raw_prg);
auto prg_info = generate_prg_info(v);
std::size_t read_size = 8;
VariantSitePath traversed_path{VariantLocus{7, FIRST_ALLELE},
VariantLocus{5, FIRST_ALLELE + 1}};
auto start_point = prg_info.coverage_graph.random_access[0];
Traverser t{start_point, traversed_path, read_size};
VariantSitePath expected_traversal{
VariantLocus{5, FIRST_ALLELE + 1}, VariantLocus{7, FIRST_ALLELE},
VariantLocus{
5, FIRST_ALLELE + 1} // After exiting site 7, we still have coverage
// to record on allele 2 of site 5 (base 'T')
};
VariantSitePath actual_traversal = collect_traversal(t);
EXPECT_EQ(expected_traversal, actual_traversal);
// Make sure we have consumed all bases of the read
EXPECT_EQ(0, t.get_remaining_bases());
// Make sure we are placed correctly in the last node
std::pair<uint32_t, uint32_t> expected_last_node_coords{0, 1};
EXPECT_EQ(expected_last_node_coords, t.get_node_coordinates());
}
TEST(Traverser_Nested,
TraverseGraphWithLevel2Nesting_CorrectChosenSitesAndEndState) {
std::string raw_prg = "A[CT[GC[c,A]A,gc]T[C,a]Tt,t]c";
marker_vec v = prg_string_to_ints(raw_prg);
auto prg_info = generate_prg_info(v);
std::size_t read_size = 10;
VariantSitePath traversed_path{
VariantLocus{11, FIRST_ALLELE}, VariantLocus{9, FIRST_ALLELE + 1},
VariantLocus{7, FIRST_ALLELE}, VariantLocus{5, FIRST_ALLELE}};
auto start_point = prg_info.coverage_graph.random_access[0];
Traverser t{start_point, traversed_path, read_size};
VariantSitePath expected_traversal{
VariantLocus{5, FIRST_ALLELE}, VariantLocus{7, FIRST_ALLELE},
VariantLocus{9, FIRST_ALLELE + 1}, VariantLocus{7, FIRST_ALLELE},
VariantLocus{5, FIRST_ALLELE}, VariantLocus{11, FIRST_ALLELE},
VariantLocus{5, FIRST_ALLELE},
};
VariantSitePath actual_traversal = collect_traversal(t);
EXPECT_EQ(expected_traversal, actual_traversal);
EXPECT_EQ(0, t.get_remaining_bases());
std::pair<uint32_t, uint32_t> expected_last_node_coords{0, 0};
EXPECT_EQ(expected_last_node_coords, t.get_node_coordinates());
}
TEST(PbCovRecorder_NodeProcessing, ProcessNewCovNode_CorrectDummyCovNodeMade) {
PbCovRecorder pb_rec;
covG_ptr cov_node =
boost::make_shared<coverage_Node>(coverage_Node{"ACTG", 102, 5, 2});
realCov_to_dummyCov expected_mapping{{cov_node, DummyCovNode(1, 3, 4)}};
pb_rec.process_Node(cov_node, 1, 3);
EXPECT_EQ(expected_mapping, pb_rec.get_cov_mapping());
}
TEST(PbCovRecorder_NodeProcessing,
ProcessExistingCovNode_CorrectlyUpdatedDummyCovNode) {
covG_ptr cov_node =
boost::make_shared<coverage_Node>(coverage_Node{"ACTGCC", 99, 5, 2});
realCov_to_dummyCov existing_mapping{{cov_node, DummyCovNode{1, 3, 6}}};
PbCovRecorder pb_rec(existing_mapping);
pb_rec.process_Node(cov_node, 2, 5);
realCov_to_dummyCov expected_mapping{{cov_node, DummyCovNode(1, 5, 6)}};
EXPECT_EQ(expected_mapping, pb_rec.get_cov_mapping());
}
/**
* Tests full coverage recording by inspecting `DummyCovNode`s and
* `coverage_Node`s
*/
using dummy_cov_nodes = std::vector<DummyCovNode>;
dummy_cov_nodes collect_dummy_cov_nodes(coverage_Graph const& cov_graph,
prg_positions positions,
realCov_to_dummyCov cov_mapping) {
dummy_cov_nodes result(positions.size());
covG_ptr accessed_node;
std::size_t index{0};
for (auto& pos : positions) {
accessed_node = cov_graph.random_access[pos].node;
if (cov_mapping.find(accessed_node) == cov_mapping.end())
result[index] = DummyCovNode{};
else
result[index] = cov_mapping.at(accessed_node);
index++;
}
return result;
}
/*
PRG: GCT5C6G6T6AG7T8CC8CT
i BWT SA text_suffix
0 T 20
1 6 10 A G 7 T 8 C C 8 C T
2 8 15 C C 8 C T
3 8 18 C T
4 G 1 C T 5 C 6 G 6 T 6 A G 7 T 8 C C 8 C T
5 5 4 C 6 G 6 T 6 A G 7 T 8 C C 8 C T
6 C 16 C 8 C T
7 0 0 G C T 5 C 6 G 6 T 6 A G 7 T 8 C C 8 C T
8 6 6 G 6 T 6 A G 7 T 8 C C 8 C T
9 A 11 G 7 T 8 C C 8 C T
10 C 19 T
11 C 2 T 5 C 6 G 6 T 6 A G 7 T 8 C C 8 C T
12 6 8 T 6 A G 7 T 8 C C 8 C T
13 7 13 T 8 C C 8 C T
14 T 3 5 C 6 G 6 T 6 A G 7 T 8 C C 8 C T
15 T 9 6 A G 7 T 8 C C 8 C T
16 C 5 6 G 6 T 6 A G 7 T 8 C C 8 C T
17 G 7 6 T 6 A G 7 T 8 C C 8 C T
18 G 12 7 T 8 C C 8 C T
19 T 14 8 C C 8 C T
20 C 17 8 C T
*/
class PbCovRecorder_TwoSitesNoNesting : public ::testing::Test {
protected:
void SetUp() {
std::string raw_prg = "GCT5C6G6T6AG7T8CC8CT";
marker_vec v = encode_prg(raw_prg);
prg_info = generate_prg_info(v);
}
PRG_Info prg_info;
prg_positions all_sequence_node_positions{0, 4, 6, 8, 10, 13, 15, 18};
// Read: CTGAGC from pos 1
std::size_t read1_size = 6;
SearchState read_1{SA_Interval{4, 4}, VariantSitePath{
VariantLocus{7, FIRST_ALLELE + 1},
VariantLocus{5, FIRST_ALLELE + 1},
}};
// Read: TAGCCC from pos 8
std::size_t read2_size = 7;
SearchState read_2{SA_Interval{12, 12}, VariantSitePath{
VariantLocus{7, FIRST_ALLELE + 1},
}};
};
TEST_F(PbCovRecorder_TwoSitesNoNesting,
ReadCoversTwoSites_CorrectCoverageNodes) {
// PRG: "gCT5c6G6t6AG7t8Cc8ct" ; Read: "CTGAGC"
PbCovRecorder{prg_info, SearchStates{read_1}, read1_size};
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{PerBaseCoverage{}, PerBaseCoverage{0},
PerBaseCoverage{1}, PerBaseCoverage{0},
PerBaseCoverage{}, PerBaseCoverage{0},
PerBaseCoverage{1, 0}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
}
TEST_F(PbCovRecorder_TwoSitesNoNesting,
ReadCoversTwoSites2_CorrectCoverageNodes) {
// PRG: "GCT5C6G6T6AG7T8CC8CT" ; Read: "TAGCCC"
PbCovRecorder{prg_info, SearchStates{read_2}, read2_size};
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{PerBaseCoverage{}, PerBaseCoverage{0},
PerBaseCoverage{0}, PerBaseCoverage{1},
PerBaseCoverage{}, PerBaseCoverage{0},
PerBaseCoverage{1, 1}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
}
/*
PRG: AAT[ATAT,AA,]AGG
i BWT SA text_suffix
0 G 16 0
1 0 0 A A T 5 A T A T 6 A A 6 6 A G G 0
2 6 9 A A 6 6 A G G 0
3 6 13 A G G 0
4 5 4 A T A T 6 A A 6 6 A G G 0
5 A 1 A T 5 A T A T 6 A A 6 6 A G G 0
6 T 6 A T 6 A A 6 6 A G G 0
7 A 10 A 6 6 A G G 0
8 G 15 G 0
9 A 14 G G 0
10 A 5 T A T 6 A A 6 6 A G G 0
11 A 2 T 5 A T A T 6 A A 6 6 A G G 0
12 A 7 T 6 A A 6 6 A G G 0
13 T 3 5 A T A T 6 A A 6 6 A G G 0
14 T 8 6 A A 6 6 A G G 0
15 6 12 6 A G G 0
16 A 11 6 6 A G G 0
*/
class PbCovRecorder_WithRepeatsAndEmptyAllele : public ::testing::Test {
protected:
void SetUp() {
std::string raw_prg = "AAT[ATAT,AA,]AGG";
marker_vec v = prg_string_to_ints(raw_prg);
prg_info = generate_prg_info(v);
}
PRG_Info prg_info;
prg_positions all_sequence_node_positions{0, 4, 9, 12};
// Read: ATAT, occurs twice: from pos 1 and from pos 4
std::size_t read1_size = 4;
SearchStates read_1{
SearchState{SA_Interval{4, 4}, VariantSitePath{}},
SearchState{SA_Interval{5, 5},
VariantSitePath{VariantLocus{5, FIRST_ALLELE}}}};
// Read: ATAAA, occurs from pos 1
std::size_t read2_size = 5;
SearchState read_2{SearchState{
SA_Interval{5, 5}, VariantSitePath{VariantLocus{5, FIRST_ALLELE + 1}}}};
// Read: AATAGG, occurs from pos 0, goes through deletion
std::size_t read3_size = 5;
SearchState read_3{SearchState{
SA_Interval{1, 1}, VariantSitePath{VariantLocus{5, FIRST_ALLELE + 2}}}};
};
TEST_F(PbCovRecorder_WithRepeatsAndEmptyAllele,
RepeatedMultiMappedRead_CoverageOnlyAddedOnce) {
// PRG: "AAT[ATAT,AA,]AGG" ; Read: ATAT
PbCovRecorder{prg_info, read_1, read1_size};
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{PerBaseCoverage{},
PerBaseCoverage{1, 1, 1, 1},
PerBaseCoverage{0, 0}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
}
TEST_F(PbCovRecorder_WithRepeatsAndEmptyAllele,
MapAReadMultipleSeparateTimes_CoverageCorrectlyMultiplyAdded) {
// PRG: "AAT[ATAT,AA]AGG" ; Read: ATAAA
uint16_t i;
for (i = 0; i <= 2; i++)
PbCovRecorder{prg_info, SearchStates{read_2}, read2_size};
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{PerBaseCoverage{},
PerBaseCoverage{0, 0, 0, 0},
PerBaseCoverage{3, 3}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
// Collect coverage on the deletion read: ATAGG
// No pb coverage recorded for it as it is not represented as a node
for (i = 0; i <= 4; i++)
PbCovRecorder{prg_info, SearchStates{read_3}, read3_size};
actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
EXPECT_EQ(expected_coverage, actual_coverage);
}
/*
PRG: AT[GC[GCC,CCGC],T]TTTT
i BWT SA text_suffix
0 T 22 0
1 0 0 A T 5 G C 7 G C C 8 C C G C 8 6 T 6 T T T T 0
2 8 10 C C G C 8 6 T 6 T T T T 0
3 G 7 C C 8 C C G C 8 6 T 6 T T T T 0
4 C 11 C G C 8 6 T 6 T T T T 0
5 G 4 C 7 G C C 8 C C G C 8 6 T 6 T T T T 0
6 C 8 C 8 C C G C 8 6 T 6 T T T T 0
7 G 13 C 8 6 T 6 T T T T 0
8 7 6 G C C 8 C C G C 8 6 T 6 T T T T 0
9 5 3 G C 7 G C C 8 C C G C 8 6 T 6 T T T T 0
10 C 12 G C 8 6 T 6 T T T T 0
11 T 21 T 0
12 T 20 T T 0
13 T 19 T T T 0
14 6 18 T T T T 0
15 A 1 T 5 G C 7 G C C 8 C C G C 8 6 T 6 T T T T 0
16 6 16 T 6 T T T T 0
17 T 2 5 G C 7 G C C 8 C C G C 8 6 T 6 T T T T 0
18 T 17 6 T T T T 0
19 8 15 6 T 6 T T T T 0
20 C 5 7 G C C 8 C C G C 8 6 T 6 T T T T 0
21 C 9 8 C C G C 8 6 T 6 T T T T 0
22 C 14 8 6 T 6 T T T T 0
*/
class PbCovRecorder_nestedDeletion : public ::testing::Test {
protected:
void SetUp() {
std::string raw_prg = "AT[GC[GCC,CCGC],T]TTTT";
marker_vec v = prg_string_to_ints(raw_prg);
prg_info = generate_prg_info(v);
}
PRG_Info prg_info;
prg_positions all_sequence_node_positions{0, 3, 6, 10, 16, 18};
// Make some read SearchStates
// Read: CGCCTT
SearchState simple_read_1{SA_Interval{5, 5},
VariantSitePath{VariantLocus{7, FIRST_ALLELE}}};
// Read: ATTTT
SearchState simple_read_2{SA_Interval{1, 1},
VariantSitePath{VariantLocus{5, FIRST_ALLELE + 1}}};
// Read: GCC. Two distinct occurrences compatible with same sites
SearchStates multi_mapped_reads_1{
SearchState{SA_Interval{9, 9},
VariantSitePath{VariantLocus{7, FIRST_ALLELE + 1}}},
SearchState{SA_Interval{8, 8}, VariantSitePath{}}};
// Read: CTT. In a single Search State
SearchStates multi_mapped_reads_2{
SearchState{SA_Interval{6, 7}, VariantSitePath{}}};
};
TEST_F(PbCovRecorder_nestedDeletion, simpleRead1Mapped_correctDummyCovNodes) {
// PRG: "AT[GC[GCC,CCGC],T]TTTT"; Read: "CGCCTT"
std::size_t read_size{6};
PbCovRecorder recorder(prg_info, read_size);
recorder.process_SearchState(simple_read_1);
auto actual_dummies = collect_dummy_cov_nodes(prg_info.coverage_graph,
all_sequence_node_positions,
recorder.get_cov_mapping());
dummy_cov_nodes expected_dummies{DummyCovNode{}, DummyCovNode{1, 1, 2},
DummyCovNode{0, 2, 3}, DummyCovNode{},
DummyCovNode{}, DummyCovNode{}};
EXPECT_EQ(expected_dummies, actual_dummies);
}
TEST_F(PbCovRecorder_nestedDeletion,
simpleRead1Mapped_correctRecordedPbCoverage) {
// PRG: "AT[GC[GCC,CCGC],T]TTTT"; Read: "CGCCTT"
SearchStates mapping{simple_read_1};
std::size_t read_size{6};
PbCovRecorder recorder(prg_info, mapping, read_size);
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{
PerBaseCoverage{}, PerBaseCoverage{0, 1},
PerBaseCoverage{1, 1, 1}, PerBaseCoverage{0, 0, 0, 0},
PerBaseCoverage{0}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
}
TEST_F(PbCovRecorder_nestedDeletion, simpleRead2Mapped_correctDummyCovNodes) {
// PRG: "AT[GC[GCC,CCGC],T]TTTT"; Read: "ATTTT"
SearchStates mapping = SearchStates{simple_read_2};
std::size_t read_size{5};
PbCovRecorder recorder(prg_info, read_size);
recorder.process_SearchState(simple_read_2);
auto actual_dummies = collect_dummy_cov_nodes(prg_info.coverage_graph,
all_sequence_node_positions,
recorder.get_cov_mapping());
dummy_cov_nodes expected_dummies{DummyCovNode{}, DummyCovNode{},
DummyCovNode{}, DummyCovNode{},
DummyCovNode{0, 0, 1}, DummyCovNode{}};
EXPECT_EQ(expected_dummies, actual_dummies);
}
TEST_F(PbCovRecorder_nestedDeletion,
simpleRead2Mapped_correctRecordedPbCoverage) {
// PRG: "AT[GC[GCC,CCGC],T]TTTT"; Read: "ATTTT"
SearchStates mapping{simple_read_2};
std::size_t read_size{5};
PbCovRecorder recorder(prg_info, mapping, read_size);
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{
PerBaseCoverage{}, PerBaseCoverage{0, 0},
PerBaseCoverage{0, 0, 0}, PerBaseCoverage{0, 0, 0, 0},
PerBaseCoverage{1}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
}
TEST_F(PbCovRecorder_nestedDeletion,
multiMappedReadDistinctSearchStates_correctRecordedPbCoverage) {
// PRG: "AT[GC[GCC,CCGC],T]TTTT"; Read: "GCC"
std::size_t read_size{3};
PbCovRecorder{prg_info, multi_mapped_reads_1, read_size};
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{
PerBaseCoverage{}, PerBaseCoverage{1, 1},
PerBaseCoverage{1, 1, 1}, PerBaseCoverage{1, 0, 0, 0},
PerBaseCoverage{0}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
}
TEST_F(PbCovRecorder_nestedDeletion,
multiMappedReadSingleSearchState_correctRecordedPbCoverage) {
// PRG: "AT[GC[GCC,CCGC],T]TTTT"; Read: "CTTT"
std::size_t read_size{4};
PbCovRecorder{prg_info, multi_mapped_reads_2, read_size};
auto actual_coverage =
collect_coverage(prg_info.coverage_graph, all_sequence_node_positions);
SitePbCoverage expected_coverage{
PerBaseCoverage{}, PerBaseCoverage{0, 0},
PerBaseCoverage{0, 0, 1}, PerBaseCoverage{0, 0, 0, 1},
PerBaseCoverage{0}, PerBaseCoverage{}};
EXPECT_EQ(expected_coverage, actual_coverage);
}
| 36.079602 | 80 | 0.689511 | [
"vector"
] |
3e40310757bd594c2f5851ba6c528c65e289d613 | 927 | hpp | C++ | host-bmc/dbus/global.hpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | null | null | null | host-bmc/dbus/global.hpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | null | null | null | host-bmc/dbus/global.hpp | raviteja-b/pldm | 413866955ff9b3dca362d8f9c7a77cd7670f37dc | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "serialize.hpp"
#include <sdbusplus/bus.hpp>
#include <sdbusplus/server.hpp>
#include <sdbusplus/server/object.hpp>
#include <xyz/openbmc_project/Inventory/Item/Global/server.hpp>
#include <string>
namespace pldm
{
namespace dbus
{
using ItemGlobal = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::Inventory::Item::server::Global>;
class Global : public ItemGlobal
{
public:
Global() = delete;
~Global() = default;
Global(const Global&) = delete;
Global& operator=(const Global&) = delete;
Global(Global&&) = default;
Global& operator=(Global&&) = default;
Global(sdbusplus::bus::bus& bus, const std::string& objPath) :
ItemGlobal(bus, objPath.c_str()), path(objPath)
{
pldm::serialize::Serialize::getSerialize().serialize(path, "Global");
}
private:
std::string path;
};
} // namespace dbus
} // namespace pldm
| 22.609756 | 77 | 0.68069 | [
"object"
] |
3e421cfeac6a62c0a867467405230dc41a825d08 | 21,971 | cc | C++ | tensorflow/lite/delegates/gpu/metal/kernels/depthwise_conv.cc | kuroko1t/tensorflow | cd567562de4743dad0ff8a33cceceac3d53f0a13 | [
"Apache-2.0"
] | 5 | 2021-04-01T15:14:48.000Z | 2021-04-02T02:56:07.000Z | tensorflow/lite/delegates/gpu/metal/kernels/depthwise_conv.cc | kuroko1t/tensorflow | cd567562de4743dad0ff8a33cceceac3d53f0a13 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/delegates/gpu/metal/kernels/depthwise_conv.cc | kuroko1t/tensorflow | cd567562de4743dad0ff8a33cceceac3d53f0a13 | [
"Apache-2.0"
] | 1 | 2022-01-11T00:57:23.000Z | 2022-01-11T00:57:23.000Z | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/delegates/gpu/metal/kernels/depthwise_conv.h"
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "absl/strings/substitute.h"
#include "absl/types/span.h"
#include "tensorflow/lite/delegates/gpu/common/convert.h"
#include "tensorflow/lite/delegates/gpu/common/model.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
#include "tensorflow/lite/delegates/gpu/common/util.h"
#include "tensorflow/lite/delegates/gpu/metal/compute_task_descriptor.h"
namespace tflite {
namespace gpu {
namespace metal {
namespace {
std::string GetKernelDepthWiseConv3x3Stride1x1() {
std::string code = R"(
kernel void ComputeFunction($0
uint3 ugid[[thread_position_in_grid]])
{
int gid_x = ugid.x * 2;
int gid_y = ugid.y * 2;
int gid_z = ugid.z;
if (gid_x >= args.dst_tensor.Width() || gid_y >= args.dst_tensor.Height()) {
return;
}
ACCUM_FLT4 r0 = ACCUM_FLT4(0.0f, 0.0f, 0.0f, 0.0f);
ACCUM_FLT4 l0 = ACCUM_FLT4(0.0f, 0.0f, 0.0f, 0.0f);
ACCUM_FLT4 t0 = ACCUM_FLT4(0.0f, 0.0f, 0.0f, 0.0f);
ACCUM_FLT4 b0 = ACCUM_FLT4(0.0f, 0.0f, 0.0f, 0.0f);
int x0 = gid_x + args.padding_x;
int x1 = gid_x + args.padding_x + 1;
int x2 = gid_x + args.padding_x + 2;
int x3 = gid_x + args.padding_x + 3;
int y0 = gid_y + args.padding_y;
int y1 = gid_y + args.padding_y + 1;
int y2 = gid_y + args.padding_y + 2;
int y3 = gid_y + args.padding_y + 3;
bool x0_out = x0 < 0 || x0 >= args.src_tensor.Width();
bool x1_out = x1 < 0 || x1 >= args.src_tensor.Width();
bool x2_out = x2 < 0 || x2 >= args.src_tensor.Width();
bool x3_out = x3 < 0 || x3 >= args.src_tensor.Width();
bool y0_out = y0 < 0 || y0 >= args.src_tensor.Height();
bool y1_out = y1 < 0 || y1 >= args.src_tensor.Height();
bool y2_out = y2 < 0 || y2 >= args.src_tensor.Height();
bool y3_out = y3 < 0 || y3 >= args.src_tensor.Height();
x0 = clamp(x0, 0, args.src_tensor.Width() - 1);
x1 = clamp(x1, 0, args.src_tensor.Width() - 1);
x2 = clamp(x2, 0, args.src_tensor.Width() - 1);
x3 = clamp(x3, 0, args.src_tensor.Width() - 1);
y0 = clamp(y0, 0, args.src_tensor.Height() - 1);
y1 = clamp(y1, 0, args.src_tensor.Height() - 1);
y2 = clamp(y2, 0, args.src_tensor.Height() - 1);
y3 = clamp(y3, 0, args.src_tensor.Height() - 1);
device FLT4* src_loc = args.src_tensor.GetPtrWithSliceOffset(gid_z);
device FLT4* filters_loc = args.weights.GetPtr() + gid_z * 10;
FLT4 s0 = src_loc[args.src_tensor.GetWHOffset(x0, y0)] * FLT(!(x0_out || y0_out));
FLT4 s1 = src_loc[args.src_tensor.GetWHOffset(x0, y1)] * FLT(!(x0_out || y1_out));
FLT4 s2 = src_loc[args.src_tensor.GetWHOffset(x0, y2)] * FLT(!(x0_out || y2_out));
FLT4 s3 = src_loc[args.src_tensor.GetWHOffset(x0, y3)] * FLT(!(x0_out || y3_out));
r0 += TO_ACCUM_TYPE(s0 * filters_loc[0]);
r0 += TO_ACCUM_TYPE(s1 * filters_loc[1]);
r0 += TO_ACCUM_TYPE(s2 * filters_loc[2]);
l0 += TO_ACCUM_TYPE(s1 * filters_loc[0]);
l0 += TO_ACCUM_TYPE(s2 * filters_loc[1]);
l0 += TO_ACCUM_TYPE(s3 * filters_loc[2]);
s0 = src_loc[args.src_tensor.GetWHOffset(x1, y0)] * FLT(!(x1_out || y0_out));
s1 = src_loc[args.src_tensor.GetWHOffset(x1, y1)] * FLT(!(x1_out || y1_out));
s2 = src_loc[args.src_tensor.GetWHOffset(x1, y2)] * FLT(!(x1_out || y2_out));
s3 = src_loc[args.src_tensor.GetWHOffset(x1, y3)] * FLT(!(x1_out || y3_out));
r0 += TO_ACCUM_TYPE(s0 * filters_loc[3]);
r0 += TO_ACCUM_TYPE(s1 * filters_loc[4]);
r0 += TO_ACCUM_TYPE(s2 * filters_loc[5]);
l0 += TO_ACCUM_TYPE(s1 * filters_loc[3]);
l0 += TO_ACCUM_TYPE(s2 * filters_loc[4]);
l0 += TO_ACCUM_TYPE(s3 * filters_loc[5]);
t0 += TO_ACCUM_TYPE(s0 * filters_loc[0]);
t0 += TO_ACCUM_TYPE(s1 * filters_loc[1]);
t0 += TO_ACCUM_TYPE(s2 * filters_loc[2]);
b0 += TO_ACCUM_TYPE(s1 * filters_loc[0]);
b0 += TO_ACCUM_TYPE(s2 * filters_loc[1]);
b0 += TO_ACCUM_TYPE(s3 * filters_loc[2]);
s0 = src_loc[args.src_tensor.GetWHOffset(x2, y0)] * FLT(!(x2_out || y0_out));
s1 = src_loc[args.src_tensor.GetWHOffset(x2, y1)] * FLT(!(x2_out || y1_out));
s2 = src_loc[args.src_tensor.GetWHOffset(x2, y2)] * FLT(!(x2_out || y2_out));
s3 = src_loc[args.src_tensor.GetWHOffset(x2, y3)] * FLT(!(x2_out || y3_out));
r0 += TO_ACCUM_TYPE(s0 * filters_loc[6]);
r0 += TO_ACCUM_TYPE(s1 * filters_loc[7]);
r0 += TO_ACCUM_TYPE(s2 * filters_loc[8]);
l0 += TO_ACCUM_TYPE(s1 * filters_loc[6]);
l0 += TO_ACCUM_TYPE(s2 * filters_loc[7]);
l0 += TO_ACCUM_TYPE(s3 * filters_loc[8]);
t0 += TO_ACCUM_TYPE(s0 * filters_loc[3]);
t0 += TO_ACCUM_TYPE(s1 * filters_loc[4]);
t0 += TO_ACCUM_TYPE(s2 * filters_loc[5]);
b0 += TO_ACCUM_TYPE(s1 * filters_loc[3]);
b0 += TO_ACCUM_TYPE(s2 * filters_loc[4]);
b0 += TO_ACCUM_TYPE(s3 * filters_loc[5]);
s0 = src_loc[args.src_tensor.GetWHOffset(x3, y0)] * FLT(!(x3_out || y0_out));
s1 = src_loc[args.src_tensor.GetWHOffset(x3, y1)] * FLT(!(x3_out || y1_out));
s2 = src_loc[args.src_tensor.GetWHOffset(x3, y2)] * FLT(!(x3_out || y2_out));
s3 = src_loc[args.src_tensor.GetWHOffset(x3, y3)] * FLT(!(x3_out || y3_out));
t0 += TO_ACCUM_TYPE(s0 * filters_loc[6]);
t0 += TO_ACCUM_TYPE(s1 * filters_loc[7]);
t0 += TO_ACCUM_TYPE(s2 * filters_loc[8]);
b0 += TO_ACCUM_TYPE(s1 * filters_loc[6]);
b0 += TO_ACCUM_TYPE(s2 * filters_loc[7]);
b0 += TO_ACCUM_TYPE(s3 * filters_loc[8]);
r0 += TO_ACCUM_TYPE(filters_loc[9]);
l0 += TO_ACCUM_TYPE(filters_loc[9]);
t0 += TO_ACCUM_TYPE(filters_loc[9]);
b0 += TO_ACCUM_TYPE(filters_loc[9]);
bool x0_in = gid_x < args.dst_tensor.Width();
bool x1_in = gid_x + 1 < args.dst_tensor.Width();
bool y0_in = gid_y < args.dst_tensor.Height();
bool y1_in = gid_y + 1 < args.dst_tensor.Height();
if (y0_in && x0_in) {
FLT4 value = FLT4(r0);
args.dst_tensor.Write(value, gid_x, gid_y, gid_z);
}
if (y1_in && x0_in) {
FLT4 value = FLT4(l0);
args.dst_tensor.Write(value, gid_x, gid_y + 1, gid_z);
}
if (y0_in && x1_in) {
FLT4 value = FLT4(t0);
args.dst_tensor.Write(value, gid_x + 1, gid_y, gid_z);
}
if (y1_in && x1_in) {
FLT4 value = FLT4(b0);
args.dst_tensor.Write(value, gid_x + 1, gid_y + 1, gid_z);
}
}
)";
return code;
}
// Reorder weights to make the weights memory access pattern cache friendly for
// DepthWiseConv3x3Stride1x1
std::vector<float> ReorderWeightsDepthWiseConv3x3Stride1x1(
const DepthwiseConvolution2DAttributes& attr) {
const int src_depth = DivideRoundUp(attr.weights.shape.i, 4);
const int kernel_x = 3;
const int kernel_y = 3;
std::vector<float> weights_reordered((kernel_x * kernel_y + 1) * src_depth *
4);
int counter = 0;
for (int s = 0; s < src_depth; ++s) {
for (int x = 0; x < kernel_x; ++x) {
for (int y = 0; y < kernel_y; ++y) {
for (int i = 0; i < 4; ++i) {
const int s_ch = s * 4 + i;
if (s_ch < attr.weights.shape.i) {
const int f_index = attr.weights.shape.LinearIndex({0, y, x, s_ch});
weights_reordered[counter++] = attr.weights.data[f_index];
} else {
weights_reordered[counter++] = 0.0f;
}
}
}
}
for (int i = 0; i < 4; ++i) {
const int dst_ch = s * 4 + i;
if (dst_ch < attr.bias.shape.v) {
weights_reordered[counter++] = attr.bias.data[dst_ch];
} else {
weights_reordered[counter++] = 0.0f;
}
}
}
return weights_reordered;
}
std::string GetKernelDepthWiseConv3x3Stride2() {
std::string code = R"(
kernel void ComputeFunction($0
uint3 ugid[[thread_position_in_grid]])
{
int gid_x = ugid.x;
int gid_y = ugid.y * 2;
int gid_z = ugid.z;
if (gid_x >= args.dst_tensor.Width() || gid_y >= args.dst_tensor.Height()) {
return;
}
device FLT4* src_loc = args.src_tensor.GetPtrWithSliceOffset(gid_z);
device FLT4* filters_loc = args.weights.GetPtr() + gid_z * 10;
ACCUM_FLT4 r0 = ACCUM_FLT4(0.0f, 0.0f, 0.0f, 0.0f);
ACCUM_FLT4 l0 = ACCUM_FLT4(0.0f, 0.0f, 0.0f, 0.0f);
int x0 = gid_x * args.stride_x + args.padding_x;
int x1 = gid_x * args.stride_x + args.padding_x + args.dilation_x;
int x2 = gid_x * args.stride_x + args.padding_x + 2 * args.dilation_x;
int y0 = gid_y * 2 + args.padding_y;
int y1 = gid_y * 2 + args.padding_y + 1;
int y2 = gid_y * 2 + args.padding_y + 2;
int y3 = gid_y * 2 + args.padding_y + 3;
int y4 = gid_y * 2 + args.padding_y + 4;
bool x0_out = x0 < 0 || x0 >= args.src_tensor.Width();
bool x1_out = x1 < 0 || x1 >= args.src_tensor.Width();
bool x2_out = x2 < 0 || x2 >= args.src_tensor.Width();
bool y0_out = y0 < 0 || y0 >= args.src_tensor.Height();
bool y1_out = y1 < 0 || y1 >= args.src_tensor.Height();
bool y2_out = y2 < 0 || y2 >= args.src_tensor.Height();
bool y3_out = y3 < 0 || y3 >= args.src_tensor.Height();
bool y4_out = y4 < 0 || y4 >= args.src_tensor.Height();
x0 = clamp(x0, 0, args.src_tensor.Width() - 1);
x1 = clamp(x1, 0, args.src_tensor.Width() - 1);
x2 = clamp(x2, 0, args.src_tensor.Width() - 1);
y0 = clamp(y0, 0, args.src_tensor.Height() - 1);
y1 = clamp(y1, 0, args.src_tensor.Height() - 1);
y2 = clamp(y2, 0, args.src_tensor.Height() - 1);
y3 = clamp(y3, 0, args.src_tensor.Height() - 1);
y4 = clamp(y4, 0, args.src_tensor.Height() - 1);
FLT4 s0 = src_loc[args.src_tensor.GetWHOffset(x0, y0)] * FLT(!(x0_out || y0_out));
FLT4 s1 = src_loc[args.src_tensor.GetWHOffset(x1, y0)] * FLT(!(x1_out || y0_out));
FLT4 s2 = src_loc[args.src_tensor.GetWHOffset(x2, y0)] * FLT(!(x2_out || y0_out));
r0 += TO_ACCUM_TYPE(s0 * filters_loc[0]);
r0 += TO_ACCUM_TYPE(s1 * filters_loc[1]);
r0 += TO_ACCUM_TYPE(s2 * filters_loc[2]);
s0 = src_loc[args.src_tensor.GetWHOffset(x0, y1)] * FLT(!(x0_out || y1_out));
s1 = src_loc[args.src_tensor.GetWHOffset(x1, y1)] * FLT(!(x1_out || y1_out));
s2 = src_loc[args.src_tensor.GetWHOffset(x2, y1)] * FLT(!(x2_out || y1_out));
r0 += TO_ACCUM_TYPE(s0 * filters_loc[3]);
r0 += TO_ACCUM_TYPE(s1 * filters_loc[4]);
r0 += TO_ACCUM_TYPE(s2 * filters_loc[5]);
s0 = src_loc[args.src_tensor.GetWHOffset(x0, y2)] * FLT(!(x0_out || y2_out));
s1 = src_loc[args.src_tensor.GetWHOffset(x1, y2)] * FLT(!(x1_out || y2_out));
s2 = src_loc[args.src_tensor.GetWHOffset(x2, y2)] * FLT(!(x2_out || y2_out));
r0 += TO_ACCUM_TYPE(s0 * filters_loc[6]);
r0 += TO_ACCUM_TYPE(s1 * filters_loc[7]);
r0 += TO_ACCUM_TYPE(s2 * filters_loc[8]);
l0 += TO_ACCUM_TYPE(s0 * filters_loc[0]);
l0 += TO_ACCUM_TYPE(s1 * filters_loc[1]);
l0 += TO_ACCUM_TYPE(s2 * filters_loc[2]);
s0 = src_loc[args.src_tensor.GetWHOffset(x0, y3)] * FLT(!(x0_out || y3_out));
s1 = src_loc[args.src_tensor.GetWHOffset(x1, y3)] * FLT(!(x1_out || y3_out));
s2 = src_loc[args.src_tensor.GetWHOffset(x2, y3)] * FLT(!(x2_out || y3_out));
l0 += TO_ACCUM_TYPE(s0 * filters_loc[3]);
l0 += TO_ACCUM_TYPE(s1 * filters_loc[4]);
l0 += TO_ACCUM_TYPE(s2 * filters_loc[5]);
s0 = src_loc[args.src_tensor.GetWHOffset(x0, y4)] * FLT(!(x0_out || y4_out));
s1 = src_loc[args.src_tensor.GetWHOffset(x1, y4)] * FLT(!(x1_out || y4_out));
s2 = src_loc[args.src_tensor.GetWHOffset(x2, y4)] * FLT(!(x2_out || y4_out));
l0 += TO_ACCUM_TYPE(s0 * filters_loc[6]);
l0 += TO_ACCUM_TYPE(s1 * filters_loc[7]);
l0 += TO_ACCUM_TYPE(s2 * filters_loc[8]);
r0 += TO_ACCUM_TYPE(filters_loc[9]);
l0 += TO_ACCUM_TYPE(filters_loc[9]);
bool y0_in = gid_y < args.dst_tensor.Height();
bool y1_in = gid_y + 1 < args.dst_tensor.Height();
if (y0_in) {
FLT4 value = FLT4(r0);
args.dst_tensor.Write(value, gid_x, gid_y, gid_z);
}
if (y1_in) {
FLT4 value = FLT4(l0);
args.dst_tensor.Write(value, gid_x, gid_y + 1, gid_z);
}
}
)";
return code;
}
// Reorder weights to make the weights memory access pattern cache friendly for
// DepthWiseConv3x3Stride2
std::vector<float> ReorderWeightsDepthWiseConv3x3Stride2(
const DepthwiseConvolution2DAttributes& attr) {
const int src_depth = DivideRoundUp(attr.weights.shape.i, 4);
const int kernel_x = 3;
const int kernel_y = 3;
std::vector<float> weights_reordered((kernel_x * kernel_y + 1) * src_depth *
4);
int counter = 0;
for (int s = 0; s < src_depth; ++s) {
for (int y = 0; y < kernel_y; ++y) {
for (int x = 0; x < kernel_x; ++x) {
for (int i = 0; i < 4; ++i) {
const int s_ch = s * 4 + i;
if (s_ch < attr.weights.shape.i) {
const int f_index = attr.weights.shape.LinearIndex({0, y, x, s_ch});
weights_reordered[counter++] = attr.weights.data[f_index];
} else {
weights_reordered[counter++] = 0.0f;
}
}
}
}
for (int i = 0; i < 4; ++i) {
const int dst_ch = s * 4 + i;
if (dst_ch < attr.bias.shape.v) {
weights_reordered[counter++] = attr.bias.data[dst_ch];
} else {
weights_reordered[counter++] = 0.0f;
}
}
}
return weights_reordered;
}
} // namespace
int3 DepthWiseConvolution::GetGridSize() const {
return int3(dst_[0]->Width(), dst_[0]->Height(), dst_[0]->Slices());
}
DepthWiseConvolution CreateDepthWiseConvolution(
const OperationDef& definition,
const DepthwiseConvolution2DAttributes& attr) {
int channels_multiplier = attr.weights.shape.o;
std::string shader_source = R"(
kernel void ComputeFunction($0
uint tid[[thread_index_in_threadgroup]],
uint3 gid[[thread_position_in_grid]]) {
int dst_x = static_cast<int>(gid.x);
int dst_y = static_cast<int>(gid.y);
int dst_z = static_cast<int>(gid.z);
if (dst_x >= args.dst_tensor.Width() || dst_y >= args.dst_tensor.Height()) return;
device FLT4* temp = args.weights.GetPtr() + dst_z * args.kernel_size_x * args.kernel_size_y;
ACCUM_FLT4 sum0 = ACCUM_FLT4(0.0f, 0.0f, 0.0f, 0.0f);
int src_x = dst_x * args.stride_x + args.padding_x;
int src_y = dst_y * args.stride_y + args.padding_y;
for(int ky = 0; ky < args.kernel_size_y; ++ky) {
int yc = ky * args.dilation_y + src_y;
if (yc < 0 || yc >= args.src_tensor.Height()) continue;
for(int kx = 0; kx < args.kernel_size_x; ++kx) {
int xc = kx * args.dilation_x + src_x;
if (xc < 0 || xc >= args.src_tensor.Width()) continue;
)";
if (channels_multiplier == 1) {
shader_source += R"(
int src_layer = dst_z;
FLT4 src_modified = args.src_tensor.Read(xc, yc, src_layer);
)";
} else if (channels_multiplier == 2) {
shader_source += R"(
int src_layer = dst_z / 2;
FLT4 src = args.src_tensor.Read(xc, yc, src_layer);
FLT2 t0 = dst_z % 2 == 0 ? src.xy : src.zw;
FLT4 src_modified = FLT4(t0.x, t0.x, t0.y, t0.y);
)";
} else if (channels_multiplier == 4) {
shader_source += R"(
int src_layer = dst_z / 4;
FLT4 src = args.src_tensor.Read(xc, yc, src_layer);
FLT t0 = src[dst_z % 4];
FLT4 src_modified = FLT4(t0, t0, t0, t0);
)";
} else {
shader_source += R"(
int src_layer = dst_z / args.channel_multiplier;
FLT4 src = args.src_tensor.Read(xc, yc, src_layer);
FLT4 src_modified;
const int src_layer_offset = (dst_z % args.channel_multiplier) * 4;
src_modified.x = src[(src_layer_offset + 0) / args.channel_multiplier];
src_modified.y = src[(src_layer_offset + 1) / args.channel_multiplier];
src_modified.z = src[(src_layer_offset + 2) / args.channel_multiplier];
src_modified.w = src[(src_layer_offset + 3) / args.channel_multiplier];
)";
}
shader_source += R"(
sum0 += TO_ACCUM_TYPE(src_modified * temp[ky * args.kernel_size_x + kx]);
}
}
FLT4 res = FLT4(sum0) + args.biases.Read(dst_z);
args.dst_tensor.Write(res, dst_x, dst_y, dst_z);
}
)";
DepthWiseConvolution desc(definition);
desc.code_ = shader_source;
desc.AddSrcTensor("src_tensor", definition.src_tensors[0]);
desc.AddDstTensor("dst_tensor", definition.dst_tensors[0]);
desc.args_.AddInt("padding_x", -attr.padding.prepended.w);
desc.args_.AddInt("padding_y", -attr.padding.prepended.h);
desc.args_.AddInt("dilation_x", attr.dilations.w);
desc.args_.AddInt("dilation_y", attr.dilations.h);
desc.args_.AddInt("stride_x", attr.strides.w);
desc.args_.AddInt("stride_y", attr.strides.h);
desc.args_.AddInt("kernel_size_x", attr.weights.shape.w);
desc.args_.AddInt("kernel_size_y", attr.weights.shape.h);
desc.args_.AddInt("channel_multiplier", attr.weights.shape.o);
auto data_type = DeduceDataTypeFromPrecision(definition.precision);
const int output_channels_count = attr.weights.shape.i * attr.weights.shape.o;
const int dst_ch_aligned = AlignByN(output_channels_count, 4);
BufferDescriptor weights_desc;
weights_desc.element_type = data_type;
weights_desc.element_size = 4;
weights_desc.data =
GetByteBufferConverted(ConvertToPIOHW4(attr.weights), data_type);
weights_desc.size = weights_desc.data.size();
desc.args_.AddObject(
"weights", absl::make_unique<BufferDescriptor>(std::move(weights_desc)));
BufferDescriptor bias_desc;
bias_desc.element_type = data_type;
bias_desc.element_size = 4;
bias_desc.data =
GetByteBufferConvertedResized(attr.bias.data, data_type, dst_ch_aligned);
bias_desc.size = bias_desc.data.size();
desc.args_.AddObject(
"biases", absl::make_unique<BufferDescriptor>(std::move(bias_desc)));
desc.work_group_size_ = int3(8, 4, 1);
return desc;
}
void DepthWiseConv3x3Stride1x1::GetPossibleKernelWorkGroups(
TuningType tuning_type, const GpuInfo& gpu_info,
const KernelInfo& kernel_info, std::vector<int3>* work_groups) const {
const int grid_x = DivideRoundUp(dst_[0]->Width(), 2);
const int grid_z = dst_[0]->Slices();
int3 group_size{8, 4, 1};
if (grid_x <= 4) {
group_size.x = 4;
group_size.z = grid_z % 2 == 0 ? 2 : 1;
}
work_groups->push_back(group_size);
}
int3 DepthWiseConv3x3Stride1x1::GetGridSize() const {
const int grid_x = DivideRoundUp(dst_[0]->Width(), 2);
const int grid_y = DivideRoundUp(dst_[0]->Height(), 2);
const int grid_z = dst_[0]->Slices();
return int3(grid_x, grid_y, grid_z);
}
DepthWiseConv3x3Stride1x1 CreateDepthWiseConv3x3Stride1x1(
const OperationDef& definition,
const DepthwiseConvolution2DAttributes& attr) {
DepthWiseConv3x3Stride1x1 desc(definition);
desc.code_ = GetKernelDepthWiseConv3x3Stride1x1();
desc.AddSrcTensor("src_tensor", definition.src_tensors[0]);
desc.AddDstTensor("dst_tensor", definition.dst_tensors[0]);
desc.args_.AddInt("padding_x", -attr.padding.prepended.w);
desc.args_.AddInt("padding_y", -attr.padding.prepended.h);
// For this operation we keep weights and biases in one buffer
auto weights_reordered = ReorderWeightsDepthWiseConv3x3Stride1x1(attr);
auto data_type = DeduceDataTypeFromPrecision(definition.precision);
BufferDescriptor weights_desc;
weights_desc.element_type = data_type;
weights_desc.element_size = 4;
weights_desc.data = GetByteBufferConverted(weights_reordered, data_type);
weights_desc.size = weights_desc.data.size();
desc.args_.AddObject(
"weights", absl::make_unique<BufferDescriptor>(std::move(weights_desc)));
return desc;
}
bool CheckDepthWiseConv3x3Stride1x1Support(
const DepthwiseConvolution2DAttributes& attr) {
return attr.weights.shape.o == 1 && attr.weights.shape.h == 3 &&
attr.weights.shape.w == 3 && attr.strides.h == 1 &&
attr.strides.w == 1 && attr.dilations.h == 1 && attr.dilations.w == 1;
}
int3 DepthWiseConv3x3Stride2::GetGridSize() const {
const int grid_x = dst_[0]->Width();
const int grid_y = DivideRoundUp(dst_[0]->Height(), 2);
const int grid_z = dst_[0]->Slices();
return int3(grid_x, grid_y, grid_z);
}
DepthWiseConv3x3Stride2 CreateDepthWiseConv3x3Stride2(
const OperationDef& definition,
const DepthwiseConvolution2DAttributes& attr) {
DepthWiseConv3x3Stride2 desc(definition);
desc.code_ = GetKernelDepthWiseConv3x3Stride2();
desc.AddSrcTensor("src_tensor", definition.src_tensors[0]);
desc.AddDstTensor("dst_tensor", definition.dst_tensors[0]);
desc.args_.AddInt("padding_x", -attr.padding.prepended.w);
desc.args_.AddInt("padding_y", -attr.padding.prepended.h);
desc.args_.AddInt("stride_x", attr.strides.w);
desc.args_.AddInt("dilation_x", attr.dilations.w);
// For this operation we keep weights and biases in one buffer
auto weights_reordered = ReorderWeightsDepthWiseConv3x3Stride2(attr);
auto data_type = DeduceDataTypeFromPrecision(definition.precision);
BufferDescriptor weights_desc;
weights_desc.element_type = data_type;
weights_desc.element_size = 4;
weights_desc.data = GetByteBufferConverted(weights_reordered, data_type);
weights_desc.size = weights_desc.data.size();
desc.args_.AddObject(
"weights", absl::make_unique<BufferDescriptor>(std::move(weights_desc)));
desc.work_group_size_ = int3(8, 4, 1);
return desc;
}
bool CheckDepthWiseConv3x3Stride2Support(
const DepthwiseConvolution2DAttributes& attr) {
return attr.weights.shape.o == 1 && attr.weights.shape.h == 3 &&
attr.weights.shape.w == 3 && attr.strides.h == 2 &&
attr.dilations.h == 1;
}
} // namespace metal
} // namespace gpu
} // namespace tflite
| 38.343805 | 94 | 0.662555 | [
"shape",
"vector",
"model"
] |
3e45a431f6f37eb7c7486efa5df1e7a842217dd9 | 8,141 | cpp | C++ | pyunidoe/wrapper.cpp | SelfExplainML/pyunidoe | 01ab0af7d494d3622b55443fec9e3fa7597574b7 | [
"BSD-3-Clause"
] | null | null | null | pyunidoe/wrapper.cpp | SelfExplainML/pyunidoe | 01ab0af7d494d3622b55443fec9e3fa7597574b7 | [
"BSD-3-Clause"
] | null | null | null | pyunidoe/wrapper.cpp | SelfExplainML/pyunidoe | 01ab0af7d494d3622b55443fec9e3fa7597574b7 | [
"BSD-3-Clause"
] | null | null | null | #include "wrapper.h"
int criteria_selector(char* crit)
{
int critopt;
critopt = 1;
if(!strcmp(crit,"CD2")) critopt=1;
else if(!strcmp(crit,"MD2")) critopt=2;
else if(!strcmp(crit,"WD2")) critopt=3;
else if(!strcmp(crit,"maximin")) critopt=4;
else if(!strcmp(crit,"MC")) critopt=5;
else if(!strcmp(crit,"A2")) critopt=6;
return critopt;
}
double CritEval(vector<vector<double> > x0, int nlevel, char* crit)
{
Criteria *c;
double criteria = 0;
int i, j, nv = (int) x0[0].size(), nsamp= (int) x0.size();
int critopt = criteria_selector(crit);
vector<vector<double> > x(nsamp, vector<double>(nv, 0));
for(i=0;i<nsamp;i++) for(j=0;j<nv;j++) x[i][j] = x0[i][j];
switch(critopt)
{
case 1:
c = new CD2(x, nsamp, nv, nlevel);
break;
case 2:
c = new MD2(x, nsamp, nv, nlevel);
break;
case 3:
c = new WD2(x, nsamp, nv, nlevel);
break;
case 4:
c = new Maximin(x, nsamp, nv, nlevel);
break;
case 5:
c = new MC(x, nsamp, nv, nlevel);
break;
case 6:
c = new A2(x, nsamp, nv, nlevel);
break;
default:
c = new CD2(x, nsamp, nv, nlevel);
break;
}
c->evaluate_criteria();
criteria = c->get_criteria();
return(criteria);
}
vector<vector<double> > Generate_init_matrix(char* init_method, int nsamp, int nv, int nlevel, vector<vector<double> > initX)
{
int i,j;
vector<double> col;
vector<vector<double> > return_matrix(nsamp, vector<double>(nv, 0));
if ((!strcmp(init_method,"input")) && (initX.size()>1))
{
for(i=0;i<(int) initX[0].size();i++) {
for(j=0;j<(int) initX.size();j++) {
return_matrix[j][i] = initX[j][i];
}
}
}
else if ((!strcmp(init_method,"rand")))
{
for(i=1;i<=nsamp;i++) col.push_back((i%nlevel)+1.0);
for(i=0;i<nv;i++)
{
random_shuffle (col.begin(), col.end());
for(j=0;j<nsamp;j++) return_matrix[j][i] = col[j];
}
}
return return_matrix;
}
vector<vector<double> > Generate_Aug_matrix(char* init_method, vector< vector < double > > xp, int nnew, int nv,
int nlevel, vector< vector < double > > initX)
{
int i,j,k, np, nsamp, fill_size, all_fill_size, max_k = 0;
np = (int) xp.size();
nsamp = np + nnew;
vector<double> temp(np,0);
vector<vector<int> > freq_table;
vector<vector<double> > return_matrix(nnew, vector<double>(nv, 0));
freq_table.assign(nlevel, vector<int>(nv, 0));
if ((!strcmp(init_method,"input")) && (initX.size()>1))
{
for(i=0;i<(int) initX[0].size();i++) {
for(j=0;j<(int) initX.size();j++) {
return_matrix[j][i] = initX[j][i];
}
}
}
else if ((!strcmp(init_method,"rand")))
{
for (i=0;i<nv;i++)
{
for (j=0;j<np;j++) temp[j] = xp[j][i];
for (j=0;j<nlevel;j++)
{
freq_table[j][i] = (int) count(temp.begin(), temp.end(), j+1);
if (max_k<freq_table[j][i]) max_k = freq_table[j][i];
}
}
max_k = max(max_k, nsamp/nlevel);
for (i=0;i<nv;i++)
{
all_fill_size = 0;
for (j=0;j<nlevel;j++)
{
fill_size = max_k-freq_table[j][i];
for (k=all_fill_size;k<all_fill_size+fill_size;k++)
{
return_matrix[k][i] = j+1;
}
all_fill_size += fill_size;
}
}
}
return return_matrix;
}
List SATA_UD(int nsamp, int nv, int nlevel, char* init_method, vector<vector<double> > initX,
char* crit, int maxiter, double hits_ratio, bool levelpermt, int rand_seed)
{
List lst;
int i,j;
clock_t start_time;
vector<double> critobj_vector;
vector<int> optimize_columns(nv,1);
vector<vector<double> > final_design;
double critobj, critobj0, search_time;
int critopt = criteria_selector(crit);
vector<vector<double> > Init_matrix, return_matrix(nsamp, vector<double>(nv, 0));
vector<vector<double> > x(nsamp, vector<double>(nv, 0));
srand(rand_seed);
start_time = clock();
Init_matrix = Generate_init_matrix(init_method,nsamp,nv,nlevel,initX);
for(i=0;i<nsamp;i++) for(j=0;j<nv;j++) x[i][j] = Init_matrix[i][j];
Optimizer opt(x, nsamp, 0, nv, nlevel, optimize_columns, critopt, maxiter, hits_ratio, levelpermt);
critobj_vector = opt.SATA_Optimize();
final_design = opt.get_design();
critobj0 = critobj_vector.front();
critobj = critobj_vector.back();
for(i=0;i<nsamp; i++) for(j=0;j<nv;j++) return_matrix[i][j] = final_design[i][j];
search_time = (double)(clock()-start_time)/CLOCKS_PER_SEC;
lst.Init_Design = Init_matrix;
lst.Final_Design = return_matrix;
lst.Init_Obj = critobj0;
lst.Final_Obj = critobj;
lst.Time_Second= search_time;
lst.Criterion_history = critobj_vector;
return lst;
}
List SATA_AUD(vector<vector<double> > xp,int nnew, int nv, int nlevel, char* init_method, vector<vector<double> > initX,
char* crit, int maxiter, double hits_ratio, bool levelpermt, int rand_seed)
{
List lst;
int i,j;
int np= (int) xp.size();
int nsamp = np+nnew;
clock_t start_time;
vector<double> critobj_vector;
vector<int> optimize_columns(nv,1);
vector<vector<double> > final_design;
double critobj, critobj0, search_time;
int critopt = criteria_selector(crit);
vector<vector<double> > x(nsamp, vector<double>(nv, 0));
vector<vector<double> > InputX(nnew, vector<double>(nv, 0));
vector<vector<double> > Init_matrix(nsamp, vector<double>(nv, 0));
vector<vector<double> > return_matrix(nsamp, vector<double>(nv, 0));
srand(rand_seed);
start_time = clock();
InputX = Generate_Aug_matrix(init_method,xp,nnew,nv,nlevel,initX);
for(j=0;j<nv;j++)
{
for(i=0;i<np;i++) {x[i][j] =Init_matrix[i][j]= xp[i][j];}
for(i=0;i<nnew;i++) {x[i+np][j] = Init_matrix[i+np][j]=InputX[i][j];}
}
Optimizer opt(x, nnew, np, nv, nlevel, optimize_columns, critopt, maxiter, hits_ratio, levelpermt);
critobj_vector = opt.SATA_Optimize();
final_design = opt.get_design();
critobj0 = critobj_vector[0];
critobj = critobj_vector.back();
for(i=0;i<nsamp; i++) for(j=0;j<nv;j++) return_matrix[i][j] = final_design[i][j];
search_time = (double)(clock()-start_time)/CLOCKS_PER_SEC;
lst.Init_Design = Init_matrix;
lst.Final_Design = return_matrix;
lst.Init_Obj = critobj0;
lst.Final_Obj = critobj;
lst.Time_Second= search_time;
lst.Criterion_history = critobj_vector;
return lst;
}
List SATA_AUD_COL(vector<vector<double> > xp, int nvnew, int nlevel, char* init_method, vector<vector<double> > initX,
char* crit, int maxiter, double hits_ratio, bool levelpermt, int rand_seed)
{
List lst;
int i,j;
int nsamp = (int)xp.size();
int nvp = (int)xp[0].size();
int nv = nvnew+nvp;
clock_t start_time;
vector<double> critobj_vector;
vector<int> optimize_columns(nv,1);
vector<vector<double> > final_design;
double critobj, critobj0, search_time;
int critopt = criteria_selector(crit);
vector<vector<double> > x(nsamp, vector<double>(nv, 0));
vector<vector<double> > InputX(nsamp, vector<double>(nvnew, 0));
vector<vector<double> > Init_matrix(nsamp, vector<double>(nv, 0));
vector<vector<double> > return_matrix(nsamp, vector<double>(nv, 0));
srand(rand_seed);
start_time = clock();
InputX = Generate_init_matrix(init_method,nsamp,nvnew,nlevel,initX);
for(j=0;j<nvp;j++) optimize_columns[j] = 0;
for(i=0;i<nsamp;i++)
{
for(j=0;j<nvp;j++) x[i][j] =Init_matrix[i][j]= xp[i][j];
for(j=0;j<nvnew;j++) x[i][j+nvp] =Init_matrix[i][j+nvp]= InputX[i][j];
}
Optimizer opt(x, nsamp, 0, nv, nlevel, optimize_columns, critopt, maxiter, hits_ratio, levelpermt);
critobj_vector = opt.SATA_Optimize();
final_design = opt.get_design();
critobj0 = critobj_vector[0];
critobj = critobj_vector.back();
for(i=0;i<nsamp; i++) for(j=0;j<nv;j++) return_matrix[i][j] = final_design[i][j];
search_time = (double)(clock()-start_time)/CLOCKS_PER_SEC;
lst.Init_Design = Init_matrix;
lst.Final_Design = return_matrix;
lst.Init_Obj = critobj0;
lst.Final_Obj = critobj;
lst.Time_Second= search_time;
lst.Criterion_history = critobj_vector;
return lst;
} | 31.92549 | 125 | 0.634197 | [
"vector"
] |
3e4f68efc1f8cf14fe82e1403383a9276de077ed | 5,586 | cpp | C++ | HelloWorldDemo/Classes/SocketSever.cpp | omf2333/TjRedAlert | c0d9535d5969adccc3013db82a15639e9b94cd59 | [
"MIT"
] | null | null | null | HelloWorldDemo/Classes/SocketSever.cpp | omf2333/TjRedAlert | c0d9535d5969adccc3013db82a15639e9b94cd59 | [
"MIT"
] | null | null | null | HelloWorldDemo/Classes/SocketSever.cpp | omf2333/TjRedAlert | c0d9535d5969adccc3013db82a15639e9b94cd59 | [
"MIT"
] | null | null | null | #include"SocketServer.h"
io_service * socket_server::io_service_ = new io_service;
void talk_to_client::start()
{
async_read(socket_, buffer(read_msg_.data(), socket_message::header_length),
boost::bind(&talk_to_client::handle_read_header, this, _1));
}
talk_to_client::ptr talk_to_client::create(io_service & io_service, socket_server * socket_server)
{
return talk_to_client::ptr(new talk_to_client(io_service, socket_server));
}
ip::tcp::socket & talk_to_client::socket()
{
return socket_;
}
std::string talk_to_client::read_data()
{
if (error_flag_)
{
return "";
}
boost::unique_lock<boost::mutex> lk{ mut_ };
while (read_msg_deque_.empty())
{
data_conditioner_.wait(lk);
}
auto read_msg = read_msg_deque_.front();
read_msg_deque_.pop_front();
lk.unlock();
auto ret = std::string(read_msg.body(), read_msg.body_length());
return ret;
}
void talk_to_client::write_data(std::string s)
{
if (error_flag_)
{
return;
}
socket_message msg;
if (s.size() == 0)
{
s = std::string("\0");
msg.set_body_length(1);
}
else
{
msg.set_body_length(s.size());
}
memcpy(msg.body(), &s[0u], msg.body_length());
msg.encode_header();
write(socket_,buffer(msg.data(), msg.length()));
}
void talk_to_client::do_close()
{
try
{
// steady_timer_.cancel();
error_flag_ = true;
socket_message empty_msg;
memcpy(empty_msg.data(), "0001\0", 5);
read_msg_deque_.push_back(empty_msg);
read_msg_deque_.push_back(empty_msg);
data_conditioner_.notify_one();
error_code ec;
socket_.shutdown(ip::tcp::socket::shutdown_both, ec);
if (!ec)
throw std::system_error(ec);
socket_.close();
}
catch (std::exception&e)
{
e.what();
}
delete_from_server();
}
void talk_to_client::handle_read_header(const boost::system::error_code& error)
{
if (!error && read_msg_.decode_header())
{
async_read(socket_, buffer(read_msg_.body(), read_msg_.body_length()),
boost::bind(&talk_to_client::handle_read_body, this, _1));
}
else
{
do_close();
}
}
void talk_to_client::handle_read_body(const boost::system::error_code& error)
{
if (!error)
{
boost::lock_guard<boost::mutex> lk{ mut_ };
read_msg_deque_.push_back(read_msg_);
data_conditioner_.notify_one();
async_read(socket_, buffer(read_msg_.data(), socket_message::header_length),
boost::bind(&talk_to_client::handle_read_header, this, _1));
}
else
{
do_close();
}
}
talk_to_client::talk_to_client(io_service & io_service, socket_server * socket_server)
:socket_(io_service), socket_server_(socket_server)
{
std::cout << "new tcp" << std::endl;
}
void talk_to_client::delete_from_server()
{
if (socket_server_)
{
shared_from_this()->socket_server_->remove_connection(shared_from_this());
}
socket_server_ = nullptr;
}
socket_server * socket_server::create(int port)
{
auto s = new socket_server(port);
s->thread_ = new boost::thread(boost::bind(static_cast<std::size_t(io_service::*)()>(&io_service::run), io_service_));
return s;
}
void socket_server::close()
{
try
{
connections_.clear();
io_service_->stop();
acceptor_.close();
thread_->join();
delete io_service_;
}
catch (std::exception&e)
{
std::cerr << e.what() << std::endl;
}
io_service_ = new io_service;
}
void socket_server::button_start()
{
acceptor_.close();
using namespace std;
char total[5] = "";
sprintf(total, "%4d", static_cast<int>(connections_.size()));
for (auto i = 0; i < connections_.size(); i++)
{
connections_[i]->write_data("PLAYER" + std::string(total) + std::to_string(i + 1));
}
connection_num_ = connections_.size();
this->button_thread_ = new boost::thread(std::bind(&socket_server::loop_process, this));
button_thread_->detach();
}
bool socket_server::error() const
{
return error_flag_;
}
int socket_server::connection_num() const
{
return connections_.size();
}
std::vector<talk_to_client::ptr> socket_server::get_connection() const
{
return connections_;
}
void socket_server::remove_connection(talk_to_client::ptr p)
{
std::unique_lock<std::mutex> lock(delete_mutex_);
auto position = std::find(connections_.begin(), connections_.end(), p);
if (position == connections_.end())
std::cout << "delete not succ\n";
else
connections_.erase(position);
std::cout << "delete succ\n";
}
socket_server::socket_server(int port) : acceptor_(*io_service_, ip::tcp::endpoint(ip::tcp::v4(), port))
{
start_accept();
}
void socket_server::start_accept()
{
talk_to_client::ptr new_connection = talk_to_client::create(acceptor_.get_io_service(), this);
acceptor_.async_accept(new_connection->socket(), boost::bind(&socket_server::handle_accept, this, new_connection, _1));
std::cout << "start accept " << std::endl;
}
void socket_server::handle_accept(talk_to_client::ptr new_connection, const boost::system::error_code& error)
{
std::cout << "handle_accept" << std::endl;
if (!error)
{
connections_.push_back(new_connection);
std::cout << new_connection->socket().remote_endpoint().address()
<< ":" << new_connection->socket().remote_endpoint().port() << std::endl;
new_connection->start();
}
start_accept();
}
void socket_server::loop_process()
{
while (true)
{
if (connections_.size() != connection_num_)
{
error_flag_ = true;
break;
}
std::unique_lock<std::mutex> lock(delete_mutex_);
std::vector<std::string> ret;
for (auto r : connections_)
{
if (r->error())
{
error_flag_ |= r->error();
}
ret.push_back(r->read_data());
}
auto game_msg = GameMessageWrap::combine_message(ret);
for (auto r : connections_)
r->write_data(game_msg);
}
}
| 22.615385 | 120 | 0.701038 | [
"vector"
] |
3e54c1eb4a3341b1f5288673ce317f6e732da7e3 | 9,974 | cxx | C++ | cgv/media/mesh/simple_mesh.cxx | kahlertfr/cgv | a48139eb8af777ab63c78c09fc6aa44592908bc7 | [
"BSD-3-Clause"
] | null | null | null | cgv/media/mesh/simple_mesh.cxx | kahlertfr/cgv | a48139eb8af777ab63c78c09fc6aa44592908bc7 | [
"BSD-3-Clause"
] | null | null | null | cgv/media/mesh/simple_mesh.cxx | kahlertfr/cgv | a48139eb8af777ab63c78c09fc6aa44592908bc7 | [
"BSD-3-Clause"
] | null | null | null | #include "simple_mesh.h"
#include <cgv/media/mesh/obj_reader.h>
#include <cgv/math/bucket_sort.h>
namespace cgv {
namespace media {
namespace mesh {
/// sort faces by group and material indices with two bucket sorts
void simple_mesh_base::sort_faces(std::vector<idx_type>& perm, bool by_group, bool by_material) const
{
if (by_group && by_material) {
std::vector<idx_type> perm0;
cgv::math::bucket_sort(group_indices, get_nr_groups(), perm0);
cgv::math::bucket_sort(material_indices, get_nr_materials(), perm, &perm0);
}
else if (by_group)
cgv::math::bucket_sort(group_indices, get_nr_groups(), perm);
else
cgv::math::bucket_sort(material_indices, get_nr_materials(), perm);
}
/// merge the three indices into one index into a vector of unique index triples
void simple_mesh_base::merge_indices(std::vector<idx_type>& indices, std::vector<vec3i>& unique_triples, bool* include_tex_coords_ptr, bool* include_normals_ptr) const
{
bool include_tex_coords = false;
if (include_tex_coords_ptr)
*include_tex_coords_ptr = include_tex_coords = (tex_coord_indices.size() > 0) && *include_tex_coords_ptr;
bool include_normals = false;
if (include_normals_ptr)
*include_normals_ptr = include_normals = (normal_indices.size() > 0) && *include_normals_ptr;
std::map<std::tuple<idx_type, idx_type, idx_type>, idx_type> corner_to_index;
for (idx_type ci = 0; ci < position_indices.size(); ++ci) {
// construct corner
vec3i c(position_indices[ci],
(include_tex_coords && ci < tex_coord_indices.size()) ? tex_coord_indices[ci] : 0,
(include_normals && ci < normal_indices.size()) ? normal_indices[ci] : 0);
std::tuple<idx_type, idx_type, idx_type> triple(c(0),c(1),c(2));
// look corner up in map
auto iter = corner_to_index.find(triple);
// determine vertex index
idx_type vi;
if (iter == corner_to_index.end()) {
vi = idx_type(unique_triples.size());
corner_to_index[triple] = vi;
unique_triples.push_back(c);
}
else
vi = iter->second;
indices.push_back(vi);
}
}
/// extract element array buffers for triangulation
void simple_mesh_base::extract_triangle_element_buffer(
const std::vector<idx_type>& vertex_indices, std::vector<idx_type>& triangle_element_buffer,
const std::vector<idx_type>* face_perm_ptr, std::vector<vec3i>* material_group_start_ptr) const
{
idx_type mi = idx_type(-1);
idx_type gi = idx_type(-1);
// construct triangle element buffer
for (idx_type fi = 0; fi < faces.size(); ++fi) {
idx_type fj = face_perm_ptr ? face_perm_ptr->at(fi) : fi;
if (material_group_start_ptr) {
if (mi != material_indices[fj] || gi != group_indices[fj]) {
mi = material_indices[fj];
gi = group_indices[fj];
material_group_start_ptr->push_back(vec3i(mi, gi, idx_type(triangle_element_buffer.size())));
}
}
if (face_degree(fj) == 3) {
for (idx_type ci = begin_corner(fj); ci < end_corner(fj); ++ci)
triangle_element_buffer.push_back(vertex_indices.at(ci));
}
else {
// in case of non triangular faces do simplest triangulation approach that assumes convexity of faces
for (idx_type ci = begin_corner(fj) + 2; ci < end_corner(fj); ++ci) {
triangle_element_buffer.push_back(vertex_indices.at(begin_corner(fj)));
triangle_element_buffer.push_back(vertex_indices.at(ci - 1));
triangle_element_buffer.push_back(vertex_indices.at(ci));
}
}
}
}
/// extract element array buffers for edges in wireframe
void simple_mesh_base::extract_wireframe_element_buffer(const std::vector<idx_type>& vertex_indices, std::vector<idx_type>& edge_element_buffer) const
{
// map stores for each halfedge the number of times it has been seen before
std::map<std::tuple<idx_type, idx_type>, idx_type> halfedge_to_count;
for (idx_type fi = 0; fi < faces.size(); ++fi) {
idx_type last_vi = vertex_indices.at(end_corner(fi) - 1);
for (idx_type ci = begin_corner(fi); ci < end_corner(fi); ++ci) {
// construct halfedge with sorted vertex indices
idx_type vi = vertex_indices.at(ci);
std::tuple<idx_type, idx_type> halfedge(last_vi, vi);
if (vi < last_vi)
std::swap(std::get<0>(halfedge), std::get<1>(halfedge));
// lookup corner in map
auto iter = halfedge_to_count.find(halfedge);
// determine vertex index
if (iter == halfedge_to_count.end()) {
halfedge_to_count[halfedge] = 1;
edge_element_buffer.push_back(last_vi);
edge_element_buffer.push_back(vi);
}
else
++halfedge_to_count[halfedge];
last_vi = vi;
}
}
}
template <typename T>
class simple_mesh_obj_reader : public obj_reader_generic<T>
{
public:
typedef typename simple_mesh<T>::idx_type idx_type;
protected:
simple_mesh<T> &mesh;
public:
simple_mesh_obj_reader(simple_mesh<T>& _mesh) : mesh(_mesh) {}
/// overide this function to process a vertex
void process_vertex(const v3d_type& p) { mesh.positions.push_back(p); }
/// overide this function to process a texcoord
void process_texcoord(const v2d_type& t) { mesh.tex_coords.push_back(v2d_type(t(0),t(1))); }
/// overide this function to process a color (this called for vc prefixes which is is not in the standard but for example used in pobj-files)
void process_color(const color_type& c) { mesh.resize_colors(mesh.get_nr_colors() + 1); mesh.set_color(mesh.get_nr_colors()-1, c); }
/// overide this function to process a normal
void process_normal(const v3d_type& n) { mesh.normals.push_back(n); }
/// overide this function to process a face, the indices start with 0
void process_face(unsigned vcount, int *vertices, int *texcoords, int *normals)
{
convert_to_positive(vcount, vertices, texcoords, normals, unsigned(mesh.positions.size()), unsigned(mesh.normals.size()), unsigned(mesh.tex_coords.size()));
mesh.faces.push_back(idx_type(mesh.position_indices.size()));
if (get_current_group() != -1)
mesh.group_indices.push_back(get_current_group());
if (get_current_material() != -1)
mesh.material_indices.push_back(get_current_material());
for (idx_type i = 0; i < vcount; ++i) {
mesh.position_indices.push_back(idx_type(vertices[i]));
if (texcoords)
mesh.tex_coord_indices.push_back(idx_type(texcoords[i]));
if (normals)
mesh.normal_indices.push_back(idx_type(normals[i]));
}
}
/// overide this function to process a group given by name and parameter string
void process_group(const std::string& name, const std::string& parameters)
{
mesh.group_names.push_back(name);
}
/// process a material definition. If a material with a certain name is overwritten, it will receive the same index
void process_material(const cgv::media::illum::obj_material& mtl, unsigned idx)
{
if (idx >= mesh.materials.size())
mesh.materials.resize(idx+1);
mesh.materials[idx] = mtl;
}
};
/// clear simple mesh
template <typename T>
void simple_mesh<T>::clear()
{
positions.clear();
normals.clear();
tex_coords.clear();
position_indices.clear();
tex_coord_indices.clear();
normal_indices.clear();
faces.clear();
}
/// read simple mesh from file
template <typename T>
bool simple_mesh<T>::read(const std::string& file_name)
{
simple_mesh_obj_reader<T> reader(*this);
return reader.read_obj(file_name);
}
/// compute the axis aligned bounding box
template <typename T>
typename simple_mesh<T>::box_type simple_mesh<T>::compute_box() const
{
box_type box;
for (const auto& p : positions)
box.add_point(p);
return box;
}
/// compute vertex normals by averaging triangle normals
template <typename T>
void simple_mesh<T>::compute_vertex_normals()
{
// clear previous normal info
if (has_normals())
normals.clear();
// copy position indices to normals
normal_indices = position_indices;
// initialize normals to null vectors
normals.resize(positions.size(), vec3(0.0f));
// iterate faces
for (idx_type fi = 0; fi < get_nr_faces(); ++fi) {
idx_type c0 = begin_corner(fi);
idx_type ce = end_corner(fi);
vec3 p0 = position(position_indices[c0]);
vec3 dj = position(position_indices[c0 + 1]) - p0;
vec3 nml(0.0f);
for (idx_type ci = c0+2; ci < ce; ++ci) {
vec3 di = position(position_indices[ci]) - p0;
nml += cross(dj, di);
dj = di;
}
T nl = nml.length();
if (nl > 1e-8f) {
nml *= 1.0f/nl;
for (idx_type ci = c0; ci < ce; ++ci)
normal(normal_indices[ci]) += nml;
}
}
for (auto& n : normals)
n.normalize();
}
/// extract vertex attribute array and element array buffers for triangulation and edges in wireframe
template <typename T>
unsigned simple_mesh<T>::extract_vertex_attribute_buffer(
const std::vector<idx_type>& vertex_indices,
const std::vector<vec3i>& unique_triples,
bool include_tex_coords, bool include_normals,
std::vector<T>& attrib_buffer, bool* include_colors_ptr) const
{
// correct inquiry in case data is missing
include_tex_coords = include_tex_coords && !tex_coord_indices.empty() && !tex_coords.empty();
include_normals = include_normals && !normal_indices.empty() && !normals.empty();
bool include_colors = false;
if (include_colors_ptr)
*include_colors_ptr = include_colors = has_colors() && *include_colors_ptr;
// determine number floats per vertex
unsigned nr_floats = 3;
nr_floats += include_tex_coords ? 2 : 0;
nr_floats += include_normals ? 3 : 0;
unsigned color_increment = 0;
if (include_colors) {
color_increment = (int)ceil((float)get_color_size() / sizeof(T));
nr_floats += color_increment;
}
attrib_buffer.resize(nr_floats*unique_triples.size());
T* data_ptr = &attrib_buffer.front();
for (auto t : unique_triples) {
*reinterpret_cast<vec3*>(data_ptr) = positions[t[0]];
data_ptr += 3;
if (include_tex_coords) {
*reinterpret_cast<vec2*>(data_ptr) = tex_coords[t[1]];
data_ptr += 2;
}
if (include_normals) {
*reinterpret_cast<vec3*>(data_ptr) = normals[t[2]];
data_ptr += 3;
}
if (include_colors) {
put_color(t[0], data_ptr);
data_ptr += color_increment;
}
}
return color_increment;
}
template class simple_mesh<float>;
template class simple_mesh<double>;
}
}
}
| 35.119718 | 167 | 0.720373 | [
"mesh",
"vector"
] |
3e554ad379c93a1e15809cb7ac848b0ae4959dfe | 7,008 | tcc | C++ | include/meta/util/sparse_vector.tcc | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 615 | 2015-01-31T17:14:03.000Z | 2022-03-27T03:03:02.000Z | include/meta/util/sparse_vector.tcc | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 167 | 2015-01-20T17:48:16.000Z | 2021-12-20T00:15:29.000Z | include/meta/util/sparse_vector.tcc | Lolik111/meta | c7019401185cdfa15e1193aad821894c35a83e3f | [
"MIT"
] | 264 | 2015-01-30T00:08:01.000Z | 2022-03-02T17:19:11.000Z | /**
* @file sparse_vector.tcc
* @author Chase Geigle
*/
#include <algorithm>
#include "meta/util/sparse_vector.h"
namespace meta
{
namespace util
{
template <class Index, class Value>
sparse_vector<Index, Value>::sparse_vector(uint64_t size) : storage_(size)
{
// nothing
}
template <class Index, class Value>
template <class Iter>
sparse_vector<Index, Value>::sparse_vector(Iter begin, Iter end)
: storage_{begin, end}
{
// nothing
}
template <class Index, class Value>
Value& sparse_vector<Index, Value>::operator[](const Index& index)
{
auto it = std::lower_bound(
std::begin(storage_), std::end(storage_), index,
[](const pair_type& p, const Index& idx) { return p.first < idx; });
if (it == std::end(storage_))
{
storage_.emplace_back(index, Value{});
return storage_.back().second;
}
else if (it->first != index)
{
auto ins = storage_.emplace(it, index, Value{});
return ins->second;
}
else
{
return it->second;
}
}
template <class Index, class Value>
Value sparse_vector<Index, Value>::at(const Index& index) const
{
auto it = std::lower_bound(
std::begin(storage_), std::end(storage_), index,
[](const pair_type& p, const Index& idx) { return p.first < idx; });
if (it == std::end(storage_) || it->first != index)
return Value{};
return it->second;
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::find(const Index& index) const
-> const_iterator
{
auto it = std::lower_bound(
std::begin(storage_), std::end(storage_), index,
[](const pair_type& p, const Index& idx) { return p.first < idx; });
if (it == std::end(storage_) || it->first != index)
return std::end(storage_);
return it;
}
template <class Index, class Value>
template <class... Ts>
void sparse_vector<Index, Value>::emplace_back(Ts&&... ts)
{
storage_.emplace_back(std::forward<Ts>(ts)...);
}
template <class Index, class Value>
void sparse_vector<Index, Value>::reserve(uint64_t size)
{
storage_.reserve(size);
}
template <class Index, class Value>
void sparse_vector<Index, Value>::clear()
{
storage_.clear();
}
template <class Index, class Value>
void sparse_vector<Index, Value>::shrink_to_fit()
{
storage_.shrink_to_fit();
}
template <class Index, class Value>
void sparse_vector<Index, Value>::condense()
{
Value default_value{};
// erase-remove idiom looking for value-initalized elements
storage_.erase(std::remove_if(storage_.begin(), storage_.end(),
[&](const pair_type& p) {
return p.second == default_value;
}),
storage_.end());
shrink_to_fit();
}
template <class Index, class Value>
uint64_t sparse_vector<Index, Value>::size() const
{
return storage_.size();
}
template <class Index, class Value>
uint64_t sparse_vector<Index, Value>::capacity() const
{
return storage_.capacity();
}
template <class Index, class Value>
bool sparse_vector<Index, Value>::empty() const
{
return storage_.empty();
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::contents() const -> const container_type&
{
return storage_;
}
template <class Index, class Value>
void sparse_vector<Index, Value>::contents(container_type cont)
{
storage_ = std::move(cont);
std::sort(std::begin(storage_), std::end(storage_),
[](const pair_type& a, const pair_type& b) {
return a.first < b.first;
});
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::begin() -> iterator
{
return std::begin(storage_);
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::begin() const -> const_iterator
{
return std::begin(storage_);
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::cbegin() const -> const_iterator
{
return storage_.cbegin();
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::end() -> iterator
{
return std::end(storage_);
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::end() const -> const_iterator
{
return std::end(storage_);
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::cend() const -> const_iterator
{
return storage_.cend();
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::erase(iterator pos) -> iterator
{
return storage_.erase(pos);
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::erase(iterator first, iterator last)
-> iterator
{
return storage_.erase(first, last);
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::operator+=(const sparse_vector& rhs)
-> sparse_vector&
{
// use index into the current vector so that we can properly handle
// invalidation of iterators during the loop
uint64_t idx = 0;
uint64_t end = size();
auto second_it = rhs.begin();
auto second_end = rhs.end();
while (idx != end && second_it != second_end)
{
if (storage_[idx].first == second_it->first)
{
storage_[idx].second += second_it->second;
++idx;
++second_it;
}
else if (storage_[idx].first < second_it->first)
{
++idx;
}
else
{
using diff_type = typename iterator::difference_type;
storage_.emplace(begin() + static_cast<diff_type>(idx),
second_it->first, second_it->second);
++idx;
++second_it;
}
}
for (; second_it != second_end; ++second_it)
{
storage_.emplace_back(second_it->first, second_it->second);
}
return *this;
}
template <class Index, class Value>
auto sparse_vector<Index, Value>::operator-=(const sparse_vector& rhs)
-> sparse_vector&
{
// use index into the current vector so that we can properly handle
// invalidation of iterators during the loop
uint64_t idx = 0;
uint64_t end = size();
auto second_it = rhs.begin();
auto second_end = rhs.end();
while (idx != end && second_it != second_end)
{
if (storage_[idx].first == second_it->first)
{
storage_[idx].second -= second_it->second;
++idx;
++second_it;
}
else if (storage_[idx].first < second_it->first)
{
++idx;
}
else
{
using diff_type = typename iterator::difference_type;
storage_.emplace(begin() + static_cast<diff_type>(idx),
second_it->first, -second_it->second);
++idx;
++second_it;
}
}
for (; second_it != second_end; ++second_it)
{
storage_.emplace_back(second_it->first, -second_it->second);
}
return *this;
}
}
}
| 24.589474 | 76 | 0.619578 | [
"vector"
] |
3e5c05665c299e235c7b68b5dcc7d47c409d8196 | 3,488 | cpp | C++ | yices2/src/yices2_sort.cpp | kris-brown/smt-switch | f7fd018eea079dbd05eebf10ac7cc1db146568b0 | [
"BSD-3-Clause"
] | null | null | null | yices2/src/yices2_sort.cpp | kris-brown/smt-switch | f7fd018eea079dbd05eebf10ac7cc1db146568b0 | [
"BSD-3-Clause"
] | null | null | null | yices2/src/yices2_sort.cpp | kris-brown/smt-switch | f7fd018eea079dbd05eebf10ac7cc1db146568b0 | [
"BSD-3-Clause"
] | null | null | null | /********************* */
/*! \file yices2_sort.cpp
** \verbatim
** Top contributors (to current version):
** Amalee Wilson
** This file is part of the smt-switch project.
** Copyright (c) 2020 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file LICENSE in the top-level source
** directory for licensing information.\endverbatim
**
** \brief Yices2 implementation of AbsSort
**
**
**/
#include "yices2_sort.h"
#include <sstream>
#include "exceptions.h"
using namespace std;
namespace smt {
// Yices2Sort implementation
std::size_t Yices2Sort::hash() const
{
// type_t is a unique id, see Yices2 docs.
return type;
}
uint64_t Yices2Sort::get_width() const
{
size_t out_width;
if (yices_type_is_bitvector(type))
{
return (unsigned int)yices_bvtype_size(type);
}
else
{
throw IncorrectUsageException("Can only get width from bit-vector sort");
}
}
Sort Yices2Sort::get_indexsort() const
{
// Arrays are functions in Yices.
if (yices_type_is_function(type))
{
return Sort(new Yices2Sort(yices_type_child(type, 0)));
}
else
{
throw IncorrectUsageException("Can only get index sort from array sort");
}
}
Sort Yices2Sort::get_elemsort() const
{
// Arrays are functions in Yices.
if (yices_type_is_function(type))
{
return Sort(new Yices2Sort(yices_type_child(type, 1)));
}
else
{
throw IncorrectUsageException("Can only get element sort from array sort");
}
}
SortVec Yices2Sort::get_domain_sorts() const
{
if (yices_type_is_function(type))
{
// one less because last is return sort.
int32_t s_arity = yices_type_num_children(type) - 1;
SortVec sorts;
sorts.reserve(s_arity);
for (size_t i = 0; i < s_arity; i++)
{
sorts.push_back(Sort(new Yices2Sort(yices_type_child(type, i))));
}
return sorts;
}
else
{
throw IncorrectUsageException(
"Can't get domain sorts from non-function sort.");
}
}
Sort Yices2Sort::get_codomain_sort() const
{
if (yices_type_is_function(type))
{
// The last element of the result of num_children is the range/codomain
// type.
return Sort(new Yices2Sort(
yices_type_child(type, yices_type_num_children(type) - 1)));
}
else
{
throw IncorrectUsageException("Can only get element sort from array sort");
}
}
string Yices2Sort::get_uninterpreted_name() const
{
throw NotImplementedException(
"get_uninterpreted_name not implemented for Yices2Sort");
}
bool Yices2Sort::compare(const Sort s) const
{
shared_ptr<Yices2Sort> ys = std::static_pointer_cast<Yices2Sort>(s);
return type == ys->type;
}
SortKind Yices2Sort::get_sort_kind() const
{
if (yices_type_is_int(type))
{
return INT;
}
else if (yices_type_is_real(type))
{
return REAL;
}
else if (yices_type_is_bool(type))
{
return BOOL;
}
else if (yices_type_is_bitvector(type))
{
return BV;
}
else if (yices_type_is_function(type))
{
// Test if array or actually function.
// This may not be the most effective way to do this.
if (!is_function)
{
return ARRAY;
}
else
{
return FUNCTION;
}
}
else
{
std::string msg("Unknown Yices2 type: ");
msg += yices_type_to_string(type, 120, 1, 0);
throw NotImplementedException(msg.c_str());
}
}
} // namespace smt
| 21.530864 | 80 | 0.668005 | [
"vector"
] |
3e63c0647ea7a17a62a0400226b052b1d1f4f637 | 8,935 | cpp | C++ | client/client-multi/client-cpp/impl/channel/impl/AbstractHttpChannel.cpp | jbt-iot/kaa | 530787f373b8f8f77d0836698fa2280821c47bbd | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | client/client-multi/client-cpp/impl/channel/impl/AbstractHttpChannel.cpp | jbt-iot/kaa | 530787f373b8f8f77d0836698fa2280821c47bbd | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2022-01-21T23:49:37.000Z | 2022-02-16T01:16:18.000Z | client/client-multi/client-cpp/impl/channel/impl/AbstractHttpChannel.cpp | jbt-iot/kaa | 530787f373b8f8f77d0836698fa2280821c47bbd | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-08-02T17:56:24.000Z | 2018-08-02T17:56:24.000Z | /*
* Copyright 2014-2016 CyberVision, 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.
*/
#if defined(KAA_DEFAULT_BOOTSTRAP_HTTP_CHANNEL) || defined (KAA_DEFAULT_OPERATION_HTTP_CHANNEL)
#include "kaa/channel/impl/AbstractHttpChannel.hpp"
#include "kaa/common/exception/HttpTransportException.hpp"
namespace kaa {
static KaaFailoverReason getNotAccessibleFailoverReason(ServerType type)
{
return type == ServerType::BOOTSTRAP ?
KaaFailoverReason::CURRENT_BOOTSTRAP_SERVER_NA :
KaaFailoverReason::CURRENT_OPERATIONS_SERVER_NA;
}
AbstractHttpChannel::AbstractHttpChannel(IKaaChannelManager& channelManager,
const KeyPair& clientKeys,
IKaaClientContext& context)
: channelManager_(channelManager)
, context_(context)
, clientKeys_(clientKeys)
, httpDataProcessor_(context)
, httpClient_(context)
{
}
void AbstractHttpChannel::processTypes(const std::map<TransportType, ChannelDirection>& types
#ifdef KAA_THREADSAFE
, KAA_MUTEX_UNIQUE& lock
#endif
)
{
auto postRequest = createRequest(currentServer_, multiplexer_->compileRequest(types));
KAA_MUTEX_UNLOCKING("channelGuard_");
KAA_UNLOCK(lock);
KAA_MUTEX_UNLOCKED("channelGuard_");
try {
// Sending http request
EndpointConnectionInfo connection("", "", getServerType());
auto response = httpClient_.sendRequest(*postRequest, &connection);
if (!response) {
KAA_LOG_WARN(boost::format("Channel [%1%] failed to send request %2%:%3%: An empty response returned")
% getId()
% currentServer_->getHost()
% currentServer_->getPort());
KaaFailoverReason reason = getNotAccessibleFailoverReason(getServerType());
onServerFailed(reason);
return;
}
channelManager_.onConnected(connection);
KAA_MUTEX_LOCKING("channelGuard_");
KAA_MUTEX_UNIQUE_DECLARE(lockInternal, channelGuard_);
KAA_MUTEX_LOCKED("channelGuard_");
// Retrieving the avro data from the HTTP response
const std::string& processedResponse = retrieveResponse(*response);
KAA_MUTEX_UNLOCKING("channelGuard_");
KAA_UNLOCK(lockInternal);
KAA_MUTEX_UNLOCKED("channelGuard_");
if (!processedResponse.empty()) {
demultiplexer_->processResponse(
std::vector<std::uint8_t>(reinterpret_cast<const std::uint8_t *>(processedResponse.data()),
reinterpret_cast<const std::uint8_t *>(processedResponse.data() + processedResponse.size())));
}
} catch (HttpTransportException& e) {
KAA_LOG_WARN(boost::format("Channel [%1%] failed to connect %2%:%3%: %4%")
% getId()
% currentServer_->getHost()
% currentServer_->getPort()
% e.getHttpStatusCode());
KaaFailoverReason reason;
switch (e.getHttpStatusCode()) {
case HttpStatusCode::UNAUTHORIZED:
reason = KaaFailoverReason::ENDPOINT_NOT_REGISTERED;
break;
case HttpStatusCode::FORBIDDEN:
reason = KaaFailoverReason::CREDENTIALS_REVOKED;
break;
default:
reason = getNotAccessibleFailoverReason(getServerType());
break;
}
onServerFailed(reason);
} catch (TransportException& e) {
KAA_LOG_WARN(boost::format("Channel [%1%] failed to connect %2%:%3%: %4%")
% getId()
% currentServer_->getHost()
% currentServer_->getPort()
% e.getErrorCode().message());
KaaFailoverReason reason = getNotAccessibleFailoverReason(getServerType());
// Workaround for a case, when the agent has access only to Kaa servers.
/* if (connectivityChecker_ && !connectivityChecker_->checkConnectivity()) {
KAA_LOG_WARN(boost::format("Channel [%1%] detected loss of connectivity")
% getId());
reason = KaaFailoverReason::NO_CONNECTIVITY;
}*/
onServerFailed(reason);
}
}
void AbstractHttpChannel::onServerFailed(KaaFailoverReason reason)
{
auto server = std::dynamic_pointer_cast<ITransportConnectionInfo, IPTransportInfo>(currentServer_);
KAA_LOG_WARN(boost::format("Channel [%1%] detected '%2%' failover for %3%")
% getId()
% LoggingUtils::toString(reason)
% LoggingUtils::toString(*server));
channelManager_.onServerFailed(server, reason);
}
void AbstractHttpChannel::sync(TransportType type)
{
const auto& supportedTypes = getSupportedTransportTypes();
auto it = supportedTypes.find(type);
if (it == supportedTypes.end() || it->second == ChannelDirection::DOWN) {
KAA_LOG_ERROR(boost::format("Channel [%1%] unsupported transport type '%2%'")
% getId()
% LoggingUtils::toString(type));
return;
}
KAA_MUTEX_LOCKING("channelGuard_");
KAA_MUTEX_UNIQUE_DECLARE(lock, channelGuard_);
KAA_MUTEX_LOCKED("channelGuard_");
if (!currentServer_) {
KAA_LOG_WARN(boost::format("Channel [%1%] can't sync: server is null") % getId());
return;
}
processTypes(std::map<TransportType, ChannelDirection>({ { type, it->second } })
#ifdef KAA_THREADSAFE
, lock
#endif
);
}
void AbstractHttpChannel::syncAll()
{
KAA_MUTEX_LOCKING("channelGuard_");
KAA_MUTEX_UNIQUE_DECLARE(lock, channelGuard_);
KAA_MUTEX_LOCKED("channelGuard_");
if (!currentServer_) {
KAA_LOG_WARN(boost::format("Channel [%1%] can't sync: server is null") % getId());
return;
}
processTypes(getSupportedTransportTypes()
#ifdef KAA_THREADSAFE
, lock
#endif
);
}
void AbstractHttpChannel::syncAck(TransportType type)
{
KAA_LOG_WARN(boost::format("Channel [%1%] not support sync ACK operation") % getId());
}
void AbstractHttpChannel::setMultiplexer(IKaaDataMultiplexer *multiplexer)
{
KAA_MUTEX_LOCKING("channelGuard_");
KAA_MUTEX_UNIQUE_DECLARE(lock, channelGuard_);
KAA_MUTEX_LOCKED("channelGuard_");
multiplexer_ = multiplexer;
}
void AbstractHttpChannel::setDemultiplexer(IKaaDataDemultiplexer *demultiplexer)
{
KAA_MUTEX_LOCKING("channelGuard_");
KAA_MUTEX_UNIQUE_DECLARE(lock, channelGuard_);
KAA_MUTEX_LOCKED("channelGuard_");
demultiplexer_ = demultiplexer;
}
void AbstractHttpChannel::setServer(ITransportConnectionInfoPtr server)
{
if (server->getTransportId() != getTransportProtocolId()) {
KAA_LOG_ERROR(boost::format("Channel [%1%] ignored invalid server info") % getId());
return;
}
KAA_MUTEX_LOCKING("channelGuard_");
KAA_MUTEX_UNIQUE_DECLARE(lock, channelGuard_);
KAA_MUTEX_LOCKED("channelGuard_");
KAA_LOG_TRACE(boost::format("Channel [%1%] preparing to use new server %2%")
% getId()
% LoggingUtils::toString(*server));
currentServer_ = std::make_shared<IPTransportInfo>(server);
httpDataProcessor_.setEncoderDecoder(
std::make_shared<RsaEncoderDecoder>(clientKeys_.getPublicKey(),
clientKeys_.getPrivateKey(),
currentServer_->getPublicKey(),
context_));
}
}
#endif
| 38.183761 | 140 | 0.5831 | [
"vector"
] |
3e65cc557e6b50b1bb2a0d80020c775ccddf4168 | 6,769 | hh | C++ | src/physics/material/MaterialData.hh | tmdelellis/celeritas | 5252bcb0659892ae9082ca2b6716e3c84e18004b | [
"Apache-2.0",
"MIT"
] | 22 | 2020-03-31T14:18:22.000Z | 2022-01-10T09:43:06.000Z | src/physics/material/MaterialData.hh | tmdelellis/celeritas | 5252bcb0659892ae9082ca2b6716e3c84e18004b | [
"Apache-2.0",
"MIT"
] | 261 | 2020-04-29T15:14:29.000Z | 2022-03-31T19:07:14.000Z | src/physics/material/MaterialData.hh | tmdelellis/celeritas | 5252bcb0659892ae9082ca2b6716e3c84e18004b | [
"Apache-2.0",
"MIT"
] | 15 | 2020-05-01T19:47:19.000Z | 2021-12-25T06:12:09.000Z | //----------------------------------*-C++-*----------------------------------//
// Copyright 2020 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file MaterialData.hh
//---------------------------------------------------------------------------//
#pragma once
#include "base/Collection.hh"
#include "base/CollectionBuilder.hh"
#include "base/Types.hh"
#include "physics/base/Units.hh"
#include "Types.hh"
namespace celeritas
{
//---------------------------------------------------------------------------//
// PARAMS
//---------------------------------------------------------------------------//
/*!
* Fundamental, invariant properties of an element.
*
* Add elemental properties as needed if they apply to more than one physics
* model. TODO:
* - atomic shell
* - isotopic components
*
* Note that more than one "element def" can exist for a single atomic number:
* there might be different enrichments of an element in the problem.
*/
struct ElementDef
{
int atomic_number = 0; //!< Z number
units::AmuMass atomic_mass; //!< Isotope-weighted average atomic mass
// COMPUTED PROPERTIES
real_type cbrt_z = 0; //!< Z^{1/3}
real_type cbrt_zzp = 0; //!< (Z (Z + 1))^{1/3}
real_type log_z = 0; //!< log Z
real_type coulomb_correction = 0; //!< f(Z)
real_type mass_radiation_coeff = 0; //!< 1/X_0 (bremsstrahlung)
};
//---------------------------------------------------------------------------//
/*!
* Fractional element component of a material.
*
* This represents, e.g., the fraction of hydrogen in water.
*/
struct MatElementComponent
{
ElementId element; //!< Index in MaterialParams elements
real_type fraction; //!< Fraction of number density
};
//---------------------------------------------------------------------------//
/*!
* Fundamental (static) properties of a material.
*
* Multiple material definitions are allowed to reuse a single element
* definition vector (memory management from the params store should handle
* this). Derivative properties such as electron_density are calculated from
* the elemental components.
*/
struct MaterialDef
{
real_type number_density; //!< Atomic number density [1/cm^3]
real_type temperature; //!< Temperature [K]
MatterState matter_state; //!< Solid, liquid, gas
ItemRange<MatElementComponent> elements; //!< Element components
// COMPUTED PROPERTIES
real_type density; //!< Density [g/cm^3]
real_type electron_density; //!< Electron number density [1/cm^3]
real_type rad_length; //!< Radiation length [cm]
units::MevEnergy mean_exc_energy; //!< Mean excitation energy [MeV]
units::LogMevEnergy log_mean_exc_energy; //!< Log mean excitation energy
};
//---------------------------------------------------------------------------//
/*!
* Access material properties on the device.
*
* This view is created from \c MaterialParams.
*
* \sa MaterialParams (owns the pointed-to data)
* \sa ElementView (uses the pointed-to element data in a kernel)
* \sa MaterialView (uses the pointed-to material data in a kernel)
*/
template<Ownership W, MemSpace M>
struct MaterialParamsData
{
template<class T>
using Items = celeritas::Collection<T, W, M>;
Items<ElementDef> elements;
Items<MatElementComponent> elcomponents;
Items<MaterialDef> materials;
ElementComponentId::size_type max_element_components{};
//// MEMBER FUNCTIONS ////
//! Whether the data is assigned
explicit inline CELER_FUNCTION operator bool() const
{
return !materials.empty();
}
//! Assign from another set of data
template<Ownership W2, MemSpace M2>
MaterialParamsData& operator=(const MaterialParamsData<W2, M2>& other)
{
CELER_EXPECT(other);
elements = other.elements;
elcomponents = other.elcomponents;
materials = other.materials;
max_element_components = other.max_element_components;
return *this;
}
};
//---------------------------------------------------------------------------//
// STATE
//---------------------------------------------------------------------------//
/*!
* Dynamic material state of a particle track.
*/
struct MaterialTrackState
{
MaterialId material_id; //!< Current material being tracked
};
//---------------------------------------------------------------------------//
/*!
* Store dynamic states of multiple physical particles.
*
* The size of the view will be the size of the vector of tracks. Each particle
* track state corresponds to the thread ID (\c ThreadId).
*
* The "element scratch space" is a 2D array of reals, indexed with
* [track_id][el_component_id], where the fast-moving dimension has the
* greatest number of element components of any material in the problem. This
* can be used for the physics to calculate microscopic cross sections.
*
* \sa MaterialStateStore (owns the pointed-to data)
* \sa MaterialTrackView (uses the pointed-to data in a kernel)
*/
template<Ownership W, MemSpace M>
struct MaterialStateData
{
template<class T>
using Items = celeritas::StateCollection<T, W, M>;
Items<MaterialTrackState> state;
Items<real_type> element_scratch; // 2D array: [num states][max components]
//! Whether the interface is assigned
explicit CELER_FUNCTION operator bool() const { return !state.empty(); }
//! State size
CELER_FUNCTION size_type size() const { return state.size(); }
//! Assign from another set of data
template<Ownership W2, MemSpace M2>
MaterialStateData& operator=(MaterialStateData<W2, M2>& other)
{
CELER_EXPECT(other);
state = other.state;
element_scratch = other.element_scratch;
return *this;
}
};
//---------------------------------------------------------------------------//
/*!
* Resize a material state in host code.
*/
template<MemSpace M>
inline void resize(
MaterialStateData<Ownership::value, M>* data,
const MaterialParamsData<Ownership::const_reference, MemSpace::host>& params,
size_type size)
{
CELER_EXPECT(size > 0);
make_builder(&data->state).resize(size);
make_builder(&data->element_scratch)
.resize(size * params.max_element_components);
}
//---------------------------------------------------------------------------//
} // namespace celeritas
| 34.535714 | 81 | 0.569213 | [
"vector",
"model",
"solid"
] |
3e6b9aa877b4c0f09f8ddf4f6820422d6267fffc | 15,619 | cpp | C++ | flashlight/fl/distributed/backend/cuda/DistributedBackend.cpp | codekansas/flashlight | 6b9e1f5d00269bda8ca6f453ab7f15bd2b8627f9 | [
"BSD-3-Clause"
] | 1 | 2021-05-26T11:56:41.000Z | 2021-05-26T11:56:41.000Z | flashlight/fl/distributed/backend/cuda/DistributedBackend.cpp | codekansas/flashlight | 6b9e1f5d00269bda8ca6f453ab7f15bd2b8627f9 | [
"BSD-3-Clause"
] | null | null | null | flashlight/fl/distributed/backend/cuda/DistributedBackend.cpp | codekansas/flashlight | 6b9e1f5d00269bda8ca6f453ab7f15bd2b8627f9 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <algorithm>
#include <cstring>
#include <mutex>
#include <stdexcept>
#include <mpi.h>
#include <nccl.h>
#include "flashlight/fl/common/CudaUtils.h"
#include "flashlight/fl/common/Defines.h"
#include "flashlight/fl/common/DevicePtr.h"
#include "flashlight/fl/distributed/DistributedApi.h"
#include "flashlight/fl/distributed/FileStore.h"
#define NCCLCHECK(expr) ::fl::detail::ncclCheck((expr))
#define MPICHECK(expr) ::fl::detail::mpiCheck((expr))
namespace fl {
namespace detail {
namespace {
// We need to pass this flag to our dedicated NCCL CUDA stream, else activity in
// the stream will be precluded from running in parallel with the default stream
constexpr unsigned int kDefaultStreamFlags = cudaStreamNonBlocking;
constexpr const char* kNcclKey = "ncclUniqueId";
class NcclContext {
public:
static NcclContext& getInstance();
NcclContext() = default;
~NcclContext();
void initWithMPI(const std::unordered_map<std::string, std::string>& params);
void initWithFileSystem(
int worldRank,
int worldSize,
const std::unordered_map<std::string, std::string>& params);
ncclComm_t& getComm();
int getWorldSize() const;
int getWorldRank() const;
cudaStream_t getReductionStream() const;
cudaStream_t getWorkerStream() const;
cudaEvent_t getEvent() const;
void* getCoalesceBuffer();
private:
// create CUDA resources
void createCudaResources();
ncclComm_t comm_;
int worldSize_, worldRank_;
// CUDA stream in which NCCL calls run if in async mode
cudaStream_t reductionStream_;
// CUDA stream in which cudaMemcpyAsync calls run if in contiguous mode
cudaStream_t workerStream_;
// Buffer for storing copied gradients contiguously; exists on device memory
void* coalesceBuffer_{nullptr};
std::once_flag allocBuffer_;
// CUDA event to reuse for stream synchronization
cudaEvent_t event_;
};
bool isNonNegativeInteger(const std::string& s) {
return !s.empty() && std::find_if(s.begin(), s.end(), [](char c) {
return !std::isdigit(c);
}) == s.end();
}
ncclDataType_t getNcclTypeForArray(const af::array& arr) {
switch (arr.type()) {
case af::dtype::f16:
return ncclHalf;
case af::dtype::f32:
return ncclFloat32;
case af::dtype::f64:
return ncclFloat64;
case af::dtype::s32:
return ncclInt32;
case af::dtype::s64:
return ncclInt64;
break;
default:
throw std::runtime_error("unsupported data type for allreduce with NCCL");
}
}
} // namespace
void ncclCheck(ncclResult_t r);
void mpiCheck(int ec);
void allreduceCuda(
void* ptr,
size_t count,
ncclDataType_t ncclType,
bool async,
bool contiguous);
} // namespace detail
void allReduce(af::array& arr, bool async /* = false */) {
if (!isDistributedInit()) {
throw std::runtime_error("distributed environment not initialized");
}
ncclDataType_t type = detail::getNcclTypeForArray(arr);
DevicePtr arrPtr(arr);
detail::allreduceCuda(
arrPtr.get(),
arr.elements(),
type,
async,
/* contiguous = */ false);
}
void allReduceMultiple(
std::vector<af::array*> arrs,
bool async /* = false */,
bool contiguous /* = false */) {
// Fast paths
if (arrs.size() == 0) {
return;
}
if (!contiguous) {
// Use nccl groups to do everything in a single kernel launch
NCCLCHECK(ncclGroupStart());
for (auto& arr : arrs) {
allReduce(*arr);
}
NCCLCHECK(ncclGroupEnd());
return;
}
// We can only do a contiguous set reduction if all arrays in the set are of
// the same type, else fail
ncclDataType_t ncclType = detail::getNcclTypeForArray(*arrs[0]);
for (auto& arr : arrs) {
if (detail::getNcclTypeForArray(*arr) != ncclType) {
throw std::runtime_error(
"Cannot perform contiguous set allReduce on a set of tensors "
"of different types");
}
}
// Size of each element in each tensor in bytes
size_t typeSize = af::getSizeOf(arrs[0]->type());
// Device ptrs from each array
std::vector<std::pair<DevicePtr, size_t>> arrPtrs;
arrPtrs.reserve(arrs.size());
size_t totalEls{0};
for (auto& arr : arrs) {
totalEls += arr->elements();
arrPtrs.emplace_back(std::make_pair(DevicePtr(*arr), arr->bytes()));
}
// Make sure our coalesce buffer is large enough. Since we're initializing our
// coalescing cache to the same size, if we're using contiguous sync, it
// should never be larger since we flush if adding an additional buffer would
// exceed the max cache size
if (totalEls * typeSize > DistributedConstants::kCoalesceCacheSize) {
throw std::runtime_error(
"Total coalesce buffer size is larger than existing buffer size");
}
auto& ncclContext = detail::NcclContext::getInstance();
cudaStream_t workerStream = ncclContext.getWorkerStream();
// Block the copy worker stream on the ArrayFire CUDA stream
cuda::synchronizeStreams(
workerStream, cuda::getActiveStream(), ncclContext.getEvent());
// In the worker stream, coalesce gradients into one large buffer so we
// only need to call allReduce
void* coalesceBuffer = ncclContext.getCoalesceBuffer();
auto* cur = reinterpret_cast<char*>(coalesceBuffer);
for (auto& entry : arrPtrs) {
FL_CUDA_CHECK(cudaMemcpyAsync(
cur,
entry.first.get(),
entry.second,
cudaMemcpyDeviceToDevice,
workerStream));
cur += entry.second;
}
// Now, call allReduce once on the entire copy buffer
detail::allreduceCuda(coalesceBuffer, totalEls, ncclType, async, contiguous);
// Block the worker stream's copy operations on allReduce operations that are
// currently enqueued in the reduction stream
cudaStream_t syncStream;
if (async) {
syncStream = ncclContext.getReductionStream();
} else {
syncStream = cuda::getActiveStream();
}
cuda::synchronizeStreams(workerStream, syncStream, ncclContext.getEvent());
// Enqueue operations in the stream to copy back to each respective array from
// the coalesce buffer
cur = reinterpret_cast<char*>(coalesceBuffer);
for (auto& entry : arrPtrs) {
FL_CUDA_CHECK(cudaMemcpyAsync(
entry.first.get(),
cur,
entry.second,
cudaMemcpyDeviceToDevice,
workerStream));
cur += entry.second;
}
}
/**
* Block future operations in the AF Stream on operations currently running in
* the NCCL CUDA stream.
*/
void syncDistributed() {
// If the worker or reduction streams have nothing enqueued, the AF CUDA
// stream will proceed without waiting for anything
auto& ncclContext = detail::NcclContext::getInstance();
cuda::synchronizeStreams(
cuda::getActiveStream(),
ncclContext.getWorkerStream(),
ncclContext.getEvent());
cuda::synchronizeStreams(
cuda::getActiveStream(),
ncclContext.getReductionStream(),
ncclContext.getEvent());
}
int getWorldRank() {
if (!isDistributedInit()) {
return 0;
}
return detail::NcclContext::getInstance().getWorldRank();
}
int getWorldSize() {
if (!isDistributedInit()) {
return 1;
}
return detail::NcclContext::getInstance().getWorldSize();
}
void distributedInit(
DistributedInit initMethod,
int worldRank,
int worldSize,
const std::unordered_map<std::string, std::string>& params /* = {} */) {
if (isDistributedInit()) {
std::cerr << "warning: fl::distributedInit() called more than once\n";
return;
}
if (initMethod == DistributedInit::MPI) {
detail::NcclContext::getInstance().initWithMPI(params);
detail::DistributedInfo::getInstance().initMethod_ = DistributedInit::MPI;
} else if (initMethod == DistributedInit::FILE_SYSTEM) {
detail::NcclContext::getInstance().initWithFileSystem(
worldRank, worldSize, params);
detail::DistributedInfo::getInstance().initMethod_ =
DistributedInit::FILE_SYSTEM;
} else {
throw std::runtime_error(
"unsupported distributed init method for NCCL backend");
}
detail::DistributedInfo::getInstance().isInitialized_ = true;
detail::DistributedInfo::getInstance().backend_ = DistributedBackend::NCCL;
if (getWorldRank() == 0) {
std::cout << "Initialized NCCL " << NCCL_MAJOR << "." << NCCL_MINOR << "."
<< NCCL_PATCH << " successfully!\n";
}
}
namespace detail {
void ncclCheck(ncclResult_t r) {
if (r == ncclSuccess) {
return;
}
const char* err = ncclGetErrorString(r);
if (r == ncclInvalidArgument) {
throw std::invalid_argument(err);
} else if (r == ncclInvalidUsage) {
throw std::logic_error(err);
} else {
throw std::runtime_error(err);
}
}
void mpiCheck(int ec) {
if (ec == MPI_SUCCESS) {
return;
} else {
char buf[MPI_MAX_ERROR_STRING];
int resultlen;
MPI_Error_string(ec, buf, &resultlen);
throw std::runtime_error(buf);
}
}
void allreduceCuda(
void* ptr,
size_t count,
ncclDataType_t ncclType,
bool async,
bool contiguous) {
cudaStream_t syncStream;
auto& ncclContext = detail::NcclContext::getInstance();
if (async) {
syncStream = ncclContext.getReductionStream();
} else {
// AF CUDA stream
syncStream = cuda::getActiveStream(); // assumes current device id
}
// Synchronize with whatever CUDA stream is performing operations needed
// pre-reduction. If we're in contiguous mode, we need the reduction stream to
// wait for the copy in the worker stream to complete. If we're not in
// contiguous mode, we need to wait for the JIT eval triggered by acquisition
// of the af::array's device pointer to complete, which will occur in the AF
// CUDA stream.
if (contiguous) {
// block future reduction stream ops on the copy-worker stream
cuda::synchronizeStreams(
syncStream, ncclContext.getWorkerStream(), ncclContext.getEvent());
} else {
// block future reduction stream ops on the AF CUDA stream
if (async) {
cuda::synchronizeStreams(
syncStream, cuda::getActiveStream(), ncclContext.getEvent());
}
// don't synchronize streams if not async and not contiguous - the AF CUDA
// stream does everything
}
NCCLCHECK(ncclAllReduce(
ptr, ptr, count, ncclType, ncclSum, ncclContext.getComm(), syncStream));
}
namespace {
ncclComm_t& NcclContext::getComm() {
return comm_;
}
int NcclContext::getWorldSize() const {
return worldSize_;
}
int NcclContext::getWorldRank() const {
return worldRank_;
}
cudaStream_t NcclContext::getReductionStream() const {
return reductionStream_;
}
cudaStream_t NcclContext::getWorkerStream() const {
return workerStream_;
}
cudaEvent_t NcclContext::getEvent() const {
return event_;
}
void* NcclContext::getCoalesceBuffer() {
std::call_once(allocBuffer_, [&]() {
FL_CUDA_CHECK(
cudaMalloc(&coalesceBuffer_, DistributedConstants::kCoalesceCacheSize));
});
return coalesceBuffer_;
}
/* static */ NcclContext& NcclContext::getInstance() {
static NcclContext ncclCtx;
return ncclCtx;
}
void NcclContext::createCudaResources() {
// initialize dedicated NCCL CUDA stream to support async allReduce
FL_CUDA_CHECK(cudaStreamCreateWithFlags(
&reductionStream_, detail::kDefaultStreamFlags));
// initialize a third dedicated stream to asynchronously copy gradients
// into a coalesced form if using a contiguous allReduce
FL_CUDA_CHECK(
cudaStreamCreateWithFlags(&workerStream_, detail::kDefaultStreamFlags));
FL_CUDA_CHECK(cudaEventCreate(&event_, cuda::detail::kCudaEventDefaultFlags));
}
void NcclContext::initWithMPI(
const std::unordered_map<std::string, std::string>& params) {
// initializing MPI
MPICHECK(MPI_Init(nullptr, nullptr));
MPICHECK(MPI_Comm_rank(MPI_COMM_WORLD, &worldRank_));
MPICHECK(MPI_Comm_size(MPI_COMM_WORLD, &worldSize_));
auto maxDevicePerNode = params.find(DistributedConstants::kMaxDevicePerNode);
if (maxDevicePerNode == params.end() ||
!isNonNegativeInteger(maxDevicePerNode->second) ||
std::stoi(maxDevicePerNode->second) == 0) {
throw std::invalid_argument(
"invalid MaxDevicePerNode for NCCL initWithMPI");
}
ncclUniqueId id;
// TODO: Determining device is ugly. Find a better way.
af::setDevice(worldRank_ % std::stoi(maxDevicePerNode->second));
// get NCCL unique ID at rank 0 and broadcast it to all others
if (worldRank_ == 0) {
ncclGetUniqueId(&id);
}
MPICHECK(MPI_Bcast((void*)&id, sizeof(id), MPI_BYTE, 0, MPI_COMM_WORLD));
// initializing NCCL
NCCLCHECK(ncclCommInitRank(&comm_, worldSize_, id, worldRank_));
createCudaResources();
}
void NcclContext::initWithFileSystem(
int worldRank,
int worldSize,
const std::unordered_map<std::string, std::string>& params) {
auto filePath = params.find(DistributedConstants::kFilePath);
auto maxDevicePerNode = params.find(DistributedConstants::kMaxDevicePerNode);
if (filePath == params.end() || filePath->second.empty()) {
throw std::invalid_argument("invalid FilePath for NCCL initWithFileSystem");
}
if (maxDevicePerNode == params.end()) {
throw std::invalid_argument(
"invalid MaxDevicePerNode for NCCL initWithFileSystem");
}
worldRank_ = worldRank;
worldSize_ = worldSize;
ncclUniqueId id;
af::setDevice(worldRank_ % std::stoi(maxDevicePerNode->second));
// get NCCL unique ID at rank 0 and broadcast it to all others
if (worldRank_ == 0) {
ncclGetUniqueId(&id);
}
auto fs = FileStore(filePath->second);
if (worldRank_ == 0) {
std::vector<char> data(sizeof(id));
std::memcpy(data.data(), &id, sizeof(id));
fs.set(kNcclKey, data);
} else {
auto data = fs.get(kNcclKey);
std::memcpy(&id, data.data(), sizeof(id));
}
// No need for barrier here as ncclCommInitRank inherently synchronizes
// initializing NCCL
NCCLCHECK(ncclCommInitRank(&comm_, worldSize_, id, worldRank_));
createCudaResources();
}
NcclContext::~NcclContext() {
#ifdef NO_NCCL_COMM_DESTROY_HANDLE
// DEBUG : ncclCommDestroy disabled as it leads to segfault.
#else
// finalizing NCCL
NCCLCHECK(ncclCommDestroy(comm_));
#endif
#ifdef CUDA_NCCL_EVENT_DESTROY_ON_SHUTDOWN
// destroy stream sync event
FL_CUDA_CHECK(cudaEventDestroy(event_));
#endif
// Destroying the dedicated NCCL CUDA stream is a bit odd since the stream
// lives in a global NcclContext singleton. The CUDA driver shuts down when
// exit(0) is called, but the context may not be destroyed until
// afterwards, and destroying streams when the driver has already shut down is
// ungraceful. Manually destroying streams races against the driver, but in
// all cases, streams are destroyed when the driver shuts down, so don't
// destroy the stream by default.
#ifdef CUDA_STREAM_POOL_DESTROY_ON_SHUTDOWN
FL_CUDA_CHECK(cudaStreamDestroy(reductionStream_));
FL_CUDA_CHECK(cudaStreamDestroy(workerStream_));
#endif
// The CUDA driver has already shut down before we can free, so don't free by
// default, as driver shutdown will clean up this memory anyways.
#ifdef CUDA_CONTIGUOUS_BUFFER_FREE_ON_SHUTDOWN
// Free the coalesce buffer if it was allocated
if (coalesceBuffer_ != nullptr) {
FL_CUDA_CHECK(cudaFree(coalesceBuffer_));
}
#endif
if (DistributedInfo::getInstance().initMethod_ == DistributedInit::MPI) {
// finalizing MPI
MPICHECK(MPI_Finalize());
}
}
} // namespace
} // namespace detail
} // namespace fl
| 30.328155 | 80 | 0.70299 | [
"vector"
] |
3e7a3c75d085b91037d843b91e132f28bcfa834b | 2,555 | cpp | C++ | Vic2ToHoI4/Source/HOI4World/Ideologies/Ideologies.cpp | kingofmen/Vic2ToHoI4 | 04e3b872f84cf8aa56e44a63021fe66db1cfe233 | [
"MIT"
] | 1 | 2020-12-19T07:55:43.000Z | 2020-12-19T07:55:43.000Z | Vic2ToHoI4/Source/HOI4World/Ideologies/Ideologies.cpp | kingofmen/Vic2ToHoI4 | 04e3b872f84cf8aa56e44a63021fe66db1cfe233 | [
"MIT"
] | null | null | null | Vic2ToHoI4/Source/HOI4World/Ideologies/Ideologies.cpp | kingofmen/Vic2ToHoI4 | 04e3b872f84cf8aa56e44a63021fe66db1cfe233 | [
"MIT"
] | null | null | null | #include "Ideologies.h"
#include "HOI4World/HoI4Country.h"
#include "IdeologyFile.h"
#include "Log.h"
#include "ParserHelpers.h"
HoI4::Ideologies::Ideologies(const Configuration& theConfiguration)
{
Log(LogLevel::Info) << "\tReading ideologies";
registerKeyword("ideologies", [this](const std::string& unused, std::istream& theStream) {
const IdeologyFile theFile(theStream);
for (const auto& ideology: theFile.getIdeologies())
{
ideologies.insert(ideology);
}
});
registerRegex(commonItems::catchallRegex, commonItems::ignoreItem);
if (theConfiguration.getIdeologiesOptions() != ideologyOptions::keep_default)
{
parseFile("converterIdeologies.txt");
}
parseFile(theConfiguration.getHoI4Path() + "/common/ideologies/00_ideologies.txt");
clearRegisteredKeywords();
}
void HoI4::Ideologies::identifyMajorIdeologies(const std::vector<std::shared_ptr<Country>>& greatPowers,
const std::map<std::string, std::shared_ptr<Country>>& countries,
const Configuration& theConfiguration)
{
Log(LogLevel::Info) << "\tIdentifying major ideologies";
if (theConfiguration.getIdeologiesOptions() == ideologyOptions::keep_major)
{
for (const auto& greatPower: greatPowers)
{
majorIdeologies.insert(greatPower->getGovernmentIdeology());
}
for (const auto& country: countries)
{
if (country.second->isHuman())
{
majorIdeologies.insert(country.second->getGovernmentIdeology());
}
}
majorIdeologies.insert("neutrality");
}
else if (theConfiguration.getIdeologiesOptions() == ideologyOptions::specified)
{
for (const auto& ideology: theConfiguration.getSpecifiedIdeologies())
{
majorIdeologies.insert(ideology);
}
}
// keep default is accomplished by only importing the default ideologies, so we can include
// all ideologies the converter knows for both keep_default and keep_all
else
{
for (const auto& ideology: ideologies)
{
majorIdeologies.insert(ideology.first);
}
}
}
bool HoI4::Ideologies::subIdeologyIsValid(const std::string& ideologyName, const std::string_view subIdeology) const
{
if (const auto ideology = ideologies.find(ideologyName); ideology != ideologies.end())
{
for (const auto& type: ideology->second.getTypes())
{
if (subIdeology == type)
{
return true;
}
}
}
return true;
}
std::optional<HoI4::Ideology> HoI4::Ideologies::getIdeology(const std::string& ideologyName) const
{
if (const auto ideology = ideologies.find(ideologyName); ideology != ideologies.end())
{
return ideology->second;
}
else
{
return std::nullopt;
}
} | 26.340206 | 116 | 0.732681 | [
"vector"
] |
3e7c2c447f2d7e3931a038e20e99d90c6cb49a13 | 1,727 | hpp | C++ | src/mbgl/annotation/annotation_tile.hpp | PareshGupta-WAL/mapbox-gl-native | de0cb554d676a8a84e01ed18508fd3ef52661368 | [
"BSL-1.0",
"Apache-2.0"
] | 1 | 2021-04-26T05:41:57.000Z | 2021-04-26T05:41:57.000Z | src/mbgl/annotation/annotation_tile.hpp | PareshGupta-WAL/mapbox-gl-native | de0cb554d676a8a84e01ed18508fd3ef52661368 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/mbgl/annotation/annotation_tile.hpp | PareshGupta-WAL/mapbox-gl-native | de0cb554d676a8a84e01ed18508fd3ef52661368 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | #pragma once
#include <mbgl/tile/geometry_tile.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
namespace mbgl {
class AnnotationManager;
namespace style {
class UpdateParameters;
} // namespace style
class AnnotationTile : public GeometryTile {
public:
AnnotationTile(const OverscaledTileID&,
const style::UpdateParameters&);
~AnnotationTile() override;
void setNecessity(Necessity) final;
private:
AnnotationManager& annotationManager;
};
class AnnotationTileFeature : public GeometryTileFeature {
public:
AnnotationTileFeature(FeatureType, GeometryCollection,
std::unordered_map<std::string, std::string> properties = {{}});
FeatureType getType() const override { return type; }
optional<Value> getValue(const std::string&) const override;
GeometryCollection getGeometries() const override { return geometries; }
const FeatureType type;
const std::unordered_map<std::string, std::string> properties;
const GeometryCollection geometries;
};
class AnnotationTileLayer : public GeometryTileLayer {
public:
AnnotationTileLayer(std::string);
std::size_t featureCount() const override { return features.size(); }
util::ptr<const GeometryTileFeature> getFeature(std::size_t i) const override { return features[i]; }
std::string getName() const override { return name; };
std::vector<util::ptr<const AnnotationTileFeature>> features;
private:
std::string name;
};
class AnnotationTileData : public GeometryTileData {
public:
util::ptr<GeometryTileLayer> getLayer(const std::string&) const override;
std::unordered_map<std::string, util::ptr<AnnotationTileLayer>> layers;
};
} // namespace mbgl
| 27.854839 | 105 | 0.730168 | [
"vector"
] |
3e7c495d1477c70afd323b7e9006c7340605c70d | 6,078 | hpp | C++ | include/derecho/sst/multicast.hpp | xinzheyang/derecho-unified | b5e79638fcf667cdba42a78fe1404db4235cd462 | [
"BSD-3-Clause"
] | null | null | null | include/derecho/sst/multicast.hpp | xinzheyang/derecho-unified | b5e79638fcf667cdba42a78fe1404db4235cd462 | [
"BSD-3-Clause"
] | null | null | null | include/derecho/sst/multicast.hpp | xinzheyang/derecho-unified | b5e79638fcf667cdba42a78fe1404db4235cd462 | [
"BSD-3-Clause"
] | null | null | null | #include <cassert>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <thread>
#include <vector>
#include "sst.hpp"
namespace sst {
template <typename sstType>
class multicast_group {
// number of messages for which get_buffer has been called
long long int queued_num = -1;
// number of messages for which RDMA write is complete
uint64_t num_sent = 0;
// the number of messages acknowledged by all the nodes
long long int finished_multicasts_num = -1;
// row of the node in the sst
const uint32_t my_row;
// rank of the node in the members list
uint32_t my_member_index;
// rank of node in the senders list
int32_t my_sender_index;
// only one send at a time
std::mutex msg_send_mutex;
// SST
std::shared_ptr<sstType> sst;
// rows indices
const std::vector<uint32_t> row_indices;
const std::vector<int> is_sender;
// start indexes for sst fields it uses
// need to know the range it can operate on
const uint32_t num_received_offset;
const uint32_t slots_offset;
// number of members
const uint32_t num_members;
// number of senders
uint32_t num_senders;
// window size
const uint32_t window_size;
// maximum size that the SST can send
const uint64_t max_msg_size;
std::thread timeout_thread;
void initialize() {
for(auto i : row_indices) {
for(uint j = num_received_offset; j < num_received_offset + num_senders; ++j) {
sst->num_received_sst[i][j] = -1;
}
for(uint j = 0; j < window_size; ++j) {
sst->slots[i][slots_offset + max_msg_size * j] = 0;
(uint64_t&)sst->slots[i][slots_offset + (max_msg_size * (j + 1)) - sizeof(uint64_t)] = 0;
}
}
sst->sync_with_members(row_indices);
}
public:
multicast_group(std::shared_ptr<sstType> sst,
std::vector<uint32_t> row_indices,
uint32_t window_size,
uint64_t max_msg_size,
std::vector<int> is_sender = {},
uint32_t num_received_offset = 0,
uint32_t slots_offset = 0)
: my_row(sst->get_local_index()),
sst(sst),
row_indices(row_indices),
is_sender([is_sender, row_indices]() {
if(is_sender.size() == 0) {
return std::vector<int32_t>(row_indices.size(), 1);
} else {
return is_sender;
}
}()),
num_received_offset(num_received_offset),
slots_offset(slots_offset),
num_members(row_indices.size()),
window_size(window_size),
max_msg_size(max_msg_size + 2 * sizeof(uint64_t)) {
// find my_member_index
for(uint i = 0; i < num_members; ++i) {
if(row_indices[i] == my_row) {
my_member_index = i;
}
}
int j = 0;
for(uint i = 0; i < num_members; ++i) {
if(i == my_member_index) {
my_sender_index = j;
}
if(this->is_sender[i]) {
j++;
}
}
num_senders = j;
if(!this->is_sender[my_member_index]) {
my_sender_index = -1;
}
initialize();
}
volatile char* get_buffer(uint64_t msg_size) {
assert(my_sender_index >= 0);
std::lock_guard<std::mutex> lock(msg_send_mutex);
assert(msg_size <= max_msg_size);
while(true) {
if(queued_num - finished_multicasts_num < window_size) {
queued_num++;
uint32_t slot = queued_num % window_size;
// set size appropriately
(uint64_t&)sst->slots[my_row][slots_offset + (max_msg_size * (slot + 1)) - 2 * sizeof(uint64_t)] = msg_size;
return &sst->slots[my_row][slots_offset + (max_msg_size * slot)];
} else {
long long int min_multicast_num = sst->num_received_sst[my_row][num_received_offset + my_sender_index];
for(auto i : row_indices) {
long long int num_received_sst_copy = sst->num_received_sst[i][num_received_offset + my_sender_index];
min_multicast_num = std::min(min_multicast_num, num_received_sst_copy);
}
if(finished_multicasts_num == min_multicast_num) {
return nullptr;
} else {
finished_multicasts_num = min_multicast_num;
}
}
}
}
void send() {
uint32_t slot = num_sent % window_size;
num_sent++;
((uint64_t&)sst->slots[my_row][slots_offset + max_msg_size * (slot + 1) - sizeof(uint64_t)])++;
sst->put(
(char*)std::addressof(sst->slots[0][slots_offset + max_msg_size * slot]) - sst->getBaseAddress(),
max_msg_size - sizeof(uint64_t));
sst->put(
(char*)std::addressof(sst->slots[0][slots_offset + slot * max_msg_size]) - sst->getBaseAddress() + max_msg_size - sizeof(uint64_t),
sizeof(uint64_t));
}
void debug_print() {
using std::cout;
using std::endl;
cout << "Printing slots::next_seq" << endl;
for(auto i : row_indices) {
for(uint j = 0; j < window_size; ++j) {
cout << (uint64_t&)sst->slots[i][slots_offset + (max_msg_size * (j + 1)) - sizeof(uint64_t)] << " ";
}
cout << endl;
}
cout << "Printing num_received_sst" << endl;
for(auto i : row_indices) {
for(uint j = num_received_offset; j < num_received_offset + num_senders; ++j) {
cout << sst->num_received_sst[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
};
} // namespace sst
| 35.132948 | 147 | 0.55051 | [
"vector"
] |
3e7d44f7f3ff4622052427b248b3880afb97cdc4 | 3,585 | hpp | C++ | data_structures/vector/vector.hpp | JD235/algorithms | 71346a498720dc3da064b3e61de0b369cf7eb76a | [
"MIT"
] | 44 | 2017-12-11T11:13:07.000Z | 2022-03-15T02:59:43.000Z | data_structures/vector/vector.hpp | JD235/algorithms | 71346a498720dc3da064b3e61de0b369cf7eb76a | [
"MIT"
] | 23 | 2018-10-06T06:17:21.000Z | 2021-03-08T17:13:53.000Z | data_structures/vector/vector.hpp | JD235/algorithms | 71346a498720dc3da064b3e61de0b369cf7eb76a | [
"MIT"
] | 113 | 2017-12-12T06:46:04.000Z | 2021-11-15T17:33:11.000Z | #pragma once
#include <memory>
#include <iterator>
#include <utility>
#include <cstddef>
namespace ds {
template <typename T, typename Alloc = std::allocator<T>>
class vector {
using alloc_traits = std::allocator_traits<Alloc>;
public:
// Aliases
using value_type = T;
using allocator_type = Alloc;
using size_type = typename alloc_traits::size_type;
using difference_type = typename alloc_traits::difference_type;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename alloc_traits::pointer;
using const_pointer = typename alloc_traits::const_pointer;
using iterator = value_type*;
using const_iterator = const value_type*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// Constructors
explicit vector(const allocator_type& alloc = allocator_type{})
: m_alloc{alloc}, m_data{nullptr}, m_size{0}, m_capacity{0} {}
// Iterators
constexpr iterator begin() noexcept { return &m_data[0]; }
constexpr const_iterator cbegin() noexcept { return &m_data[0]; }
constexpr const_iterator begin() const noexcept { return &m_data[0]; }
constexpr iterator end() noexcept { return &m_data[m_size]; }
constexpr const_iterator cend() noexcept { return &m_data[m_size]; }
constexpr const_iterator end() const noexcept { return &m_data[m_size]; }
constexpr reverse_iterator rbegin() noexcept { return &m_data[m_size]; }
constexpr const_reverse_iterator crbegin() noexcept { return &m_data[m_size]; }
constexpr const_reverse_iterator rbegin() const noexcept { return &m_data[m_size]; }
constexpr reverse_iterator rend() noexcept { return &m_data[0]; }
constexpr const_reverse_iterator crend() noexcept { return &m_data[0]; }
constexpr const_reverse_iterator rend() const noexcept { return &m_data[0]; }
// Element access
constexpr value_type& operator[](size_type i) { return data()[i]; }
constexpr const value_type& operator[](size_type i) const { return data()[i]; }
constexpr value_type* data() noexcept { return static_cast<value_type*>(m_data); }
constexpr const value_type* data() const noexcept { return static_cast<value_type*>(m_data); }
// Modifiers
void push_back(const value_type& value) { emplace_back(value); }
void push_back(value_type&& value) { emplace_back(std::move(value)); }
template <typename ...Args>
value_type& emplace_back(Args&&... args) {
if (m_size == m_capacity) {
m_capacity = (m_capacity + 1) * 2;
pointer new_data = alloc_traits::allocate(m_alloc, m_capacity);
iterator first = begin();
const_iterator last = cend();
pointer dest = new_data;
for (; first != last; ++dest, ++first) {
alloc_traits::construct(m_alloc, dest, std::forward<Args>(args)...);
alloc_traits::destroy(m_alloc, first);
}
alloc_traits::deallocate(m_alloc, m_data, m_size);
m_data = new_data;
}
alloc_traits::construct(m_alloc, &m_data[m_size], std::forward<Args>(args)...);
return m_data[++m_size];
}
// Capacity
constexpr size_type size() const noexcept { return m_size; }
constexpr size_type capacity() const noexcept { return m_capacity; }
constexpr bool empty() const noexcept { return m_size == 0; }
constexpr size_type max_size() const noexcept { return alloc_traits::max_size(m_alloc); }
private:
allocator_type m_alloc;
pointer m_data;
size_type m_size;
size_type m_capacity;
};
} // namespace ds
| 37.34375 | 98 | 0.704881 | [
"vector"
] |
3e89d665334d9a621b270abfc7221da4deae43ef | 895 | hpp | C++ | Engine/Code/Engine/Renderer/RenderSceneGraph.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Engine/Code/Engine/Renderer/RenderSceneGraph.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | Engine/Code/Engine/Renderer/RenderSceneGraph.hpp | tonyatpeking/SmuSpecialTopic | b61d44e4efacb3c504847deb4d00234601bca49c | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
class Light;
class Camera;
class GameObject;
class Renderable;
class GameObjectManager;
class RenderSceneGraph
{
public:
static RenderSceneGraph* GetDefault();
static void SetCurrentScene( RenderSceneGraph* scene ) { s_default = scene; };
RenderSceneGraph();
~RenderSceneGraph() {};
std::vector<GameObject*>& GetGameObjects();
std::vector<Renderable*>& GetRenderables();
std::vector<GameObject*>& GetLights();
void AddCamera( Camera* camera ) { m_cameras.push_back( camera ); };
void RemoveCamera( Camera* camera );
std::vector<Camera*>& GetCameras();
void SetGameObjectManager( GameObjectManager* manager ) { m_manager = manager; };
private:
std::vector<Renderable*> m_renderables;
static RenderSceneGraph* s_default;
GameObjectManager* m_manager = nullptr;
std::vector<Camera*> m_cameras;
};
| 23.552632 | 85 | 0.70838 | [
"vector"
] |
3e8e2241b448246dcf2ef7fe364c34e611ef52c2 | 5,520 | cpp | C++ | src/interface/TWBitcoinScript.cpp | codeFarmL/wallet-core | 88b6e3c065ebb2965c2d45ac470958d9a863f650 | [
"MIT"
] | null | null | null | src/interface/TWBitcoinScript.cpp | codeFarmL/wallet-core | 88b6e3c065ebb2965c2d45ac470958d9a863f650 | [
"MIT"
] | null | null | null | src/interface/TWBitcoinScript.cpp | codeFarmL/wallet-core | 88b6e3c065ebb2965c2d45ac470958d9a863f650 | [
"MIT"
] | 1 | 2020-09-03T16:07:07.000Z | 2020-09-03T16:07:07.000Z | // Copyright © 2017-2020 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include <TrustWalletCore/TWBitcoinScript.h>
#include "../Bitcoin/Script.h"
#include "../Bitcoin/SigHashType.h"
using namespace TW::Bitcoin;
struct TWBitcoinScript *_Nonnull TWBitcoinScriptCreate() {
auto script = new TWBitcoinScript{};
return script;
}
struct TWBitcoinScript *TWBitcoinScriptCreateWithData(TWData *data) {
auto script = new TWBitcoinScript{};
script->impl.bytes.resize(TWDataSize(data));
TWDataCopyBytes(data, 0, TWDataSize(data), script->impl.bytes.data());
return script;
}
struct TWBitcoinScript *_Nonnull TWBitcoinScriptCreateWithBytes(uint8_t *_Nonnull bytes, size_t size) {
auto script = new TWBitcoinScript{};
std::copy(bytes, bytes + size, std::back_inserter(script->impl.bytes));
return script;
}
struct TWBitcoinScript *TWBitcoinScriptCreateCopy(const struct TWBitcoinScript *script) {
auto newScript = new TWBitcoinScript{};
newScript->impl.bytes = script->impl.bytes;
return newScript;
}
void TWBitcoinScriptDelete(struct TWBitcoinScript *script) {
delete script;
}
size_t TWBitcoinScriptSize(const struct TWBitcoinScript *script) {
return script->impl.bytes.size();
}
TWData *TWBitcoinScriptData(const struct TWBitcoinScript *script) {
return TWDataCreateWithBytes(&script->impl.bytes[0], script->impl.bytes.size());
}
TWData *TWBitcoinScriptScriptHash(const struct TWBitcoinScript *_Nonnull script) {
auto result = script->impl.hash();
return TWDataCreateWithBytes(result.data(), result.size());
}
bool TWBitcoinScriptIsPayToScriptHash(const struct TWBitcoinScript *script) {
return script->impl.isPayToScriptHash();
}
bool TWBitcoinScriptIsPayToWitnessScriptHash(const struct TWBitcoinScript *script) {
return script->impl.isPayToWitnessScriptHash();
}
bool TWBitcoinScriptIsPayToWitnessPublicKeyHash(const struct TWBitcoinScript *script) {
return script->impl.isPayToWitnessPublicKeyHash();
}
bool TWBitcoinScriptIsWitnessProgram(const struct TWBitcoinScript *script) {
return script->impl.isWitnessProgram();
}
bool TWBitcoinScriptEqual(const struct TWBitcoinScript *_Nonnull lhs, const struct TWBitcoinScript *_Nonnull rhs) {
return lhs->impl.bytes == rhs->impl.bytes;
}
TWData *TWBitcoinScriptMatchPayToPubkey(const struct TWBitcoinScript *script) {
std::vector<uint8_t> data;
if (script->impl.matchPayToPublicKey(data)) {
return TWDataCreateWithBytes(data.data(), data.size());
}
return nullptr;
}
TWData *TWBitcoinScriptMatchPayToPubkeyHash(const struct TWBitcoinScript *script) {
std::vector<uint8_t> data;
if (script->impl.matchPayToPublicKeyHash(data)) {
return TWDataCreateWithBytes(data.data(), data.size());
}
return nullptr;
}
TWData *_Nullable TWBitcoinScriptMatchPayToScriptHash(const struct TWBitcoinScript *script) {
std::vector<uint8_t> data;
if (script->impl.matchPayToScriptHash(data)) {
return TWDataCreateWithBytes(data.data(), data.size());
}
return nullptr;
}
TWData *_Nullable TWBitcoinScriptMatchPayToWitnessPublicKeyHash(const struct TWBitcoinScript *script) {
std::vector<uint8_t> data;
if (script->impl.matchPayToWitnessPublicKeyHash(data)) {
return TWDataCreateWithBytes(data.data(), data.size());
}
return nullptr;
}
TWData *_Nullable TWBitcoinScriptMatchPayToWitnessScriptHash(const struct TWBitcoinScript *script) {
std::vector<uint8_t> data;
if (script->impl.matchPayToWitnessScriptHash(data)) {
return TWDataCreateWithBytes(data.data(), data.size());
}
return nullptr;
}
TWData *TWBitcoinScriptEncode(const struct TWBitcoinScript *script) {
auto result = std::vector<uint8_t>{};
script->impl.encode(result);
return TWDataCreateWithBytes(result.data(), result.size());
}
struct TWBitcoinScript *TWBitcoinScriptBuildPayToPublicKeyHash(TWData *hash) {
auto v = reinterpret_cast<const std::vector<uint8_t>*>(hash);
auto script = Script::buildPayToPublicKeyHash(*v);
return new TWBitcoinScript{ .impl = script };
}
struct TWBitcoinScript *TWBitcoinScriptBuildPayToScriptHash(TWData *scriptHash) {
auto v = reinterpret_cast<const std::vector<uint8_t>*>(scriptHash);
auto script = Script::buildPayToScriptHash(*v);
return new TWBitcoinScript{ .impl = script };
}
struct TWBitcoinScript *TWBitcoinScriptBuildPayToWitnessPubkeyHash(TWData *hash) {
auto v = reinterpret_cast<const std::vector<uint8_t>*>(hash);
auto script = Script::buildPayToWitnessPublicKeyHash(*v);
return new TWBitcoinScript{ .impl = script };
}
struct TWBitcoinScript *TWBitcoinScriptBuildPayToWitnessScriptHash(TWData *scriptHash) {
auto v = reinterpret_cast<const std::vector<uint8_t>*>(scriptHash);
auto script = Script::buildPayToWitnessScriptHash(*v);
return new TWBitcoinScript{ .impl = script };
}
struct TWBitcoinScript *_Nonnull TWBitcoinScriptLockScriptForAddress(TWString *_Nonnull address, enum TWCoinType coin) {
auto s = reinterpret_cast<const std::string*>(address);
auto script = Script::lockScriptForAddress(*s, coin);
return new TWBitcoinScript{ .impl = script };
}
enum TWBitcoinSigHashType TWBitcoinScriptHashTypeForCoin(enum TWCoinType coinType) {
return TW::Bitcoin::hashTypeForCoin(coinType);
}
| 35.844156 | 120 | 0.753623 | [
"vector"
] |
3e94b398779ed0e1377322ef3ed8977ec9f8a5e2 | 2,387 | hpp | C++ | include/unicomm/server_comm.hpp | Chrizzly/libunicomm | 3aefc02445a5b1e047cc40daaddb7cf9b5082404 | [
"BSL-1.0"
] | null | null | null | include/unicomm/server_comm.hpp | Chrizzly/libunicomm | 3aefc02445a5b1e047cc40daaddb7cf9b5082404 | [
"BSL-1.0"
] | null | null | null | include/unicomm/server_comm.hpp | Chrizzly/libunicomm | 3aefc02445a5b1e047cc40daaddb7cf9b5082404 | [
"BSL-1.0"
] | 2 | 2019-03-16T07:07:16.000Z | 2020-01-05T11:14:58.000Z | ///////////////////////////////////////////////////////////////////////////////
// server_comm.hpp
//
// unicomm - Unified Communication protocol C++ library.
//
// Server's communication service definition.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// 2010, (c) Dmitry Timoshenko.
#ifdef _MSC_VER
# pragma once
#endif // _MSC_VER
#ifndef UNI_SERVER_COMM_HPP_
#define UNI_SERVER_COMM_HPP_
/** @file server_comm.hpp Server's communication service definition. */
#include <unicomm/config/auto_link.hpp>
#include <unicomm/comm.hpp>
/** @namespace unicomm Unicomm library root namespace. */
namespace unicomm
{
// forward
class config;
/** Server's communication service.
*
* Unicomm transport layer.
*/
class UNICOMM_DECL server_communicator : public communicator
{
//////////////////////////////////////////////////////////////////////////
// interface
public:
/** Server's communicator smart pointer type. */
typedef boost::shared_ptr<server_communicator> pointer_type;
public:
#ifdef UNICOMM_SSL
/** Constructs an object.
*
* @param owner Reference to the communicator object's owner.
* @param ioservice Boost asio io service object.
* @param context Boost asio ssl context object.
* @param config Configuration object.
*/
server_communicator(dispatcher& owner, boost::asio::io_service &ioservice,
boost::asio::ssl::context& context, const unicomm::config& config);
#else // UNICOMM_SSL
/** Constructs an object.
*
* @param owner Reference to the communicator object's owner.
* @param ioservice Boost asio io service object.
* @param config Configuration object.
*/
server_communicator(dispatcher& owner, boost::asio::io_service &ioservice,
const unicomm::config& config);
#endif // UNICOMM_SSL
/** Close connection and destroys an object. */
~server_communicator(void);
public:
#ifdef UNICOMM_SSL
//////////////////////////////////////////////////////////////////////////
// private stuff
private:
/** Used by owner to handle connection success.
*
* @param handler Boost asio handshake handler.
*/
void asio_success_connect_handler(const asio_handshake_handler_type& handler);
#endif // UNICOMM_SSL
};
} // namespace unicomm
#endif // UNI_SERVER_COMM_HPP_
| 25.126316 | 80 | 0.656054 | [
"object"
] |
3e98a004b766912d0a1997e57347d5b8f1d0b070 | 9,049 | cpp | C++ | src/Database.cpp | ArlingtonBrooks/tfstat | 1e0164710587024247ced249be1c900024c06d1e | [
"BSD-2-Clause"
] | null | null | null | src/Database.cpp | ArlingtonBrooks/tfstat | 1e0164710587024247ced249be1c900024c06d1e | [
"BSD-2-Clause"
] | null | null | null | src/Database.cpp | ArlingtonBrooks/tfstat | 1e0164710587024247ced249be1c900024c06d1e | [
"BSD-2-Clause"
] | null | null | null | #include "Common.hpp"
#include "Database.hpp"
bool operator<(DBASE_ENTRY a, const DBASE_ENTRY b) {return (a.TimeVal < b.TimeVal);};
bool operator>(DBASE_ENTRY a, const DBASE_ENTRY b) {return (a.TimeVal < b.TimeVal);};
bool operator<=(DBASE_ENTRY a, const DBASE_ENTRY b) {return (a.TimeVal < b.TimeVal);};
bool operator>=(DBASE_ENTRY a, const DBASE_ENTRY b) {return (a.TimeVal < b.TimeVal);};
//FIXME: doesn't appear to be properly overwriting old DBase entries.
//First 64-bits is saved checksum
std::vector<DBASE_ENTRY> LoadDB(std::string KeyLoc)
{
long unsigned int chk = checksum(KeyLoc,sizeof(long unsigned int));
if (DEBUG)
fprintf(stderr,"Database Keylist Checksum: %lu\n",chk);
std::vector<DBASE_ENTRY> DBK;
std::fstream f;
f.open(KeyLoc.c_str(),std::ios::in | std::ios::binary);
if (!f)
return DBK;
long unsigned int chk_file;
f.read((char*)&chk_file,sizeof(long unsigned int));
if (chk_file != chk)
{
fprintf(stderr,"Checksum is invalid for %s: %lu != %lu\n",KeyLoc.c_str(),chk_file,chk);
return DBK;
}
while (f.good()) //FIXME: another way to avoid errors?
{
DBASE_ENTRY et;
f.read((char*)&et,sizeof(DBASE_ENTRY));
if (f.gcount() != sizeof(DBASE_ENTRY))
{
printf("Unable to read entry from database %s\n",KeyLoc.c_str());
break;
}
else
DBK.push_back(et);
}
if (DEBUG)
fprintf(stderr,"Database keylist loaded successfully\n");
f.close();
SortDBase(&DBK[0],DBK.size());
return DBK;
}
long unsigned int checksum(std::string FileLoc, unsigned int SkipStart)
{
std::fstream f;
long unsigned int SUM = 0;
unsigned char VAL = 0;
f.open(FileLoc.c_str(),std::ios::in | std::ios::binary);
f.seekp(SkipStart);
while (f.good()) //FIXME: another way to avoid errors?
{
f.read((char*)&VAL,sizeof(char));
if (f.gcount() == sizeof(char))
SUM += (long unsigned int) VAL;
}
f.close();
return SUM;
}
void SortDBase(DBASE_ENTRY* DB, unsigned int size, bool HTL)
{
//Create a min heap (algorithm)
std::make_heap(DB,DB+size);
//Sort min heap (algorithm)
std::sort_heap(DB,DB+size);
//Reverse if desired;
if (HTL)
std::reverse(DB,DB+size);
}
//FIXME: check for errors; //FIXME: this might multiply number of keys between uses.
bool SaveDBK(std::string Location, std::vector<DBASE_ENTRY> vals, bool FailOnHistoryLimit)
{
if (vals.size() > 0)
SortDBase(&vals[0],vals.size());
else
{
fprintf(stderr,"ERROR: no database values to save.\n");
return 0;
}
if (FailOnHistoryLimit && vals.back().TimeVal - vals.front().TimeVal > History)
{
fprintf(stderr,"Exceeds history limit!\n");
return 0;
}
if (vals.back().TimeVal - vals.front().TimeVal > History)
fprintf(stderr,"WARNING: History Limit Exceeded. Saving anyway...");
std::fstream f;
f.open(Location.c_str(),std::ios::in|std::ios::out|std::ios::binary);
if (!f)
{
MakeFile(Location);
f.open(Location.c_str(),std::ios::in|std::ios::out|std::ios::binary);
}
f.seekp(sizeof(long unsigned int)); //skip checksum storage;
for (int i = 0; i < vals.size(); i++)
{
f.write((char*)&vals[i],sizeof(DBASE_ENTRY));
}
//save checksum
f.flush();
long unsigned int CK = checksum(Location,sizeof(long unsigned int));
f.seekp(0);
f.write((char*)&CK,sizeof(long unsigned int));
f.flush();
f.close();
printf("WROTE DBASE KEYS; CHKSUM = %d\n",CK);
return true;
}
//FIXME: do a case for time1 == time2 and also FIGURE OUT WHY IT'S SAVING SO MANY!
std::vector<DBASE_ENTRY> SaveToDB(std::string Location, std::string DBK_Location, TFSTATS entry, std::vector<DBASE_ENTRY> dbk)
{
std::fstream f;
f.open(Location.c_str(),std::ios::in|std::ios::out|std::ios::binary|std::ios::ate);
if (!f)
{
if (!MakeFile(Location))
fprintf(stderr,"Failed to create file at %s\n",Location.c_str());
f.open(Location.c_str(),std::ios::in|std::ios::out|std::ios::binary|std::ios::ate);
}
if (dbk.size() > 0)
{
SortDBase(&dbk[0],dbk.size(),true);
unsigned int EndLoc = f.tellg();
if (dbk.back().TimeVal - dbk.front().TimeVal > History)
{//FIXME This doesn't actually work;
printf("HISTORY EXCEEDS\n");
//Overwrite oldest entry;
if (entry.DateTimeZulu != dbk.back().TimeVal) //NB: Refresh time is handled externally;
{//Check for overlap and write if necessary;
TFSTATS LastVal;
f.seekp(dbk.back().SeekPos);
f.read((char*)&LastVal,sizeof(TFSTATS));
printf("Last: %ld,%ld,%ld,%ld\n",LastVal.Statlist.b_rcv,LastVal.Statlist.pk_rcv,LastVal.Statlist.b_tx,LastVal.Statlist.pk_tx);
printf("NEW: %ld,%ld,%ld,%ld\n",entry.Statlist.b_rcv,entry.Statlist.pk_rcv,entry.Statlist.b_tx,entry.Statlist.pk_tx);
if (SaveAll || LastVal.Statlist != entry.Statlist)
{
if (DEBUG)
printf("NEW DATA: Saving to file\n");
dbk[0].TimeVal = entry.DateTimeZulu; //Overwrite key time loc
f.seekp(dbk[0].SeekPos); //Overwrite dbase entry
f.write((char*)&entry,sizeof(TFSTATS));
}
else if (DEBUG)
printf("DEBUG: Not saving history due to stat overlap\n");
}
else
if (DEBUG)
printf("DEBUG: Not saving history due to time overlap.\n");
//dbk[0] = NewVal;
//f.seekp(NewVal.SeekPos);
//f.write((char*)&entry,sizeof(TFSTATS));
}
else
{
printf("History not exceeded\n");
if (entry.DateTimeZulu != dbk.back().TimeVal)
{
TFSTATS LastVal;
f.seekp(dbk.back().SeekPos);
f.read((char*)&LastVal,sizeof(TFSTATS));
printf("Last: %ld,%ld,%ld,%ld\n",LastVal.Statlist.b_rcv,LastVal.Statlist.pk_rcv,LastVal.Statlist.b_tx,LastVal.Statlist.pk_tx);
printf("NEW: %ld,%ld,%ld,%ld\n",entry.Statlist.b_rcv,entry.Statlist.pk_rcv,entry.Statlist.b_tx,entry.Statlist.pk_tx);
if (SaveAll || LastVal.Statlist != entry.Statlist)
{
if (DEBUG)
printf("NEW DATA: Saving to file\n");
DBASE_ENTRY NewVal;
NewVal.TimeVal = entry.DateTimeZulu;
NewVal.SeekPos = EndLoc;
dbk.push_back(NewVal);
f.seekp(NewVal.SeekPos);
f.write((char*)&entry,sizeof(TFSTATS));
}
else if (DEBUG)
printf("DEBUG: Not saving history due to stat overlap\n");
}
else
if (DEBUG)
printf("DEBUG: Not saving history due to time overlap.\n");
}
SaveDBK(DBK_Location,dbk,false);
}
else
{
if (DEBUG)
printf("Database key is null length; Saving to file;\n");
DBASE_ENTRY NewVal;
NewVal.TimeVal = entry.DateTimeZulu;
NewVal.SeekPos = (unsigned int)f.tellg() + sizeof(long unsigned int);
dbk.push_back(NewVal);
f.seekp(NewVal.SeekPos);
f.write((char*)&entry,sizeof(TFSTATS));
SaveDBK(DBK_Location,dbk,false);
}
f.flush();
f.close();
return dbk;
}
void DumpDatabase(std::string Location)
{
std::fstream f;
f.open(Location.c_str(),std::ios::in|std::ios::binary);
if (f.fail())
{
printf("Failed to open database file %s\n",Location.c_str());
return;
}
printf("Database for %s\n",Location.c_str());
printf("YYYYMMDDHHMM,Bytes RCV,Bytes TX,Packets RCV,Packets TX\n");
f.seekp(sizeof(long unsigned int));
TFSTATS Entry;
while (f.good()) //FIXME: prints double at end of file;
{
f.read((char*)&Entry,sizeof(Entry));
printf("%04d%02d%02d%02d%02d,",Entry.DateTimeZulu.year+1900, Entry.DateTimeZulu.month, Entry.DateTimeZulu.day, Entry.DateTimeZulu.hour, Entry.DateTimeZulu.minute); //Date
printf("%lu,%lu,",Entry.Statlist.b_rcv,Entry.Statlist.b_tx); //Bytes
printf("%lu,%lu\n",Entry.Statlist.pk_rcv,Entry.Statlist.pk_tx); //Packet count;
}
}
void DumpKeys(std::string Location)
{
std::fstream f;
f.open(Location.c_str(),std::ios::in|std::ios::binary);
f.seekp(sizeof(long unsigned int));
DBASE_ENTRY DBE;
while (f.good()) //FIXME: prints double at end of file;
{
f.read((char*)&DBE,sizeof(DBASE_ENTRY));
printf("KEY: %lu at %02d:%02d on %d\n",DBE.SeekPos,DBE.TimeVal.hour,DBE.TimeVal.minute,DBE.TimeVal.day);
}
}
| 35.073643 | 178 | 0.575091 | [
"vector"
] |
3e993debe6b74a1554ff70c0e4d41a185fa335a3 | 23,732 | cpp | C++ | catboost/libs/quantized_pool/serialization.cpp | bsharchilev/catboost | c6e4a9375c1650668750dd4b127ccb387365423d | [
"Apache-2.0"
] | null | null | null | catboost/libs/quantized_pool/serialization.cpp | bsharchilev/catboost | c6e4a9375c1650668750dd4b127ccb387365423d | [
"Apache-2.0"
] | null | null | null | catboost/libs/quantized_pool/serialization.cpp | bsharchilev/catboost | c6e4a9375c1650668750dd4b127ccb387365423d | [
"Apache-2.0"
] | null | null | null | #include "serialization.h"
#include "pool.h"
#include <catboost/idl/pool/flat/quantized_chunk_t.fbs.h>
#include <catboost/idl/pool/proto/metainfo.pb.h>
#include <catboost/idl/pool/proto/quantization_schema.pb.h>
#include <catboost/libs/helpers/exception.h>
#include <contrib/libs/flatbuffers/include/flatbuffers/flatbuffers.h>
#include <util/digest/numeric.h>
#include <util/folder/path.h>
#include <util/generic/algorithm.h>
#include <util/generic/array_ref.h>
#include <util/generic/array_size.h>
#include <util/generic/deque.h>
#include <util/generic/strbuf.h>
#include <util/generic/string.h>
#include <util/generic/utility.h>
#include <util/generic/vector.h>
#include <util/memory/blob.h>
#include <util/stream/file.h>
#include <util/stream/input.h>
#include <util/stream/length.h>
#include <util/stream/mem.h>
#include <util/stream/output.h>
#include <util/system/byteorder.h>
#include <util/system/unaligned_mem.h>
using NCB::NIdl::TPoolMetainfo;
using NCB::NIdl::TPoolQuantizationSchema;
static const char Magic[] = "CatboostQuantizedPool";
static const size_t MagicSize = Y_ARRAY_SIZE(Magic); // yes, with terminating zero
static const char MagicEnd[] = "CatboostQuantizedPoolEnd";
static const size_t MagicEndSize = Y_ARRAY_SIZE(MagicEnd); // yes, with terminating zero
static const ui32 Version = 1;
static const ui32 VersionHash = IntHash(Version);
static TDeque<ui32> CollectAndSortKeys(const THashMap<size_t, size_t>& m) {
TDeque<ui32> res;
for (const auto kv : m) {
Y_ASSERT(kv.first <= static_cast<size_t>(Max<ui32>()));
res.push_back(kv.first);
}
Sort(res);
return res;
}
template <typename T>
static void WriteLittleEndian(const T value, IOutputStream* const output) {
const auto le = HostToLittle(value);
output->Write(&le, sizeof(le));
}
template <typename T>
static void ReadLittleEndian(T* const value, IInputStream* const input) {
T le;
const auto bytesRead = input->Load(&le, sizeof(le));
CB_ENSURE(bytesRead == sizeof(le));
*value = LittleToHost(le);
}
static void AddPadding(const ui64 alignment, TCountingOutput* const output) {
if (output->Counter() % alignment == 0) {
return;
}
const auto bytesToWrite = alignment - output->Counter() % alignment;
for (ui64 i = 0; i < bytesToWrite; ++i) {
output->Write('\0');
}
}
static void SkipPadding(const ui64 alignment, TCountingInput* const input) {
if (input->Counter() % alignment == 0) {
return;
}
const auto bytesToSkip = alignment - input->Counter() % alignment;
const auto bytesSkipped = input->Skip(bytesToSkip);
CB_ENSURE(bytesToSkip == bytesSkipped);
}
namespace {
struct TChunkInfo {
ui32 Size = 0;
ui64 Offset = 0;
ui32 DocumentOffset = 0;
ui32 DocumentsInChunkCount = 0;
TChunkInfo() = default;
TChunkInfo(ui32 size, ui64 offset, ui32 documentOffset, ui32 documentsInChunkCount)
: Size(size)
, Offset(offset)
, DocumentOffset(documentOffset)
, DocumentsInChunkCount(documentsInChunkCount) {
}
};
}
static void WriteChunk(
const NCB::TQuantizedPool::TChunkDescription& chunk,
TCountingOutput* const output,
TDeque<TChunkInfo>* const chunkInfos,
flatbuffers::FlatBufferBuilder* const builder) {
builder->Clear();
const auto quantsOffset = builder->CreateVector(
chunk.Chunk->Quants()->data(),
chunk.Chunk->Quants()->size());
NCB::NIdl::TQuantizedFeatureChunkBuilder chunkBuilder(*builder);
chunkBuilder.add_BitsPerDocument(chunk.Chunk->BitsPerDocument());
chunkBuilder.add_Quants(quantsOffset);
builder->Finish(chunkBuilder.Finish());
AddPadding(16, output);
const auto chunkOffset = output->Counter();
output->Write(builder->GetBufferPointer(), builder->GetSize());
chunkInfos->emplace_back(builder->GetSize(), chunkOffset, chunk.DocumentOffset, chunk.DocumentCount);
}
static void WriteHeader(TCountingOutput* const output) {
output->Write(Magic, MagicSize);
WriteLittleEndian(Version, output);
WriteLittleEndian(VersionHash, output);
const ui32 metainfoSize = 0;
WriteLittleEndian(metainfoSize, output);
AddPadding(16, output);
// we may add some metainfo here
}
static TPoolMetainfo MakePoolMetainfo(
const THashMap<size_t, size_t>& columnIndexToLocalIndex,
const TConstArrayRef<EColumn> columnTypes,
const size_t documentCount,
const TConstArrayRef<size_t> ignoredColumnIndices) {
Y_ASSERT(columnIndexToLocalIndex.size() == columnTypes.size());
TPoolMetainfo metainfo;
metainfo.SetDocumentCount(documentCount);
for (const auto& kv : columnIndexToLocalIndex) {
NCB::NIdl::EColumnType pbColumnType;
switch (columnTypes[kv.second]) {
case EColumn::Num:
pbColumnType = NCB::NIdl::CT_NUMERIC;
break;
case EColumn::Categ:
pbColumnType = NCB::NIdl::CT_CATEGORICAL;
break;
case EColumn::Label:
pbColumnType = NCB::NIdl::CT_LABEL;
break;
case EColumn::Baseline:
pbColumnType = NCB::NIdl::CT_BASELINE;
break;
case EColumn::Weight:
pbColumnType = NCB::NIdl::CT_WEIGHT;
break;
case EColumn::DocId:
pbColumnType = NCB::NIdl::CT_DOCUMENT_ID;
break;
case EColumn::GroupId:
pbColumnType = NCB::NIdl::CT_GROUP_ID;
break;
case EColumn::GroupWeight:
pbColumnType = NCB::NIdl::CT_GROUP_WEIGHT;
break;
case EColumn::SubgroupId:
pbColumnType = NCB::NIdl::CT_SUBGROUP_ID;
break;
case EColumn::Sparse:
pbColumnType = NCB::NIdl::CT_SPARSE;
break;
case EColumn::Timestamp:
case EColumn::Prediction:
case EColumn::Auxiliary:
ythrow TCatboostException() << "unexpected column type in quantized pool";
}
metainfo.MutableColumnIndexToType()->insert({static_cast<ui32>(kv.first), pbColumnType});
}
if (ignoredColumnIndices) {
metainfo.MutableIgnoredColumnIndices()->Reserve(ignoredColumnIndices.size());
for (const auto index : ignoredColumnIndices) {
metainfo.AddIgnoredColumnIndices(index);
}
}
return metainfo;
}
static void WriteAsOneFile(const NCB::TQuantizedPool& pool, IOutputStream* slave) {
TCountingOutput output(slave);
WriteHeader(&output);
const auto chunksOffset = output.Counter();
const auto sortedTrueFeatureIndices = CollectAndSortKeys(pool.ColumnIndexToLocalIndex);
TDeque<TDeque<TChunkInfo>> perFeatureChunkInfos;
perFeatureChunkInfos.resize(pool.ColumnIndexToLocalIndex.size());
{
flatbuffers::FlatBufferBuilder builder;
for (const auto trueFeatureIndex : sortedTrueFeatureIndices) {
const auto localIndex = pool.ColumnIndexToLocalIndex.at(trueFeatureIndex);
auto* const chunkInfos = &perFeatureChunkInfos[localIndex];
for (const auto& chunk : pool.Chunks[localIndex]) {
WriteChunk(chunk, &output, chunkInfos, &builder);
}
}
}
const ui64 poolMetainfoSizeOffset = output.Counter();
{
const auto poolMetainfo = MakePoolMetainfo(
pool.ColumnIndexToLocalIndex,
pool.ColumnTypes,
pool.DocumentCount,
pool.IgnoredColumnIndices);
const ui32 poolMetainfoSize = poolMetainfo.ByteSizeLong();
WriteLittleEndian(poolMetainfoSize, &output);
poolMetainfo.SerializeToStream(&output);
}
const ui64 quantizationSchemaSizeOffset = output.Counter();
const ui32 quantizationSchemaSize = pool.QuantizationSchema.ByteSizeLong();
WriteLittleEndian(quantizationSchemaSize, &output);
pool.QuantizationSchema.SerializeToStream(&output);
const ui64 featureCountOffset = output.Counter();
const ui32 featureCount = sortedTrueFeatureIndices.size();
WriteLittleEndian(featureCount, &output);
for (const ui32 trueFeatureIndex : sortedTrueFeatureIndices) {
const auto localIndex = pool.ColumnIndexToLocalIndex.at(trueFeatureIndex);
const ui32 chunkCount = perFeatureChunkInfos[localIndex].size();
WriteLittleEndian(trueFeatureIndex, &output);
WriteLittleEndian(chunkCount, &output);
for (const auto& chunkInfo : perFeatureChunkInfos[localIndex]) {
WriteLittleEndian(chunkInfo.Size, &output);
WriteLittleEndian(chunkInfo.Offset, &output);
WriteLittleEndian(chunkInfo.DocumentOffset, &output);
WriteLittleEndian(chunkInfo.DocumentsInChunkCount, &output);
}
}
WriteLittleEndian(chunksOffset, &output);
WriteLittleEndian(poolMetainfoSizeOffset, &output);
WriteLittleEndian(quantizationSchemaSizeOffset, &output);
WriteLittleEndian(featureCountOffset, &output);
output.Write(MagicEnd, MagicEndSize);
}
void NCB::SaveQuantizedPool(const TQuantizedPool& pool, IOutputStream* const output) {
WriteAsOneFile(pool, output);
}
static void ValidatePoolPart(const TConstArrayRef<char> blob) {
// TODO(yazevnul)
(void)blob;
}
static void ReadHeader(TCountingInput* const input) {
char magic[MagicSize];
const auto magicSize = input->Load(magic, MagicSize);
CB_ENSURE(MagicSize == magicSize);
CB_ENSURE(!std::memcmp(magic, Magic, MagicSize));
ui32 version;
ReadLittleEndian(&version, input);
CB_ENSURE(Version == version);
ui32 versionHash;
ReadLittleEndian(&versionHash, input);
CB_ENSURE(VersionHash == versionHash);
ui32 metainfoSize;
ReadLittleEndian(&metainfoSize, input);
SkipPadding(16, input);
const auto metainfoBytesSkipped = input->Skip(metainfoSize);
CB_ENSURE(metainfoSize == metainfoBytesSkipped);
}
template <typename T>
static T RoundUpTo(const T value, const T multiple) {
if (value % multiple == 0) {
return value;
}
return value + (multiple - value % multiple);
}
static void AddPoolMetainfo(const TPoolMetainfo& metainfo, NCB::TQuantizedPool* const pool) {
pool->DocumentCount = metainfo.GetDocumentCount();
pool->IgnoredColumnIndices.assign(
metainfo.GetIgnoredColumnIndices().begin(),
metainfo.GetIgnoredColumnIndices().end());
if (metainfo.GetColumnIndexToType().size() != pool->ColumnIndexToLocalIndex.size()) {
for (const auto& kv : metainfo.GetColumnIndexToType()) {
const auto inserted = pool->ColumnIndexToLocalIndex.emplace(
kv.first,
pool->ColumnIndexToLocalIndex.size()).second;
if (inserted) {
// create empty chunks vector for this column
pool->Chunks.push_back({});
}
}
}
pool->ColumnTypes.resize(pool->ColumnIndexToLocalIndex.size());
for (const auto kv : pool->ColumnIndexToLocalIndex) {
const auto pbType = metainfo.GetColumnIndexToType().at(kv.first);
EColumn type;
switch (pbType) {
case NCB::NIdl::CT_UNKNOWN:
ythrow TCatboostException() << "unknown column type in quantized pool";
case NCB::NIdl::CT_NUMERIC:
type = EColumn::Num;
break;
case NCB::NIdl::CT_LABEL:
type = EColumn::Label;
break;
case NCB::NIdl::CT_WEIGHT:
type = EColumn::Weight;
break;
case NCB::NIdl::CT_GROUP_WEIGHT:
type = EColumn::GroupWeight;
break;
case NCB::NIdl::CT_BASELINE:
type = EColumn::Baseline;
break;
case NCB::NIdl::CT_SUBGROUP_ID:
type = EColumn::SubgroupId;
break;
case NCB::NIdl::CT_DOCUMENT_ID:
type = EColumn::DocId;
break;
case NCB::NIdl::CT_GROUP_ID:
type = EColumn::GroupId;
break;
case NCB::NIdl::CT_CATEGORICAL:
type = EColumn::Categ;
break;
case NCB::NIdl::CT_SPARSE:
type = EColumn::Sparse;
break;
case NCB::NIdl::CT_TIMESTAMP:
type = EColumn::Timestamp;
break;
case NCB::NIdl::CT_PREDICTION:
type = EColumn::Prediction;
break;
case NCB::NIdl::CT_AUXILIARY:
type = EColumn::Auxiliary;
break;
}
pool->ColumnTypes[kv.second] = type;
}
}
namespace {
struct TEpilogOffsets {
ui64 ChunksOffset = 0;
ui64 PoolMetainfoSizeOffset = 0;
ui64 QuantizationSchemaSizeOffset = 0;
ui64 FeatureCountOffset = 0;
};
}
static TEpilogOffsets ReadEpilogOffsets(const TConstArrayRef<char> blob) {
TEpilogOffsets offsets;
CB_ENSURE(!std::memcmp(MagicEnd, blob.data() + blob.size() - MagicEndSize, MagicEndSize));
offsets.ChunksOffset = LittleToHost(ReadUnaligned<ui64>(
blob.data() + blob.size() - MagicEndSize - sizeof(ui64) * 4));
offsets.PoolMetainfoSizeOffset = LittleToHost(ReadUnaligned<ui64>(
blob.data() + blob.size() - MagicEndSize - sizeof(ui64) * 3));
CB_ENSURE(offsets.PoolMetainfoSizeOffset < blob.size());
CB_ENSURE(offsets.PoolMetainfoSizeOffset > offsets.ChunksOffset);
offsets.QuantizationSchemaSizeOffset = LittleToHost(ReadUnaligned<ui64>(
blob.data() + blob.size() - MagicEndSize - sizeof(ui64) * 2));
CB_ENSURE(offsets.QuantizationSchemaSizeOffset < blob.size());
CB_ENSURE(offsets.QuantizationSchemaSizeOffset > offsets.PoolMetainfoSizeOffset);
offsets.FeatureCountOffset = LittleToHost(ReadUnaligned<ui64>(
blob.data() + blob.size() - MagicEndSize - sizeof(ui64)));
CB_ENSURE(offsets.FeatureCountOffset < blob.size());
CB_ENSURE(offsets.FeatureCountOffset > offsets.QuantizationSchemaSizeOffset);
return offsets;
}
static void CollectChunks(const TConstArrayRef<char> blob, NCB::TQuantizedPool& pool) {
const auto chunksOffsetByReading = [blob] {
TMemoryInput slave(blob.data(), blob.size());
TCountingInput input(&slave);
ReadHeader(&input);
return input.Counter();
}();
const auto epilogOffsets = ReadEpilogOffsets(blob);
CB_ENSURE(chunksOffsetByReading == epilogOffsets.ChunksOffset);
TPoolMetainfo poolMetainfo;
const auto poolMetainfoSize = LittleToHost(ReadUnaligned<ui32>(
blob.data() + epilogOffsets.PoolMetainfoSizeOffset));
const auto poolMetainfoParsed = poolMetainfo.ParseFromArray(
blob.data() + epilogOffsets.PoolMetainfoSizeOffset + sizeof(ui32),
poolMetainfoSize);
CB_ENSURE(poolMetainfoParsed);
const auto quantizationSchemaSize = LittleToHost(ReadUnaligned<ui32>(
blob.data() + epilogOffsets.QuantizationSchemaSizeOffset));
const auto quantizationSchemaParsed = pool.QuantizationSchema.ParseFromArray(
blob.data() + epilogOffsets.QuantizationSchemaSizeOffset + sizeof(ui32),
quantizationSchemaSize);
CB_ENSURE(quantizationSchemaParsed);
TMemoryInput epilog(
blob.data() + epilogOffsets.FeatureCountOffset,
blob.size() - epilogOffsets.FeatureCountOffset - MagicEndSize - sizeof(ui64) + 4);
ui32 featureCount;
ReadLittleEndian(&featureCount, &epilog);
for (ui32 i = 0; i < featureCount; ++i) {
ui32 featureIndex;
ReadLittleEndian(&featureIndex, &epilog);
ui32 localFeatureIndex;
if (const auto* const it = pool.ColumnIndexToLocalIndex.FindPtr(featureIndex)) {
localFeatureIndex = *it;
} else {
localFeatureIndex = pool.Chunks.size();
pool.ColumnIndexToLocalIndex.emplace(featureIndex, localFeatureIndex);
pool.Chunks.push_back({});
}
ui32 chunkCount;
ReadLittleEndian(&chunkCount, &epilog);
for (ui32 chunkIndex = 0; chunkIndex < chunkCount; ++chunkIndex) {
ui32 chunkSize;
ReadLittleEndian(&chunkSize, &epilog);
ui64 chunkOffset;
ReadLittleEndian(&chunkOffset, &epilog);
CB_ENSURE(chunkOffset >= epilogOffsets.ChunksOffset);
CB_ENSURE(chunkOffset < blob.size());
ui32 docOffset;
ReadLittleEndian(&docOffset, &epilog);
ui32 docsInChunkCount;
ReadLittleEndian(&docsInChunkCount, &epilog);
const TConstArrayRef<char> chunkBlob{blob.data() + chunkOffset, chunkSize};
// TODO(yazevnul): validate flatbuffer, including document count
const auto* const chunk = flatbuffers::GetRoot<NCB::NIdl::TQuantizedFeatureChunk>(chunkBlob.data());
pool.Chunks[localFeatureIndex].emplace_back(docOffset, docsInChunkCount, chunk);
}
}
AddPoolMetainfo(poolMetainfo, &pool);
}
NCB::TQuantizedPool NCB::LoadQuantizedPool(
const TStringBuf path,
const TLoadQuantizedPoolParameters& params) {
TQuantizedPool pool;
pool.Blobs.push_back(params.LockMemory
? TBlob::LockedFromFile(TString(path))
: TBlob::FromFile(TString(path)));
// TODO(yazevnul): optionally precharge pool
const TConstArrayRef<char> blobView{
pool.Blobs.back().AsCharPtr(),
pool.Blobs.back().Size()};
ValidatePoolPart(blobView);
CollectChunks(blobView, pool);
return pool;
}
static NCB::TQuantizedPoolDigest GetQuantizedPoolDigest(
const TPoolMetainfo& poolMetainfo,
const TPoolQuantizationSchema& quantizationSchema) {
NCB::TQuantizedPoolDigest digest;
for (const auto& kv : poolMetainfo.GetColumnIndexToType()) {
switch (kv.second) {
case NCB::NIdl::CT_UNKNOWN:
ythrow TCatboostException() << "unknown column type in quantized pool";
case NCB::NIdl::CT_NUMERIC: {
const auto& borders = quantizationSchema
.GetColumnIndexToSchema()
.at(kv.first)
.GetBorders();
if (borders.empty()) {
// const feature, do nothing
} else if (borders.size() < 1 << 1) {
++digest.NumericFeature1BitCount;
} else if (borders.size() < 1 << 4) {
++digest.NumericFeature4BitCount;
} else if (borders.size() < 1 << 8) {
++digest.NumericFeature8BitCount;
} else {
ythrow TCatboostException() << "unsupported quantized feature bitness";
}
break;
}
case NCB::NIdl::CT_LABEL:
++digest.NonFeatureColumnCount;
break;
case NCB::NIdl::CT_WEIGHT:
++digest.NonFeatureColumnCount;
break;
case NCB::NIdl::CT_GROUP_WEIGHT:
++digest.NonFeatureColumnCount;
break;
case NCB::NIdl::CT_BASELINE:
++digest.NonFeatureColumnCount;
break;
case NCB::NIdl::CT_SUBGROUP_ID:
++digest.NonFeatureColumnCount;
break;
case NCB::NIdl::CT_DOCUMENT_ID:
++digest.NonFeatureColumnCount;
break;
case NCB::NIdl::CT_GROUP_ID:
++digest.NonFeatureColumnCount;
break;
case NCB::NIdl::CT_CATEGORICAL:
// TODO(yazevnul): account them too when categorical features will be quantized
break;
case NCB::NIdl::CT_SPARSE:
// not implemented in CatBoost yet
break;
case NCB::NIdl::CT_TIMESTAMP:
// not implemented for quantization yet;
case NCB::NIdl::CT_PREDICTION:
case NCB::NIdl::CT_AUXILIARY:
// these are always ignored
break;
}
}
digest.NumericFeatureCount =
digest.NumericFeature1BitCount +
digest.NumericFeature4BitCount +
digest.NumericFeature8BitCount;
return digest;
}
NCB::TQuantizedPoolDigest NCB::CalculateQuantizedPoolDigest(const TStringBuf path) {
const auto file = TBlob::FromFile(TString(path));
const TConstArrayRef<char> blob(file.AsCharPtr(), file.Size());
const auto chunksOffsetByReading = [blob] {
TMemoryInput slave(blob.data(), blob.size());
TCountingInput input(&slave);
ReadHeader(&input);
return input.Counter();
}();
const auto epilogOffsets = ReadEpilogOffsets(blob);
CB_ENSURE(chunksOffsetByReading == epilogOffsets.ChunksOffset);
const auto columnsInfoSize = LittleToHost(ReadUnaligned<ui32>(
blob.data() + epilogOffsets.PoolMetainfoSizeOffset));
TPoolMetainfo poolMetainfo;
const auto poolMetainfoParsed = poolMetainfo.ParseFromArray(
blob.data() + epilogOffsets.PoolMetainfoSizeOffset + sizeof(ui32),
columnsInfoSize);
CB_ENSURE(poolMetainfoParsed);
const auto quantizationSchemaSize = LittleToHost(ReadUnaligned<ui32>(
blob.data() + epilogOffsets.QuantizationSchemaSizeOffset));
NCB::NIdl::TPoolQuantizationSchema quantizationSchema;
quantizationSchema.ParseFromArray(
blob.data() + epilogOffsets.QuantizationSchemaSizeOffset + sizeof(ui32),
quantizationSchemaSize);
return ::GetQuantizedPoolDigest(poolMetainfo, quantizationSchema);
}
NCB::NIdl::TPoolQuantizationSchema NCB::LoadQuantizationSchema(const TStringBuf path) {
const auto file = TBlob::FromFile(TString(path));
const TConstArrayRef<char> blob(file.AsCharPtr(), file.Size());
const auto chunksOffsetByReading = [blob] {
TMemoryInput slave(blob.data(), blob.size());
TCountingInput input(&slave);
ReadHeader(&input);
return input.Counter();
}();
const auto epilogOffsets = ReadEpilogOffsets(blob);
CB_ENSURE(chunksOffsetByReading == epilogOffsets.ChunksOffset);
NCB::NIdl::TPoolQuantizationSchema quantizationSchema;
const auto quantizationSchemaSize = LittleToHost(ReadUnaligned<ui32>(
blob.data() + epilogOffsets.QuantizationSchemaSizeOffset));
const auto quantizationSchemaParsed = quantizationSchema.ParseFromArray(
blob.data() + epilogOffsets.QuantizationSchemaSizeOffset + sizeof(ui32),
quantizationSchemaSize);
CB_ENSURE(quantizationSchemaParsed);
return quantizationSchema;
}
NCB::NIdl::TPoolMetainfo NCB::LoadPoolMetainfo(const TStringBuf path) {
const auto file = TBlob::FromFile(TString(path));
const TConstArrayRef<char> blob(file.AsCharPtr(), file.Size());
const auto chunksOffsetByReading = [blob] {
TMemoryInput slave(blob.data(), blob.size());
TCountingInput input(&slave);
ReadHeader(&input);
return input.Counter();
}();
const auto epilogOffsets = ReadEpilogOffsets(blob);
CB_ENSURE(chunksOffsetByReading == epilogOffsets.ChunksOffset);
NCB::NIdl::TPoolMetainfo poolMetainfo;
const auto poolMetainfoSize = LittleToHost(ReadUnaligned<ui32>(
blob.data() + epilogOffsets.PoolMetainfoSizeOffset));
const auto poolMetainfoParsed = poolMetainfo.ParseFromArray(
blob.data() + epilogOffsets.PoolMetainfoSizeOffset + sizeof(ui32),
poolMetainfoSize);
CB_ENSURE(poolMetainfoParsed);
return poolMetainfo;
}
| 36.567026 | 112 | 0.650514 | [
"vector"
] |
3e99ff921d53015971f4049328e9796c04d3c99c | 1,717 | cc | C++ | src/main/Rasterizer.cc | gaetano-foster/SoftwareRasterizer_PGE | 85ba331de3a95d424a8663caf6491ac57af375ef | [
"MIT"
] | null | null | null | src/main/Rasterizer.cc | gaetano-foster/SoftwareRasterizer_PGE | 85ba331de3a95d424a8663caf6491ac57af375ef | [
"MIT"
] | null | null | null | src/main/Rasterizer.cc | gaetano-foster/SoftwareRasterizer_PGE | 85ba331de3a95d424a8663caf6491ac57af375ef | [
"MIT"
] | null | null | null | #include "Rasterizer.h"
Rasterizer::Rasterizer() {
sAppName = "SoftwareRasterizer";
olc_hideCursor = true;
}
bool Rasterizer::OnUserCreate() {
depth_buffer = new float[ScreenWidth() * ScreenHeight()];
matProj.MakeProjection(0.1f, 1000.0f, camera.fov);
if (!mesh.mesh.LoadFromObjectFile("res/castle.obj", true))
return false;
mesh.z = 9;
mesh.mesh.texture = new olc::Sprite("res/man.png");
return true;
}
bool Rasterizer::OnUserUpdate(float fElapsedTime) {
if (GetKey(olc::W).bHeld) {
camera.z += cosf(camera.roty) * 8 * fElapsedTime;
camera.x += sinf(camera.roty) * 8 * fElapsedTime;
}
if (GetKey(olc::S).bHeld) {
camera.z -= cosf(camera.roty) * 8 * fElapsedTime;
camera.x -= sinf(camera.roty) * 8 * fElapsedTime;
}
if (GetKey(olc::A).bHeld) {
camera.z -= sinf(camera.roty) * 8 * fElapsedTime;
camera.x += cosf(camera.roty) * 8 * fElapsedTime;
}
if (GetKey(olc::D).bHeld) {
camera.z += sinf(camera.roty) * 8 * fElapsedTime;
camera.x -= cosf(camera.roty) * 8 * fElapsedTime;
}
camera.y -= (GetKey(olc::SHIFT).bHeld) * 8 * fElapsedTime;
camera.y += (GetKey(olc::SPACE).bHeld) * 8 * fElapsedTime;
camera.roty -= (GetKey(olc::RIGHT).bHeld) * 2 * fElapsedTime;
camera.roty += (GetKey(olc:: LEFT).bHeld) * 2 * fElapsedTime;
camera.rotx -= (GetKey(olc:: UP).bHeld) * 2 * fElapsedTime;
camera.rotx += (GetKey(olc:: DOWN).bHeld) * 2 * fElapsedTime;
if (camera.rotx > 1.5707f)
camera.rotx = 1.5707f;
else if (camera.rotx < -1.5707f)
camera.rotx = -1.5707f;
Clear(olc::BLACK);
for (int i = 0; i < ScreenWidth()*ScreenHeight(); i++)
depth_buffer[i] = 0;
camera.Update();
mesh.Update();
mesh.Render(camera, matProj, this, depth_buffer);
return true;
} | 27.693548 | 62 | 0.65463 | [
"mesh",
"render"
] |
3e9bdd26b597d734b960aab3a66014b7f42951c2 | 16,342 | cpp | C++ | Tools/TestWebKitAPI/Tests/WebCore/CBORWriterTest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Tools/TestWebKitAPI/Tests/WebCore/CBORWriterTest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Tools/TestWebKitAPI/Tests/WebCore/CBORWriterTest.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Copyright (C) 2018 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "config.h"
#if ENABLE(WEB_AUTHN)
#include <WebCore/CBORWriter.h>
#include <limits>
// Leveraging RFC 7049 examples from https://github.com/cbor/test-vectors/blob/master/appendix_a.json.
namespace TestWebKitAPI {
using namespace cbor;
bool eq(const Vector<uint8_t>& cbor, const CString& expect)
{
if (cbor.size() != expect.length())
return false;
return !memcmp(cbor.data(), reinterpret_cast<const uint8_t*>(expect.data()), cbor.size());
}
bool eq(const Vector<uint8_t>& cbor, const uint8_t* expect, const size_t expectLength)
{
if (cbor.size() != expectLength)
return false;
return !memcmp(cbor.data(), expect, expectLength);
}
TEST(CBORWriterTest, TestWriteUint)
{
typedef struct {
const int64_t value;
const CString cbor;
} UintTestCase;
static const UintTestCase kUintTestCases[] = {
// Reminder: must specify length when creating string pieces
// with null bytes, else the string will truncate prematurely.
{0, CString("\x00", 1)},
{1, CString("\x01")},
{10, CString("\x0a")},
{23, CString("\x17")},
{24, CString("\x18\x18")},
{25, CString("\x18\x19")},
{100, CString("\x18\x64")},
{1000, CString("\x19\x03\xe8")},
{1000000, CString("\x1a\x00\x0f\x42\x40", 5)},
{0xFFFFFFFF, CString("\x1a\xff\xff\xff\xff")},
{0x100000000,
CString("\x1b\x00\x00\x00\x01\x00\x00\x00\x00", 9)},
{std::numeric_limits<int64_t>::max(),
CString("\x1b\x7f\xff\xff\xff\xff\xff\xff\xff")}
};
for (const UintTestCase& testCase : kUintTestCases) {
auto cbor = CBORWriter::write(CBORValue(testCase.value));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), testCase.cbor));
}
}
TEST(CBORWriterTest, TestWriteNegativeInteger)
{
static const struct {
const int64_t negativeInt;
const CString cbor;
} kNegativeIntTestCases[] = {
{ -1LL, CString("\x20") },
{ -10LL, CString("\x29") },
{ -23LL, CString("\x36") },
{ -24LL, CString("\x37") },
{ -25LL, CString("\x38\x18") },
{ -100LL, CString("\x38\x63") },
{ -1000LL, CString("\x39\x03\xe7") },
{ -4294967296LL, CString("\x3a\xff\xff\xff\xff") },
{ -4294967297LL,
CString("\x3b\x00\x00\x00\x01\x00\x00\x00\x00", 9) },
{ std::numeric_limits<int64_t>::min(),
CString("\x3b\x7f\xff\xff\xff\xff\xff\xff\xff") },
};
for (const auto& testCase : kNegativeIntTestCases) {
auto cbor = CBORWriter::write(CBORValue(testCase.negativeInt));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), testCase.cbor));
}
}
TEST(CBORWriterTest, TestWriteBytes)
{
typedef struct {
const Vector<uint8_t> bytes;
const CString cbor;
} BytesTestCase;
static const BytesTestCase kBytesTestCases[] = {
{ { }, CString("\x40") },
{ { 0x01, 0x02, 0x03, 0x04 }, CString("\x44\x01\x02\x03\x04") },
};
for (const BytesTestCase& testCase : kBytesTestCases) {
auto cbor = CBORWriter::write(CBORValue(testCase.bytes));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), testCase.cbor));
}
}
TEST(CBORWriterTest, TestWriteString)
{
typedef struct {
const String string;
const CString cbor;
} StringTestCase;
static const StringTestCase kStringTestCases[] = {
{ "", CString("\x60") },
{ "a", CString("\x61\x61") },
{ "IETF", CString("\x64\x49\x45\x54\x46") },
{ "\"\\", CString("\x62\x22\x5c") },
{ String::fromUTF8("\xc3\xbc"), CString("\x62\xc3\xbc") },
{ String::fromUTF8("\xe6\xb0\xb4"), CString("\x63\xe6\xb0\xb4") },
{ String::fromUTF8("\xf0\x90\x85\x91"), CString("\x64\xf0\x90\x85\x91") }
};
for (const StringTestCase& testCase : kStringTestCases) {
auto cbor = CBORWriter::write(CBORValue(testCase.string));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), testCase.cbor));
}
}
TEST(CBORWriterTest, TestWriteArray)
{
static const uint8_t kArrayTestCaseCbor[] = {
0x98, 0x19, // array of 25 elements
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x18, 0x18, 0x19,
};
Vector<CBORValue> array;
for (int64_t i = 1; i <= 25; i++)
array.append(CBORValue(i));
auto cbor = CBORWriter::write(CBORValue(array));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), kArrayTestCaseCbor, sizeof(kArrayTestCaseCbor)));
}
TEST(CBORWriterTest, TestWriteMapWithMapValue)
{
static const uint8_t kMapTestCaseCbor[] = {
0xb6, // map of 8 pairs:
0x00, // key 0
0x61, 0x61, // value "a"
0x17, // key 23
0x61, 0x62, // value "b"
0x18, 0x18, // key 24
0x61, 0x63, // value "c"
0x18, 0xFF, // key 255
0x61, 0x64, // value "d"
0x19, 0x01, 0x00, // key 256
0x61, 0x65, // value "e"
0x19, 0xFF, 0xFF, // key 65535
0x61, 0x66, // value "f"
0x1A, 0x00, 0x01, 0x00, 0x00, // key 65536
0x61, 0x67, // value "g"
0x1A, 0xFF, 0xFF, 0xFF, 0xFF, // key 4294967295
0x61, 0x68, // value "h"
// key 4294967296
0x1B, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x61, 0x69, // value "i"
// key INT64_MAX
0x1b, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x61, 0x6a, // value "j"
0x20, // key -1
0x61, 0x6b, // value "k"
0x37, // key -24
0x61, 0x6c, // value "l"
0x38, 0x18, // key -25
0x61, 0x6d, // value "m"
0x38, 0xFF, // key -256
0x61, 0x6e, // value "n"
0x39, 0x01, 0x00, // key -257
0x61, 0x6f, // value "o"
0x3A, 0x00, 0x01, 0x00, 0x00, // key -65537
0x61, 0x70, // value "p"
0x3A, 0xFF, 0xFF, 0xFF, 0xFF, // key -4294967296
0x61, 0x71, // value "q"
// key -4294967297
0x3B, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x61, 0x72, // value "r"
// key INT64_MIN
0x3b, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0x61, 0x73, // value "s"
0x60, // key ""
0x61, 0x2e, // value "."
0x61, 0x65, // key "e"
0x61, 0x45, // value "E"
0x62, 0x61, 0x61, // key "aa"
0x62, 0x41, 0x41, // value "AA"
};
CBORValue::MapValue map;
// Shorter strings sort first in CTAP, thus the “aa” value should be
// serialised last in the map.
map[CBORValue("aa")] = CBORValue("AA");
map[CBORValue("e")] = CBORValue("E");
// The empty string is shorter than all others, so should appear first among
// the strings.
map[CBORValue("")] = CBORValue(".");
// Map keys are sorted by major type, by byte length, and then by
// byte-wise lexical order. So all integer type keys should appear before
// key "" and all positive integer keys should appear before negative integer
// keys.
map[CBORValue(-1)] = CBORValue("k");
map[CBORValue(-24)] = CBORValue("l");
map[CBORValue(-25)] = CBORValue("m");
map[CBORValue(-256)] = CBORValue("n");
map[CBORValue(-257)] = CBORValue("o");
map[CBORValue(-65537)] = CBORValue("p");
map[CBORValue(int64_t(-4294967296))] = CBORValue("q");
map[CBORValue(int64_t(-4294967297))] = CBORValue("r");
map[CBORValue(std::numeric_limits<int64_t>::min())] = CBORValue("s");
map[CBORValue(0)] = CBORValue("a");
map[CBORValue(23)] = CBORValue("b");
map[CBORValue(24)] = CBORValue("c");
map[CBORValue(std::numeric_limits<uint8_t>::max())] = CBORValue("d");
map[CBORValue(256)] = CBORValue("e");
map[CBORValue(std::numeric_limits<uint16_t>::max())] = CBORValue("f");
map[CBORValue(65536)] = CBORValue("g");
map[CBORValue(int64_t(std::numeric_limits<uint32_t>::max()))] = CBORValue("h");
map[CBORValue(int64_t(4294967296))] = CBORValue("i");
map[CBORValue(std::numeric_limits<int64_t>::max())] = CBORValue("j");
auto cbor = CBORWriter::write(CBORValue(map));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), kMapTestCaseCbor, sizeof(kMapTestCaseCbor)));
}
TEST(CBORWriterTest, TestWriteMapWithArray)
{
static const uint8_t kMapArrayTestCaseCbor[] = {
0xa2, // map of 2 pairs
0x61, 0x61, // "a"
0x01,
0x61, 0x62, // "b"
0x82, // array with 2 elements
0x02,
0x03,
};
CBORValue::MapValue map;
map[CBORValue("a")] = CBORValue(1);
CBORValue::ArrayValue array;
array.append(CBORValue(2));
array.append(CBORValue(3));
map[CBORValue("b")] = CBORValue(array);
auto cbor = CBORWriter::write(CBORValue(map));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), kMapArrayTestCaseCbor, sizeof(kMapArrayTestCaseCbor)));
}
TEST(CBORWriterTest, TestWriteNestedMap)
{
static const uint8_t kNestedMapTestCase[] = {
0xa2, // map of 2 pairs
0x61, 0x61, // "a"
0x01,
0x61, 0x62, // "b"
0xa2, // map of 2 pairs
0x61, 0x63, // "c"
0x02,
0x61, 0x64, // "d"
0x03,
};
CBORValue::MapValue map;
map[CBORValue("a")] = CBORValue(1);
CBORValue::MapValue nestedMap;
nestedMap[CBORValue("c")] = CBORValue(2);
nestedMap[CBORValue("d")] = CBORValue(3);
map[CBORValue("b")] = CBORValue(nestedMap);
auto cbor = CBORWriter::write(CBORValue(map));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), kNestedMapTestCase, sizeof(kNestedMapTestCase)));
}
TEST(CBORWriterTest, TestWriteSimpleValue)
{
static const struct {
CBORValue::SimpleValue simpleValue;
const CString cbor;
} kSimpleTestCase[] = {
{ CBORValue::SimpleValue::FalseValue, CString("\xf4") },
{ CBORValue::SimpleValue::TrueValue, CString("\xf5") },
{ CBORValue::SimpleValue::NullValue, CString("\xf6") },
{ CBORValue::SimpleValue::Undefined, CString("\xf7") }
};
for (const auto& testCase : kSimpleTestCase) {
auto cbor = CBORWriter::write(CBORValue(testCase.simpleValue));
ASSERT_TRUE(cbor.hasValue());
EXPECT_TRUE(eq(cbor.value(), testCase.cbor));
}
}
// For major type 0, 2, 3, empty CBOR array, and empty CBOR map, the nesting
// depth is expected to be 0 since the CBOR decoder does not need to parse
// any nested CBOR value elements.
TEST(CBORWriterTest, TestWriteSingleLayer)
{
const CBORValue simpleUint = CBORValue(1);
const CBORValue simpleString = CBORValue("a");
const Vector<uint8_t> byteData = { 0x01, 0x02, 0x03, 0x04 };
const CBORValue simpleBytestring = CBORValue(byteData);
CBORValue::ArrayValue emptyCborArray;
CBORValue::MapValue emptyCborMap;
const CBORValue emptyArrayValue = CBORValue(emptyCborArray);
const CBORValue emptyMapValue = CBORValue(emptyCborMap);
CBORValue::ArrayValue simpleArray;
simpleArray.append(CBORValue(2));
CBORValue::MapValue simpleMap;
simpleMap[CBORValue("b")] = CBORValue(3);
const CBORValue singleLayerCborMap = CBORValue(simpleMap);
const CBORValue singleLayerCborArray = CBORValue(simpleArray);
EXPECT_TRUE(CBORWriter::write(simpleUint, 0).hasValue());
EXPECT_TRUE(CBORWriter::write(simpleString, 0).hasValue());
EXPECT_TRUE(CBORWriter::write(simpleBytestring, 0).hasValue());
EXPECT_TRUE(CBORWriter::write(emptyArrayValue, 0).hasValue());
EXPECT_TRUE(CBORWriter::write(emptyMapValue, 0).hasValue());
EXPECT_FALSE(CBORWriter::write(singleLayerCborArray, 0).hasValue());
EXPECT_TRUE(CBORWriter::write(singleLayerCborArray, 1).hasValue());
EXPECT_FALSE(CBORWriter::write(singleLayerCborMap, 0).hasValue());
EXPECT_TRUE(CBORWriter::write(singleLayerCborMap, 1).hasValue());
}
// Major type 5 nested CBOR map value with following structure.
// {"a": 1,
// "b": {"c": 2,
// "d": 3}}
TEST(CBORWriterTest, NestedMaps)
{
CBORValue::MapValue cborMap;
cborMap[CBORValue("a")] = CBORValue(1);
CBORValue::MapValue nestedMap;
nestedMap[CBORValue("c")] = CBORValue(2);
nestedMap[CBORValue("d")] = CBORValue(3);
cborMap[CBORValue("b")] = CBORValue(nestedMap);
EXPECT_TRUE(CBORWriter::write(CBORValue(cborMap), 2).hasValue());
EXPECT_FALSE(CBORWriter::write(CBORValue(cborMap), 1).hasValue());
}
// Testing Write() function for following CBOR structure with depth of 3.
// [1,
// 2,
// 3,
// {"a": 1,
// "b": {"c": 2,
// "d": 3}}]
TEST(CBORWriterTest, UnbalancedNestedContainers)
{
CBORValue::ArrayValue cborArray;
CBORValue::MapValue cborMap;
CBORValue::MapValue nestedMap;
cborMap[CBORValue("a")] = CBORValue(1);
nestedMap[CBORValue("c")] = CBORValue(2);
nestedMap[CBORValue("d")] = CBORValue(3);
cborMap[CBORValue("b")] = CBORValue(nestedMap);
cborArray.append(CBORValue(1));
cborArray.append(CBORValue(2));
cborArray.append(CBORValue(3));
cborArray.append(CBORValue(cborMap));
EXPECT_TRUE(CBORWriter::write(CBORValue(cborArray), 3).hasValue());
EXPECT_FALSE(CBORWriter::write(CBORValue(cborArray), 2).hasValue());
}
// Testing Write() function for following CBOR structure.
// {"a": 1,
// "b": {"c": 2,
// "d": 3
// "h": { "e": 4,
// "f": 5,
// "g": [6, 7, [8]]}}}
// Since above CBOR contains 5 nesting levels. Thus, Write() is expected to
// return empty optional object when maximum nesting layer size is set to 4.
TEST(CBORWriterTest, OverlyNestedCBOR)
{
CBORValue::MapValue map;
CBORValue::MapValue nestedMap;
CBORValue::MapValue innerNestedMap;
CBORValue::ArrayValue innerArray;
CBORValue::ArrayValue array;
map[CBORValue("a")] = CBORValue(1);
nestedMap[CBORValue("c")] = CBORValue(2);
nestedMap[CBORValue("d")] = CBORValue(3);
innerNestedMap[CBORValue("e")] = CBORValue(4);
innerNestedMap[CBORValue("f")] = CBORValue(5);
innerArray.append(CBORValue(6));
array.append(CBORValue(6));
array.append(CBORValue(7));
array.append(CBORValue(innerArray));
innerNestedMap[CBORValue("g")] = CBORValue(array);
nestedMap[CBORValue("h")] = CBORValue(innerNestedMap);
map[CBORValue("b")] = CBORValue(nestedMap);
EXPECT_TRUE(CBORWriter::write(CBORValue(map), 5).hasValue());
EXPECT_FALSE(CBORWriter::write(CBORValue(map), 4).hasValue());
}
} // namespace TestWebKitAPI
#endif // ENABLE(WEB_AUTHN)
| 35.06867 | 102 | 0.62936 | [
"object",
"vector"
] |
3ea03b56be0eae644c91024cf520a4a305a73199 | 848 | cpp | C++ | leetcode/test.cpp | alyapunov/contests | 05524fb652cddb3d6d341cb43dd71e95802d8699 | [
"BSD-2-Clause"
] | null | null | null | leetcode/test.cpp | alyapunov/contests | 05524fb652cddb3d6d341cb43dd71e95802d8699 | [
"BSD-2-Clause"
] | null | null | null | leetcode/test.cpp | alyapunov/contests | 05524fb652cddb3d6d341cb43dd71e95802d8699 | [
"BSD-2-Clause"
] | null | null | null | #include <alya.h>
#include <vector>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
}
};
void
check(std::initializer_list<int> orig, int k, std::initializer_list<int> res)
{
std::vector<ListNode> nodes(orig.size());
{
size_t i = 0;
for (int val : orig) {
auto &n = nodes[i++];
n.val = val;
n.next = i == orig.size() ? nullptr : &nodes[i];
}
}
Solution sol;
ListNode* r = sol.reverseKGroup(&nodes[0], k);
{
size_t i = 0;
for (int val : res) {
if (val != r->val)
abort();
r = r->next;
}
if (r != nullptr)
abort();
}
}
int main()
{
check({1,2,3,4,5}, 2, {2,1,4,3,5});
check({1,2,3,4,5}, 3, {1,2,3,4,5});
check({1,2,3,4,5}, 1, {1,2,3,4,5});
check({1}, 1, {1});
}
| 16.307692 | 77 | 0.566038 | [
"vector"
] |
3ea4db0467777421fa56aa5fc536a4c7299d8aa6 | 1,948 | cpp | C++ | scenes/examples/01_cgp_usage/03_implicit_surface/01_marching_cube_simple/src/scene.cpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | scenes/examples/01_cgp_usage/03_implicit_surface/01_marching_cube_simple/src/scene.cpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | 2 | 2022-03-03T16:34:03.000Z | 2022-03-20T13:08:56.000Z | scenes/examples/01_cgp_usage/03_implicit_surface/01_marching_cube_simple/src/scene.cpp | drohmer/CGP | 3e7651649320d0bff19394ecd9546e872802c3e7 | [
"MIT"
] | null | null | null | #include "scene.hpp"
#include "implicit_surface/implicit_surface.hpp"
using namespace cgp;
void scene_structure::initialize()
{
// Create the Implicit Surface
// ***************************************** //
// Number of voxels
int3 const samples = { 50, 50, 50 };
// Dimension of the domain
vec3 const length = { 5,3,3 };
// Isovalue for the marching cube
float isovalue = 0.5f;
// Initialize the spatial domain and the field
spatial_domain_grid_3D domain = spatial_domain_grid_3D::from_center_length({ 0,0,0 }, length, samples);
grid_3D<float> field = compute_scalar_field(domain);
// Compute the mesh using marching cube
mesh m = marching_cube(field, domain, isovalue);
implicit_surface.initialize(m, "Implicit surface");
// Helpers
// ***************************************** //
// Helper to visualize the box of the domain
segments_drawable::default_shader = curve_drawable::default_shader;
domain_box = spatial_domain_grid_drawable(domain);
// The standard frame
global_frame.initialize(mesh_primitive_frame(), "Frame");
environment.camera.look_at({ 6,3,6 }, { 0,0,0 }, { 0,1,0 });
}
void scene_structure::display()
{
// Place the light at the camera position
environment.light = environment.camera.position();
// The standard frame
if (gui.display_frame)
draw(global_frame, environment);
if (gui.plain) // Display the implicit surface
draw(implicit_surface, environment);
if(gui.wireframe) // Display the wireframe of the implicit surface
draw_wireframe(implicit_surface, environment, { 0,0,0 });
if(gui.domain) // Display the boundary of the domain
draw(domain_box, environment);
}
void scene_structure::display_gui()
{
ImGui::Checkbox("Frame", &gui.display_frame);
ImGui::Checkbox("Wireframe", &gui.wireframe);
ImGui::Checkbox("Plain", &gui.plain);
ImGui::Checkbox("Domain", &gui.domain);
}
| 28.231884 | 105 | 0.665811 | [
"mesh"
] |
3ea6bd6a4bb32e69ed34ae78f19fb38a6581543f | 3,471 | hpp | C++ | src/solvers/krylov/idr.hpp | pruthvistony/rocALUTION | 2a5c602f41194f7730f59b4f0ce8c5cfff77fa07 | [
"MIT"
] | 1 | 2020-04-15T18:26:58.000Z | 2020-04-15T18:26:58.000Z | src/solvers/krylov/idr.hpp | pruthvistony/rocALUTION | 2a5c602f41194f7730f59b4f0ce8c5cfff77fa07 | [
"MIT"
] | null | null | null | src/solvers/krylov/idr.hpp | pruthvistony/rocALUTION | 2a5c602f41194f7730f59b4f0ce8c5cfff77fa07 | [
"MIT"
] | null | null | null | /* ************************************************************************
* Copyright (c) 2018 Advanced Micro Devices, Inc.
*
* 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.
*
* ************************************************************************ */
#ifndef ROCALUTION_KRYLOV_IDR_HPP_
#define ROCALUTION_KRYLOV_IDR_HPP_
#include "../solver.hpp"
#include <vector>
namespace rocalution
{
/** \ingroup solver_module
* \class IDR
* \brief Induced Dimension Reduction Method
* \details
* The Induced Dimension Reduction method is a Krylov subspace method for solving
* sparse (non) symmetric linear systems \f$Ax=b\f$. IDR(s) generates residuals in a
* sequence of nested subspaces.
* \cite IDR1
* \cite IDR2
*
* The dimension of the shadow space can be set by SetShadowSpace(). The default size
* of the shadow space is 4.
*
* \tparam OperatorType - can be LocalMatrix, GlobalMatrix or LocalStencil
* \tparam VectorType - can be LocalVector or GlobalVector
* \tparam ValueType - can be float, double, std::complex<float> or std::complex<double>
*/
template <class OperatorType, class VectorType, typename ValueType>
class IDR : public IterativeLinearSolver<OperatorType, VectorType, ValueType>
{
public:
IDR();
virtual ~IDR();
virtual void Print(void) const;
virtual void Build(void);
virtual void ReBuildNumeric(void);
virtual void Clear(void);
/** \brief Set the size of the Shadow Space */
void SetShadowSpace(int s);
/** \brief Set random seed for ONB creation (seed must be greater than 0) */
void SetRandomSeed(unsigned long long seed);
protected:
virtual void SolveNonPrecond_(const VectorType& rhs, VectorType* x);
virtual void SolvePrecond_(const VectorType& rhs, VectorType* x);
virtual void PrintStart_(void) const;
virtual void PrintEnd_(void) const;
virtual void MoveToHostLocalData_(void);
virtual void MoveToAcceleratorLocalData_(void);
private:
int s_;
unsigned long long seed_;
ValueType kappa_;
ValueType* c_;
ValueType* f_;
ValueType* M_;
VectorType r_;
VectorType v_;
VectorType t_;
VectorType** G_;
VectorType** U_;
VectorType** P_;
};
} // namespace rocalution
#endif // ROCALUTION_KRYLOV_IDR_HPP_
| 34.366337 | 89 | 0.664938 | [
"vector"
] |
3eb29295e70ea85f300ed8ec2786b3280e8e234c | 10,904 | cxx | C++ | src/mod/pub/lib/fonts/mws-text-vxo.cxx | indigoabstract/appplex | 83c3b903db6c6ea83690ccffbd533ff6ab01d246 | [
"MIT"
] | 1 | 2017-12-26T14:29:37.000Z | 2017-12-26T14:29:37.000Z | src/mod/pub/lib/fonts/mws-text-vxo.cxx | indigoabstract/appplex | 83c3b903db6c6ea83690ccffbd533ff6ab01d246 | [
"MIT"
] | null | null | null | src/mod/pub/lib/fonts/mws-text-vxo.cxx | indigoabstract/appplex | 83c3b903db6c6ea83690ccffbd533ff6ab01d246 | [
"MIT"
] | null | null | null | #include "stdafx.hxx"
#include "appplex-conf.hxx"
#if defined MOD_VECTOR_FONTS
#include "mws-text-vxo.hxx"
#include "mws-font.hxx"
#include "mws-font-db.hxx"
#include "gfx.hxx"
#include "gfx-color.hxx"
#include "gfx-camera.hxx"
#include "gfx-shader.hxx"
#include "gfx-tex.hxx"
#include "gfx-state.hxx"
#include "gfx-vxo.hxx"
#include "pfm-gl.h"
mws_push_disable_all_warnings
#include <freetype-gl/vertex-buffer.h>
mws_pop_disable_all_warnings
#ifdef MWS_DEBUG_BUILD
#define debug_text_vxo
#endif
using namespace ftgl;
struct vertex_t
{
float x, y, z; // position
float s, t; // texture
float r, g, b, a; // color
};
class mws_text_vxo_impl
{
public:
mws_text_vxo_impl(mws_sp<mws_text_vxo> i_inst)
{
mIs3D = false;
mws_text_vxo& ti = *i_inst;
ti[MP_SHADER_NAME] = "text-shader";
ti[MP_BLENDING] = MV_ALPHA;
ti[MP_CULL_BACK] = true;
ti[MP_CULL_FRONT] = false;
ti[MP_DEPTH_WRITE] = false;
ti[MP_DEPTH_TEST] = false;
vbuffer = vertex_buffer_new("vertex:3f,tex_coord:2f,color:4f");
update_projection_mx();
mws_report_gfx_errs();
}
~mws_text_vxo_impl()
{
vertex_buffer_delete(vbuffer);
vbuffer = nullptr;
}
void clear_text()
{
vertex_buffer_clear(vbuffer);
}
glm::vec4 add_text(const std::string& i_text, const glm::vec2& i_pos, const mws_sp<mws_font> i_font)
{
#ifdef debug_text_vxo
latest_text = i_text;
#endif
glm::vec2 pen(i_pos.x, i_pos.y + i_font->get_ascender());
auto& glyphs = mws_font_db::inst()->get_glyph_vect(i_font->get_inst(), i_text);
return add_text_2d_impl(vbuffer, glyphs, i_text, pen, (float)gfx::i()->rt.get_render_target_height(), i_font);
//std::string text = wstring2string(i_text);
//add_text_2d(text, pen, i_font);
}
void draw_in_sync(mws_sp<mws_text_vxo> i_inst, mws_sp<gfx_camera> i_camera, const glm::vec3& i_pos)
{
if (vbuffer->vertices->size == 0)
{
return;
}
mws_sp<gfx_tex> atlas = mws_font_db::inst()->get_texture_atlas();
if (atlas && atlas->is_valid())
{
mws_report_gfx_errs();
gfx_material& mat = *i_inst->get_material();
mws_sp<gfx_shader> shader = mat.get_shader();
mat["texture"][MP_TEXTURE_INST] = atlas;
i_inst->push_material_params(i_inst->get_material());
i_camera->update_glp_params(i_inst, shader);
//model[3][0] = i_pos.x;
//model[3][1] = -i_pos.y;
if (mIs3D)
{
model[3][0] = mPosition.x;
model[3][1] = mPosition.y;
model[3][2] = mPosition.z;
}
else
{
model[3][0] = glm::round(i_pos.x);// mPosition.x;
model[3][1] = glm::round(-i_pos.y);// gi()->rt.get_render_target_height() - mPosition.y;// -mFontHeight;
}
if (rt_width != i_inst->gi()->rt.get_render_target_width() || rt_height != i_inst->gi()->rt.get_render_target_height())
{
update_projection_mx();
}
shader->update_uniform("model", glm::value_ptr(model));
shader->update_uniform("view", glm::value_ptr(view));
shader->update_uniform("projection", glm::value_ptr(projection));
mws_report_gfx_errs();
vertex_buffer_render(vbuffer, GL_TRIANGLES);
mws_report_gfx_errs();
}
}
void add_text_2d(const std::string& i_text, const glm::vec2& i_position, const mws_sp<mws_font> i_font)
{
auto& glyphs = mws_font_db::inst()->get_glyph_vect(i_font->get_inst(), i_text);
if (mIs3D)
{
clear_text();
mIs3D = false;
}
mPosition = glm::vec3(i_position, 0);
mFontHeight = i_font->get_height();
AddTextImpl(vbuffer, glyphs, i_text, glm::vec3(1, 0, 0), glm::vec3(0, 1, 0), i_font, 1.f);
}
void add_text_3d(const std::string& i_text, const glm::vec3& i_position, const glm::vec3& i_hdir, const glm::vec3& i_vdir, mws_sp<mws_font> i_font)
{
auto& glyphs = mws_font_db::inst()->get_glyph_vect(i_font->get_inst(), i_text);
glm::vec2 pen(0.f);
if (!mIs3D)
{
clear_text();
mIs3D = true;
}
mPosition = i_position;
mFontHeight = i_font->get_height();
AddTextImpl(vbuffer, glyphs, i_text, i_hdir, i_vdir, i_font, 0.05f);
}
void AddTextImpl(vertex_buffer_t* i_buffer, const std::vector<font_glyph>& i_glyphs, const std::string& i_text,
const glm::vec3& i_hdir, const glm::vec3& i_vdir, const mws_sp<mws_font> i_font, float i_scale)
{
//auto crt_ctx = GraphicsContext::GetCurrentGraphicsContext();
//UpdateParams(crt_ctx->GetWidth(), crt_ctx->GetHeight());
int len = glm::min(i_text.length(), i_glyphs.size());
glm::vec4 c = i_font->get_color().to_vec4();
float r = c.r, g = c.g, b = c.b, a = c.a;
glm::vec2 pen(0.f);
for (int i = 0; i < len; ++i)
{
font_glyph glyph = i_glyphs[i];
if (glyph.is_valid())
{
char ch = i_text[i];
// ignore carriage returns
if (ch < ' ')
{
if (ch == '\n')
{
pen.x = 0.f;
pen.y -= i_font->get_height();
}
else if (ch == '\t')
{
pen.x += 2 * i_font->get_height();
}
}
// normal character
else
{
float kerning = 0.0f;
if (i > 0)
{
kerning = glyph.get_kerning(i_text[i - 1]);
}
pen.x += kerning;
glm::vec3 x0 = i_hdir * float(pen.x + glyph.get_offset_x()) * i_scale;
glm::vec3 y0 = i_vdir * float(pen.y + glyph.get_offset_y()) * i_scale;
glm::vec3 x1 = i_hdir * float(pen.x + glyph.get_offset_x() + glyph.get_width()) * i_scale;
glm::vec3 y1 = i_vdir * float(pen.y + glyph.get_offset_y() - glyph.get_height()) * i_scale;
float s0 = glyph.get_s0();
float t0 = glyph.get_t0();
float s1 = glyph.get_s1();
float t1 = glyph.get_t1();
//GLuint indices[6] = { 0, 2, 1, 2, 0, 3 };
GLuint indices[6] = { 0, 1, 2, 0, 2, 3 };
vertex_t vertices[4] =
{
{ (x0 + y0).x, (x0 + y0).y, (x0 + y0).z, s0, t0, r, g, b, a },
{ (x0 + y1).x, (x0 + y1).y, (x0 + y1).z, s0, t1, r, g, b, a },
{ (x1 + y1).x, (x1 + y1).y, (x1 + y1).z, s1, t1, r, g, b, a },
{ (x1 + y0).x, (x1 + y0).y, (x1 + y0).z, s1, t0, r, g, b, a }
};
vertex_buffer_push_back(i_buffer, vertices, 4, indices, 6);
pen.x += glyph.get_advance_x();
}
}
}
}
glm::vec4 add_text_2d_impl(vertex_buffer_t* buffer, const std::vector<font_glyph>& glyphs, const std::string& text,
const glm::vec2& i_pen, float i_rt_height, const mws_sp<mws_font> i_font)
{
glm::vec4 ret_val(i_pen, i_pen);
int len = glm::min(text.length(), glyphs.size());
glm::vec4 c = i_font->get_color().to_vec4();
float r = c.r, g = c.g, b = c.b, a = c.a;
glm::vec2 pen = i_pen;
for (int i = 0; i < len; ++i)
{
font_glyph glyph = glyphs[i];
if (glyph.is_valid())
{
char ch = text[i];
// ignore carriage returns
if (ch < ' ')
{
if (ch == '\n')
{
pen.x = i_pen.x;
pen.y += i_font->get_height();
}
else if (ch == '\t')
{
pen.x += 2 * i_font->get_height();
}
ret_val.z = glm::max(ret_val.z, pen.x);
}
// normal character
else
{
float kerning = 0.0f;
if (i > 0)
{
kerning = glyph.get_kerning(text[i - 1]);
}
pen.x += kerning;
float x0 = (float)(pen.x + glyph.get_offset_x());
float y0 = (float)(i_rt_height - pen.y + glyph.get_offset_y());
float x1 = float((int)(x0 + glyph.get_width())); x0 = float((int)x0);
float y1 = float((int)(y0 - glyph.get_height())); y0 = float((int)y0);
float s0 = glyph.get_s0();
float t0 = glyph.get_t0();
float s1 = glyph.get_s1();
float t1 = glyph.get_t1();
//GLuint indices[6] = { 1, 0, 2, 2, 0, 3 };
GLuint indices[6] = { 0, 1, 2, 0, 2, 3 };
vertex_t vertices[4] =
{
{ x0, y0, 0, s0, t0, r, g, b, a },
{ x0, y1, 0, s0, t1, r, g, b, a },
{ x1, y1, 0, s1, t1, r, g, b, a },
{ x1, y0, 0, s1, t0, r, g, b, a }
};
vertex_buffer_push_back(buffer, vertices, 4, indices, 6);
pen.x += glyph.get_advance_x();
}
}
}
ret_val.z = glm::max(ret_val.z, pen.x);
ret_val.w = pen.y;
return ret_val;
}
void update_projection_mx()
{
rt_width = gfx::i()->rt.get_render_target_width();
rt_height = gfx::i()->rt.get_render_target_height();
float left = 0;
float right = (float)rt_width;
float bottom = (float)rt_height;
float top = 0;
projection = glm::ortho(left, right, top, bottom, -100.f, 100.f);
}
#ifdef debug_text_vxo
/** used for lookup during debug of this text_vxo */
std::string latest_text;
#endif
vertex_buffer_t* vbuffer;
glm::mat4 model = glm::mat4(1.f);
glm::mat4 view = glm::mat4(1.f);
glm::mat4 projection = glm::mat4(1.f);
uint32_t rt_width;
uint32_t rt_height;
glm::vec3 mPosition;
float mFontHeight;
bool mIs3D;
};
mws_sp<mws_text_vxo> mws_text_vxo::nwi()
{
mws_sp<mws_text_vxo> inst(new mws_text_vxo());
inst->p = std::make_shared<mws_text_vxo_impl>(inst);
return inst;
}
void mws_text_vxo::draw_text(const std::string& i_text, float i_x, float i_y, const mws_sp<mws_font> i_font)
{
add_text(i_text, glm::vec2(i_x, i_y), i_font);
}
void mws_text_vxo::clear_text()
{
p->clear_text();
}
glm::vec4 mws_text_vxo::add_text(const std::string& i_text, const glm::vec2& i_pos, const mws_sp<mws_font> i_font)
{
return p->add_text(i_text, i_pos, i_font);
}
void mws_text_vxo::draw_in_sync(mws_sp<gfx_camera> i_camera)
{
if (!visible)
{
return;
}
p->draw_in_sync(static_pointer_cast<mws_text_vxo>(get_mws_sp()), i_camera, position);
}
mws_text_vxo::mws_text_vxo() : gfx_vxo(vx_info("a_v3_position, a_v2_tex_coord, a_v4_color"))
{
}
#endif
| 29.711172 | 150 | 0.536684 | [
"vector",
"model"
] |
3eb4c78ca91ca214af5e183c6b5b2c5b65fd0e94 | 722 | cpp | C++ | clang/test/PCH/pch-no-hdrstop.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,102 | 2015-01-04T02:28:35.000Z | 2022-03-30T12:53:41.000Z | clang/test/PCH/pch-no-hdrstop.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/PCH/pch-no-hdrstop.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 1,868 | 2015-01-03T04:27:11.000Z | 2022-03-25T13:37:35.000Z | // expected-no-diagnostics
// Create PCH with #pragma hdrstop processing with no #pragma hdrstop
// RUN: %clang_cc1 -verify -I %S -emit-pch -pch-through-hdrstop-create \
// RUN: -fms-extensions -o %t.pch -x c++-header %s
// Create the PCH object
// RUN: %clang_cc1 -verify -I %S -emit-obj -include-pch %t.pch \
// RUN: -pch-through-hdrstop-create -fms-extensions -o %t.obj -x c++ %s
// The use must still have a #pragma hdrstop
// RUN: %clang_cc1 -verify -I %S -emit-obj -include-pch %t.pch \
// RUN: -pch-through-hdrstop-use -fms-extensions -o %t.obj \
// RUN: -x c++ %S/Inputs/pch-no-hdrstop-use.cpp
#include "Inputs/pch-through1.h"
static int bar() { return 42; }
#include "Inputs/pch-through2.h"
int pch();
| 38 | 73 | 0.668975 | [
"object"
] |
3eb4f882f74232b6f9b45486f09531e6fa6a08c2 | 28,363 | cc | C++ | third_party/blink/renderer/core/layout/ng/table/ng_table_borders.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/core/layout/ng/table/ng_table_borders.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/core/layout/ng/table/ng_table_borders.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/layout/ng/table/ng_table_borders.h"
#include "third_party/blink/renderer/core/frame/web_feature.h"
#include "third_party/blink/renderer/core/layout/ng/ng_block_node.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h"
#include "third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h"
#include "third_party/blink/renderer/core/layout/ng/ng_length_utils.h"
#include "third_party/blink/renderer/core/layout/ng/table/layout_ng_table.h"
#include "third_party/blink/renderer/core/layout/ng/table/layout_ng_table_column_visitor.h"
#include "third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm_helpers.h"
#include "third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm_types.h"
#include "third_party/blink/renderer/core/layout/ng/table/ng_table_layout_algorithm_utils.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
namespace {
// https://www.w3.org/TR/css-tables-3/#conflict-resolution-for-collapsed-borders
bool IsSourceMoreSpecificThanEdge(EBorderStyle source_style,
LayoutUnit source_width,
const NGTableBorders::Edge& edge) {
if (edge.edge_side == NGTableBorders::EdgeSide::kDoNotFill)
return false;
if (!edge.style || source_style == EBorderStyle::kHidden)
return true;
EBorderStyle edge_border_style =
NGTableBorders::BorderStyle(edge.style.get(), edge.edge_side);
if (edge_border_style == EBorderStyle::kHidden)
return false;
LayoutUnit edge_width =
NGTableBorders::BorderWidth(edge.style.get(), edge.edge_side);
if (source_width < edge_width)
return false;
if (source_width > edge_width)
return true;
return source_style > edge_border_style;
}
class ColBordersMarker {
STACK_ALLOCATED();
public:
void VisitCol(const NGLayoutInputNode& column,
wtf_size_t start_column_index,
wtf_size_t span) {
for (wtf_size_t i = 0; i < span; ++i) {
wtf_size_t current_column_index = start_column_index + i;
borders.MergeBorders(0, current_column_index, table_row_count, 1,
column.Style(), NGTableBorders::EdgeSource::kColumn,
box_order, table_writing_direction);
}
}
void EnterColgroup(const NGLayoutInputNode& colgroup,
wtf_size_t start_column_index) {}
void LeaveColgroup(const NGLayoutInputNode& colgroup,
wtf_size_t start_column_index,
wtf_size_t span,
bool has_children) {}
ColBordersMarker(wtf_size_t table_row_count,
wtf_size_t box_order,
WritingDirectionMode table_writing_direction,
NGTableBorders& borders)
: table_row_count(table_row_count),
box_order(box_order),
table_writing_direction(table_writing_direction),
borders(borders) {}
const wtf_size_t table_row_count;
const wtf_size_t box_order;
const WritingDirectionMode table_writing_direction;
NGTableBorders& borders;
};
class ColgroupBordersMarker {
STACK_ALLOCATED();
public:
void VisitCol(const NGLayoutInputNode& column,
wtf_size_t start_column_index,
wtf_size_t span) {}
void EnterColgroup(const NGLayoutInputNode& colgroup,
wtf_size_t start_column_index) {}
void LeaveColgroup(const NGLayoutInputNode& colgroup,
wtf_size_t start_column_index,
wtf_size_t span,
bool has_children) {
borders.MergeBorders(0, start_column_index, table_row_count, span,
colgroup.Style(), NGTableBorders::EdgeSource::kColumn,
box_order, table_writing_direction);
}
ColgroupBordersMarker(wtf_size_t table_row_count,
wtf_size_t box_order,
WritingDirectionMode table_writing_direction,
NGTableBorders& borders)
: table_row_count(table_row_count),
box_order(box_order),
table_writing_direction(table_writing_direction),
borders(borders) {}
const wtf_size_t table_row_count;
const wtf_size_t box_order;
const WritingDirectionMode table_writing_direction;
NGTableBorders& borders;
};
} // namespace
scoped_refptr<NGTableBorders> NGTableBorders::ComputeTableBorders(
const NGBlockNode& table) {
const ComputedStyle& table_style = table.Style();
NGBoxStrut intrinsic_borders(LayoutUnit(table_style.BorderStartWidth()),
LayoutUnit(table_style.BorderEndWidth()),
LayoutUnit(table_style.BorderBeforeWidth()),
LayoutUnit(table_style.BorderAfterWidth()));
scoped_refptr<NGTableBorders> table_borders =
base::MakeRefCounted<NGTableBorders>(table_style, intrinsic_borders);
if (table_style.BorderCollapse() != EBorderCollapse::kCollapse)
return table_borders;
NGTableGroupedChildren grouped_children(table);
WritingDirectionMode table_writing_direction =
table.Style().GetWritingDirection();
wtf_size_t box_order = 0;
wtf_size_t table_column_count =
NGTableAlgorithmUtils::ComputeMaximumNonMergeableColumnCount(
grouped_children.columns, table.Style().IsFixedTableLayout());
wtf_size_t table_row_index = 0;
// Mark cell borders.
bool found_multispan_cells = false;
for (const NGBlockNode section : grouped_children) {
wtf_size_t section_start_row = table_row_index;
NGColspanCellTabulator tabulator;
for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row;
row = To<NGBlockNode>(row.NextSibling())) {
tabulator.StartRow();
for (NGBlockNode cell = To<NGBlockNode>(row.FirstChild()); cell;
cell = To<NGBlockNode>(cell.NextSibling())) {
tabulator.FindNextFreeColumn();
wtf_size_t cell_colspan = cell.TableCellColspan();
found_multispan_cells |=
cell.TableCellRowspan() > 1 || cell_colspan > 1;
// Rowspan has to be limited by section size. Since we do not know
// section size, we have to rerun cell distribution with limited
// rowspans.
table_column_count = std::max(
table_column_count, NGTableAlgorithmHelpers::ComputeMaxColumn(
tabulator.CurrentColumn(), cell_colspan,
table.Style().IsFixedTableLayout()));
if (!found_multispan_cells) {
table_borders->MergeBorders(
table_row_index, tabulator.CurrentColumn(),
cell.TableCellRowspan(), cell_colspan, cell.Style(),
NGTableBorders::EdgeSource::kCell, ++box_order,
table_writing_direction);
}
tabulator.ProcessCell(cell);
}
tabulator.EndRow();
++table_row_index;
}
table_borders->AddSection(section_start_row,
table_row_index - section_start_row);
}
table_borders->SetLastColumnIndex(table_column_count);
wtf_size_t table_row_count = table_row_index;
table_row_index = 0;
// Mark cell borders again with limited rowspan.
// If any cells have rowspan, need to redistribute cell borders.
if (found_multispan_cells) {
wtf_size_t section_index = 0;
for (NGBlockNode section : grouped_children) {
NGColspanCellTabulator tabulator;
for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row;
row = To<NGBlockNode>(row.NextSibling())) {
tabulator.StartRow();
for (NGBlockNode cell = To<NGBlockNode>(row.FirstChild()); cell;
cell = To<NGBlockNode>(cell.NextSibling())) {
tabulator.FindNextFreeColumn();
table_borders->MergeBorders(
table_row_index, tabulator.CurrentColumn(),
cell.TableCellRowspan(), cell.TableCellColspan(), cell.Style(),
NGTableBorders::EdgeSource::kCell, ++box_order,
table_writing_direction, section_index);
tabulator.ProcessCell(cell);
}
tabulator.EndRow();
++table_row_index;
}
++section_index;
}
}
// Mark row borders.
table_row_index = 0;
for (NGBlockNode section : grouped_children) {
for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row;
row = To<NGBlockNode>(row.NextSibling())) {
table_borders->MergeBorders(table_row_index, 0, 1, table_column_count,
row.Style(), NGTableBorders::EdgeSource::kRow,
++box_order, table_writing_direction);
++table_row_index;
}
}
// Mark section borders.
// It is tempting to traverse sections at the same time as rows,
// but it would cause precedence errors.
wtf_size_t section_index = 0;
for (NGBlockNode section : grouped_children) {
NGTableBorders::Section section_info =
table_borders->GetSection(section_index);
table_borders->MergeBorders(
section_info.start_row, 0, section_info.row_count, table_column_count,
section.Style(), NGTableBorders::EdgeSource::kSection, ++box_order,
table_writing_direction);
++section_index;
}
// Mark column borders.
// COL borders have precedence over COLGROUP borders.
// We have to traverse COL first, then COLGROUP.
ColBordersMarker col_borders_marker(table_row_count, ++box_order,
table_writing_direction,
*table_borders.get());
VisitLayoutNGTableColumn(
const_cast<Vector<NGBlockNode>&>(grouped_children.columns),
table_column_count, &col_borders_marker);
ColgroupBordersMarker colgroup_borders_marker(table_row_count, ++box_order,
table_writing_direction,
*table_borders.get());
VisitLayoutNGTableColumn(
const_cast<Vector<NGBlockNode>&>(grouped_children.columns),
table_column_count, &colgroup_borders_marker);
// Mark table borders.
table_borders->MergeBorders(0, 0, table_row_count, table_column_count,
table_style, NGTableBorders::EdgeSource::kTable,
++box_order, table_writing_direction);
table_borders->ComputeCollapsedTableBorderPadding(table_row_count,
table_column_count);
// https://github.com/w3c/csswg-drafts/issues/6230
if (table_borders->collapsed_visual_inline_start_ !=
table_borders->cached_table_border_->inline_start ||
table_borders->collapsed_visual_inline_end_ !=
table_borders->cached_table_border_->inline_end) {
UseCounter::Count(table.GetDocument(),
WebFeature::kTableCollapsedBorderDifferentToVisual);
}
return table_borders;
}
NGTableBorders::NGTableBorders(const ComputedStyle& table_style,
const NGBoxStrut& table_border)
: is_collapsed_(table_style.BorderCollapse() ==
EBorderCollapse::kCollapse) {
if (!is_collapsed_) {
cached_table_border_ = table_border;
}
}
#if DCHECK_IS_ON()
String NGTableBorders::DumpEdges() {
if (edges_per_row_ == 0)
return "No edges";
StringBuilder edge_string;
wtf_size_t row_count = edges_.size() / edges_per_row_;
for (wtf_size_t row = 0; row < row_count; ++row) {
for (wtf_size_t i = 0; i < edges_per_row_; ++i) {
const auto& edge = edges_[edges_per_row_ * row + i];
if (edge.style) {
switch (edge.edge_side) {
case EdgeSide::kTop:
edge_string.Append('-');
break;
case EdgeSide::kBottom:
edge_string.Append('_');
break;
case EdgeSide::kLeft:
edge_string.Append('[');
break;
case EdgeSide::kRight:
edge_string.Append(']');
break;
case EdgeSide::kDoNotFill:
edge_string.Append('?');
break;
}
} else { // no style.
if (edge.edge_side == EdgeSide::kDoNotFill)
edge_string.Append('X');
else
edge_string.Append('.');
}
if (i & 1) // i is odd.
edge_string.Append(' ');
}
edge_string.Append('\n');
}
return edge_string.ToString();
}
void NGTableBorders::ShowEdges() {
LOG(INFO) << "\n" << DumpEdges().Utf8();
}
bool NGTableBorders::operator==(const NGTableBorders& other) const {
// Compare by traversal, because we must call edge comparsion function.
if (edges_.size() != other.edges_.size())
return false;
for (unsigned i = 0; i < edges_.size(); i++) {
if (edges_[i].edge_side != other.edges_[i].edge_side)
return false;
if (edges_[i].box_order != other.edges_[i].box_order)
return false;
}
return sections_ == other.sections_ &&
edges_per_row_ == other.edges_per_row_ &&
cached_table_border_ == other.cached_table_border_ &&
collapsed_visual_inline_start_ ==
other.collapsed_visual_inline_start_ &&
collapsed_visual_inline_end_ == other.collapsed_visual_inline_end_ &&
last_column_index_ == other.last_column_index_ &&
is_collapsed_ == other.is_collapsed_;
}
#endif
NGBoxStrut NGTableBorders::GetCellBorders(wtf_size_t row,
wtf_size_t column,
wtf_size_t rowspan,
wtf_size_t colspan) const {
NGBoxStrut border_strut;
if (edges_per_row_ == 0)
return border_strut;
DCHECK_EQ(edges_.size() % edges_per_row_, 0u);
if (column * 2 >= edges_per_row_ || row >= edges_.size() / edges_per_row_)
return border_strut;
// Compute inline border widths.
wtf_size_t first_inline_start_edge = row * edges_per_row_ + column * 2;
wtf_size_t first_inline_end_edge = first_inline_start_edge + colspan * 2;
for (wtf_size_t i = 0; i < rowspan; ++i) {
wtf_size_t start_edge_index = first_inline_start_edge + i * edges_per_row_;
border_strut.inline_start =
std::max(border_strut.inline_start, CanPaint(start_edge_index)
? BorderWidth(start_edge_index)
: LayoutUnit());
if (start_edge_index >= edges_.size())
break;
wtf_size_t end_edge_index = first_inline_end_edge + i * edges_per_row_;
border_strut.inline_end = std::max(
border_strut.inline_end,
CanPaint(end_edge_index) ? BorderWidth(end_edge_index) : LayoutUnit());
}
// Compute block border widths.
wtf_size_t start_edge_column_index = column * 2 + 1;
for (wtf_size_t i = 0; i < colspan; ++i) {
wtf_size_t current_column_index = start_edge_column_index + i * 2;
if (current_column_index >= edges_per_row_)
break;
wtf_size_t start_edge_index = row * edges_per_row_ + current_column_index;
border_strut.block_start =
std::max(border_strut.block_start, CanPaint(start_edge_index)
? BorderWidth(start_edge_index)
: LayoutUnit());
wtf_size_t end_edge_index = start_edge_index + rowspan * edges_per_row_;
border_strut.block_end = std::max(
border_strut.block_end,
CanPaint(end_edge_index) ? BorderWidth(end_edge_index) : LayoutUnit());
}
DCHECK(is_collapsed_);
// If borders are not divisible by 2, two half borders will not add up
// to original border size (off by 1/64px). This is ok, because
// pixel snapping will round to physical pixels.
border_strut.block_start /= 2;
border_strut.block_end /= 2;
border_strut.inline_start /= 2;
border_strut.inline_end /= 2;
return border_strut;
}
void NGTableBorders::ComputeCollapsedTableBorderPadding(
wtf_size_t table_row_count,
wtf_size_t table_column_count) {
DCHECK(is_collapsed_);
// https://www.w3.org/TR/CSS2/tables.html#collapsing-borders
// block[start|end] borders are computed by traversing all the edges.
// inline[start|end] borders are computed by looking at first/last edge.
if (edges_per_row_ == 0) {
cached_table_border_ = NGBoxStrut();
return;
}
DCHECK_GE((table_column_count + 1) * 2, edges_per_row_);
// We still need visual border rect.
NGBoxStrut borders =
GetCellBorders(0, 0, table_row_count, table_column_count);
collapsed_visual_inline_start_ = borders.inline_start;
collapsed_visual_inline_end_ = borders.inline_end;
wtf_size_t inline_start_edge = 0;
wtf_size_t inline_end_edge = 2 * table_column_count;
borders.inline_start = CanPaint(inline_start_edge)
? BorderWidth(inline_start_edge) / 2
: LayoutUnit();
borders.inline_end = CanPaint(inline_end_edge)
? BorderWidth(inline_end_edge) / 2
: LayoutUnit();
cached_table_border_ = borders;
}
NGBoxStrut NGTableBorders::GetCollapsedBorderVisualSizeDiff() const {
if (!is_collapsed_)
return NGBoxStrut();
// Inline sizes expand by difference between visual and
// layout border width.
NGBoxStrut visual_diff;
visual_diff.inline_start =
collapsed_visual_inline_start_ - cached_table_border_->inline_start;
visual_diff.inline_end =
collapsed_visual_inline_end_ - cached_table_border_->inline_end;
return visual_diff;
}
NGBoxStrut NGTableBorders::CellBorder(
const NGBlockNode& cell,
wtf_size_t row,
wtf_size_t column,
wtf_size_t section,
WritingDirectionMode table_writing_direction) const {
if (is_collapsed_) {
return GetCellBorders(row, column,
ClampRowspan(section, row, cell.TableCellRowspan()),
ClampColspan(column, cell.TableCellColspan()));
}
return ComputeBorders(
NGConstraintSpaceBuilder(table_writing_direction.GetWritingMode(),
table_writing_direction, /* is_new_fc */ false)
.ToConstraintSpace(),
cell);
}
// As we are determining the intrinsic size of the table at this stage,
// %-padding resolves against an indefinite size.
NGBoxStrut NGTableBorders::CellPaddingForMeasure(
const ComputedStyle& cell_style,
WritingDirectionMode table_writing_direction) const {
if (!cell_style.MayHavePadding())
return NGBoxStrut();
return ComputePadding(
NGConstraintSpaceBuilder(table_writing_direction.GetWritingMode(),
table_writing_direction,
/* is_new_fc */ false)
.ToConstraintSpace(),
cell_style);
}
void NGTableBorders::MergeBorders(wtf_size_t cell_start_row,
wtf_size_t cell_start_column,
wtf_size_t rowspan,
wtf_size_t colspan,
const ComputedStyle& source_style,
EdgeSource source,
const wtf_size_t box_order,
WritingDirectionMode table_writing_direction,
wtf_size_t section_index) {
DCHECK(is_collapsed_);
// Can be 0 in empty table parts.
if (rowspan == 0 || colspan == 0)
return;
wtf_size_t clamped_colspan = ClampColspan(cell_start_column, colspan);
wtf_size_t clamped_rowspan =
source == EdgeSource::kCell
? ClampRowspan(section_index, cell_start_row, rowspan)
: rowspan;
bool mark_inner_borders = source == EdgeSource::kCell &&
(clamped_rowspan > 1 || clamped_colspan > 1);
if (mark_inner_borders) {
EnsureCellColumnFits(cell_start_column + clamped_colspan - 1);
EnsureCellRowFits(cell_start_row + clamped_rowspan - 1);
} else {
PhysicalToLogical<EBorderStyle> border_style(
table_writing_direction, source_style.BorderTopStyle(),
source_style.BorderRightStyle(), source_style.BorderBottomStyle(),
source_style.BorderLeftStyle());
if (border_style.InlineStart() == EBorderStyle::kNone &&
border_style.InlineEnd() == EBorderStyle::kNone &&
border_style.BlockStart() == EBorderStyle::kNone &&
border_style.BlockEnd() == EBorderStyle::kNone) {
return;
}
// Only need to ensure edges that will be assigned exist.
if (border_style.InlineEnd() == EBorderStyle::kNone &&
border_style.BlockStart() == EBorderStyle::kNone &&
border_style.BlockEnd() == EBorderStyle::kNone) {
EnsureCellColumnFits(cell_start_column);
} else {
EnsureCellColumnFits(cell_start_column + clamped_colspan - 1);
}
if (border_style.InlineStart() == EBorderStyle::kNone &&
border_style.InlineEnd() == EBorderStyle::kNone &&
border_style.BlockEnd() == EBorderStyle::kNone) {
EnsureCellRowFits(cell_start_row);
} else {
EnsureCellRowFits(cell_start_row + clamped_rowspan - 1);
}
}
PhysicalToLogical<EdgeSide> edge_side(table_writing_direction, EdgeSide::kTop,
EdgeSide::kRight, EdgeSide::kBottom,
EdgeSide::kLeft);
MergeRowAxisBorder(cell_start_row, cell_start_column, clamped_colspan,
source_style, box_order, edge_side.BlockStart());
MergeRowAxisBorder(cell_start_row + clamped_rowspan, cell_start_column,
clamped_colspan, source_style, box_order,
edge_side.BlockEnd());
MergeColumnAxisBorder(cell_start_row, cell_start_column, clamped_rowspan,
source_style, box_order, edge_side.InlineStart());
MergeColumnAxisBorder(cell_start_row, cell_start_column + clamped_colspan,
clamped_rowspan, source_style, box_order,
edge_side.InlineEnd());
if (mark_inner_borders) {
MarkInnerBordersAsDoNotFill(cell_start_row, cell_start_column,
clamped_rowspan, clamped_colspan);
}
}
void NGTableBorders::MergeRowAxisBorder(wtf_size_t start_row,
wtf_size_t start_column,
wtf_size_t colspan,
const ComputedStyle& source_style,
const wtf_size_t box_order,
EdgeSide physical_side) {
EBorderStyle source_border_style = BorderStyle(&source_style, physical_side);
if (source_border_style == EBorderStyle::kNone)
return;
LayoutUnit source_border_width = BorderWidth(&source_style, physical_side);
wtf_size_t start_edge = edges_per_row_ * start_row + start_column * 2 + 1;
wtf_size_t end_edge = start_edge + colspan * 2;
for (wtf_size_t current_edge = start_edge; current_edge < end_edge;
current_edge += 2) {
// https://www.w3.org/TR/css-tables-3/#border-specificity
if (IsSourceMoreSpecificThanEdge(source_border_style, source_border_width,
edges_[current_edge])) {
edges_[current_edge].style = &source_style;
edges_[current_edge].edge_side = physical_side;
edges_[current_edge].box_order = box_order;
}
}
}
void NGTableBorders::MergeColumnAxisBorder(wtf_size_t start_row,
wtf_size_t start_column,
wtf_size_t rowspan,
const ComputedStyle& source_style,
const wtf_size_t box_order,
EdgeSide physical_side) {
EBorderStyle source_border_style = BorderStyle(&source_style, physical_side);
if (source_border_style == EBorderStyle::kNone)
return;
LayoutUnit source_border_width = BorderWidth(&source_style, physical_side);
wtf_size_t start_edge = edges_per_row_ * start_row + start_column * 2;
wtf_size_t end_edge = start_edge + (rowspan * edges_per_row_);
for (wtf_size_t current_edge = start_edge; current_edge < end_edge;
current_edge += edges_per_row_) {
// https://www.w3.org/TR/css-tables-3/#border-specificity
if (IsSourceMoreSpecificThanEdge(source_border_style, source_border_width,
edges_[current_edge])) {
edges_[current_edge].style = &source_style;
edges_[current_edge].edge_side = physical_side;
edges_[current_edge].box_order = box_order;
}
}
}
// Rowspanned/colspanned cells need to mark inner edges as do-not-fill to
// prevent tables parts from drawing into them.
void NGTableBorders::MarkInnerBordersAsDoNotFill(wtf_size_t start_row,
wtf_size_t start_column,
wtf_size_t rowspan,
wtf_size_t colspan) {
// Mark block axis edges.
wtf_size_t start_edge = (start_column * 2) + 2;
wtf_size_t end_edge = start_edge + (colspan - 1) * 2;
for (wtf_size_t row = start_row;
row < start_row + rowspan && start_edge != end_edge; ++row) {
wtf_size_t row_offset = row * edges_per_row_;
for (wtf_size_t edge = row_offset + start_edge;
edge < row_offset + end_edge; edge += 2) {
// DCHECK(!edges_[edge].style) is true in most tables. But,
// when two cells overlap each other, (really an error)
// style might already be assigned.
if (!edges_[edge].style)
edges_[edge].edge_side = EdgeSide::kDoNotFill;
}
}
// Mark inline axis edges.
start_edge = start_column * 2 + 1;
end_edge = start_edge + colspan * 2;
for (wtf_size_t row = start_row + 1; row < start_row + rowspan; ++row) {
wtf_size_t row_offset = row * edges_per_row_;
for (wtf_size_t edge = row_offset + start_edge;
edge < row_offset + end_edge; edge += 2) {
if (!edges_[edge].style)
edges_[edge].edge_side = EdgeSide::kDoNotFill;
}
}
}
// Inline edges are edges between columns.
void NGTableBorders::EnsureCellColumnFits(wtf_size_t cell_column) {
wtf_size_t desired_edges_per_row = (cell_column + 2) * 2;
if (desired_edges_per_row <= edges_per_row_)
return;
// When number of columns changes, all rows have to be resized.
// Edges must be copied to new positions. This can be expensive.
// Most tables do not change number of columns after the 1st row.
wtf_size_t row_count =
edges_per_row_ == 0 ? 1 : edges_.size() / edges_per_row_;
edges_.resize(row_count * desired_edges_per_row);
for (wtf_size_t row_index = row_count - 1; row_index > 0; --row_index) {
wtf_size_t new_edge = desired_edges_per_row - 1;
bool done = false;
// while loop is necessary to count down with unsigned.
do {
wtf_size_t new_edge_index = row_index * desired_edges_per_row + new_edge;
if (new_edge < edges_per_row_) {
wtf_size_t old_edge_index = row_index * edges_per_row_ + new_edge;
DCHECK_LT(row_index * edges_per_row_ + new_edge, edges_.size());
edges_[new_edge_index] = edges_[old_edge_index];
} else {
edges_[new_edge_index].style = nullptr;
edges_[new_edge_index].edge_side = EdgeSide::kTop;
}
done = new_edge-- == 0;
} while (!done);
}
// Previous loop does not clear out new cells in the first row.
for (wtf_size_t edge_index = edges_per_row_;
edge_index < desired_edges_per_row; ++edge_index) {
edges_[edge_index].style = nullptr;
edges_[edge_index].edge_side = EdgeSide::kTop;
}
edges_per_row_ = desired_edges_per_row;
}
// Block edges are edges between rows.
void NGTableBorders::EnsureCellRowFits(wtf_size_t cell_row) {
DCHECK_NE(edges_per_row_, 0u);
wtf_size_t current_block_edges = edges_.size() / edges_per_row_;
wtf_size_t desired_block_edges = cell_row + 2;
if (desired_block_edges <= current_block_edges)
return;
edges_.resize(desired_block_edges * edges_per_row_);
}
} // namespace blink
| 42.144131 | 94 | 0.654197 | [
"vector"
] |
3ebb310680ce9c2f4f6a6deb92dd95ffe3457808 | 4,172 | cpp | C++ | src/parser/Statements.cpp | dead-tech/tek | dbf8b8b55e318792fbfc9e26a56f2fab605ed89e | [
"MIT"
] | null | null | null | src/parser/Statements.cpp | dead-tech/tek | dbf8b8b55e318792fbfc9e26a56f2fab605ed89e | [
"MIT"
] | 1 | 2022-02-27T13:20:49.000Z | 2022-02-27T13:20:49.000Z | src/parser/Statements.cpp | dead-tech/tek | dbf8b8b55e318792fbfc9e26a56f2fab605ed89e | [
"MIT"
] | null | null | null | #include "Statements.hpp"
namespace tek::parser {
PrintStatement::PrintStatement(Statement::ExpressionPtr expression) : expression{ std::move(expression) } {}
std::string PrintStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_print_statement(*this);
}
void PrintStatement::accept(StatementVisitor<void> &visitor) { return visitor.visit_print_statement(*this); }
ExpressionStatement::ExpressionStatement(Statement::ExpressionPtr expression) : expression{ std::move(expression) }
{}
std::string ExpressionStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_expression_statement(*this);
}
void ExpressionStatement::accept(StatementVisitor<void> &visitor)
{
return visitor.visit_expression_statement(*this);
}
VarStatement::VarStatement(tokenizer::Token name, Statement::ExpressionPtr initializer)
: name{ std::move(name) }, initializer{ std::move(initializer) }
{}
std::string VarStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_var_statement(*this);
}
void VarStatement::accept(StatementVisitor<void> &visitor) { return visitor.visit_var_statement(*this); }
BlockStatement::BlockStatement(BlockStatement::StatementsVec statements) : statements{ std::move(statements) } {}
std::string BlockStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_block_statement(*this);
}
void BlockStatement::accept(StatementVisitor<void> &visitor) { return visitor.visit_block_statement(*this); }
IfStatement::IfStatement(
Statement::ExpressionPtr condition,
IfStatement::StatementPtr then_branch,
IfStatement::StatementPtr else_branch)
: condition{ std::move(condition) }, then_branch{ std::move(then_branch) }, else_branch{ std::move(else_branch) }
{}
std::string IfStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_if_statement(*this);
}
void IfStatement::accept(StatementVisitor<void> &visitor) { return visitor.visit_if_statement(*this); }
WhileStatement::WhileStatement(Statement::ExpressionPtr condition, WhileStatement::StatementPtr body)
: condition{ std::move(condition) }, body{ std::move(body) }
{}
std::string WhileStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_while_statement(*this);
}
void WhileStatement::accept(StatementVisitor<void> &visitor) { return visitor.visit_while_statement(*this); }
ForStatement::ForStatement(
ForStatement::StatementPtr initializer,
Statement::ExpressionPtr condition,
ForStatement::StatementPtr body)
: initializer{ std::move(initializer) }, condition{ std::move(condition) }, body{ std::move(body) }
{}
std::string ForStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_for_statement(*this);
}
void ForStatement::accept(StatementVisitor<void> &visitor) { return visitor.visit_for_statement(*this); }
FunctionStatement::FunctionStatement(
tokenizer::Token name,
std::vector<tokenizer::Token> parameters,
StatementsVec body)
: name{ std::move(name) }, parameters{ std::move(parameters) }, body{ std::move(body) }
{}
std::string FunctionStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_function_statement(*this);
}
void FunctionStatement::accept(StatementVisitor<void> &visitor) { visitor.visit_function_statement(*this); }
ReturnStatement::ReturnStatement(tokenizer::Token keyword, Statement::ExpressionPtr expression)
: keyword{ std::move(keyword) }, expression{ std::move(expression) }
{}
std::string ReturnStatement::accept(StatementVisitor<std::string> &visitor)
{
return visitor.visit_return_statement(*this);
}
void ReturnStatement::accept(StatementVisitor<void> &visitor) { return visitor.visit_return_statement(*this); }
}// namespace tek::parser
| 37.585586 | 119 | 0.708293 | [
"vector"
] |
3ebcab8733369c81636c7395843f704a85a9047c | 6,059 | cpp | C++ | src/plugins/fontiac/substsmanager.cpp | rayslava/leechcraft | 4ecc8aa56dc6030d2593922ff41b00ff50902db8 | [
"BSL-1.0"
] | 1 | 2017-01-12T07:05:45.000Z | 2017-01-12T07:05:45.000Z | src/plugins/fontiac/substsmanager.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | src/plugins/fontiac/substsmanager.cpp | ForNeVeR/leechcraft | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "substsmanager.h"
#include <QStandardItemModel>
#include <QSettings>
#include <QtDebug>
#include <QCoreApplication>
#include <xmlsettingsdialog/datasourceroles.h>
#include <util/sll/prelude.h>
namespace LeechCraft
{
namespace Fontiac
{
SubstsManager::SubstsManager (QObject* parent)
: QObject { parent }
, Model_ { new QStandardItemModel { this } }
{
InitHeader ();
LoadSettings ();
}
QAbstractItemModel* SubstsManager::GetModel () const
{
return Model_;
}
void SubstsManager::InitHeader ()
{
Model_->setHorizontalHeaderLabels ({ tr ("Font family"), tr ("Substitution") });
Model_->horizontalHeaderItem (0)->setData (DataSources::DataFieldType::String,
DataSources::DataSourceRole::FieldType);
Model_->horizontalHeaderItem (1)->setData (DataSources::DataFieldType::Font,
DataSources::DataSourceRole::FieldType);
}
void SubstsManager::LoadSettings ()
{
QSettings settings
{
QCoreApplication::organizationName (),
QCoreApplication::applicationName () + "_Fontiac"
};
int size = settings.beginReadArray ("Substs");
for (int i = 0; i < size; ++i)
{
settings.setArrayIndex (i);
const auto& family = settings.value ("Family").toString ();
const auto& subst = settings.value ("Subst").toString ();
AddItem (family, subst, { subst });
}
settings.endArray ();
}
void SubstsManager::SaveSettings () const
{
QSettings settings
{
QCoreApplication::organizationName (),
QCoreApplication::applicationName () + "_Fontiac"
};
settings.beginWriteArray ("Substs");
for (int i = 0; i < Substitutes_.size (); ++i)
{
settings.setArrayIndex (i);
const auto& pair = Substitutes_.at (i);
settings.setValue ("Family", pair.first);
settings.setValue ("Subst", pair.second);
}
settings.endArray ();
}
void SubstsManager::AddItem (const QString& family, const QString& subst, const QFont& font)
{
if (family.isEmpty () || subst.isEmpty ())
{
qWarning () << Q_FUNC_INFO
<< "empty data";
return;
}
if (Substitutes_.contains ({ family, subst }))
return;
Substitutes_.append ({ family, subst });
QFont::insertSubstitution (family, subst);
QList<QStandardItem*> row
{
new QStandardItem { family },
new QStandardItem { subst }
};
for (const auto item : row)
item->setEditable (false);
row.value (0)->setFont ({ family });
row.value (1)->setFont (font);
Model_->appendRow (row);
}
void SubstsManager::RebuildSubsts (const QString& family)
{
#if QT_VERSION >= 0x050000
QFont::removeSubstitutions (family);
#else
QFont::removeSubstitution (family);
#endif
const auto& remaining = Util::Filter (Substitutes_,
[&family] (const auto& pair) { return pair.first == family; });
if (!remaining.isEmpty ())
QFont::insertSubstitutions (family,
Util::Map (remaining, [] (const auto& pair) { return pair.second; }));
}
namespace
{
struct DatasParseResult
{
QString Family_;
QFont Font_;
QString Subst_;
DatasParseResult (const QVariantList& datas)
: Family_ { datas.value (0).toString ().trimmed () }
, Font_ { datas.value (1).value<QFont> () }
, Subst_ { Font_.family ().trimmed ()}
{
}
};
}
void SubstsManager::addRequested (const QString&, const QVariantList& datas)
{
const DatasParseResult parsed { datas };
AddItem (parsed.Family_, parsed.Subst_, parsed.Font_);
SaveSettings ();
}
void SubstsManager::modifyRequested (const QString&, int row, const QVariantList& datas)
{
const DatasParseResult parsed { datas };
Model_->item (row, 0)->setText (parsed.Family_);
Model_->item (row, 0)->setFont ({ parsed.Family_ });
Model_->item (row, 1)->setText (parsed.Subst_);
Model_->item (row, 1)->setFont ({ parsed.Font_ });
const auto& oldFamily = Substitutes_.at (row).first;
Substitutes_ [row].first = parsed.Family_;
Substitutes_ [row].second = parsed.Subst_;
RebuildSubsts (parsed.Family_);
if (oldFamily != parsed.Family_)
RebuildSubsts (oldFamily);
SaveSettings ();
}
void SubstsManager::removeRequested (const QString&, const QModelIndexList& rows)
{
for (const auto& idx : rows)
{
const auto row = idx.row ();
if (row < 0 || row >= Substitutes_.size ())
continue;
Model_->removeRow (row);
const auto& family = Substitutes_.at (row).first;
Substitutes_.removeAt (row);
RebuildSubsts (family);
}
SaveSettings ();
}
}
}
| 28.71564 | 93 | 0.682291 | [
"object"
] |
3ebe613fd0ff8b6bf597b084235c7e1c42f01d97 | 676 | hpp | C++ | src/ComputeSYMGS.hpp | hpcg-benchmark/KHPCG3.0 | 9591b148ea6552342a0471a932d2abf332e490e0 | [
"BSD-3-Clause"
] | null | null | null | src/ComputeSYMGS.hpp | hpcg-benchmark/KHPCG3.0 | 9591b148ea6552342a0471a932d2abf332e490e0 | [
"BSD-3-Clause"
] | null | null | null | src/ComputeSYMGS.hpp | hpcg-benchmark/KHPCG3.0 | 9591b148ea6552342a0471a932d2abf332e490e0 | [
"BSD-3-Clause"
] | 3 | 2019-03-05T16:46:25.000Z | 2021-12-22T03:49:00.000Z |
//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra (dongarra@eecs.utk.edu)
// Piotr Luszczek (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER
#ifndef COMPUTESYMGS_HPP
#define COMPUTESYMGS_HPP
#include "SparseMatrix.hpp"
#include "Vector.hpp"
#include "KokkosSetup.hpp"
#ifdef SYMGS_COLOR
#include "ColorSYMGS.hpp"
#endif
#ifdef SYMGS_LEVEL
#include "LevelSYMGS.hpp"
#endif
int ComputeSYMGS( const SparseMatrix & A, const Vector & r, Vector & x);
#endif // COMPUTESYMGS_HPP
| 21.806452 | 73 | 0.610947 | [
"vector"
] |
3ec1999edc4f0549cc348d9da39e3e23b76a1a91 | 7,582 | cc | C++ | paddle/fluid/platform/device/ipu/popart_canonicalization/op_builder.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 1 | 2022-02-22T01:08:00.000Z | 2022-02-22T01:08:00.000Z | paddle/fluid/platform/device/ipu/popart_canonicalization/op_builder.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | null | null | null | paddle/fluid/platform/device/ipu/popart_canonicalization/op_builder.cc | zmxdream/Paddle | 04f042a5d507ad98f7f2cfc3cbc44b06d7a7f45c | [
"Apache-2.0"
] | 1 | 2022-03-02T11:36:03.000Z | 2022-03-02T11:36:03.000Z | // Copyright (c) 2021 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 "paddle/fluid/platform/device/ipu/popart_canonicalization/op_builder.h"
namespace paddle {
namespace platform {
namespace ipu {
// singleton
static int var_count = 0;
static int op_count = 0;
const std::string GenerateVarName() {
return std::string("_gen_var_") + std::to_string(var_count++);
}
const std::string GenerateOpName() {
return std::string("_gen_op_") + std::to_string(op_count++);
}
const std::string CreateOpIdentifyId(Node *node) {
// format:
// if has custom op_namescope:
// {op_namescope}/op_type/_gen_*
// else:
// {op_type}/{out_var0}/{out_var1}/.../_gen_*
// this name will be used as op name when exporting onnx model from popart
auto op_type = node->Name();
std::string op_namescope;
if (node->Op()->HasAttr("op_namescope")) {
op_namescope =
BOOST_GET_CONST(std::string, node->Op()->GetAttr("op_namescope"));
} else {
op_namescope = "/";
}
if (op_namescope != "/") {
return {op_namescope + op_type + "/" + GenerateOpName()};
} else {
std::string op_out = "";
for (auto *out_node : node->outputs) {
op_out += "/";
op_out += out_node->Name();
}
return {op_type + op_out + "/" + GenerateOpName()};
}
}
Node *MakeVarNode(Graph *graph, Node *node) {
auto var_name = GenerateVarName();
auto var_desc = std::make_unique<framework::VarDesc>(var_name);
auto var = graph->CreateVarNode(var_desc.get());
return var;
}
Node *MakeOpNode(Graph *graph, Node *node, const std::string &type,
const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs) {
auto op_desc = std::make_unique<framework::OpDesc>();
op_desc->SetType(type);
auto op = graph->CreateOpNode(op_desc.get());
for (auto *in : inputs) {
ConnectNodes(in, op);
}
if (outputs.empty()) {
auto var = MakeVarNode(graph, node);
ConnectNodes(op, var);
} else {
for (auto *out : outputs) {
ConnectNodes(op, out);
}
}
// i/o
std::vector<std::string> input_names;
for (auto node : op->inputs) {
input_names.push_back(node->Name());
}
op->Op()->SetInput("__inputs__", input_names);
std::vector<std::string> output_names;
for (auto node : op->outputs) {
output_names.push_back(node->Name());
}
op->Op()->SetOutput("__outputs__", output_names);
op->Op()->Flush();
return op;
}
Node *CreateBaseOp(Graph *graph, Node *node, const std::string &type,
const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs,
const AttributeMap &attrs) {
auto new_node = MakeOpNode(graph, node, type, inputs, outputs);
if (!attrs.empty()) {
new_node->Op()->SetAttrMap(attrs);
}
// deal special attr
if (!new_node->Op()->HasAttr(sIpuIndexAttr)) {
CopyOpAttr(sIpuIndexAttr, node->Op(), new_node->Op());
}
if (!new_node->Op()->HasAttr(sIpuStageAttr)) {
CopyOpAttr(sIpuStageAttr, node->Op(), new_node->Op());
}
if (node->Op()->HasAttr(sMatmulSerializeFactor)) {
CopyOpAttr(sMatmulSerializeFactor, node->Op(), new_node->Op());
}
if (node->Op()->HasAttr(sMatmulSerializeMode)) {
CopyOpAttr(sMatmulSerializeMode, node->Op(), new_node->Op());
}
{
new_node->Op()->SetAttr(sOpIdentifyIdAttr, CreateOpIdentifyId(node));
new_node->Op()->Flush();
}
return new_node;
}
Node *CreateConst(Graph *graph, Node *node, const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs,
const AttributeMap &attrs) {
return CreateBaseOp(graph, node, "popart_constant", inputs, outputs, attrs);
}
Node *CreateCast(Graph *graph, Node *node, const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs, const int otype) {
auto to = VarType2PopStr(otype);
return CreateBaseOp(graph, node, "popart_cast", inputs, outputs,
{{"to", to}});
}
Node *CreateGemm(Graph *graph, Node *node, const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs, int64_t transA,
int64_t transB, float alpha, float beta) {
return CreateBaseOp(graph, node, "popart_gemm", inputs, outputs,
{
{"alpha", alpha},
{"beta", beta},
{"transA", transA},
{"transB", transB},
});
}
Node *CreateReshape(Graph *graph, Node *node, const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs,
const std::vector<int64_t> &oshape) {
auto attr = AttributeMap{
{"value", oshape},
{"dims", std::vector<int64_t>{static_cast<int64_t>(oshape.size())}},
{"dtype", ONNXDataType::INT64}};
auto new_node_const =
CreateBaseOp(graph, node, "popart_constant", {}, {}, attr);
auto new_node_reshape =
CreateBaseOp(graph, node, "popart_reshape",
{inputs[0], new_node_const->outputs[0]}, outputs);
return new_node_reshape;
}
Node *CreateConv(Graph *graph, Node *node, const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs,
const std::vector<int64_t> &dilations, int64_t group,
const std::vector<int64_t> &kernel_shape,
const std::vector<int64_t> &pads,
const std::vector<int64_t> &strides) {
auto attrs = AttributeMap{
{"dilations", dilations}, {"group", group},
{"kernel_shape", kernel_shape}, {"pads", pads},
{"strides", strides},
};
return CreateBaseOp(graph, node, "popart_conv", inputs, outputs, attrs);
}
Node *CreateSoftmaxOpset11(Graph *graph, Node *node,
const std::vector<Node *> &inputs,
const std::vector<Node *> &outputs, int64_t axis) {
PADDLE_ENFORCE_EQ(inputs.size(), 1, platform::errors::InvalidArgument(
"Softmax op only support one input"));
auto x_shape = inputs[0]->Var()->GetShape();
int x_rank = x_shape.size();
if (axis < 0) {
axis = axis + x_rank;
}
if (axis == x_rank - 1) {
return CreateBaseOp(graph, node, "popart_softmax", inputs, outputs,
{{"axis", int64_t{-1}}});
} else {
auto perm = std::vector<int64_t>(x_rank);
std::iota(perm.begin(), perm.end(), 0);
perm[x_rank - 1] = axis;
perm[axis] = x_rank - 1;
auto new_transpose_pre = CreateBaseOp(graph, node, "popart_transpose",
inputs, {}, {{"perm", perm}});
auto new_softmax =
CreateBaseOp(graph, node, "popart_softmax", new_transpose_pre->outputs,
{}, {{"axis", int64_t{-1}}});
return CreateBaseOp(graph, node, "popart_transpose", new_softmax->outputs,
outputs, {{"perm", perm}});
}
}
} // namespace ipu
} // namespace platform
} // namespace paddle
| 34.779817 | 80 | 0.604722 | [
"vector",
"model"
] |
3ece0468450be26c61b204d97a28cb1a39751447 | 16,542 | cpp | C++ | Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp | RonnieXiong/o3de | 3fb903b03b64cdf7f04a59c051f272a194d43655 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp | RonnieXiong/o3de | 3fb903b03b64cdf7f04a59c051f272a194d43655 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp | RonnieXiong/o3de | 3fb903b03b64cdf7f04a59c051f272a194d43655 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Math/MathUtils.h>
#include <AzCore/Math/Random.h>
#include <EMotionFX/Source/AnimGraph.h>
#include <EMotionFX/Source/AnimGraphBindPoseNode.h>
#include <EMotionFX/Source/AnimGraphNode.h>
#include <EMotionFX/Source/AnimGraphStateMachine.h>
#include <EMotionFX/Source/BlendTree.h>
#include <EMotionFX/Source/BlendTreeBlend2Node.h>
#include <EMotionFX/Source/BlendTreeFloatConstantNode.h>
#include <EMotionFX/Source/BlendTreeFloatMath1Node.h>
#include <EMotionFX/Source/BlendTreeParameterNode.h>
#include <EMotionFX/Source/EMotionFXManager.h>
#include <EMotionFX/Source/Parameter/BoolParameter.h>
#include <EMotionFX/Source/Parameter/FloatSliderParameter.h>
#include <EMotionFX/Source/Parameter/IntSliderParameter.h>
#include <Tests/AnimGraphFixture.h>
namespace EMotionFX
{
struct BlendTreeFloatMath1NodeTestData
{
std::vector<float> m_xInputFloat;
std::vector<int> m_xInputInt;
std::vector<bool> m_xInputBool;
};
std::vector<BlendTreeFloatMath1NodeTestData> blendTreeFloatMath1NodeTestData
{
{
// TODO: MCore RandF function does not handle extreme values properly
// eg. MCore::Math::RandF(0, FLT_MAX) returns inf
{1000.3f, -1000.3f, 0.1f, -1.2f, 1.2f},
{1000, -1000, 0, -1, 1},
{true, false}
}
};
class BlendTreeFloatMath1NodeFixture
: public AnimGraphFixture
, public ::testing::WithParamInterface<BlendTreeFloatMath1NodeTestData>
{
public:
void ConstructGraph() override
{
AnimGraphFixture::ConstructGraph();
m_param = GetParam();
m_blendTreeAnimGraph = AnimGraphFactory::Create<OneBlendTreeNodeAnimGraph>();
m_rootStateMachine = m_blendTreeAnimGraph->GetRootStateMachine();
m_blendTree = m_blendTreeAnimGraph->GetBlendTreeNode();
AddParameter<FloatSliderParameter>("FloatParam", 0.0f);
AddParameter<BoolParameter>("BoolParam", false);
AddParameter<IntSliderParameter>("IntParam", 0);
/*
+------------------+
| |
| bindPoseNode |
| | +------------------+ +------------------+
+------------------+-->+ | | |
| blend2Node +-->+ finalNode |
+------------------+ +------------------+ | | | |
| | | +-->+------------------+ +------------------+
| m_paramNode +-->+ m_floatMath1Node |
| | | |
+------------------+ +------------------+
*/
BlendTreeFinalNode* finalNode = aznew BlendTreeFinalNode();
m_blendTree->AddChildNode(finalNode);
AnimGraphBindPoseNode* bindPoseNode = aznew AnimGraphBindPoseNode();
m_blendTree->AddChildNode(bindPoseNode);
BlendTreeBlend2Node* blend2Node = aznew BlendTreeBlend2Node();
m_blendTree->AddChildNode(blend2Node);
m_floatMath1Node = aznew BlendTreeFloatMath1Node();
m_blendTree->AddChildNode(m_floatMath1Node);
m_paramNode = aznew BlendTreeParameterNode();
m_blendTree->AddChildNode(m_paramNode);
// Connect the nodes.
blend2Node->AddConnection(bindPoseNode, AnimGraphBindPoseNode::PORTID_OUTPUT_POSE, BlendTreeBlend2Node::INPUTPORT_POSE_A);
blend2Node->AddConnection(bindPoseNode, AnimGraphBindPoseNode::PORTID_OUTPUT_POSE, BlendTreeBlend2Node::INPUTPORT_POSE_B);
blend2Node->AddConnection(m_floatMath1Node, BlendTreeFloatMath1Node::OUTPUTPORT_RESULT, BlendTreeBlend2Node::INPUTPORT_WEIGHT);
finalNode->AddConnection(blend2Node, BlendTreeBlend2Node::PORTID_OUTPUT_POSE, BlendTreeFinalNode::PORTID_INPUT_POSE);
m_blendTreeAnimGraph->InitAfterLoading();
}
template <class paramType, class inputType>
void TestInput(const AZStd::string& paramName, std::vector<inputType> xInputs)
{
BlendTreeConnection* connection = m_floatMath1Node->AddConnection(m_paramNode,
m_paramNode->FindOutputPortByName(paramName)->m_portId, BlendTreeFloatMath1Node::PORTID_INPUT_X);
for (inputType i : xInputs)
{
// Get and set parameter value to different test data inputs
const AZ::Outcome<size_t> parameterIndex = m_animGraphInstance->FindParameterIndex(paramName);
MCore::Attribute* param = m_animGraphInstance->GetParameterValue(static_cast<AZ::u32>(parameterIndex.GetValue()));
paramType* typeParam = static_cast<paramType*>(param);
typeParam->SetValue(i);
for (AZ::u8 j = 0; j < BlendTreeFloatMath1Node::MATHFUNCTION_NUMFUNCTIONS; j++)
{
// Test input with all 26 math functions
const BlendTreeFloatMath1Node::EMathFunction eMathFunc = static_cast<BlendTreeFloatMath1Node::EMathFunction>(j);
m_floatMath1Node->SetMathFunction(eMathFunc);
GetEMotionFX().Update(1.0f / 60.0f);
const float actualOutput = m_floatMath1Node->GetOutputFloat(m_animGraphInstance,
BlendTreeFloatMath1Node::OUTPUTPORT_RESULT)->GetValue();
const float expectedOutput = CalculateMathFunctionOutput(eMathFunc, static_cast<float>(i));
// Special cases for random float where float equal is not suitable
// If actual and expected outputs are both NaN, then they should be considered same
if (eMathFunc == BlendTreeFloatMath1Node::MATHFUNCTION_RANDOMFLOAT)
{
EXPECT_TRUE(RandomFloatIsInRange(actualOutput, 0, static_cast<float>(i))) << "Random float is not in range.";
continue;
}
if (isnan(actualOutput) && isnan(expectedOutput))
{
continue;
}
if (isinf(actualOutput) && isinf(expectedOutput))
{
continue;
}
EXPECT_NEAR(actualOutput, expectedOutput, 0.004f) << "Actual and expected outputs does not match.";
}
}
m_floatMath1Node->RemoveConnection(connection);
}
void SetUp() override
{
AnimGraphFixture::SetUp();
m_animGraphInstance->Destroy();
m_animGraphInstance = m_blendTreeAnimGraph->GetAnimGraphInstance(m_actorInstance, m_motionSet);
}
protected:
AZStd::unique_ptr<OneBlendTreeNodeAnimGraph> m_blendTreeAnimGraph;
BlendTree* m_blendTree = nullptr;
BlendTreeFloatMath1Node* m_floatMath1Node = nullptr;
BlendTreeFloatMath1NodeTestData m_param;
BlendTreeParameterNode* m_paramNode = nullptr;
private:
bool RandomFloatIsInRange(float randomFloat, float bound1, float bound2)
{
if (bound1 > bound2)
{
return (randomFloat - bound2) <= (bound1 - bound2);
}
return (randomFloat - bound1) <= (bound2 - bound1);
}
template<class ParameterType, class ValueType>
void AddParameter(const AZStd::string name, const ValueType& defaultValue)
{
ParameterType* parameter = aznew ParameterType();
parameter->SetName(name);
parameter->SetDefaultValue(defaultValue);
m_blendTreeAnimGraph->AddParameter(parameter);
}
float CalculateMathFunctionOutput(BlendTreeFloatMath1Node::EMathFunction mathFunction, float input)
{
switch (mathFunction)
{
case BlendTreeFloatMath1Node::MATHFUNCTION_SIN:
return CalculateSin(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_COS:
return CalculateCos(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_TAN:
return CalculateTan(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_SQR:
return CalculateSqr(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_SQRT:
return CalculateSqrt(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ABS:
return CalculateAbs(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_FLOOR:
return CalculateFloor(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_CEIL:
return CalculateCeil(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ONEOVERINPUT:
return CalculateOneOverInput(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_INVSQRT:
return CalculateInvSqrt(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_LOG:
return CalculateLog(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_LOG10:
return CalculateLog10(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_EXP:
return CalculateExp(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_FRACTION:
return CalculateFraction(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_SIGN:
return CalculateSign(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ISPOSITIVE:
return CalculateIsPositive(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ISNEGATIVE:
return CalculateIsNegative(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ISNEARZERO:
return CalculateIsNearZero(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_RANDOMFLOAT:
return 0.0f;
case BlendTreeFloatMath1Node::MATHFUNCTION_RADTODEG:
return CalculateRadToDeg(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_DEGTORAD:
return CalculateDegToRad(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_SMOOTHSTEP:
return CalculateSmoothStep(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ACOS:
return CalculateACos(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ASIN:
return CalculateASin(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_ATAN:
return CalculateATan(input);
case BlendTreeFloatMath1Node::MATHFUNCTION_NEGATE:
return CalculateNegate(input);
default:
AZ_Assert(false, "EMotionFX: Math function unknown.");
return 0.0f;
}
}
//-----------------------------------------------
// The math functions
//-----------------------------------------------
float CalculateSin(float input) { return sin(input); }
float CalculateCos(float input) { return cos(input); }
float CalculateTan(float input) { return tan(input); }
float CalculateSqr(float input) { return (input * input); }
float CalculateSqrt(float input)
{
if (input > AZ::Constants::FloatEpsilon)
{
return sqrt(input);
}
return 0.0f;
}
float CalculateAbs(float input) { return abs(input); }
float CalculateFloor(float input) { return floor(input); }
float CalculateCeil(float input) { return ceil(input); }
float CalculateOneOverInput(float input)
{
if (input > AZ::Constants::FloatEpsilon)
{
return 1.0f / input;
}
return 0.0f;
}
float CalculateInvSqrt(float input)
{
if (input > AZ::Constants::FloatEpsilon)
{
return 1.0f / sqrt(input);
}
return 0.0f;
}
float CalculateLog(float input)
{
if (input > AZ::Constants::FloatEpsilon)
{
return log(input);
}
return 0.0f;
}
float CalculateLog10(float input)
{
if (input > AZ::Constants::FloatEpsilon)
{
return log10f(input);
}
return 0.0f;
}
float CalculateExp(float input) { return exp(input); }
float CalculateFraction(float input) { return AZ::GetMod(input, 1.0f); }
float CalculateSign(float input)
{
if (input < 0.0f)
{
return -1.0f;
}
if (input > 0.0f)
{
return 1.0f;
}
return 0.0f;
}
float CalculateIsPositive(float input)
{
if (input >= 0.0f)
{
return 1.0f;
}
return 0.0f;
}
float CalculateIsNegative(float input)
{
if (input < 0.0f)
{
return 1.0f;
}
return 0.0f;
}
float CalculateIsNearZero(float input)
{
if ((input > -AZ::Constants::FloatEpsilon) && (input < AZ::Constants::FloatEpsilon))
{
return 1.0f;
}
return 0.0f;
}
float CalculateRadToDeg(float input) { return AZ::RadToDeg(input); }
float CalculateDegToRad(float input) { return AZ::DegToRad(input); }
float CalculateSmoothStep(float input)
{
const float f = AZ::GetClamp<float>(input, 0.0f, 1.0f);
const float weight = (1.0f - cos(f * AZ::Constants::Pi)) * 0.5f;;
return 0.0f * (1.0f - weight) + (weight * 1.0f);
}
float CalculateACos(float input) { return acos(input); }
float CalculateASin(float input) { return asin(input); }
float CalculateATan(float input) { return atan(input); }
float CalculateNegate(float input) { return -input; }
};
TEST_P(BlendTreeFloatMath1NodeFixture, NoInput_OutputsCorrectFloatTest)
{
// Testing float math1 node without input node
for (AZ::u8 i = 0; i < BlendTreeFloatMath1Node::MATHFUNCTION_NUMFUNCTIONS; i++)
{
BlendTreeFloatMath1Node::EMathFunction eMathFunc = static_cast<BlendTreeFloatMath1Node::EMathFunction>(i);
m_floatMath1Node->SetMathFunction(eMathFunc);
GetEMotionFX().Update(1.0f / 60.0f);
// Default output should be 0.0f
EXPECT_FLOAT_EQ(m_floatMath1Node->GetOutputFloat(m_animGraphInstance,
BlendTreeFloatMath1Node::OUTPUTPORT_RESULT)->GetValue(), 0.0f) << "Expected Output: 0.0f";
}
};
#if AZ_TRAIT_DISABLE_FAILED_EMOTION_FX_TESTS
TEST_P(BlendTreeFloatMath1NodeFixture, DISABLED_FloatInput_OutputsCorrectFloatTest)
#else
TEST_P(BlendTreeFloatMath1NodeFixture, FloatInput_OutputsCorrectFloatTest)
#endif // AZ_TRAIT_DISABLE_FAILED_EMOTION_FX_TESTS
{
TestInput<MCore::AttributeFloat, float>("FloatParam", m_param.m_xInputFloat);
};
#if AZ_TRAIT_DISABLE_FAILED_EMOTION_FX_TESTS
TEST_P(BlendTreeFloatMath1NodeFixture, DISABLED_IntInput_OutputsCorrectFloatTest)
#else
TEST_P(BlendTreeFloatMath1NodeFixture, IntInput_OutputsCorrectFloatTest)
#endif // AZ_TRAIT_DISABLE_FAILED_EMOTION_FX_TESTS
{
TestInput<MCore::AttributeInt32, int>("IntParam", m_param.m_xInputInt);
};
TEST_P(BlendTreeFloatMath1NodeFixture, BoolInput_OutputsCorrectFloatTest)
{
TestInput<MCore::AttributeBool, bool>("BoolParam", m_param.m_xInputBool);
};
INSTANTIATE_TEST_CASE_P(BlendTreeFloatMath1Node_ValidOutputTests,
BlendTreeFloatMath1NodeFixture,
::testing::ValuesIn(blendTreeFloatMath1NodeTestData)
);
} // end namespace EMotionFX
| 43.190601 | 139 | 0.589711 | [
"vector",
"3d"
] |
3ecf513b0a470a14a16975cfd860cbada5ef3257 | 1,747 | cpp | C++ | Free_And_Delete_Kernel/Free_Delete.cpp | M0rtale/KernelDel | 3b960ccbcf71bf4372b5003257ee44f3c9e65892 | [
"MIT"
] | 12 | 2020-11-11T23:45:41.000Z | 2022-03-01T03:47:27.000Z | Free_And_Delete_Kernel/Free_Delete.cpp | c3358/KernelDel | 3b960ccbcf71bf4372b5003257ee44f3c9e65892 | [
"MIT"
] | null | null | null | Free_And_Delete_Kernel/Free_Delete.cpp | c3358/KernelDel | 3b960ccbcf71bf4372b5003257ee44f3c9e65892 | [
"MIT"
] | 6 | 2019-05-16T13:52:15.000Z | 2022-01-21T01:14:44.000Z | #include "Free_Delete.h"
bool Free_Delete::Delete_Model(wchar_t *Path)
{
HANDLE hFile;
UNICODE_STRING uPath;
OBJECT_ATTRIBUTES oaFileObject;
IO_STATUS_BLOCK ioBlock;
DEVICE_OBJECT *device = 0;
PEPROCESS peProc = PsGetCurrentProcess();
//R3 Context
KeAttachProcess(peProc);
RtlInitUnicodeString(&uPath, Path); // copy path to a unicode string
InitializeObjectAttributes(&oaFileObject, &uPath, OBJ_CASE_INSENSITIVE, 0, 0);
NTSTATUS result = IoCreateFileSpecifyDeviceObjectHint(
&hFile,
SYNCHRONIZE | FILE_WRITE_ATTRIBUTES | FILE_READ_ATTRIBUTES | FILE_READ_DATA,
&oaFileObject,
&ioBlock,
0,
0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN,
FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_ALERT,
0,
0,
CreateFileTypeNone,
0,
IO_IGNORE_SHARE_ACCESS_CHECK,
device
);
if (!NT_SUCCESS(result))
{
DbgPrintEx(0, 0, "\nIoCreateFileSpecifyDeviceObjectHint Failed...");
ZwClose(hFile);
KeDetachProcess();
return false;
}
PVOID object = 0;
result = ObReferenceObjectByHandle(hFile, 0, 0, 0, &object, 0);
if (!NT_SUCCESS(result))
{
DbgPrintEx(0, 0, "\nObReferenceObjectByHandle Failed...");
ZwClose(hFile);
KeDetachProcess();
return false;
}
//CopyPasta
((FILE_OBJECT*)object)->SectionObjectPointer->ImageSectionObject = 0;
((FILE_OBJECT*)object)->DeleteAccess = 1; // Remove all access, might give access denied for higher altitude
result = ZwDeleteFile(&oaFileObject);
ObDereferenceObject(object);
ZwClose(hFile);
if (!NT_SUCCESS(result))
{
DbgPrintEx(0, 0, "\nZwDeleteFile Failed...");
ZwClose(hFile);
KeDetachProcess();
return false;
}
result = ZwDeleteFile(&oaFileObject);
if (NT_SUCCESS(result))
{
KeDetachProcess();
return true;
}
} | 22.986842 | 109 | 0.734974 | [
"object"
] |
3ed06b7e02ea411f6177da7b3d2dc6f55482c17b | 9,766 | hpp | C++ | autodiff/forward/utils/derivative.hpp | ruelj2/autodiff | 2c241bec04d3924fdd42a342165d0cc168a843c6 | [
"MIT"
] | null | null | null | autodiff/forward/utils/derivative.hpp | ruelj2/autodiff | 2c241bec04d3924fdd42a342165d0cc168a843c6 | [
"MIT"
] | null | null | null | autodiff/forward/utils/derivative.hpp | ruelj2/autodiff | 2c241bec04d3924fdd42a342165d0cc168a843c6 | [
"MIT"
] | null | null | null | // _ _
// _ _|_ _ _|o_|__|_
// (_||_||_(_)(_|| | |
//
// automatic differentiation made easier in C++
// https://github.com/autodiff/autodiff
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2018-2020 Allan Leal
//
// 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.
// C++ includes
#include <cassert>
#include <cstddef>
// autodiff includes
#include <autodiff/common/meta.hpp>
#include <autodiff/common/vectortraits.hpp>
#pragma once
namespace autodiff {
namespace detail {
template<typename... Args>
struct At
{
std::tuple<Args...> args;
};
template<typename... Args>
struct Wrt
{
std::tuple<Args...> args;
};
template<typename... Args>
struct Along
{
std::tuple<Args...> args;
};
/// The keyword used to denote the variables *with respect to* the derivative is calculated.
template<typename... Args>
auto wrt(Args&&... args)
{
return Wrt<Args&&...>{ std::forward_as_tuple(std::forward<Args>(args)...) };
}
/// The keyword used to denote the variables *at* which the derivatives are calculated.
template<typename... Args>
auto at(Args&&... args)
{
return At<Args&&...>{ std::forward_as_tuple(std::forward<Args>(args)...) };
}
/// The keyword used to denote the direction vector *along* which the derivatives are calculated.
template<typename... Args>
auto along(Args&&... args)
{
return Along<Args&&...>{ std::forward_as_tuple(std::forward<Args>(args)...) };
}
/// Seed each dual number in the **wrt** list using its position as the derivative order to be seeded.
/// Using `seed(wrt(x, y, z), 1)` will set the 1st order derivative of `x`, the
/// 2nd order derivative of `y`, and the 3rd order derivative of `z` to 1. If
/// these dual numbers have order greater than 3, then the last dual number will
/// be used for the remaining higher-order derivatives. For example, if these
/// numbers are 5th order, than the 4th and 5th order derivatives of `z` will be
/// set to 1 as well. In this example, `wrt(x, y, z)` is equivalent to `wrt(x,
/// y, z, z, z)`. This automatic seeding permits derivatives `fx`, `fxy`,
/// `fxyz`, `fxyzz`, and `fxyzzz` to be computed in a more convenient way.
template<typename Var, typename... Vars, typename T>
auto seed(const Wrt<Var&, Vars&...>& wrt, T&& seedval)
{
constexpr static auto N = Order<Var>;
constexpr static auto size = 1 + sizeof...(Vars);
static_assert(size <= N, "It is not possible to compute higher-order derivatives with order greater than that of the autodiff number (e.g., using wrt(x, x, y, z) will fail if the autodiff numbers in use have order below 4).");
For<N>([&](auto i) constexpr {
if constexpr (i.index < size)
seed<i.index + 1>(std::get<i>(wrt.args), seedval);
else
seed<i.index + 1>(std::get<size - 1>(wrt.args), seedval); // use the last variable in the wrt list as the variable for which the remaining higher-order derivatives are calculated (e.g., derivatives(f, wrt(x), at(x)) will produce [f0, fx, fxx, fxxx, fxxxx] when x is a 4th order dual number).
});
}
template<typename... Vars>
auto seed(const Wrt<Vars...>& wrt)
{
seed(wrt, 1.0);
}
template<typename... Vars>
auto unseed(const Wrt<Vars...>& wrt)
{
seed(wrt, 0.0);
}
template<typename... Args, typename... Vecs>
auto seed(const At<Args...>& at, const Along<Vecs...>& along)
{
static_assert(sizeof...(Args) == sizeof...(Vecs));
ForEach(at.args, along.args, [&](auto& arg, auto&& dir) constexpr {
if constexpr (isVector<decltype(arg)>) {
static_assert(isVector<decltype(dir)>);
assert(arg.size() == dir.size());
for(auto i = 0; i < dir.size(); ++i)
seed<1>(arg[i], dir[i]);
}
else seed<1>(arg, dir);
});
}
template<typename... Args>
auto unseed(const At<Args...>& at)
{
ForEach(at.args, [&](auto& arg) constexpr {
if constexpr (isVector<decltype(arg)>) {
for(auto i = 0; i < arg.size(); ++i)
seed<1>(arg[i], 0.0);
}
else seed<1>(arg, 0.0);
});
}
template<size_t order = 1, typename T, EnableIf<Order<T>>...>
auto seed(T& x)
{
seed<order>(x, 1.0);
}
template<size_t order = 1, typename T, EnableIf<Order<T>>...>
auto unseed(T& x)
{
seed<order>(x, 0.0);
}
template<typename Fun, typename... Args, typename... Vars>
auto eval(const Fun& f, const At<Args...>& at, const Wrt<Vars...>& wrt)
{
seed(wrt);
auto u = std::apply(f, at.args);
unseed(wrt);
return u;
}
template<typename Fun, typename... Args, typename... Vecs>
auto eval(const Fun& f, const At<Args...>& at, const Along<Vecs...>& along)
{
seed(at, along);
auto u = std::apply(f, at.args);
unseed(at);
return u;
}
/// Extract the derivative of given order from a vector of dual/real numbers.
template<size_t order = 1, typename Vec, EnableIf<isVector<Vec>>...>
auto derivative(const Vec& u)
{
size_t len = u.size(); // the length of the vector containing dual/real numbers
using NumType = decltype(u[0]); // get the type of the dual/real number
using T = NumericType<NumType>; // get the numeric/floating point type of the dual/real number
using Res = VectorReplaceValueType<Vec, T>; // get the type of the vector containing numeric values instead of dual/real numbers (e.g., vector<real> becomes vector<double>, VectorXdual becomes VectorXd, etc.)
Res res(len); // create an array to store the derivatives stored inside the dual/real number
for(auto i = 0; i < len; ++i)
res[i] = derivative<order>(u[i]); // get the derivative of given order from i-th dual/real number
return res;
}
/// Alias method to `derivative<order>(x)` where `x` is either a dual/real number or vector/array of such numbers.
template<size_t order = 1, typename T>
auto grad(const T& x)
{
return derivative<order>(x);
}
/// Unpack the derivatives from the result of an @ref eval call into an array.
template<typename Result>
auto derivatives(const Result& result)
{
if constexpr (isVector<Result>) // check if the argument is a vector container of dual/real numbers
{
size_t len = result.size(); // the length of the vector containing dual/real numbers
using NumType = decltype(result[0]); // get the type of the dual/real number
using T = NumericType<NumType>; // get the numeric/floating point type of the dual/real number
using Vec = VectorReplaceValueType<Result, T>; // get the type of the vector containing numeric values instead of dual/real numbers (e.g., vector<real> becomes vector<double>, VectorXdual becomes VectorXd, etc.)
constexpr auto N = Order<NumType>; // the order of the dual/real number
std::array<Vec, N + 1> values; // create an array to store the derivatives stored inside the dual/real number
For<N + 1>([&](auto i) constexpr {
values[i].resize(len);
for(auto j = 0; j < len; ++j)
values[i][j] = derivative<i>(result[j]); // get the ith derivative of the jth dual/real number
});
return values;
}
else // result is then just a dual/real number
{
using T = NumericType<Result>; // get the numeric/floating point type of the dual/real result number
constexpr auto N = Order<Result>; // the order of the dual/real result number
std::array<T, N + 1> values; // create an array to store the derivatives stored inside the dual/real number
For<N + 1>([&](auto i) constexpr {
values[i] = derivative<i>(result);
});
return values;
}
}
template<typename Fun, typename... Vars, typename... Args>
auto derivatives(const Fun& f, const Wrt<Vars...>& wrt, const At<Args...>& at)
{
return derivatives(eval(f, at, wrt));
}
template<size_t order=1, typename Fun, typename... Vars, typename... Args, typename Result>
auto derivative(const Fun& f, const Wrt<Vars...>& wrt, const At<Args...>& at, Result& u)
{
u = derivatives(f, wrt, at);
return derivative<order>(u);
}
template<size_t order=1, typename Fun, typename... Vars, typename... Args>
auto derivative(const Fun& f, const Wrt<Vars...>& wrt, const At<Args...>& at)
{
auto u = eval(f, at, wrt);
return derivative<order>(u);
}
template<typename Fun, typename... Vecs, typename... Args>
auto derivatives(const Fun& f, const Along<Vecs...>& along, const At<Args...>& at)
{
return derivatives(eval(f, at, along));
}
} // namespace detail
using detail::derivatives;
using detail::derivative;
using detail::grad;
using detail::along;
using detail::wrt;
using detail::at;
using detail::seed;
using detail::unseed;
using detail::Along;
using detail::At;
using detail::Wrt;
} // namespace autodiff
| 36.304833 | 303 | 0.661786 | [
"vector"
] |
a796b71017bb7fb7e384e190c81a389079632f3c | 990 | hpp | C++ | libs/core/include/fcppt/math/from_array.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | libs/core/include/fcppt/math/from_array.hpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | libs/core/include/fcppt/math/from_array.hpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#define FCPPT_MATH_FROM_ARRAY_HPP_INCLUDED
#include <fcppt/math/to_array_type.hpp>
#include <fcppt/config/external_begin.hpp>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace fcppt::math
{
/**
\brief Constructs an object with static storage from an array rvalue
\ingroup fcpptmath
*/
template <typename Type>
inline Type from_array(fcppt::math::to_array_type<Type> &&_value)
{
return Type{typename Type::storage_type{std::move(_value)}};
}
/**
\brief Constructs an object with static storage from an array lvalue
\ingroup fcpptmath
*/
template <typename Type>
inline Type from_array(fcppt::math::to_array_type<Type> const &_value)
{
return Type{typename Type::storage_type{_value}};
}
}
#endif
| 24.146341 | 70 | 0.755556 | [
"object"
] |
a796d0305c371306fe3faf59c706170f1f870fad | 6,528 | cpp | C++ | src/kits/debug/DebugLooper.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | 3 | 2018-05-21T15:32:32.000Z | 2019-03-21T13:34:55.000Z | src/kits/debug/DebugLooper.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | src/kits/debug/DebugLooper.cpp | stasinek/BHAPI | 5d9aa61665ae2cc5c6e34415957d49a769325b2b | [
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
* Copyright 2010, Ingo Weinhold, ingo_weinhold@gmx.de.
* Distributed under the terms of the MIT License.
*/
#include <DebugLooper.h>
#include <new>
#include <AutoLocker.h>
#include <DebugMessageHandler.h>
#include <TeamDebugger.h>
#include <util/DoublyLinkedList.h>
struct BDebugLooper::Debugger {
BTeamDebugger* debugger;
BDebugMessageHandler* handler;
Debugger(BTeamDebugger* debugger, BDebugMessageHandler* handler)
:
debugger(debugger),
handler(handler)
{
}
};
struct BDebugLooper::Job : DoublyLinkedListLinkImpl<Job> {
Job()
:
fDoneSemaphore(-1)
{
}
virtual ~Job()
{
}
status_t Wait(BLocker& lock)
{
fDoneSemaphore = create_sem(0, "debug looper job");
lock.Unlock();
while (acquire_sem(fDoneSemaphore) == B_INTERRUPTED) {
}
lock.Lock();
delete_sem(fDoneSemaphore);
fDoneSemaphore = -1;
return fResult;
}
void Done(status_t result)
{
fResult = result;
release_sem(fDoneSemaphore);
}
virtual status_t Do(BDebugLooper* looper) = 0;
protected:
sem_id fDoneSemaphore;
status_t fResult;
};
struct BDebugLooper::JobList : DoublyLinkedList<Job> {
};
struct BDebugLooper::AddDebuggerJob : Job {
AddDebuggerJob(BTeamDebugger* debugger,
BDebugMessageHandler* handler)
:
fDebugger(debugger),
fHandler(handler)
{
}
virtual status_t Do(BDebugLooper* looper)
{
Debugger* debugger = new(std::nothrow) Debugger(fDebugger, fHandler);
if (debugger == NULL || !looper->fDebuggers.AddItem(debugger)) {
delete debugger;
return B_NO_MEMORY;
}
return B_OK;
}
private:
BTeamDebugger* fDebugger;
BDebugMessageHandler* fHandler;
};
struct BDebugLooper::RemoveDebuggerJob : Job {
RemoveDebuggerJob(team_id team)
:
fTeam(team)
{
}
virtual status_t Do(BDebugLooper* looper)
{
for (int32 i = 0; Debugger* debugger = looper->fDebuggers.ItemAt(i);
i++) {
if (debugger->debugger->Team() == fTeam) {
delete looper->fDebuggers.RemoveItemAt(i);
return B_OK;
}
}
return B_ENTRY_NOT_FOUND;
}
private:
team_id fTeam;
};
// #pragma mark -
BDebugLooper::BDebugLooper()
:
fLock("debug looper"),
fThread(-1),
fOwnsThread(false),
fTerminating(false),
fNotified(false),
fJobs(NULL),
fEventSemaphore(-1)
{
}
BDebugLooper::~BDebugLooper()
{
}
status_t BDebugLooper::Init()
{
status_t error = fLock.InitCheck();
if (error != B_OK)
return error;
AutoLocker<BLocker> locker(fLock);
if (fThread >= 0)
return B_BAD_VALUE;
if (fJobs == NULL) {
fJobs = new(std::nothrow) JobList;
if (fJobs == NULL)
return B_NO_MEMORY;
}
if (fEventSemaphore < 0) {
fEventSemaphore = create_sem(0, "debug looper event");
if (fEventSemaphore < 0)
return fEventSemaphore;
}
return B_OK;
}
thread_id
BDebugLooper::Run(bool spawnThread)
{
AutoLocker<BLocker> locker(fLock);
if (fThread >= 0)
return B_BAD_VALUE;
fNotified = false;
if (spawnThread) {
fThread = spawn_thread(&_MessageLoopEntry, "debug looper",
B_NORMAL_PRIORITY, this);
if (fThread < 0)
return fThread;
fOwnsThread = true;
resume_thread(fThread);
return B_OK;
}
fThread = find_thread(NULL);
fOwnsThread = false;
_MessageLoop();
return B_OK;
}
void BDebugLooper::Quit()
{
AutoLocker<BLocker> locker(fLock);
fTerminating = true;
_Notify();
}
status_t BDebugLooper::AddTeamDebugger(BTeamDebugger* debugger,
BDebugMessageHandler* handler)
{
if (debugger == NULL || handler == NULL)
return B_BAD_VALUE;
AddDebuggerJob job(debugger, handler);
return _DoJob(&job);
}
bool BDebugLooper::RemoveTeamDebugger(BTeamDebugger* debugger)
{
if (debugger == NULL)
return false;
RemoveDebuggerJob job(debugger->Team());
return _DoJob(&job) == B_OK;
}
bool BDebugLooper::RemoveTeamDebugger(team_id team)
{
if (team < 0)
return false;
RemoveDebuggerJob job(team);
return _DoJob(&job) == B_OK;
}
/*static*/ status_t BDebugLooper::_MessageLoopEntry(void* data)
{
return ((BDebugLooper*)data)->_MessageLoop();
}
status_t BDebugLooper::_MessageLoop()
{
while (true) {
// prepare the wait info array
int32 debuggerCount = fDebuggers.CountItems();
object_wait_info waitInfos[debuggerCount + 1];
for (int32 i = 0; i < debuggerCount; i++) {
waitInfos[i].object
= fDebuggers.ItemAt(i)->debugger->DebuggerPort();
waitInfos[i].type = B_OBJECT_TYPE_PORT;
waitInfos[i].events = B_EVENT_READ;
}
waitInfos[debuggerCount].object = fEventSemaphore;
waitInfos[debuggerCount].type = B_OBJECT_TYPE_SEMAPHORE;
waitInfos[debuggerCount].events = B_EVENT_ACQUIRE_SEMAPHORE;
// wait for the next event
wait_for_objects(waitInfos, debuggerCount + 1);
AutoLocker<BLocker> locker(fLock);
// handle all pending jobs
bool handledJobs = fJobs->Head() != NULL;
while (Job* job = fJobs->RemoveHead())
job->Done(job->Do(this));
// acquire notification semaphore and mark unnotified
if ((waitInfos[debuggerCount].events & B_EVENT_ACQUIRE_SEMAPHORE) != 0)
acquire_sem(fEventSemaphore);
fNotified = false;
if (fTerminating)
return B_OK;
// Always loop when jobs were executed, since that might add/remove
// debuggers.
if (handledJobs)
continue;
// read a pending port message
for (int32 i = 0; i < debuggerCount; i++) {
if ((waitInfos[i].events & B_EVENT_READ) != 0) {
Debugger* debugger = fDebuggers.ItemAt(i);
// read the message
debug_debugger_message_data message;
int32 code;
ssize_t messageSize = read_port(
debugger->debugger->DebuggerPort(), &code, &message,
sizeof(message));
if (messageSize < 0)
continue;
// handle the message
bool continueThread = debugger->handler->HandleDebugMessage(
code, message);
// If requested, tell the thread to continue (only when there
// is a thread and the message was synchronous).
if (continueThread && message.origin.thread >= 0
&& message.origin.nub_port >= 0) {
debugger->debugger->ContinueThread(message.origin.thread);
}
// Handle only one message -- the hook might have added/removed
// debuggers which makes further iteration problematic.
break;
}
}
}
}
status_t BDebugLooper::_DoJob(Job* job)
{
AutoLocker<BLocker> locker(fLock);
// execute directly, if in looper thread or not running yet
if (fThread < 0 || fThread == find_thread(NULL))
return job->Do(this);
// execute in the looper thread
fJobs->Add(job);
_Notify();
return job->Wait(fLock);
}
void BDebugLooper::_Notify()
{
if (fNotified)
return;
fNotified = true;
release_sem(fEventSemaphore);
}
| 18.651429 | 73 | 0.696691 | [
"object"
] |
a7978b4d3c15f25bed5f8285bfc84b0b40cb0172 | 3,522 | hpp | C++ | testing/utils/order_of_accuracy.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 3 | 2022-01-25T19:31:17.000Z | 2022-01-25T21:10:39.000Z | testing/utils/order_of_accuracy.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 20 | 2021-12-17T14:58:00.000Z | 2022-02-05T21:25:35.000Z | testing/utils/order_of_accuracy.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <cmath>
#include <fstream>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include <iomanip>
#include "typedefs.hpp"
inline double errorRateByNdof(double ndof0, double ndof1, double e0, double e1)
{
return -log10(e1 / e0) / log10(ndof1 / ndof0);
}
class OrderOfAccuracy
{
public:
using dpair = std::pair<double, double>;
void addSolutionError(std::size_t order, double ndof, double error)
{
solutions_[order].push_back(std::make_pair(ndof, error));
std::sort(
solutions_[order].begin(), solutions_[order].end(), [](const dpair& p0, const dpair& p1) {
return p0.first < p1.first;
});
}
std::map<std::size_t, std::vector<double>> getConvergenceRate() const
{
std::map<std::size_t, std::vector<double>> rate;
for (const auto& kv : solutions_) {
rate[kv.first].push_back(0);
for (std::size_t i = 0; i < kv.second.size() - 1; ++i) {
rate[kv.first].push_back(
errorRateByNdof(
kv.second[i].first,
kv.second[i + 1].first,
kv.second[i].second,
kv.second[i + 1].second));
}
}
return rate;
}
const std::map<std::size_t, std::vector<dpair>>& get() const { return solutions_; }
real_t getMinimumError() const
{
real_t err = std::numeric_limits<real_t>::max();
for (const auto& kv : solutions_) {
for (std::size_t i = 0; i < kv.second.size(); ++i) {
err = std::min(err, kv.second[i].second);
}
}
return err;
}
void writeToFiles(const std::string& prefix)
{
for (const auto& kv : solutions_) {
const std::string filename = prefix + "_N" + std::to_string(kv.first) + ".dat";
std::ofstream fout;
fout.open(filename);
for (std::size_t i = 0; i < kv.second.size(); ++i) {
fout << std::scientific << std::setprecision(6) << kv.second[i].first << " "
<< kv.second[i].second << "\n";
}
fout.close();
}
}
private:
std::map<std::size_t, std::vector<dpair>> solutions_;
friend std::ostream& operator<<(std::ostream&, const OrderOfAccuracy&);
};
inline std::ostream& operator<<(std::ostream& os, const OrderOfAccuracy& accuracy)
{
os << std::setw(11) << "P-Order" << std::setw(11) << "nDOFs" << std::setw(11) << "error"
<< std::setw(11) << "order\n";
os << std::string(44, '-') << "\n";
for (const auto& kv : accuracy.solutions_) {
// std::sort(kv.second.begin(), kv.second.end(),
// [](const dpair& p0, const dpair& p1){return p0.first < p1.first;});
for (std::size_t i = 0; i < kv.second.size(); ++i) {
if (i == 0) {
os << std::setw(11) << kv.first;
os << std::scientific << std::setprecision(3) << std::setw(11) << kv.second[i].first;
os << std::scientific << std::setprecision(3) << std::setw(11) << kv.second[i].second
<< "\n";
} else {
double err = errorRateByNdof(
kv.second[i - 1].first,
kv.second[i].first,
kv.second[i - 1].second,
kv.second[i].second);
os << std::setw(11) << kv.first;
os << std::scientific << std::setprecision(3) << std::setw(11) << kv.second[i].first;
os << std::scientific << std::setprecision(3) << std::setw(11) << kv.second[i].second;
os << std::defaultfloat << std::setw(11) << err << "\n";
}
}
os << std::string(44, '-') << "\n";
}
return os;
}
| 28.176 | 98 | 0.555934 | [
"vector"
] |
a79d62273acb87d8a8b1cda51cbe4cd7468469b3 | 8,341 | cpp | C++ | ze_vi_simulation/src/camera_simulator.cpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 30 | 2016-09-27T07:41:28.000Z | 2021-12-03T20:44:28.000Z | ze_vi_simulation/src/camera_simulator.cpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 1 | 2018-12-18T15:53:06.000Z | 2018-12-21T03:10:06.000Z | ze_vi_simulation/src/camera_simulator.cpp | rockenbf/ze_oss | ee04158e2d51acb07a267196f618e9afbc3ffd83 | [
"BSD-3-Clause"
] | 12 | 2016-11-05T07:51:29.000Z | 2020-07-13T02:26:08.000Z | // Copyright (c) 2015-2016, ETH Zurich, Wyss Zurich, Zurich Eye
// 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 ETH Zurich, Wyss Zurich, Zurich Eye 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 <ze/vi_simulation/camera_simulator.hpp>
#include <ze/cameras/camera_rig.hpp>
#include <ze/cameras/camera_utils.hpp>
#include <ze/common/random_matrix.hpp>
#include <ze/vi_simulation/trajectory_simulator.hpp>
#include <ze/visualization/viz_interface.hpp>
namespace ze {
// -----------------------------------------------------------------------------
void CameraSimulator::initializeMap()
{
uint32_t num_frames = options_.max_num_landmarks_
/ options_.num_keypoints_per_frame;
real_t time = trajectory_->start();
real_t dt = (trajectory_->end() - time) / num_frames;
int num_landmarks_per_frame = options_.num_keypoints_per_frame / rig_->size();
uint32_t num_landmarks = 0u;
landmarks_W_.resize(Eigen::NoChange, options_.max_num_landmarks_);
for (uint32_t i = 0u; i < num_frames; ++i)
{
Transformation T_W_B = trajectory_->T_W_B(time);
for (uint32_t cam_idx = 0u; cam_idx < rig_->size(); ++cam_idx)
{
// Check how many landmarks are already visible:
CameraMeasurements measurements = visibleLandmarks(cam_idx, T_W_B, 0u, num_landmarks);
int num_visible = measurements.keypoints_.cols();
if (num_visible >= num_landmarks_per_frame)
{
continue;
}
// Initialize new random visible landmarks.
int32_t num_new_landmarks = std::max(0, num_landmarks_per_frame - num_visible);
CHECK_GE(num_new_landmarks, 0);
Positions p_C;
std::tie(std::ignore, std::ignore, p_C) =
generateRandomVisible3dPoints(
rig_->at(cam_idx), num_new_landmarks,
10u, options_.min_depth_m, options_.max_depth_m);
DEBUG_CHECK_LE(static_cast<int>(num_landmarks + num_new_landmarks),
landmarks_W_.cols());
landmarks_W_.middleCols(num_landmarks, num_new_landmarks)
= (T_W_B * rig_->T_B_C(cam_idx)).transformVectorized(p_C);
num_landmarks += num_new_landmarks;
}
time += dt;
}
VLOG(1) << "Initialized map with " << num_landmarks << " visible landmarks.";
landmarks_W_.conservativeResize(Eigen::NoChange, num_landmarks);
}
// -----------------------------------------------------------------------------
CameraMeasurements CameraSimulator::visibleLandmarks(
const uint32_t cam_idx,
const Transformation& T_W_B,
const uint32_t lm_min_idx,
const uint32_t lm_max_idx)
{
auto t = timer_[SimTimer::visible_landmarks].timeScope();
const uint32_t num_landmarks = lm_max_idx - lm_min_idx;
if (num_landmarks == 0)
{
return CameraMeasurements();
}
const Size2u image_size = rig_->at(cam_idx).size();
const auto lm_W = landmarks_W_.middleCols(lm_min_idx, num_landmarks);
const auto lm_C = (T_W_B * rig_->T_B_C(cam_idx)).inverse().transformVectorized(lm_W);
Keypoints px = rig_->at(cam_idx).projectVectorized(lm_C);
std::vector<uint32_t> visible_indices;
for (uint32_t i = 0u; i < num_landmarks; ++i)
{
if (lm_C(2,i) < options_.min_depth_m ||
lm_C(2,i) > options_.max_depth_m)
{
// Landmark is either behind or too far from the camera.
continue;
}
if (isVisible(image_size, px.col(i)))
{
visible_indices.push_back(i);
}
}
// Copy visible indices into Camera Measurements struct:
CameraMeasurements m;
m.keypoints_.resize(Eigen::NoChange, visible_indices.size());
m.global_landmark_ids_.resize(visible_indices.size());
for (size_t i = 0; i < visible_indices.size(); ++i)
{
m.keypoints_.col(i) = px.col(visible_indices[i]);
m.global_landmark_ids_[i] = visible_indices[i];
}
return m;
}
// -----------------------------------------------------------------------------
CameraMeasurementsVector CameraSimulator::getMeasurements(real_t time)
{
CHECK_GT(landmarks_W_.cols(), 0) << "Map has not been initialized.";
CHECK_GE(time, trajectory_->start());
CHECK_LT(time, trajectory_->end());
auto t = timer_[SimTimer::get_measurements].timeScope();
Transformation T_W_B = trajectory_->T_W_B(time);
std::unordered_map<int32_t, int32_t> new_global_lm_id_to_track_id_map;
CameraMeasurementsVector measurements;
for (uint32_t cam_idx = 0u; cam_idx < rig_->size(); ++cam_idx)
{
CameraMeasurements m = visibleLandmarks(cam_idx, T_W_B, 0u, landmarks_W_.cols());
m.local_track_ids_.resize(m.keypoints_.cols());
for (int32_t i = 0; i < m.keypoints_.cols(); ++i)
{
const int32_t lm_id = m.global_landmark_ids_[i];
int32_t track_id = -1;
auto res = global_lm_id_to_track_id_map_.find(lm_id);
if (res == global_lm_id_to_track_id_map_.end())
{
// This is a new track:
track_id = track_id_counter_;
++track_id_counter_;
}
else
{
// This is an existing track:
track_id = res->second;
}
m.local_track_ids_[i] = track_id;
// Update our list of tracks:
new_global_lm_id_to_track_id_map[lm_id] = track_id;
}
measurements.push_back(m);
}
// Update our list of active tracks:
global_lm_id_to_track_id_map_ = new_global_lm_id_to_track_id_map;
return measurements;
}
// -----------------------------------------------------------------------------
CameraMeasurementsVector CameraSimulator::getMeasurementsCorrupted(real_t time)
{
CameraMeasurementsVector measurements = getMeasurements(time);
for (CameraMeasurements& m : measurements)
{
m.keypoints_ += randomMatrixNormalDistributed(2, m.keypoints_.cols(), false,
0.0, options_.keypoint_noise_sigma);
}
return measurements;
}
// -----------------------------------------------------------------------------
void CameraSimulator::reset()
{
global_lm_id_to_track_id_map_.clear();
}
// -----------------------------------------------------------------------------
void CameraSimulator::setVisualizer(const std::shared_ptr<Visualizer>& visualizer)
{
viz_ = visualizer;
}
// -----------------------------------------------------------------------------
void CameraSimulator::visualize(
real_t dt,
real_t marker_size_trajectory,
real_t marker_size_landmarks)
{
CHECK_GT(landmarks_W_.cols(), 0) << "Map has not been initialized.";
CHECK(viz_) << "No visualizer has been registered.";
std::vector<Position> trajectory;
for (real_t time = trajectory_->start(), time_end = trajectory_->end();
time < time_end; time += dt)
{
trajectory.push_back(trajectory_->T_W_B(time).getPosition());
}
viz_->drawTrajectory("simulation_trajectory", 0, trajectory, Colors::Green, marker_size_trajectory);
viz_->drawPoints("simulated_map", 0u, landmarks_W_, Colors::Orange, marker_size_landmarks);
}
} // namespace ze
| 37.236607 | 102 | 0.660113 | [
"vector"
] |
a7a1bb4723a4be573f94786627eca48af3ec4be9 | 9,064 | cpp | C++ | dev/Code/CryEngine/Cry3DEngine/CloudRenderNode.cpp | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | 5 | 2018-08-17T21:05:55.000Z | 2021-04-17T10:48:26.000Z | dev/Code/CryEngine/Cry3DEngine/CloudRenderNode.cpp | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | null | null | null | dev/Code/CryEngine/Cry3DEngine/CloudRenderNode.cpp | horvay/lumberyardtutor | 63b0681a7ed2a98d651b699984de92951721353e | [
"AML"
] | 5 | 2017-12-05T16:36:00.000Z | 2021-04-27T06:33:54.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "StdAfx.h"
#include "CloudRenderNode.h"
#include "CloudsManager.h"
#include "VisAreas.h"
#include "ObjMan.h"
//////////////////////////////////////////////////////////////////////////
CCloudRenderNode::CCloudRenderNode()
{
m_bounds.min = Vec3(-1, -1, -1);
m_bounds.max = Vec3(1, 1, 1);
m_fScale = 1.0f;
m_offsetedMatrix.SetIdentity();
m_matrix.SetIdentity();
m_vOffset.Set(0, 0, 0);
m_alpha = 1.f;
m_pCloudRenderElement = (CREBaseCloud*)GetRenderer()->EF_CreateRE(eDATA_Cloud);
m_pREImposter = (CREImposter*) GetRenderer()->EF_CreateRE(eDATA_Imposter);
GetCloudsManager()->AddCloudRenderNode(this);
m_origin = Vec3(0, 0, 0);
m_moveProps.m_autoMove = false;
m_moveProps.m_speed = Vec3(0, 0, 0);
m_moveProps.m_spaceLoopBox = Vec3(2000.0f, 2000.0f, 2000.0f);
m_moveProps.m_fadeDistance = 0;
}
//////////////////////////////////////////////////////////////////////////
CCloudRenderNode::~CCloudRenderNode()
{
GetCloudsManager()->RemoveCloudRenderNode(this);
m_pCloudRenderElement->Release(false);
m_pREImposter->Release(false);
Get3DEngine()->FreeRenderNodeState(this);
}
//////////////////////////////////////////////////////////////////////////
bool CCloudRenderNode::LoadCloudFromXml(XmlNodeRef root)
{
m_pCloudDesc = new SCloudDescription;
GetCloudsManager()->ParseCloudFromXml(root, m_pCloudDesc);
SetCloudDesc(m_pCloudDesc);
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CCloudRenderNode::LoadCloud(const char* sCloudFilename)
{
m_bounds.min = Vec3(-1, -1, -1);
m_bounds.max = Vec3(1, 1, 1);
SetCloudDesc(GetCloudsManager()->LoadCloud(sCloudFilename));
return m_pCloudDesc != 0;
}
//////////////////////////////////////////////////////////////////////////
void CCloudRenderNode::SetMovementProperties(const SCloudMovementProperties& properties)
{
m_moveProps = properties;
}
//////////////////////////////////////////////////////////////////////////
void CCloudRenderNode::SetCloudDesc(SCloudDescription* pCloud)
{
m_pCloudDesc = pCloud;
if (m_pCloudDesc != NULL && m_pCloudDesc->m_particles.size() > 0)
{
m_vOffset = m_pCloudDesc->m_offset;
m_bounds.min = m_pCloudDesc->m_bounds.min - m_pCloudDesc->m_offset;
m_bounds.max = m_pCloudDesc->m_bounds.max - m_pCloudDesc->m_offset;
if (m_pCloudDesc->m_pMaterial)
{
m_pMaterial = m_pCloudDesc->m_pMaterial;
}
m_pCloudRenderElement->SetParticles(&m_pCloudDesc->m_particles[0], m_pCloudDesc->m_particles.size());
m_WSBBox.SetTransformedAABB(m_matrix, m_bounds);
m_fScale = m_matrix.GetColumn(0).GetLength();
// Offset matrix by the cloud bounds offset.
m_offsetedMatrix = m_matrix * Matrix34::CreateTranslationMat(-m_vOffset);
}
}
//////////////////////////////////////////////////////////////////////////
void CCloudRenderNode::SetMatrix(const Matrix34& mat)
{
SetMatrixInternal(mat, true);
}
//////////////////////////////////////////////////////////////////////////
void CCloudRenderNode::SetMatrixInternal(const Matrix34& mat, bool updateOrigin)
{
m_dwRndFlags |= ERF_OUTDOORONLY;
if (updateOrigin)
{
m_origin = mat.GetTranslation();
}
m_matrix = mat;
m_pos = mat.GetTranslation();
// m_WSBBox.SetTransformedAABB( m_matrix,m_bounds );
m_fScale = mat.GetColumn(0).GetLength();
m_WSBBox.SetTransformedAABB(Matrix34::CreateTranslationMat(m_pos), AABB(m_bounds.min * m_fScale, m_bounds.max * m_fScale));
// Offset matrix by the cloud bounds offset.
// m_offsetedMatrix = m_matrix * Matrix34::CreateTranslationMat(-m_vOffset);
m_offsetedMatrix = Matrix34::CreateTranslationMat(m_pos - m_vOffset * m_fScale);
m_offsetedMatrix.ScaleColumn(Vec3(m_fScale, m_fScale, m_fScale));
Get3DEngine()->RegisterEntity(this);
}
//////////////////////////////////////////////////////////////////////////
void CCloudRenderNode::MoveCloud()
{
FUNCTION_PROFILER_3DENGINE;
Vec3 pos(m_matrix.GetTranslation());
ITimer* pTimer(gEnv->pTimer);
if (m_moveProps.m_autoMove)
{
// update position
float deltaTime = pTimer->GetFrameTime();
assert(deltaTime >= 0);
pos += deltaTime * m_moveProps.m_speed;
// constrain movement to specified loop box
Vec3 loopBoxMin(m_origin - m_moveProps.m_spaceLoopBox);
Vec3 loopBoxMax(m_origin + m_moveProps.m_spaceLoopBox);
if (pos.x < loopBoxMin.x)
{
pos.x = loopBoxMax.x;
}
if (pos.y < loopBoxMin.y)
{
pos.y = loopBoxMax.y;
}
if (pos.z < loopBoxMin.z)
{
pos.z = loopBoxMax.z;
}
if (pos.x > loopBoxMax.x)
{
pos.x = loopBoxMin.x;
}
if (pos.y > loopBoxMax.y)
{
pos.y = loopBoxMin.y;
}
if (pos.z > loopBoxMax.z)
{
pos.z = loopBoxMin.z;
}
// set new position
Matrix34 mat(m_matrix);
mat.SetTranslation(pos);
SetMatrixInternal(mat, false);
// fade out clouds at the borders of the loop box
if (m_moveProps.m_fadeDistance > 0)
{
Vec3 fade(max(m_moveProps.m_spaceLoopBox.x, m_moveProps.m_fadeDistance),
max(m_moveProps.m_spaceLoopBox.y, m_moveProps.m_fadeDistance),
max(m_moveProps.m_spaceLoopBox.z, m_moveProps.m_fadeDistance));
fade -= Vec3(fabs(pos.x - m_origin.x), fabs(pos.y - m_origin.y), fabs(pos.z - m_origin.z));
m_alpha = clamp_tpl(min(min(fade.x, fade.y), fade.z) / m_moveProps.m_fadeDistance, 0.0f, 1.0f);
}
}
else
{
if ((m_origin - pos).GetLengthSquared() > 1e-4f)
{
Matrix34 mat(m_matrix);
mat.SetTranslation(m_origin);
SetMatrixInternal(mat, false);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CCloudRenderNode::Render(const SRendParams& rParams, const SRenderingPassInfo& passInfo)
{
FUNCTION_PROFILER_3DENGINE;
if (!m_pMaterial || !passInfo.RenderClouds())
{
return;
}
IRenderer* pRenderer(GetRenderer());
// get render objects
CRenderObject* pRO = pRenderer->EF_GetObject_Temp(passInfo.ThreadID());
if (!pRO)
{
return;
}
SShaderItem& shaderItem = (rParams.pMaterial) ? rParams.pMaterial->GetShaderItem(0) : m_pMaterial->GetShaderItem(0);
pRO->m_II.m_Matrix = m_offsetedMatrix;
SRenderObjData* pOD = pRenderer->EF_GetObjData(pRO, true, passInfo.ThreadID());
pOD->m_pRE = m_pREImposter;
pOD->m_fTempVars[0] = m_fScale;
pRO->m_fSort = 0;
pRO->m_fDistance = rParams.fDistance;
int nAfterWater = GetObjManager()->IsAfterWater(m_offsetedMatrix.GetTranslation(), passInfo.GetCamera().GetPosition(), passInfo, Get3DEngine()->GetWaterLevel()) ? 1 : 0;
pRO->m_II.m_AmbColor = rParams.AmbientColor;
pRO->m_fAlpha = rParams.fAlpha * m_alpha;
float mvd(GetMaxViewDist());
float d((passInfo.GetCamera().GetPosition() - m_offsetedMatrix.GetTranslation()).GetLength());
if (d > 0.9f * mvd)
{
float s(clamp_tpl(1.0f - (d - 0.9f * mvd) / (0.1f * mvd), 0.0f, 1.0f));
pRO->m_fAlpha *= s;
}
pRenderer->EF_AddEf(m_pCloudRenderElement, shaderItem, pRO, passInfo, EFSLIST_TRANSP, nAfterWater, SRendItemSorter(rParams.rendItemSorter));
}
//////////////////////////////////////////////////////////////////////////
bool CCloudRenderNode::CheckIntersection(const Vec3& p1, const Vec3& p2)
{
if (p1 == p2)
{
return false;
}
if (m_pCloudDesc && m_pCloudDesc->m_pCloudTree)
{
Vec3 outp;
if (Intersect::Lineseg_AABB(Lineseg(p1, p2), m_WSBBox, outp))
{
Matrix34 pInv = m_offsetedMatrix.GetInverted();
return m_pCloudDesc->m_pCloudTree->CheckIntersection(pInv * p1, pInv * p2);
}
}
return false;
}
void CCloudRenderNode::OffsetPosition(const Vec3& delta)
{
if (m_pRNTmpData)
{
m_pRNTmpData->OffsetPosition(delta);
}
m_pos += delta;
m_origin += delta;
m_matrix.SetTranslation(m_matrix.GetTranslation() + delta);
m_offsetedMatrix.SetTranslation(m_offsetedMatrix.GetTranslation() + delta);
m_WSBBox.Move(delta);
}
| 32.256228 | 173 | 0.598742 | [
"render"
] |
a7a4d78b80ef0825c619ce7ff41994148e2058d6 | 37,908 | cpp | C++ | src/backpacktravel/app/table/impl/TableSyncItem.cpp | Py9595/Backpack-Travel-Underlying-Code | c5758792eba7cdd62cb6ff46e642e8e4e4e5417e | [
"BSL-1.0"
] | null | null | null | src/backpacktravel/app/table/impl/TableSyncItem.cpp | Py9595/Backpack-Travel-Underlying-Code | c5758792eba7cdd62cb6ff46e642e8e4e4e5417e | [
"BSL-1.0"
] | null | null | null | src/backpacktravel/app/table/impl/TableSyncItem.cpp | Py9595/Backpack-Travel-Underlying-Code | c5758792eba7cdd62cb6ff46e642e8e4e4e5417e | [
"BSL-1.0"
] | null | null | null | //------------------------------------------------------------------------------
/*
This file is part of backpacktravelalliancesd: https://github.com/backpacktravelalliances/backpacktravelalliancesd
2016-2018 BACKPACK FOUNDATION W18235552G Corp.
backpacktravelalliancesd is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
backpacktravelalliancesd is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
//==============================================================================
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/core/JobQueue.h>
#include <boost/optional.hpp>
#include <ripple/overlay/Peer.h>
#include <ripple/overlay/Overlay.h>
#include <ripple/app/main/Application.h>
#include <ripple/protocol/RippleAddress.h>
#include <ripple/json/json_reader.h>
#include <ripple/app/misc/NetworkOPs.h>
#include <backpacktravel/app/table/TableSyncItem.h>
#include <backpacktravel/app/sql/TxStore.h>
#include <backpacktravel/protocol/STEntry.h>
#include <backpacktravel/protocol/TableDefines.h>
#include <backpacktravel/app/storage/TableStorage.h>
#include <backpacktravel/app/table/TableStatusDBMySQL.h>
#include <backpacktravel/app/table/TableStatusDBSQLite.h>
#include <backpacktravel/app/table/TableStatusDB.h>
#include <backpacktravel/app/table/TableStatusDB.h>
#include <backpacktravel/app/table/TableSync.h>
using namespace std::chrono;
auto constexpr TABLE_DATA_OVERTM = 30s;
auto constexpr LEDGER_DATA_OVERTM = 30s;
auto const TXID_LENGTH = 64;
#define OPTYPELEN 6
namespace ripple {
TableSyncItem::~TableSyncItem()
{
}
TableSyncItem::TableSyncItem(Application& app, beast::Journal journal, Config& cfg, SyncTargetType eTargetType)
:app_(app)
,journal_(journal)
,cfg_(cfg)
,eSyncTargetType_(eTargetType)
,operateSqlEvent(true,true)
,readDataEvent(true, true)
{
eState_ = SYNC_INIT;
bOperateSQL_ = false;
bIsChange_ = true;
bGetLocalData_ = false;
conn_ = NULL;
pObjTxStore_ = NULL;
sTableNameInDB_ = "";
sNickName_ = "";
uCreateLedgerSequence_ = 0;
deleted_ = false;
}
TableSyncItem::cond const & TableSyncItem::GetCondition()
{
return sCond_;
}
time_t TableSyncItem::StringToDatetime(const char *str)
{
tm tm_;
int year, month, day, hour, minute, second;
sscanf(str, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
tm_.tm_year = year - 1900;
tm_.tm_mon = month - 1;
tm_.tm_mday = day;
tm_.tm_hour = hour;
tm_.tm_min = minute;
tm_.tm_sec = second;
tm_.tm_isdst = 0;
time_t t_ = mktime(&tm_) - std::chrono::seconds(days(10957)).count();
return t_;
}
void TableSyncItem::Init(const AccountID& id, const std::string& sName, bool isAutoSync)
{
accountID_ = id;
sTableName_ = sName;
bIsAutoSync_ = isAutoSync;
}
void TableSyncItem::InitCondition(const std::string& cond)
{
if (cond.size() > 0)
{
if (cond[0] == '~') //SYNC_JUMP
{
if (cond.size() - 1 == TXID_LENGTH)
sCond_.stxid = cond.substr(1);
else
sCond_.uledgerIndex = std::stoi(cond.substr(1));
sCond_.eSyncType = SYNC_JUMP;
}
else
{
int pos1 = cond.find('-');
int pos2 = cond.find(':');
if (pos1 > 0 || pos2 > 0) //time
{
sCond_.utime = StringToDatetime(cond.c_str());
}
else //uledgerIndex
{
sCond_.uledgerIndex = std::stoi(cond);
}
sCond_.eSyncType = SYNC_PRIOR;
}
}
}
void TableSyncItem::Init(const AccountID& id, const std::string& sName, const std::string& cond, bool isAutoSync)
{
Init(id, sName, isAutoSync);
InitCondition(cond);
}
void TableSyncItem::Init(const AccountID& id, const std::string& sName, const AccountID& userId, const SecretKey& user_secret, const std::string& condition, bool isAutoSync)
{
Init(id, sName, isAutoSync);
user_accountID_ = userId;
user_secret_ = user_secret;
InitCondition(condition);
}
void TableSyncItem::ReInit()
{
ReSetContex();
{
std::lock_guard<std::mutex> lock(mutexInfo_);
eState_ = SYNC_REINIT;
}
}
void TableSyncItem::SetPara(std::string sNameInDB,LedgerIndex iSeq, uint256 hash, LedgerIndex TxnSeq, uint256 Txnhash, uint256 TxnUpdateHash)
{
sTableNameInDB_ = sNameInDB;
u32SeqLedger_ = iSeq;
uHash_ = hash;
uTxSeq_ = TxnSeq;
uTxHash_ = Txnhash;
uTxDBUpdateHash_ = TxnUpdateHash;
}
TxStoreDBConn& TableSyncItem::getTxStoreDBConn()
{
if (conn_ == NULL)
{
conn_ = std::make_unique<TxStoreDBConn>(cfg_);
if (conn_->GetDBConn() == NULL)
{
JLOG(journal_.error()) << "TableSyncItem::getTxStoreDBConn() return null";
SetSyncState(SYNC_STOP);
}
}
return *conn_;
}
TxStore& TableSyncItem::getTxStore()
{
if (pObjTxStore_ == NULL)
{
auto &conn = getTxStoreDBConn();
pObjTxStore_ = std::make_unique<TxStore>(conn.GetDBConn(),cfg_,journal_);
}
return *pObjTxStore_;
}
TableStatusDB& TableSyncItem::getTableStatusDB()
{
if (pObjTableStatusDB_ == NULL)
{
DatabaseCon::Setup setup = ripple::setup_SyncDatabaseCon(cfg_);
std::pair<std::string, bool> result = setup.sync_db.find("type");
if (result.first.compare("sqlite") == 0)
pObjTableStatusDB_ = std::make_unique<TableStatusDBSQLite>(getTxStoreDBConn().GetDBConn(), &app_, journal_);
else
pObjTableStatusDB_ = std::make_unique<TableStatusDBMySQL>(getTxStoreDBConn().GetDBConn(), &app_, journal_);
}
return *pObjTableStatusDB_;
}
bool TableSyncItem::getAutoSync()
{
return bIsAutoSync_;
}
void TableSyncItem::ReSetContex()
{
{
std::lock_guard<std::mutex> lock(mutexInfo_);
u32SeqLedger_ = uTxSeq_ = 0;
uHash_.zero();
uTxHash_.zero();
uTxDBUpdateHash_.zero();
}
{
std::lock_guard<std::mutex> lock(mutexBlockData_);
aBlockData_.clear();
}
{
std::lock_guard<std::mutex> lock(mutexWholeData_);
aWholeData_.clear();
}
{
std::lock_guard<std::mutex> lock(mutexWaitCheckQueue_);
aWaitCheckData_.clear();
}
}
void TableSyncItem::ReSetContexAfterDrop()
{
{
std::lock_guard<std::mutex> lock(mutexInfo_);
sTableNameInDB_.clear();
eState_ = SYNC_DELETING;
}
ReSetContex();
}
void TableSyncItem::SetIsDataFromLocal(bool bLocal)
{
bGetLocalData_ = bLocal;
}
void TableSyncItem::PushDataByOrder(std::list <sqldata_type> &aData, sqldata_type &sqlData)
{
if (aData.size() == 0)
{
aData.push_back(sqlData);
return;
}
else if (sqlData.first > aData.rbegin()->first)
{
aData.push_back(sqlData);
return;
}
else
{
if (aData.size() == 1)
{
aData.push_front(sqlData);
return;
}
else
{
for (auto it = aData.begin(); it != aData.end(); it++)
{
if (sqlData.first == it->first) return;
else if (sqlData.first > it->first)
{
aData.insert(it++, sqlData);
return;
}
}
}
}
}
void TableSyncItem::DealWithWaitCheckQueue(std::function<bool (sqldata_type const&)> f)
{
std::lock_guard<std::mutex> lock(mutexWaitCheckQueue_);
for (auto it = aWaitCheckData_.begin(); it != aWaitCheckData_.end(); it++)
{
f(*it);
}
aWaitCheckData_.clear();
}
void TableSyncItem::PushDataToWaitCheckQueue(sqldata_type &sqlData)
{
std::lock_guard<std::mutex> lock(mutexWaitCheckQueue_);
PushDataByOrder(aWaitCheckData_, sqlData);
}
void TableSyncItem::PushDataToBlockDataQueue(sqldata_type &sqlData)
{
std::lock_guard<std::mutex> lock(mutexBlockData_);
PushDataByOrder(aBlockData_, sqlData);
}
bool TableSyncItem::GetRightRequestRange(TableSyncItem::BaseInfo &stRange)
{
std::lock_guard<std::mutex> lock(mutexBlockData_);
if (aBlockData_.size() > 0)
{
LedgerIndex iBegin = u32SeqLedger_;
LedgerIndex iCheckSeq = uTxSeq_;
uint256 uHash = uHash_;
uint256 uCheckHash = uTxHash_;
for (auto it = aBlockData_.begin(); it != aBlockData_.end(); it++)
{
if (it->second.seekstop())
{
if (iBegin == it->second.lastledgerseq())
{
stRange.u32SeqLedger = 0;
stRange.uHash = uint256();
stRange.uStopSeq = 0;
stRange.uTxSeq = 0;
stRange.uTxHash = uint256();;
return true;
}
else
{
stRange.u32SeqLedger = iBegin;
stRange.uHash = uHash;
stRange.uStopSeq = it->second.ledgerseq() - 1;
stRange.uTxSeq = iCheckSeq;
stRange.uTxHash = uCheckHash;
return true;
}
}
if (iBegin == it->second.lastledgerseq())
{
iBegin = it->second.ledgerseq();
iCheckSeq = it->second.ledgerseq();
uHash = from_hex_text<uint256>(it->second.ledgerhash());
uCheckHash = from_hex_text<uint256>(it->second.ledgercheckhash());
}
else
{
stRange.u32SeqLedger = iBegin;
stRange.uHash = uHash;
stRange.uStopSeq = it->second.ledgerseq() - 1;
stRange.uTxSeq = iCheckSeq;
stRange.uTxHash = uCheckHash;
return true;
}
}
stRange.u32SeqLedger = iBegin;
stRange.uHash = uHash;
stRange.uStopSeq = (u32SeqLedger_ + 255) & (~255);
stRange.uTxSeq = iCheckSeq;
stRange.uTxHash = uCheckHash;
return true;
}
stRange.u32SeqLedger = u32SeqLedger_;
stRange.uHash = uHash_;
stRange.uStopSeq = (u32SeqLedger_ + 1 + 255) & (~255);
stRange.uTxSeq = uTxSeq_;
stRange.uTxHash = uTxHash_;
return true;
}
bool TableSyncItem::TransBlock2Whole(LedgerIndex iSeq, uint256)
{
std::lock_guard<std::mutex> lock1(mutexBlockData_);
std::lock_guard<std::mutex> lock2(mutexWholeData_);
auto iBegin = iSeq;
bool bHasStop = false;
while(aBlockData_.size() > 0)
{
auto it = aBlockData_.begin();
if (iBegin == it->second.lastledgerseq())
{
uint256 uCurhash = from_hex_text<uint256>(it->second.ledgerhash());
uint256 uCheckhash = from_hex_text<uint256>(it->second.ledgercheckhash());
iBegin = it->second.ledgerseq();
bHasStop = it->second.seekstop();
SetSyncLedger(iBegin, uCurhash);
if (it->second.txnodes().size() > 0)
{
SetSyncTxLedger(iBegin, uCheckhash);
}
aWholeData_.push_back(std::move(*it));
aBlockData_.erase(it);
}
else
{
break;
}
}
bool bStop = aBlockData_.size() == 0 && bHasStop;
if (bStop && !bGetLocalData_)
{
SetSyncState(SYNC_BLOCK_STOP);
}
return bStop;
}
bool TableSyncItem::IsGetLedgerExpire()
{
if (duration_cast<seconds>(steady_clock::now() - clock_ledger_) > LEDGER_DATA_OVERTM)
{
auto iter = std::find_if(lfailList_.begin(), lfailList_.end(),
[this](beast::IP::Endpoint &item) {
return item == uPeerAddr_;
});
if (iter == lfailList_.end())
{
lfailList_.push_back(uPeerAddr_);
}
bIsChange_ = true;
return true;
}
return false;
}
bool TableSyncItem::IsGetDataExpire()
{
if (duration_cast<seconds>(steady_clock::now() - clock_data_) > TABLE_DATA_OVERTM)
{
auto iter = std::find_if(lfailList_.begin(), lfailList_.end(),
[this](beast::IP::Endpoint &item) {
return item == uPeerAddr_;
});
if (iter == lfailList_.end())
{
lfailList_.push_back(uPeerAddr_);
}
bIsChange_ = true;
return true;
}
return false;
}
void TableSyncItem::UpdateLedgerTm()
{
clock_ledger_ = steady_clock::now();
}
void TableSyncItem::UpdateDataTm()
{
clock_data_ = steady_clock::now();
}
AccountID TableSyncItem::GetAccount()
{
return accountID_;
}
std::string TableSyncItem::GetTableName()
{
return sTableName_;
}
std::string TableSyncItem::GetNickName()
{
return sNickName_;
}
std::mutex &TableSyncItem::WriteDataMutex()
{
return this->mutexWriteData_;
}
void TableSyncItem::GetSyncLedger(LedgerIndex &iSeq, uint256 &uHash)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
iSeq = u32SeqLedger_;
uHash = uHash_;
}
void TableSyncItem::GetSyncTxLedger(LedgerIndex &iSeq, uint256 &uHash)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
iSeq = uTxSeq_;
uHash = uTxHash_;
}
TableSyncItem::TableSyncState TableSyncItem::GetSyncState()
{
std::lock_guard<std::mutex> lock(mutexInfo_);
return eState_;
}
void TableSyncItem::GetBaseInfo(BaseInfo &stInfo)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
stInfo.accountID = accountID_;
stInfo.sTableNameInDB = sTableNameInDB_;
stInfo.sTableName = sTableName_;
stInfo.sNickName = sNickName_;
stInfo.u32SeqLedger = u32SeqLedger_;
stInfo.uHash = uHash_;
stInfo.uTxSeq = uTxSeq_;
stInfo.uTxHash = uTxHash_;
stInfo.eState = eState_;
stInfo.lState = lState_;
stInfo.isAutoSync = bIsAutoSync_;
stInfo.eTargetType = eSyncTargetType_;
stInfo.uTxUpdateHash = uTxDBUpdateHash_;
stInfo.isDeleted = deleted_;
}
void TableSyncItem::SetSyncLedger(LedgerIndex iSeq, uint256 uHash)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
u32SeqLedger_ = iSeq;
uHash_ = uHash;
}
void TableSyncItem::SetSyncTxLedger(LedgerIndex iSeq, uint256 uHash)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
uTxSeq_ = iSeq;
uTxHash_ = uHash;
}
void TableSyncItem::SetSyncState(TableSyncState eState)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
if(eState_ != SYNC_STOP) eState_ = eState;
}
void TableSyncItem::SetDeleted(bool deleted)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
deleted_ = deleted;
}
void TableSyncItem::SetLedgerState(LedgerSyncState lState)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
lState_ = lState;
}
bool TableSyncItem::IsInFailList(beast::IP::Endpoint& peerAddr)
{
bool ret = false;
auto iter = std::find_if(lfailList_.begin(), lfailList_.end(),
[peerAddr](beast::IP::Endpoint &item) {
return item == peerAddr;
});
if (iter != lfailList_.end())
ret = true;
return ret;
}
std::shared_ptr<Peer> TableSyncItem::GetRightPeerTarget(LedgerIndex iSeq)
{
auto peerList = app_.overlay().getActivePeers();
bool isChange = GetIsChange();
if (!isChange)
{
for (auto const& peer : peerList)
{
if (uPeerAddr_ == peer->getRemoteAddress())
return peer;
}
}
std::shared_ptr<Peer> target = NULL;
if (peerList.size() > 0)
{
int iRandom = rand() % (peerList.size());
for (int i = 0; i < peerList.size(); i++)
{
int iRelIndex = (iRandom + i) % peerList.size();
auto peer = peerList.at(iRelIndex);
if (peer == NULL) continue;
auto addrTmp = peer->getRemoteAddress();
if (IsInFailList(addrTmp))
continue;
target = peer;
SetPeer(peer);
break;
}
}
if (!target)
{
lfailList_.clear();
if (peerList.size() > 0)
{
target = peerList.at(0);
SetPeer(target);
}
}
return target;
}
void TableSyncItem::ClearFailList()
{
lfailList_.clear();
}
void TableSyncItem::SendTableMessage(Message::pointer const& m)
{
auto peer = GetRightPeerTarget(u32SeqLedger_);
if(peer != NULL)
peer->send(m);
}
TableSyncItem::LedgerSyncState TableSyncItem::GetCheckLedgerState()
{
std::lock_guard<std::mutex> lock(mutexInfo_);
return lState_;
}
void TableSyncItem::SetTableName(std::string sName)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
sTableName_ = sName;
}
std::string TableSyncItem::TableNameInDB()
{
return sTableNameInDB_;
}
TableSyncItem::SyncTargetType TableSyncItem::TargetType()
{
return eSyncTargetType_;
}
void TableSyncItem::SetTableNameInDB(uint160 NameInDB)
{
sTableNameInDB_ = to_string(NameInDB);
}
void TableSyncItem::SetTableNameInDB(std::string sNameInDB)
{
sTableNameInDB_ = sNameInDB;
}
void TableSyncItem::TryOperateSQL()
{
if (bOperateSQL_) return;
bOperateSQL_ = true;
operateSqlEvent.reset();
app_.getJobQueue().addJob(jtOPERATESQL, "operateSQL", [this](Job&) { OperateSQLThread(); });
}
bool TableSyncItem::IsExist(AccountID accountID, std::string TableNameInDB)
{
return app_.getTableStatusDB().IsExist(accountID, TableNameInDB);
}
bool TableSyncItem::IsNameInDBExist(std::string TableName, std::string Owner, bool delCheck, std::string &TableNameInDB)
{
return app_.getTableStatusDB().isNameInDBExist(TableName, Owner, delCheck, TableNameInDB);
}
bool TableSyncItem::DeleteRecord(AccountID accountID, std::string TableName)
{
return app_.getTableStatusDB().DeleteRecord(accountID, TableName);
}
bool TableSyncItem::GetMaxTxnInfo(std::string TableName, std::string Owner, LedgerIndex &TxnLedgerSeq, uint256 &TxnLedgerHash)
{
return app_.getTableStatusDB().GetMaxTxnInfo(TableName, Owner, TxnLedgerSeq, TxnLedgerHash);
}
bool TableSyncItem::DeleteTable(std::string nameInDB)
{
auto ret = app_.getTxStore().DropTable(nameInDB);
return ret.first;
}
bool TableSyncItem::RenameRecord(AccountID accountID, std::string TableNameInDB, std::string TableName)
{
return app_.getTableStatusDB().RenameRecord(accountID, TableNameInDB, TableName);
}
bool TableSyncItem::UpdateSyncDB(AccountID accountID, std::string TableName, std::string TableNameInDB)
{
auto ret = app_.getTableStatusDB().UpdateSyncDB(accountID, TableName, TableNameInDB);
return ret == soci_success;
}
bool TableSyncItem::UpdateStateDB(const std::string & owner, const std::string & tablename, const bool &isAutoSync)
{
return app_.getTableStatusDB().UpdateStateDB(owner, tablename, isAutoSync);
}
bool TableSyncItem::DoUpdateSyncDB(const std::string &Owner, const std::string &TableNameInDB, bool bDel,
const std::string &PreviousCommit)
{
auto ret = getTableStatusDB().UpdateSyncDB(Owner, TableNameInDB, bDel, PreviousCommit);
if (ret == soci_exception) {
SetSyncState(SYNC_STOP);
}
return ret == soci_success;
}
std::pair<bool, std::string> TableSyncItem::InitPassphrase()
{
auto ledger = app_.getLedgerMaster().getValidatedLedger();
if (ledger == NULL)
{
return std::make_pair(false, "ledger error");
}
auto id = keylet::table(accountID_);
auto const tablesle = ledger->read(id);
if (tablesle == nullptr)
{
return std::make_pair(false, "can't find account table sle.");
}
auto aTableEntries = tablesle->getFieldArray(sfTableEntries);
bool bGetTable = false;
for (auto const &table : aTableEntries)
{
bool bRightName = false;
if (eSyncTargetType_ == SyncTarget_db) bRightName = to_string(table.getFieldH160(sfNameInDB)) == sTableNameInDB_;
else bRightName = strCopy(table.getFieldVL(sfTableName)) == sTableName_;;
if (bRightName)
{
uCreateLedgerSequence_ = table.getFieldU32(sfCreateLgrSeq);
auto& users = table.getFieldArray(sfUsers);
assert(users.size() > 0);
bool bConfidential = users[0].isFieldPresent(sfToken);
if (bConfidential)
{
confidential_ = true;
if (!user_accountID_) return std::make_pair(false, "user account is null.");;
for (auto & user : users) //check if there same user
{
if (user.getAccountID(sfUser) == user_accountID_)
{
auto selectFlags = getFlagFromOptype(R_GET);
auto userFlags = user.getFieldU32(sfFlags);
if ((userFlags & selectFlags) == 0)
{
return std::make_pair(false, "no authority.");
}
else
{
if (user.isFieldPresent(sfToken))
{
auto token = user.getFieldVL(sfToken);
//passBlob_ = RippleAddress::decryptPassword(token, *user_secret_);
passBlob_ = ripple::decrypt(token, *user_secret_);
if(passBlob_.size() > 0) return std::make_pair(true, "");
else return std::make_pair(false, "cann't get password for this table.");
}
else
{
return std::make_pair(false, "table error");
}
}
}
}
}
else
{
return std::make_pair(true, "");
}
bGetTable = true;
break;
}
}
if (!bGetTable)
{
return std::make_pair(false, "Can't find the table in the chain.");
}
return std::make_pair(false, "error");
}
void TableSyncItem::TryDecryptRaw(std::vector<STTx>& vecTxs)
{
for (auto& tx : vecTxs)
{
TryDecryptRaw(tx);
}
}
void TableSyncItem::TryDecryptRaw(STTx& tx)
{
if (!user_accountID_ || passBlob_.size() == 0)
return;
Blob raw;
if (tx.isFieldPresent(sfRaw)) //check sfTables
{
raw = tx.getFieldVL(sfRaw);
if (raw.size() == 0)
{
return;
}
}
else
{
return;
}
if (user_accountID_ && user_secret_)
{
//decrypt passphrase
Blob rawDecrypted;
HardEncrypt* hEObj = HardEncryptObj::getInstance();
if (nullptr == hEObj)
{
rawDecrypted = RippleAddress::decryptAES(passBlob_, raw);
}
else
{
unsigned char* pPlainData = new unsigned char[raw.size()];
unsigned long plainDataLen = raw.size();
hEObj->SM4SymDecrypt(passBlob_.data(),passBlob_.size(),raw.data(),raw.size(),pPlainData,&plainDataLen);
rawDecrypted = Blob(pPlainData, pPlainData + plainDataLen);
delete[] pPlainData;
}
if (rawDecrypted.size() > 0)
{
tx.setFieldVL(sfRaw, rawDecrypted);
}
}
}
bool TableSyncItem::DoUpdateSyncDB(const std::string &Owner, const std::string &TableNameInDB, const std::string &TxnLedgerHash,
const std::string &TxnLedgerSeq, const std::string &LedgerHash, const std::string &LedgerSeq, const std::string &TxHash,
const std::string &cond, const std::string &PreviousCommit)
{
auto ret = app_.getTableStatusDB().UpdateSyncDB(Owner, TableNameInDB, TxnLedgerHash, TxnLedgerSeq, LedgerHash,
LedgerSeq, TxHash, cond, PreviousCommit);
if (ret == soci_exception) {
SetSyncState(SYNC_STOP);
}
return ret == soci_success;
}
std::string TableSyncItem::getOperationRule(const STTx& tx)
{
std::string rule;
auto opType = tx.getFieldU16(sfOpType);
if (!isSqlStatementOpType((TableOpType)opType))
return rule;
auto ledger = app_.getLedgerMaster().getValidatedLedger();
if (ledger == NULL)
return rule;
auto id = keylet::table(accountID_);
auto const tablesle = ledger->read(id);
if (tablesle == nullptr)
return rule;
auto aTableEntries = tablesle->getFieldArray(sfTableEntries);
STEntry* pEntry = NULL;
for (auto const &table : aTableEntries)
{
bool bRightName = false;
if (eSyncTargetType_ == SyncTarget_db)
bRightName = to_string(table.getFieldH160(sfNameInDB)) == sTableNameInDB_;
else
bRightName = strCopy(table.getFieldVL(sfTableName)) == sTableName_;;
if (bRightName)
pEntry = (STEntry*)&table;
}
if (pEntry != NULL)
rule = pEntry->getOperationRule((TableOpType)opType);
return rule;
}
std::pair<bool, std::string> TableSyncItem::DealWithTx(const std::vector<STTx>& vecTxs)
{
auto ret = std::make_pair(true, std::string(""));
for (auto& tx : vecTxs)
{
auto retTmp = DealTranCommonTx(tx);
if (!retTmp.first && ret.first)
{
ret = retTmp;
break;
}
}
return ret;
}
std::pair<bool, std::string> TableSyncItem::DealTranCommonTx(const STTx &tx)
{
auto ret = std::make_pair(true, std::string(""));
auto op_type = tx.getFieldU16(sfOpType);
if (!isNotNeedDisposeType((TableOpType)op_type))
{
auto sOperationRule = getOperationRule(tx);
ret = this->getTxStore().Dispose(tx,sOperationRule);
if (ret.first)
{
JLOG(journal_.trace()) << "Dispose success";
}
else
{
JLOG(journal_.trace()) << "Dispose error";
}
}
if (ret.first)
{
if (T_DROP == op_type)
{
this->ReSetContexAfterDrop();
}
else if (T_RENAME == op_type)
{
auto tables = tx.getFieldArray(sfTables);
if (tables.size() > 0)
{
auto newTableName = strCopy(tables[0].getFieldVL(sfTableNewName));
sTableName_ = newTableName;
getTableStatusDB().RenameRecord(accountID_, sTableNameInDB_, newTableName);
}
}
}
return ret;
}
void TableSyncItem::InsertPressData(const STTx& tx,uint32 ledger_seq,uint32 ledger_time)
{
std::string pressRealName;
if (tx.isFieldPresent(sfFlags))
{
auto tables = tx.getFieldArray(sfTables);
std::string table_name = strCopy(tables[0].getFieldVL(sfTableName));
if (table_name == "press_time")
{
return;
}
else
{
pressRealName = app_.getTableSync().GetPressTableName();
if (pressRealName.empty())
return;
}
std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds> tp = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
auto tmp = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
uint32 submit_time = tx.getFieldU32(sfFlags);
uint32 db_time = tmp.count();
submit_time -= std::chrono::seconds(days(10957)).count();
db_time -= std::chrono::seconds(days(10957)).count();
ledger_time = ledger_time > submit_time ? ledger_time - submit_time : ledger_time;
db_time -= submit_time;
try
{
LockedSociSession sql_session = getTxStoreDBConn().GetDBConn()->checkoutDb();
std::string sql = "INSERT INTO " + pressRealName + " (ledger_seq, submit_time, ledger_time,db_time) VALUES('";
sql += to_string(ledger_seq);
sql += "','";
sql += to_string(submit_time);
sql += "','";
sql += to_string(ledger_time);
sql += "','";
sql += to_string(db_time);
sql += "');";
soci::statement st = (sql_session->prepare << sql);
st.execute();
}
catch (std::exception const& e)
{
JLOG(journal_.error()) <<
"InsertPressData exception" << e.what();
}
}
}
bool TableSyncItem::DealWithEveryLedgerData(const std::vector<protocol::TMTableData> &aData)
{
for (std::vector<protocol::TMTableData>::const_iterator iter = aData.begin(); iter != aData.end(); ++iter)
{
std::string LedgerHash = iter->ledgerhash();
std::string LedgerCheckHash = iter->ledgercheckhash();
std::string LedgerSeq = to_string(iter->ledgerseq());
std::string PreviousCommit;
//check for jump one seq, check for deadline time and deadline seq
CheckConditionState checkRet = CondFilter(iter->closetime(), iter->ledgerseq(), uint256(0));
if (checkRet == CHECK_JUMP) continue;
else if(checkRet == CHECK_REJECT)
{
SetSyncState(SYNC_STOP);
return false;
}
if (iter->txnodes().size() > 0)
{
int count = 0; //count success times
bool bFindLastSuccessTx = uTxDBUpdateHash_.isZero() ? true : false;
for (int i = 0; i < iter->txnodes().size(); i++)
{
const protocol::TMLedgerNode &node = iter->txnodes().Get(i);
auto str = node.nodedata();
Blob blob;
blob.assign(str.begin(), str.end());
STTx tx = std::move((STTx)(SerialIter{ blob.data(), blob.size() }));
if (!bFindLastSuccessTx) //if a ledger have many txs,first handles some txs,then stop rippled,next start rippled,must jump those txs
{
if (tx.getTransactionID() == uTxDBUpdateHash_)
{
bFindLastSuccessTx = true;
}
count++;
continue;
}
try {
//check for jump one tx.
if (isJumpThisTx(tx.getTransactionID()))
{
count++;
continue;
}
auto vecTxs = STTx::getTxs(tx, sTableNameInDB_);
if (vecTxs.size() > 0)
{
TryDecryptRaw(vecTxs);
for (auto& tx : vecTxs)
{
if (T_CREATE == tx.getFieldU16(sfOpType))
{
DeleteTable(sTableNameInDB_);
}
}
}
JLOG(journal_.info()) << "got sync tx" << tx.getFullText();
auto conn = getTxStoreDBConn().GetDBConn();
if (conn == NULL)
{
SetSyncState(SYNC_STOP);
return false;
}
LockedSociSession sql_session = conn->checkoutDb();
TxStoreTransaction stTran(&getTxStoreDBConn());
auto ret = DealWithTx(vecTxs);
uTxDBUpdateHash_ = tx.getTransactionID();
if (!ret.first)
{
stTran.rollback();
auto updateRet = getTableStatusDB().UpdateSyncDB(to_string(accountID_), sTableNameInDB_, to_string(uTxDBUpdateHash_), PreviousCommit);
if (updateRet == soci_exception) {
JLOG(journal_.error()) << "UpdateSyncDB soci_exception";
}
}
else
{
auto updateRet = getTableStatusDB().UpdateSyncDB(to_string(accountID_), sTableNameInDB_, to_string(uTxDBUpdateHash_), PreviousCommit);
if (updateRet == soci_exception) {
JLOG(journal_.error()) << "UpdateSyncDB soci_exception";
}
stTran.commit();
}
//press test
if (app_.getTableSync().IsPressSwitchOn())
{
if (ret.first)
InsertPressData(tx, iter->ledgerseq(), iter->closetime());
}
//deal with subscribe
std::pair<std::string, std::string> result;
if (ret.first)
result = std::make_pair("db_success", "");
else
result = std::make_pair("db_error", ret.second);
app_.getOPs().pubTableTxs(accountID_, sTableName_, tx, result, false);
count++;
}
catch (std::exception const& e)
{
JLOG(journal_.info()) <<
"Dispose exception" << e.what();
std::pair<std::string, std::string> result = std::make_pair("db_error", e.what());
app_.getOPs().pubTableTxs(accountID_, sTableName_, tx, result, false);
}
}
if (count == iter->txnodes().size())
{
JLOG(journal_.info()) <<
"find tx and UpdateSyncDB LedgerSeq:" << LedgerSeq<<"count:"<<count;
uTxDBUpdateHash_.zero();
auto ret = getTableStatusDB().UpdateSyncDB(to_string(accountID_), sTableNameInDB_, LedgerCheckHash, LedgerSeq, LedgerHash, LedgerSeq, to_string(uTxDBUpdateHash_), to_string(iter->closetime()), PreviousCommit); //write tx time into db,so next start rippled can get last txntime and compare it to time condition
if (ret == soci_exception) {
SetSyncState(SYNC_STOP);
}
}
if (uTxDBUpdateHash_.isNonZero())
SetSyncState(SYNC_STOP);
}
else
{
soci_ret ret = getTableStatusDB().UpdateSyncDB(to_string(accountID_), sTableNameInDB_, LedgerHash, LedgerSeq, PreviousCommit);
if (ret == soci_exception) {
SetSyncState(SYNC_STOP);
}
JLOG(journal_.info()) <<
"find no tx and DoUpdateSyncDB LedgerSeq:" << LedgerSeq;
}
}
return true;
}
void TableSyncItem::OperateSQLThread()
{
//check the connection is ok
getTxStoreDBConn();
if (GetSyncState() == SYNC_STOP)
{
bOperateSQL_ = false;
return;
}
std::vector<protocol::TMTableData> vec_tmdata;
std::list <sqldata_type> list_tmdata;
{
std::lock_guard<std::mutex> lock(mutexWholeData_);
for (std::list<sqldata_type>::iterator iter = aWholeData_.begin(); iter != aWholeData_.end(); ++iter)
{
vec_tmdata.push_back((*iter).second);
}
aWholeData_.clear();
}
DealWithEveryLedgerData(vec_tmdata);
bOperateSQL_ = false;
operateSqlEvent.signal();
}
bool TableSyncItem::isJumpThisTx(uint256 txid)
{
if (sCond_.eSyncType == SYNC_JUMP && sCond_.stxid.size() > 0 && to_string(txid) == sCond_.stxid)
return true;
return false;
}
TableSyncItem::CheckConditionState TableSyncItem::CondFilter(uint32 time, uint32 ledgerIndex, uint256 txid)
{
if (sCond_.eSyncType == SYNC_PRIOR)
{
if (sCond_.uledgerIndex > 0) // check ledger index prior condition
{
if (sCond_.uledgerIndex < ledgerIndex)
{
JLOG(journal_.warn()) << "prior cond_LedgerIndex violate";
return CHECK_REJECT;
}
}
if (time > 0 && sCond_.utime > 0) //check time prior condition
{
if (sCond_.utime < time)
{
JLOG(journal_.warn()) << "prior cond_time violate";
return CHECK_REJECT;
}
}
}
else if (sCond_.eSyncType == SYNC_JUMP)
{
if (sCond_.stxid.size() > 0)
{
if (to_string(txid) == sCond_.stxid) //check txid jump condition
{
JLOG(journal_.error()) <<
"tx meet jump condition-txid,should be jump";
return CHECK_JUMP;
}
}
if (sCond_.uledgerIndex > 0)
{
if (sCond_.uledgerIndex == ledgerIndex) //check ledgerIndex jump condition
{
JLOG(journal_.warn()) <<
"tx meet jump condition-ledgerIndex,should be jump";
return CHECK_JUMP;
}
}
}
return CHECK_ADVANCED;
}
void TableSyncItem::PushDataToWholeDataQueue(sqldata_type &sqlData)
{
std::lock_guard<std::mutex> lock(mutexWholeData_);
aWholeData_.push_back(sqlData);
if (sqlData.second.txnodes().size() > 0)
{
SetSyncLedger(sqlData.first, from_hex_text<uint256>(sqlData.second.ledgerhash()));
SetSyncTxLedger(sqlData.first, from_hex_text<uint256>(sqlData.second.ledgercheckhash()));
}
else
{
SetSyncLedger(sqlData.first, from_hex_text<uint256>(sqlData.second.ledgerhash()));
}
if (sqlData.second.seekstop() && !bGetLocalData_)
{
SetSyncState(TableSyncItem::SYNC_BLOCK_STOP);
}
}
bool TableSyncItem::GetIsChange()
{
return bIsChange_;
}
void TableSyncItem::PushDataToWholeDataQueue(std::list <sqldata_type> &aSqlData)
{
if (aSqlData.size() <= 0) return;
std::lock_guard<std::mutex> lock(mutexWholeData_);
for (std::list<sqldata_type>::iterator it = aSqlData.begin(); it != aSqlData.end(); it++)
{
aWholeData_.push_back(*it);
}
auto &lastItem = aSqlData.back();
SetSyncLedger(lastItem.first, from_hex_text<uint256>(lastItem.second.ledgerhash()));
if (lastItem.second.seekstop() && !bGetLocalData_)
{
SetSyncState(TableSyncItem::SYNC_BLOCK_STOP);
}
}
void TableSyncItem::SetPeer(std::shared_ptr<Peer> peer)
{
std::lock_guard<std::mutex> lock(mutexInfo_);
bIsChange_ = false;
uPeerAddr_ = peer->getRemoteAddress();
}
void TableSyncItem::StartLocalLedgerRead()
{
readDataEvent.reset();
}
void TableSyncItem::StopLocalLedgerRead()
{
readDataEvent.signal();
}
bool TableSyncItem::StopSync()
{
SetSyncState(SYNC_STOP);
bool bRet = false;
bRet = readDataEvent.wait(1000);
if (!bRet)
{
SetSyncState(SYNC_BLOCK_STOP);
return false;
}
bRet = operateSqlEvent.wait(2000);
if (!bRet)
{
SetSyncState(SYNC_BLOCK_STOP);
return false;
}
int iSize = 0;
{
std::lock_guard<std::mutex> lock(mutexWholeData_);
aWholeData_.size();
}
iSize = aWholeData_.size();
if (iSize > 0)
{
TryOperateSQL();
bRet = operateSqlEvent.wait(2000);
if (!bRet)
{
SetSyncState(SYNC_BLOCK_STOP);
return false;
}
}
return true;
}
std::string TableSyncItem::GetPosInfo(LedgerIndex iTxLedger, std::string sTxLedgerHash, LedgerIndex iCurLedger, std::string sCurLedgerHash, bool bStop, std::string sMsg)
{
Json::Value jsPos;
jsPos["Account"] = to_string(accountID_);
jsPos["TableName"] = sTableName_;
jsPos["TxnCreateSeq"] = uCreateLedgerSequence_;
jsPos["TxnHash"] = sTxLedgerHash;
jsPos["TxnLedgerSeq"] = iTxLedger;
jsPos["LedgerHash"] = sCurLedgerHash;
jsPos["LedgerSeq"] = iCurLedger;
jsPos["State"] = bStop ? "stopped" : "processing";
jsPos["Message"] = sMsg;
auto sPos = jsPos.toStyledString();
return sPos;
}
}
| 27.955752 | 315 | 0.616624 | [
"vector"
] |
a7a509eaa15b96b754153ff0d167d93575da9eff | 30,552 | cpp | C++ | src/game/skin_change_req_handler.cpp | 0x384c0/jc4-console-thingy | 29910373c2758138ca50c0f3aa3916890a333e85 | [
"MIT"
] | null | null | null | src/game/skin_change_req_handler.cpp | 0x384c0/jc4-console-thingy | 29910373c2758138ca50c0f3aa3916890a333e85 | [
"MIT"
] | null | null | null | src/game/skin_change_req_handler.cpp | 0x384c0/jc4-console-thingy | 29910373c2758138ca50c0f3aa3916890a333e85 | [
"MIT"
] | null | null | null | #include "skin_change_req_handler.h"
#include "allocator.h"
#include "character.h"
#include "spawn_system.h"
#include "entity_provider.h"
#include "player_manager.h"
#include <algorithm>
#include <array>
namespace jc
{
SkinChangeRequestHandler::SkinChangeRequestHandler()
{
static std::once_flag _once;
std::call_once(_once, [&] {
m_provider = (CEntityProvider *)jc::_alloc(sizeof(CEntityProvider));
hk::func_call<void>(0x14025F860, m_provider); // CEntityProvider::CEntityProvider
// setup
m_provider->m_resourceCache = CSpawnSystem::instance().m_resourceCache;
m_provider->m_priority = 1; // high
m_provider->m_streamerPriority = 4; // very high
// @NOTE: Because all the models are cached and shared, they will also use the same skeleton lookup which will
// cause visual artifacts with random peds. Because the rbi_info struct is unique to each CModelInstance, we can
// switch the skeleton lookup before the skin batches are drawn, and switch back to the original after to
// prevent this from happening. magic.
static hk::inject_jump<void, jc::CModelRenderBlock *, void *, void *, bool> DrawSkinBatches(0x140D1A150);
DrawSkinBatches.inject(
[](jc::CModelRenderBlock *render_block, void *render_context, void *rbi_info, bool unknown) {
int16_t *original_skeleton_lookup = nullptr;
{
std::lock_guard<std::mutex> lk{jc::SkeletonLookup::Get()->m_mutex};
const auto skeleton_lookup = &jc::SkeletonLookup::Get()->m_lookup;
const auto find_it = skeleton_lookup->find(rbi_info);
// set the custom skeleton lookup before render
if (find_it != skeleton_lookup->end()) {
const auto &lookup = (*find_it);
const auto it = lookup.second.find(render_block);
if (it != lookup.second.end() && (*it).second != nullptr) {
original_skeleton_lookup = render_block->m_mesh->m_skeletonLookup;
render_block->m_mesh->m_skeletonLookup = (*it).second;
}
}
}
DrawSkinBatches.call(render_block, render_context, rbi_info, unknown);
// restore the original skeleton lookup after render
if (original_skeleton_lookup) {
render_block->m_mesh->m_skeletonLookup = original_skeleton_lookup;
}
});
});
}
void SkinChangeRequestHandler::Request(CSharedString &resource_path, std::function<void(const CRuntimeContainer *)> fn)
{
// @TODO: some kind of cancel if we already requested something?
// will there ever be a situation where another skin is requested before
// the current one is spawned?
m_callback = fn;
// CEntityProvider::LoadResources
hk::func_call<void>(0x140284870, m_provider, &resource_path);
}
void SkinChangeRequestHandler::Update()
{
#if 0
constexpr std::array available_models = {
"civ_alpine_scientist_female",
"civ_alpine_scientist_male",
"civ_scientist_female",
"civ_scientist_male",
"civ_alpine_worker_female_01",
"civ_alpine_worker_male_01",
"civ_node_hacker_male_01",
"civ_node_hacker_male_02",
"civ_node_hacker_male_03",
"civ_node_hacker_male_04",
"civ_techengineer_female",
"civ_techengineer_male",
"civ_miner_male",
"civ_construction_worker_female_01",
"civ_construction_worker_male_01",
"civ_lumberyard_female_01",
"civ_lumberyard_male_01",
"civ_mechanic_female_01",
"civ_mechanic_male_01",
"civ_steelworker_female_01",
"civ_steelworker_male_01",
"civ_evil_target_female_01",
"civ_evil_target_male_01",
"civ_garland_crew_female_01",
"civ_garland_crew_male_01",
"civ_garland_location_scout_001",
"civ_garland_pa_001",
"civ_garland_pa_male_01",
"civ_garland_stuntperson_helmet_female_01",
"civ_garland_stuntperson_helmet_male_01",
"civ_javi_soldier_001",
"civ_javi_soldier_full_body",
"civ_sargento_soldier_female_01",
"civ_sargento_soldier_male_01",
"civ_prisoner_female",
"civ_prisoner_male",
"civ_bolo_santosi_01",
"civ_brrd_male_01",
"civ_greenman_female_01",
"civ_greenman_male_01",
"civ_rome_male_01",
"civ_beachgoer_female_01",
"civ_beachgoer_male_01",
"civ_dockworker_female_01",
"civ_dockworker_male_01",
"civ_favela_female_01",
"civ_favela_male_01",
"civ_rainforest_female_01",
"civ_rainforest_male_01",
"civ_desert_female_01",
"civ_desert_male_01",
"civ_grasslands_female_01",
"civ_grasslands_male_01",
"civ_business_female_001",
"civ_business_male_001",
"civ_vagrant_female_001",
"civ_vagrant_male_001",
"civ_athletic_female_001",
"civ_athletic_male_001",
"civ_soccer_aa_female_01",
"civ_soccer_aa_male_01",
"civ_soccer_esp_female_01",
"civ_soccer_esp_male_01",
"civ_soccer_female_001",
"civ_soccer_male_001",
"civ_upperclass_female_01",
"civ_upperclass_male_01",
"civ_farmer_female_01",
"civ_farmer_male_01",
"civ_bartender_female_01",
"civ_bartender_male_01",
"civ_airport_worker_female_01",
"civ_airport_worker_male_01",
"civ_art_vendor_female_01",
"civ_art_vendor_male_01",
"civ_factory_worker_female_01",
"civ_factory_worker_male_01",
"civ_food_vendor_female_01",
"civ_food_vendor_male_01",
"civ_gas_station_female_01",
"civ_gas_station_male_01",
"civ_graffitiartist_female_01",
"civ_graffitiartist_male_01",
"civ_street_musician_female_01",
"civ_street_musician_male_01",
// Base game - Rebels
"sargentos_rebel_female_01",
"sargentos_rebel_female_02",
"sargentos_rebel_female_03",
"sargentos_rebel_male_01",
"sargentos_rebel_male_02",
"sargentos_rebel_male_03",
"female_rebel_001",
"female_rebel_002",
"female_rebel_003",
"female_rebel_004",
"female_rebel_prisoner_01",
"female_rebel_prisoner_02",
"female_rebel_prisoner_03",
"female_rebel_tier_1_01",
"female_rebel_tier_1_02",
"female_rebel_tier_1_03",
"female_rebel_tier_2_01",
"female_rebel_tier_2_02",
"female_rebel_tier_2_03",
"female_rebel_tier_3_01",
"female_rebel_tier_3_02",
"female_rebel_tier_3_03",
"male_rebel_001",
"male_rebel_002",
"male_rebel_003",
"male_rebel_004",
"male_rebel_prisoner_01",
"male_rebel_prisoner_02",
"male_rebel_prisoner_03",
"male_rebel_tier_1_01",
"male_rebel_tier_1_02",
"male_rebel_tier_1_03",
"male_rebel_tier_1_04",
"male_rebel_tier_2_01",
"male_rebel_tier_2_02",
"male_rebel_tier_2_03",
"male_rebel_tier_2_04",
"male_rebel_tier_3_01",
"male_rebel_tier_3_02",
"male_rebel_tier_3_03",
"male_rebel_tier_3_04",
// Base game - Main characters
"civ_female_aha_dancer_follower",
"cesar",
"editor/entities/characters/main_characters/dictator.ee",
"editor/entities/characters/main_characters/dictator_guard.ee",
"gabriela",
"garland",
"izzy",
"javi",
"lanza",
"editor/entities/characters/main_characters/miguel_rodriguez.ee",
"mira",
"oscar",
"editor/entities/characters/main_characters/oscar_young.ee",
"sargento",
"sheldon",
// Base game - Characters
"private_enemy_001",
"private_enemy_002",
"elite_enemy_001",
"elite_paratrooper",
"super_elite_enemy_001",
"titan_enemy_001",
"ghost_enemy_001",
"grenadier_enemy_001",
"machinegunner_enemy_001",
"rpg_enemy_001",
"shielder_enemy_001",
"sniper_enemy_001",
};
#if 1
static auto last_change = std::chrono::system_clock::now() + std::chrono::seconds(10);
static auto next_id = -1;
auto character = jc::CPlayerManager::GetLocalPlayerCharacter();
if (character && last_change < std::chrono::system_clock::now()) {
last_change = std::chrono::system_clock::now() + std::chrono::seconds(5);
std::vector<jc::CSpawnSystem::SResourceDef *, jc::allocator<jc::CSpawnSystem::SResourceDef *>> resources;
next_id++;
if (next_id >= available_models.size()) {
next_id = 0;
}
OutputDebugStringA(available_models[next_id]);
OutputDebugStringA("\n");
if (jc::CSpawnSystem::instance().GetMatchingResources(available_models[next_id], &resources)) {
assert(!resources.empty());
character->ChangeSkin(resources[0]->m_resourcePath, [] {
last_change = std::chrono::system_clock::now() + std::chrono::milliseconds(500);
});
} else {
OutputDebugStringA(" - NO MATCHING RESOURCES.\n");
}
}
#endif
#endif
// CEntityProvider::UpdateInternal
hk::func_call<void>(
0x140294F20, m_provider, this,
(entity_provider_callback_t)[](void *puser) {
auto request_handler = (SkinChangeRequestHandler *)puser;
assert(request_handler->m_provider->m_entityResourceLoader);
request_handler->m_callback((jc::CRuntimeContainer *)&request_handler->m_provider->m_entityResourceLoader
->m_propertyContainer->m_base);
},
(entity_provider_callback_t)[](void *puser) {
#ifdef _DEBUG
// spawn failed!
__debugbreak();
#endif
});
}
static std::array kBoneMappingsRico = {
std::pair<uint32_t, uint32_t>{2394094972, 0}, std::pair<uint32_t, uint32_t>{1252689883, 1},
std::pair<uint32_t, uint32_t>{1489289568, 2}, std::pair<uint32_t, uint32_t>{4084831349, 3},
std::pair<uint32_t, uint32_t>{3477960784, 4}, std::pair<uint32_t, uint32_t>{3223761349, 5},
std::pair<uint32_t, uint32_t>{1555958995, 6}, std::pair<uint32_t, uint32_t>{1459912489, 7},
std::pair<uint32_t, uint32_t>{2576446000, 8}, std::pair<uint32_t, uint32_t>{4129665182, 9},
std::pair<uint32_t, uint32_t>{3366567460, 10}, std::pair<uint32_t, uint32_t>{1108521370, 11},
std::pair<uint32_t, uint32_t>{3143544379, 12}, std::pair<uint32_t, uint32_t>{3685314612, 13},
std::pair<uint32_t, uint32_t>{2900729280, 14}, std::pair<uint32_t, uint32_t>{1203626394, 15},
std::pair<uint32_t, uint32_t>{1227774589, 16}, std::pair<uint32_t, uint32_t>{914656450, 17},
std::pair<uint32_t, uint32_t>{2633462918, 18}, std::pair<uint32_t, uint32_t>{1748179293, 19},
std::pair<uint32_t, uint32_t>{1141701893, 20}, std::pair<uint32_t, uint32_t>{2395612961, 21},
std::pair<uint32_t, uint32_t>{519011590, 22}, std::pair<uint32_t, uint32_t>{3970182939, 23},
std::pair<uint32_t, uint32_t>{994889083, 24}, std::pair<uint32_t, uint32_t>{4125003590, 25},
std::pair<uint32_t, uint32_t>{3242100449, 26}, std::pair<uint32_t, uint32_t>{1108266938, 27},
std::pair<uint32_t, uint32_t>{1926223301, 28}, std::pair<uint32_t, uint32_t>{661265071, 29},
std::pair<uint32_t, uint32_t>{3066825915, 30}, std::pair<uint32_t, uint32_t>{912916643, 31},
std::pair<uint32_t, uint32_t>{2317283342, 32}, std::pair<uint32_t, uint32_t>{3441638405, 33},
std::pair<uint32_t, uint32_t>{2760225489, 34}, std::pair<uint32_t, uint32_t>{3964175071, 35},
std::pair<uint32_t, uint32_t>{2752631666, 36}, std::pair<uint32_t, uint32_t>{100325420, 37},
std::pair<uint32_t, uint32_t>{1491560446, 38}, std::pair<uint32_t, uint32_t>{516832345, 39},
std::pair<uint32_t, uint32_t>{1252046159, 40}, std::pair<uint32_t, uint32_t>{4033932099, 41},
std::pair<uint32_t, uint32_t>{2639211572, 42}, std::pair<uint32_t, uint32_t>{1233549747, 43},
std::pair<uint32_t, uint32_t>{2224513931, 44}, std::pair<uint32_t, uint32_t>{2758980529, 45},
std::pair<uint32_t, uint32_t>{2695123779, 46}, std::pair<uint32_t, uint32_t>{2965608343, 47},
std::pair<uint32_t, uint32_t>{2193546120, 48}, std::pair<uint32_t, uint32_t>{2860814395, 49},
std::pair<uint32_t, uint32_t>{1308091062, 50}, std::pair<uint32_t, uint32_t>{1470279966, 51},
std::pair<uint32_t, uint32_t>{3360101082, 52}, std::pair<uint32_t, uint32_t>{2438260305, 53},
std::pair<uint32_t, uint32_t>{2923024671, 54}, std::pair<uint32_t, uint32_t>{455640735, 55},
std::pair<uint32_t, uint32_t>{3081454700, 56}, std::pair<uint32_t, uint32_t>{2580095936, 57},
std::pair<uint32_t, uint32_t>{2796181772, 58}, std::pair<uint32_t, uint32_t>{3959365138, 59},
std::pair<uint32_t, uint32_t>{1858091382, 60}, std::pair<uint32_t, uint32_t>{1674505706, 61},
std::pair<uint32_t, uint32_t>{3404332141, 62}, std::pair<uint32_t, uint32_t>{175240702, 63},
std::pair<uint32_t, uint32_t>{3536936145, 64}, std::pair<uint32_t, uint32_t>{3768499, 65},
std::pair<uint32_t, uint32_t>{3179998832, 66}, std::pair<uint32_t, uint32_t>{4120908208, 67},
std::pair<uint32_t, uint32_t>{1413498797, 68}, std::pair<uint32_t, uint32_t>{3403576838, 69},
std::pair<uint32_t, uint32_t>{2550461854, 70}, std::pair<uint32_t, uint32_t>{3416507533, 71},
std::pair<uint32_t, uint32_t>{1518475483, 72}, std::pair<uint32_t, uint32_t>{165729162, 73},
std::pair<uint32_t, uint32_t>{3267328078, 74}, std::pair<uint32_t, uint32_t>{1565745466, 75},
std::pair<uint32_t, uint32_t>{973873416, 76}, std::pair<uint32_t, uint32_t>{2222924337, 77},
std::pair<uint32_t, uint32_t>{3915943525, 78}, std::pair<uint32_t, uint32_t>{3794447476, 79},
std::pair<uint32_t, uint32_t>{724613817, 80}, std::pair<uint32_t, uint32_t>{1425464583, 81},
std::pair<uint32_t, uint32_t>{1467550696, 82}, std::pair<uint32_t, uint32_t>{2190797639, 83},
std::pair<uint32_t, uint32_t>{586670052, 84}, std::pair<uint32_t, uint32_t>{3370773187, 85},
std::pair<uint32_t, uint32_t>{2725811682, 86}, std::pair<uint32_t, uint32_t>{2544362859, 87},
std::pair<uint32_t, uint32_t>{859145367, 88}, std::pair<uint32_t, uint32_t>{529012006, 89},
std::pair<uint32_t, uint32_t>{3908814753, 90}, std::pair<uint32_t, uint32_t>{1592734258, 91},
std::pair<uint32_t, uint32_t>{1187820986, 92}, std::pair<uint32_t, uint32_t>{2077283755, 93},
std::pair<uint32_t, uint32_t>{1256173202, 94}, std::pair<uint32_t, uint32_t>{1654913162, 95},
std::pair<uint32_t, uint32_t>{3451757196, 96}, std::pair<uint32_t, uint32_t>{3794315760, 97},
std::pair<uint32_t, uint32_t>{2731679068, 98}, std::pair<uint32_t, uint32_t>{291412610, 99},
std::pair<uint32_t, uint32_t>{3805473304, 100}, std::pair<uint32_t, uint32_t>{3897936212, 101},
std::pair<uint32_t, uint32_t>{3023242332, 102}, std::pair<uint32_t, uint32_t>{560388075, 103},
std::pair<uint32_t, uint32_t>{1348953638, 104}, std::pair<uint32_t, uint32_t>{3689970757, 105},
std::pair<uint32_t, uint32_t>{405273388, 106}, std::pair<uint32_t, uint32_t>{3920139427, 107},
std::pair<uint32_t, uint32_t>{3874020345, 108}, std::pair<uint32_t, uint32_t>{1186717741, 109},
std::pair<uint32_t, uint32_t>{4052933939, 110}, std::pair<uint32_t, uint32_t>{2858741845, 111},
std::pair<uint32_t, uint32_t>{4137047442, 112}, std::pair<uint32_t, uint32_t>{3076404574, 113},
std::pair<uint32_t, uint32_t>{33194846, 114}, std::pair<uint32_t, uint32_t>{1565985537, 115},
std::pair<uint32_t, uint32_t>{552428061, 116}, std::pair<uint32_t, uint32_t>{2334448475, 117},
std::pair<uint32_t, uint32_t>{196868699, 118}, std::pair<uint32_t, uint32_t>{3041309387, 119},
std::pair<uint32_t, uint32_t>{1017860219, 120}, std::pair<uint32_t, uint32_t>{2055766129, 121},
std::pair<uint32_t, uint32_t>{3159852471, 122}, std::pair<uint32_t, uint32_t>{3473275293, 123},
std::pair<uint32_t, uint32_t>{1513462622, 124}, std::pair<uint32_t, uint32_t>{575268596, 125},
std::pair<uint32_t, uint32_t>{2392783451, 126}, std::pair<uint32_t, uint32_t>{3658374521, 127},
std::pair<uint32_t, uint32_t>{1621410674, 128}, std::pair<uint32_t, uint32_t>{567513068, 129},
std::pair<uint32_t, uint32_t>{3410833543, 130}, std::pair<uint32_t, uint32_t>{740730292, 131},
std::pair<uint32_t, uint32_t>{1831608258, 132}, std::pair<uint32_t, uint32_t>{2543190806, 133},
std::pair<uint32_t, uint32_t>{1320882368, 134}, std::pair<uint32_t, uint32_t>{1129663262, 135},
std::pair<uint32_t, uint32_t>{1083769543, 136}, std::pair<uint32_t, uint32_t>{1770750798, 137},
std::pair<uint32_t, uint32_t>{1307941776, 138}, std::pair<uint32_t, uint32_t>{3690742995, 139},
std::pair<uint32_t, uint32_t>{1668646018, 140}, std::pair<uint32_t, uint32_t>{3943696337, 141},
std::pair<uint32_t, uint32_t>{4175912225, 142}, std::pair<uint32_t, uint32_t>{967579856, 143},
std::pair<uint32_t, uint32_t>{956949182, 144}, std::pair<uint32_t, uint32_t>{2453029768, 145},
std::pair<uint32_t, uint32_t>{380016446, 146}, std::pair<uint32_t, uint32_t>{4221697845, 147},
std::pair<uint32_t, uint32_t>{1649197646, 148}, std::pair<uint32_t, uint32_t>{1125105860, 149},
std::pair<uint32_t, uint32_t>{2111592436, 150}, std::pair<uint32_t, uint32_t>{342908061, 151},
std::pair<uint32_t, uint32_t>{3803182815, 152}, std::pair<uint32_t, uint32_t>{3130931077, 153},
std::pair<uint32_t, uint32_t>{3995526818, 154}, std::pair<uint32_t, uint32_t>{3909468794, 155},
std::pair<uint32_t, uint32_t>{3905299996, 156}, std::pair<uint32_t, uint32_t>{802760491, 157},
std::pair<uint32_t, uint32_t>{1410227229, 158}, std::pair<uint32_t, uint32_t>{2715072942, 159},
std::pair<uint32_t, uint32_t>{2420269632, 160}, std::pair<uint32_t, uint32_t>{4197176223, 161},
std::pair<uint32_t, uint32_t>{3868652464, 162}, std::pair<uint32_t, uint32_t>{264702988, 163},
std::pair<uint32_t, uint32_t>{1954358957, 164}, std::pair<uint32_t, uint32_t>{54318578, 165},
std::pair<uint32_t, uint32_t>{574463303, 166}, std::pair<uint32_t, uint32_t>{1390825376, 167},
std::pair<uint32_t, uint32_t>{1854359826, 168}, std::pair<uint32_t, uint32_t>{1459217846, 169},
std::pair<uint32_t, uint32_t>{663512083, 170}, std::pair<uint32_t, uint32_t>{2445592106, 171},
std::pair<uint32_t, uint32_t>{4286418273, 172}, std::pair<uint32_t, uint32_t>{4118819487, 173},
std::pair<uint32_t, uint32_t>{578106827, 174}, std::pair<uint32_t, uint32_t>{761738650, 175},
std::pair<uint32_t, uint32_t>{3479324205, 176}, std::pair<uint32_t, uint32_t>{3471724469, 177},
std::pair<uint32_t, uint32_t>{2687883648, 178}, std::pair<uint32_t, uint32_t>{1140707517, 179},
std::pair<uint32_t, uint32_t>{2144407270, 180}, std::pair<uint32_t, uint32_t>{1019608705, 181},
std::pair<uint32_t, uint32_t>{793140648, 182}, std::pair<uint32_t, uint32_t>{1088841951, 183},
std::pair<uint32_t, uint32_t>{2666929011, 184}, std::pair<uint32_t, uint32_t>{2791220655, 185},
std::pair<uint32_t, uint32_t>{3251617740, 186}, std::pair<uint32_t, uint32_t>{1998472915, 187},
std::pair<uint32_t, uint32_t>{843322903, 188}, std::pair<uint32_t, uint32_t>{2915928333, 189},
std::pair<uint32_t, uint32_t>{1126173219, 190}, std::pair<uint32_t, uint32_t>{2127212215, 191},
std::pair<uint32_t, uint32_t>{1981159028, 192}, std::pair<uint32_t, uint32_t>{4044845400, 193},
std::pair<uint32_t, uint32_t>{3053108164, 194}, std::pair<uint32_t, uint32_t>{1194293737, 195},
std::pair<uint32_t, uint32_t>{1880966197, 196}, std::pair<uint32_t, uint32_t>{553268143, 197},
std::pair<uint32_t, uint32_t>{921735734, 198}, std::pair<uint32_t, uint32_t>{103199345, 199},
std::pair<uint32_t, uint32_t>{3781048348, 200}, std::pair<uint32_t, uint32_t>{722113249, 201},
std::pair<uint32_t, uint32_t>{426185881, 202}, std::pair<uint32_t, uint32_t>{1646043647, 203},
std::pair<uint32_t, uint32_t>{1530280872, 204}, std::pair<uint32_t, uint32_t>{3807281547, 205},
std::pair<uint32_t, uint32_t>{3136087302, 206}, std::pair<uint32_t, uint32_t>{165669168, 207},
std::pair<uint32_t, uint32_t>{1655909510, 208}, std::pair<uint32_t, uint32_t>{1984075092, 209},
std::pair<uint32_t, uint32_t>{2211922494, 210}, std::pair<uint32_t, uint32_t>{2289082043, 211},
std::pair<uint32_t, uint32_t>{747680433, 212}, std::pair<uint32_t, uint32_t>{1221183753, 213},
std::pair<uint32_t, uint32_t>{3915181747, 214}, std::pair<uint32_t, uint32_t>{1741560029, 215},
std::pair<uint32_t, uint32_t>{2073368859, 216}, std::pair<uint32_t, uint32_t>{709778699, 217},
std::pair<uint32_t, uint32_t>{2713945292, 218}, std::pair<uint32_t, uint32_t>{1087663378, 219},
std::pair<uint32_t, uint32_t>{2741324850, 220}, std::pair<uint32_t, uint32_t>{2619108735, 221},
std::pair<uint32_t, uint32_t>{1063276332, 222}, std::pair<uint32_t, uint32_t>{2737431107, 223},
std::pair<uint32_t, uint32_t>{870802327, 224}, std::pair<uint32_t, uint32_t>{2160032645, 225},
std::pair<uint32_t, uint32_t>{3329358717, 226}, std::pair<uint32_t, uint32_t>{2836032339, 227},
std::pair<uint32_t, uint32_t>{4223045062, 228}, std::pair<uint32_t, uint32_t>{485621676, 229},
std::pair<uint32_t, uint32_t>{863510078, 230}, std::pair<uint32_t, uint32_t>{3641685623, 231},
std::pair<uint32_t, uint32_t>{37904559, 232}, std::pair<uint32_t, uint32_t>{3443459293, 233},
std::pair<uint32_t, uint32_t>{2975848301, 234}, std::pair<uint32_t, uint32_t>{3645907746, 235},
std::pair<uint32_t, uint32_t>{2112223537, 236}, std::pair<uint32_t, uint32_t>{578833067, 237},
std::pair<uint32_t, uint32_t>{2576307509, 238}, std::pair<uint32_t, uint32_t>{4095443743, 239},
std::pair<uint32_t, uint32_t>{2594570093, 240}, std::pair<uint32_t, uint32_t>{3615785407, 241},
std::pair<uint32_t, uint32_t>{766926689, 242}, std::pair<uint32_t, uint32_t>{661848656, 243},
std::pair<uint32_t, uint32_t>{2011225857, 244}, std::pair<uint32_t, uint32_t>{1514792347, 245},
std::pair<uint32_t, uint32_t>{1474535392, 246}, std::pair<uint32_t, uint32_t>{1180683473, 247},
std::pair<uint32_t, uint32_t>{1567288207, 248}, std::pair<uint32_t, uint32_t>{1297945330, 249},
std::pair<uint32_t, uint32_t>{2438248688, 250}, std::pair<uint32_t, uint32_t>{2513859035, 251},
std::pair<uint32_t, uint32_t>{2046502109, 252}, std::pair<uint32_t, uint32_t>{3473331380, 253},
std::pair<uint32_t, uint32_t>{297408201, 254}, std::pair<uint32_t, uint32_t>{102891694, 255},
std::pair<uint32_t, uint32_t>{3217444895, 256}, std::pair<uint32_t, uint32_t>{1059203173, 257},
std::pair<uint32_t, uint32_t>{2636662382, 258}, std::pair<uint32_t, uint32_t>{288226583, 259},
std::pair<uint32_t, uint32_t>{2139603822, 260}, std::pair<uint32_t, uint32_t>{2310005779, 261},
std::pair<uint32_t, uint32_t>{3914499528, 262}, std::pair<uint32_t, uint32_t>{174621028, 263},
std::pair<uint32_t, uint32_t>{4025642426, 264}, std::pair<uint32_t, uint32_t>{3563732574, 265},
std::pair<uint32_t, uint32_t>{2413216009, 266}, std::pair<uint32_t, uint32_t>{2733242987, 267},
std::pair<uint32_t, uint32_t>{2494648254, 268}, std::pair<uint32_t, uint32_t>{990827083, 269},
std::pair<uint32_t, uint32_t>{3232932980, 270}, std::pair<uint32_t, uint32_t>{448731402, 271},
std::pair<uint32_t, uint32_t>{3942931707, 272}, std::pair<uint32_t, uint32_t>{2956600658, 273},
std::pair<uint32_t, uint32_t>{1495018146, 274}, std::pair<uint32_t, uint32_t>{20824016, 275},
std::pair<uint32_t, uint32_t>{2224549021, 276}, std::pair<uint32_t, uint32_t>{866849826, 277},
std::pair<uint32_t, uint32_t>{2620792770, 278}, std::pair<uint32_t, uint32_t>{3727732900, 279},
std::pair<uint32_t, uint32_t>{3491236634, 280}, std::pair<uint32_t, uint32_t>{2271170787, 281},
std::pair<uint32_t, uint32_t>{743077609, 282}, std::pair<uint32_t, uint32_t>{254324665, 283},
std::pair<uint32_t, uint32_t>{1105106875, 284}, std::pair<uint32_t, uint32_t>{2616271571, 285},
};
static std::array kBoneMappingsWorldSim = {
std::pair<uint32_t, uint32_t>{2394094972, 0}, std::pair<uint32_t, uint32_t>{1252689883, 1},
std::pair<uint32_t, uint32_t>{1489289568, 2}, std::pair<uint32_t, uint32_t>{4084831349, 3},
std::pair<uint32_t, uint32_t>{3477960784, 4}, std::pair<uint32_t, uint32_t>{3223761349, 5},
std::pair<uint32_t, uint32_t>{1555958995, 6}, std::pair<uint32_t, uint32_t>{1459912489, 7},
std::pair<uint32_t, uint32_t>{4129665182, 8}, std::pair<uint32_t, uint32_t>{3366567460, 9},
std::pair<uint32_t, uint32_t>{1108521370, 10}, std::pair<uint32_t, uint32_t>{1227774589, 11},
std::pair<uint32_t, uint32_t>{1141701893, 12}, std::pair<uint32_t, uint32_t>{4125003590, 13},
std::pair<uint32_t, uint32_t>{2451919769, 14}, std::pair<uint32_t, uint32_t>{330130356, 15},
std::pair<uint32_t, uint32_t>{455640735, 16}, std::pair<uint32_t, uint32_t>{3370773187, 17},
std::pair<uint32_t, uint32_t>{912916643, 18}, std::pair<uint32_t, uint32_t>{100325420, 19},
std::pair<uint32_t, uint32_t>{4120908208, 20}, std::pair<uint32_t, uint32_t>{1491560446, 21},
std::pair<uint32_t, uint32_t>{1413498797, 22}, std::pair<uint32_t, uint32_t>{2639211572, 23},
std::pair<uint32_t, uint32_t>{1518475483, 24}, std::pair<uint32_t, uint32_t>{3023242332, 25},
std::pair<uint32_t, uint32_t>{560388075, 26}, std::pair<uint32_t, uint32_t>{1348953638, 27},
std::pair<uint32_t, uint32_t>{3689970757, 28}, std::pair<uint32_t, uint32_t>{3920139427, 29},
std::pair<uint32_t, uint32_t>{3874020345, 30}, std::pair<uint32_t, uint32_t>{1186717741, 31},
std::pair<uint32_t, uint32_t>{4052933939, 32}, std::pair<uint32_t, uint32_t>{2858741845, 33},
std::pair<uint32_t, uint32_t>{4137047442, 34}, std::pair<uint32_t, uint32_t>{2334448475, 35},
std::pair<uint32_t, uint32_t>{196868699, 36}, std::pair<uint32_t, uint32_t>{3041309387, 37},
std::pair<uint32_t, uint32_t>{1513462622, 38}, std::pair<uint32_t, uint32_t>{575268596, 39},
std::pair<uint32_t, uint32_t>{3658374521, 40}, std::pair<uint32_t, uint32_t>{567513068, 41},
std::pair<uint32_t, uint32_t>{740730292, 42}, std::pair<uint32_t, uint32_t>{1831608258, 43},
std::pair<uint32_t, uint32_t>{2453029768, 44}, std::pair<uint32_t, uint32_t>{380016446, 45},
std::pair<uint32_t, uint32_t>{4221697845, 46}, std::pair<uint32_t, uint32_t>{1649197646, 47},
std::pair<uint32_t, uint32_t>{2111592436, 48}, std::pair<uint32_t, uint32_t>{342908061, 49},
std::pair<uint32_t, uint32_t>{3803182815, 50}, std::pair<uint32_t, uint32_t>{3130931077, 51},
std::pair<uint32_t, uint32_t>{3995526818, 52}, std::pair<uint32_t, uint32_t>{3909468794, 53},
std::pair<uint32_t, uint32_t>{2420269632, 54}, std::pair<uint32_t, uint32_t>{4197176223, 55},
std::pair<uint32_t, uint32_t>{3868652464, 56}, std::pair<uint32_t, uint32_t>{1390825376, 57},
std::pair<uint32_t, uint32_t>{1854359826, 58}, std::pair<uint32_t, uint32_t>{663512083, 59},
std::pair<uint32_t, uint32_t>{2445592106, 60}, std::pair<uint32_t, uint32_t>{4118819487, 61},
std::pair<uint32_t, uint32_t>{578106827, 62}, std::pair<uint32_t, uint32_t>{3053108164, 63},
std::pair<uint32_t, uint32_t>{3645907746, 64}, std::pair<uint32_t, uint32_t>{2112223537, 65},
std::pair<uint32_t, uint32_t>{578833067, 66}, std::pair<uint32_t, uint32_t>{2576307509, 67},
std::pair<uint32_t, uint32_t>{4095443743, 68}, std::pair<uint32_t, uint32_t>{3615785407, 69},
std::pair<uint32_t, uint32_t>{1180683473, 70}, std::pair<uint32_t, uint32_t>{2513859035, 71},
std::pair<uint32_t, uint32_t>{2046502109, 72}, std::pair<uint32_t, uint32_t>{3473331380, 73},
std::pair<uint32_t, uint32_t>{297408201, 74}, std::pair<uint32_t, uint32_t>{3217444895, 75},
std::pair<uint32_t, uint32_t>{3563732574, 76}, std::pair<uint32_t, uint32_t>{3914499528, 77},
std::pair<uint32_t, uint32_t>{2956600658, 78}, std::pair<uint32_t, uint32_t>{20824016, 79},
std::pair<uint32_t, uint32_t>{2224549021, 80}, std::pair<uint32_t, uint32_t>{866849826, 81},
std::pair<uint32_t, uint32_t>{3727732900, 82}, std::pair<uint32_t, uint32_t>{3491236634, 83},
std::pair<uint32_t, uint32_t>{2271170787, 84}, std::pair<uint32_t, uint32_t>{743077609, 85},
};
void SkeletonLookup::Make(void *rbi_info, CModelRenderBlock *render_block)
{
assert(render_block && render_block->m_mesh);
auto skeleton_lookup = render_block->m_mesh->m_skeletonLookup;
auto lookup_size = render_block->m_mesh->m_skeletonLookupSize;
assert(skeleton_lookup);
assert(lookup_size > 0);
// copy to new skeleton lookup
auto mapped_skeleton_lookup = (int16_t *)jc::_alloc(lookup_size * sizeof(int16_t));
assert(mapped_skeleton_lookup);
memcpy(mapped_skeleton_lookup, skeleton_lookup, (lookup_size * sizeof(int16_t)));
// remap the skeleton bone indices
// Credits to @xforce for the original JC3MP implementation.
for (int32_t n = 0; n < lookup_size; ++n) {
auto source_index = mapped_skeleton_lookup[n];
uint32_t source_hash = 0;
for (auto &&world_sim_map : kBoneMappingsWorldSim) {
if (world_sim_map.second == static_cast<uint32_t>(source_index)) {
source_hash = world_sim_map.first;
break;
}
}
if (source_hash != 0) {
for (auto &&rico_map : kBoneMappingsRico) {
if (rico_map.first == source_hash) {
mapped_skeleton_lookup[n] = static_cast<int16_t>(rico_map.second);
break;
}
}
} else {
mapped_skeleton_lookup[n] = 0;
}
}
std::lock_guard<std::mutex> lk{m_mutex};
m_lookup[rbi_info][render_block] = mapped_skeleton_lookup;
}
void SkeletonLookup::Empty()
{
std::lock_guard<std::mutex> lk{m_mutex};
for (auto &&lookup : m_lookup) {
for (auto &&entry : lookup.second) {
jc::_free(entry.second);
entry.second = nullptr;
}
}
m_lookup.clear();
}
}; // namespace jc
| 56.788104 | 120 | 0.677501 | [
"render",
"vector"
] |
a7ab1357428f5c7c035f961674125ce4487c9918 | 62,675 | cc | C++ | chrome/browser/web_applications/web_app_icon_manager_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | chrome/browser/web_applications/web_app_icon_manager_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | chrome/browser/web_applications/web_app_icon_manager_unittest.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/web_applications/web_app_icon_manager.h"
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include "base/callback_helpers.h"
#include "base/containers/contains.h"
#include "base/files/file_enumerator.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/web_applications/components/web_app_constants.h"
#include "chrome/browser/web_applications/components/web_app_helpers.h"
#include "chrome/browser/web_applications/components/web_app_icon_generator.h"
#include "chrome/browser/web_applications/components/web_app_utils.h"
#include "chrome/browser/web_applications/components/web_application_info.h"
#include "chrome/browser/web_applications/test/test_file_utils.h"
#include "chrome/browser/web_applications/test/test_web_app_database_factory.h"
#include "chrome/browser/web_applications/test/test_web_app_registry_controller.h"
#include "chrome/browser/web_applications/test/web_app_icon_test_utils.h"
#include "chrome/browser/web_applications/test/web_app_test.h"
#include "chrome/browser/web_applications/web_app.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/browser/web_applications/web_app_registry_update.h"
#include "chrome/browser/web_applications/web_app_sync_bridge.h"
#include "chrome/common/chrome_features.h"
#include "chrome/test/base/testing_profile.h"
#include "extensions/common/constants.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/layout.h"
#include "ui/base/resource/scale_factor.h"
#include "ui/gfx/favicon_size.h"
namespace web_app {
namespace {
using IconSizeAndPurpose = AppIconManager::IconSizeAndPurpose;
} // namespace
class WebAppIconManagerTest : public WebAppTest {
void SetUp() override {
WebAppTest::SetUp();
test_registry_controller_ =
std::make_unique<TestWebAppRegistryController>();
test_registry_controller_->SetUp(profile());
auto file_utils = std::make_unique<TestFileUtils>();
file_utils_ = file_utils.get();
icon_manager_ = std::make_unique<WebAppIconManager>(profile(), registrar(),
std::move(file_utils));
controller().Init();
}
protected:
struct GeneratedIconsInfo {
IconPurpose purpose;
std::vector<SquareSizePx> sizes_px;
std::vector<SkColor> colors;
};
void WriteGeneratedIcons(const AppId& app_id,
const std::vector<GeneratedIconsInfo>& icons_info) {
IconBitmaps icon_bitmaps;
for (const GeneratedIconsInfo& info : icons_info) {
DCHECK_EQ(info.sizes_px.size(), info.colors.size());
std::map<SquareSizePx, SkBitmap> generated_bitmaps;
for (size_t i = 0; i < info.sizes_px.size(); ++i)
AddGeneratedIcon(&generated_bitmaps, info.sizes_px[i], info.colors[i]);
icon_bitmaps.SetBitmapsForPurpose(info.purpose,
std::move(generated_bitmaps));
}
base::RunLoop run_loop;
icon_manager_->WriteData(app_id, std::move(icon_bitmaps),
base::BindLambdaForTesting([&](bool success) {
EXPECT_TRUE(success);
run_loop.Quit();
}));
run_loop.Run();
}
void WriteGeneratedShortcutsMenuIcons(
const AppId& app_id,
const std::vector<GeneratedIconsInfo>& icons_info,
int num_menu_items) {
ShortcutsMenuIconBitmaps shortcuts_menu_icons;
for (int i = 0; i < num_menu_items; ++i) {
IconBitmaps menu_item_icon_map;
for (const GeneratedIconsInfo& info : icons_info) {
DCHECK_EQ(info.sizes_px.size(), info.colors.size());
std::map<SquareSizePx, SkBitmap> generated_bitmaps;
for (size_t i = 0; i < info.sizes_px.size(); ++i)
AddGeneratedIcon(&generated_bitmaps, info.sizes_px[i],
info.colors[i]);
menu_item_icon_map.SetBitmapsForPurpose(info.purpose,
std::move(generated_bitmaps));
}
shortcuts_menu_icons.push_back(std::move(menu_item_icon_map));
}
base::RunLoop run_loop;
icon_manager_->WriteShortcutsMenuIconsData(
app_id, std::move(shortcuts_menu_icons),
base::BindLambdaForTesting([&](bool success) {
EXPECT_TRUE(success);
run_loop.Quit();
}));
run_loop.Run();
}
ShortcutsMenuIconBitmaps ReadAllShortcutsMenuIcons(const AppId& app_id) {
ShortcutsMenuIconBitmaps result;
base::RunLoop run_loop;
icon_manager().ReadAllShortcutsMenuIcons(
app_id, base::BindLambdaForTesting(
[&](ShortcutsMenuIconBitmaps shortcuts_menu_icons_map) {
result = std::move(shortcuts_menu_icons_map);
run_loop.Quit();
}));
run_loop.Run();
return result;
}
// Returns a list of downloaded sizes for the menu indexed by menu item
// number.
std::vector<IconSizes> CreateDownloadedShortcutsMenuIconsSizes(
const std::vector<SquareSizePx>& sizes_any,
const std::vector<SquareSizePx>& sizes_maskable,
const std::vector<SquareSizePx>& sizes_monochrome,
int num_menu_items) {
std::vector<IconSizes> downloaded_shortcuts_menu_icons_sizes;
for (int i = 0; i < num_menu_items; ++i) {
IconSizes icon_sizes;
for (IconPurpose purpose : kIconPurposes) {
switch (purpose) {
case IconPurpose::ANY:
icon_sizes.SetSizesForPurpose(purpose, sizes_any);
break;
case IconPurpose::MASKABLE:
icon_sizes.SetSizesForPurpose(purpose, sizes_maskable);
break;
case IconPurpose::MONOCHROME:
icon_sizes.SetSizesForPurpose(purpose, sizes_monochrome);
break;
}
}
downloaded_shortcuts_menu_icons_sizes.push_back(std::move(icon_sizes));
}
return downloaded_shortcuts_menu_icons_sizes;
}
struct PurposeAndBitmap {
IconPurpose purpose;
SkBitmap bitmap;
};
PurposeAndBitmap ReadSmallestIcon(const AppId& app_id,
const std::vector<IconPurpose>& purposes,
SquareSizePx min_icon_size) {
PurposeAndBitmap result;
base::RunLoop run_loop;
icon_manager().ReadSmallestIcon(
app_id, purposes, min_icon_size,
base::BindLambdaForTesting(
[&](IconPurpose purpose, const SkBitmap& bitmap) {
result.purpose = purpose;
result.bitmap = bitmap;
run_loop.Quit();
}));
run_loop.Run();
return result;
}
SkBitmap ReadSmallestIconAny(const AppId& app_id,
SquareSizePx min_icon_size) {
SkBitmap result;
base::RunLoop run_loop;
icon_manager().ReadSmallestIconAny(
app_id, min_icon_size,
base::BindLambdaForTesting([&](const SkBitmap& bitmap) {
result = bitmap;
run_loop.Quit();
}));
run_loop.Run();
return result;
}
struct PurposeAndData {
IconPurpose purpose;
std::vector<uint8_t> data;
};
PurposeAndData ReadSmallestCompressedIcon(
const AppId& app_id,
const std::vector<IconPurpose>& purposes,
int min_size_in_px) {
EXPECT_TRUE(
icon_manager().HasSmallestIcon(app_id, purposes, min_size_in_px));
PurposeAndData result;
base::RunLoop run_loop;
icon_manager().ReadSmallestCompressedIcon(
app_id, purposes, min_size_in_px,
base::BindLambdaForTesting(
[&](IconPurpose purpose, std::vector<uint8_t> data) {
result.purpose = purpose;
result.data = std::move(data);
run_loop.Quit();
}));
run_loop.Run();
return result;
}
SkColor ReadIconAndResize(const AppId& app_id,
IconPurpose purpose,
int desired_icon_size) {
base::RunLoop run_loop;
SkColor icon_color = SK_ColorBLACK;
icon_manager().ReadIconAndResize(
app_id, purpose, desired_icon_size,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(1u, icon_bitmaps.size());
SkBitmap bitmap = icon_bitmaps[desired_icon_size];
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(desired_icon_size, bitmap.width());
EXPECT_EQ(desired_icon_size, bitmap.height());
icon_color = bitmap.getColor(0, 0);
run_loop.Quit();
}));
run_loop.Run();
return icon_color;
}
SkColor ReadIconAndResize(const AppId& app_id, int desired_icon_size) {
return ReadIconAndResize(app_id, IconPurpose::ANY, desired_icon_size);
}
std::unique_ptr<WebApp> CreateWebApp() {
const GURL app_url = GURL("https://example.com/path");
const AppId app_id = GenerateAppIdFromURL(app_url);
auto web_app = std::make_unique<WebApp>(app_id);
web_app->AddSource(Source::kSync);
web_app->SetDisplayMode(DisplayMode::kStandalone);
web_app->SetUserDisplayMode(DisplayMode::kStandalone);
web_app->SetName("Name");
web_app->SetStartUrl(app_url);
return web_app;
}
void StartIconManagerWaitFavicon(const AppId& app_id) {
base::RunLoop run_loop;
icon_manager().SetFaviconReadCallbackForTesting(
base::BindLambdaForTesting([&](const AppId& cached_app_id) {
EXPECT_EQ(cached_app_id, app_id);
run_loop.Quit();
}));
icon_manager().Start();
run_loop.Run();
}
void StartIconManagerWaitFaviconMonochrome(const AppId& app_id) {
base::RunLoop run_loop;
icon_manager().SetFaviconMonochromeReadCallbackForTesting(
base::BindLambdaForTesting([&](const AppId& cached_app_id) {
EXPECT_EQ(cached_app_id, app_id);
run_loop.Quit();
}));
icon_manager().Start();
run_loop.Run();
}
TestWebAppRegistryController& controller() {
return *test_registry_controller_;
}
WebAppRegistrar& registrar() { return controller().registrar(); }
WebAppSyncBridge& sync_bridge() { return controller().sync_bridge(); }
WebAppIconManager& icon_manager() { return *icon_manager_; }
TestFileUtils& file_utils() {
DCHECK(file_utils_);
return *file_utils_;
}
private:
std::unique_ptr<TestWebAppRegistryController> test_registry_controller_;
std::unique_ptr<WebAppIconManager> icon_manager_;
// Owned by icon_manager_:
TestFileUtils* file_utils_ = nullptr;
};
TEST_F(WebAppIconManagerTest, WriteAndReadIcons_AnyOnly) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
EXPECT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px));
{
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::ANY, sizes_px,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(2u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[icon_size::k256].empty());
EXPECT_EQ(SK_ColorGREEN,
icon_bitmaps[icon_size::k256].getColor(0, 0));
EXPECT_FALSE(icon_bitmaps[icon_size::k512].empty());
EXPECT_EQ(SK_ColorYELLOW,
icon_bitmaps[icon_size::k512].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
EXPECT_FALSE(
icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, sizes_px));
}
TEST_F(WebAppIconManagerTest, WriteAndReadIcons_MaskableOnly) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW};
WriteGeneratedIcons(app_id, {{IconPurpose::MASKABLE, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, sizes_px);
controller().RegisterApp(std::move(web_app));
EXPECT_FALSE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px));
EXPECT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, sizes_px));
{
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::MASKABLE, sizes_px,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(2u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[icon_size::k256].empty());
EXPECT_EQ(SK_ColorGREEN,
icon_bitmaps[icon_size::k256].getColor(0, 0));
EXPECT_FALSE(icon_bitmaps[icon_size::k512].empty());
EXPECT_EQ(SK_ColorYELLOW,
icon_bitmaps[icon_size::k512].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
}
TEST_F(WebAppIconManagerTest, WriteAndReadIcons_MonochromeOnly) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k128, icon_size::k256};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorTRANSPARENT};
WriteGeneratedIcons(app_id, {{IconPurpose::MONOCHROME, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::MONOCHROME, sizes_px);
controller().RegisterApp(std::move(web_app));
EXPECT_FALSE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px));
EXPECT_FALSE(
icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, sizes_px));
EXPECT_TRUE(
icon_manager().HasIcons(app_id, IconPurpose::MONOCHROME, sizes_px));
{
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::MONOCHROME, sizes_px,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(2u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[icon_size::k128].empty());
EXPECT_EQ(SK_ColorGREEN,
icon_bitmaps[icon_size::k128].getColor(0, 0));
EXPECT_FALSE(icon_bitmaps[icon_size::k256].empty());
EXPECT_EQ(SK_ColorTRANSPARENT,
icon_bitmaps[icon_size::k256].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
}
TEST_F(WebAppIconManagerTest, WriteAndReadIcons_AnyAndMaskable) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, sizes_px);
controller().RegisterApp(std::move(web_app));
EXPECT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px));
{
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::ANY, sizes_px,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(2u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[icon_size::k256].empty());
EXPECT_EQ(SK_ColorGREEN,
icon_bitmaps[icon_size::k256].getColor(0, 0));
EXPECT_FALSE(icon_bitmaps[icon_size::k512].empty());
EXPECT_EQ(SK_ColorYELLOW,
icon_bitmaps[icon_size::k512].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
EXPECT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, sizes_px));
{
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::MASKABLE, sizes_px,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(2u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[icon_size::k256].empty());
EXPECT_EQ(SK_ColorGREEN,
icon_bitmaps[icon_size::k256].getColor(0, 0));
EXPECT_FALSE(icon_bitmaps[icon_size::k512].empty());
EXPECT_EQ(SK_ColorYELLOW,
icon_bitmaps[icon_size::k512].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
}
TEST_F(WebAppIconManagerTest, WriteAndReadIcons_AnyAndMonochrome) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px_any{icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors_any{SK_ColorGREEN, SK_ColorYELLOW};
const std::vector<int> sizes_px_monochrome{icon_size::k64, icon_size::k128};
const std::vector<SkColor> colors_monochrome{SK_ColorRED, SK_ColorBLUE};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px_any, colors_any},
{IconPurpose::MONOCHROME, sizes_px_monochrome,
colors_monochrome}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px_any);
web_app->SetDownloadedIconSizes(IconPurpose::MONOCHROME, sizes_px_monochrome);
controller().RegisterApp(std::move(web_app));
EXPECT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, sizes_px_any));
EXPECT_FALSE(icon_manager().HasIcons(app_id, IconPurpose::MASKABLE,
sizes_px_monochrome));
{
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::ANY, sizes_px_any,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(2u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[icon_size::k256].empty());
EXPECT_EQ(SK_ColorGREEN,
icon_bitmaps[icon_size::k256].getColor(0, 0));
EXPECT_FALSE(icon_bitmaps[icon_size::k512].empty());
EXPECT_EQ(SK_ColorYELLOW,
icon_bitmaps[icon_size::k512].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
EXPECT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::MONOCHROME,
sizes_px_monochrome));
{
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::MONOCHROME, sizes_px_monochrome,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(2u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[icon_size::k64].empty());
EXPECT_EQ(SK_ColorRED,
icon_bitmaps[icon_size::k64].getColor(0, 0));
EXPECT_FALSE(icon_bitmaps[icon_size::k128].empty());
EXPECT_EQ(SK_ColorBLUE,
icon_bitmaps[icon_size::k128].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
}
TEST_F(WebAppIconManagerTest, OverwriteIcons) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
// Write initial red icons to be overwritten.
{
std::vector<int> sizes_px{icon_size::k32, icon_size::k64, icon_size::k48};
const std::vector<SkColor> colors{SK_ColorRED, SK_ColorRED, SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, std::move(sizes_px));
}
controller().RegisterApp(std::move(web_app));
// k64 and k48 sizes to be overwritten. Skip k32 size and add new k96 size.
const std::vector<int> overwritten_sizes_px{icon_size::k48, icon_size::k64,
icon_size::k96};
{
IconBitmaps icon_bitmaps;
for (int size_px : overwritten_sizes_px) {
icon_bitmaps.any[size_px] = CreateSquareIcon(size_px, SK_ColorGREEN);
icon_bitmaps.maskable[size_px] = CreateSquareIcon(size_px, SK_ColorBLUE);
}
base::RunLoop run_loop;
// Overwrite red icons with green and blue ones.
icon_manager().WriteData(app_id, std::move(icon_bitmaps),
base::BindLambdaForTesting([&](bool success) {
EXPECT_TRUE(success);
run_loop.Quit();
}));
run_loop.Run();
ScopedRegistryUpdate update(&controller().sync_bridge());
update->UpdateApp(app_id)->SetDownloadedIconSizes(IconPurpose::ANY,
overwritten_sizes_px);
update->UpdateApp(app_id)->SetDownloadedIconSizes(IconPurpose::MASKABLE,
overwritten_sizes_px);
}
// Check that all IconPurpose::ANY icons are now green. Check that all red
// icons were deleted on disk (including the k32 size).
{
base::FilePath icons_dir = GetAppIconsAnyDir(profile(), app_id);
std::vector<int> sizes_on_disk_px;
base::FileEnumerator enumerator_any(icons_dir, true,
base::FileEnumerator::FILES);
for (base::FilePath path = enumerator_any.Next(); !path.empty();
path = enumerator_any.Next()) {
EXPECT_TRUE(path.MatchesExtension(FILE_PATH_LITERAL(".png")));
SkBitmap bitmap;
EXPECT_TRUE(ReadBitmap(&file_utils(), path, &bitmap));
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(bitmap.width(), bitmap.height());
EXPECT_EQ(SK_ColorGREEN, bitmap.getColor(0, 0));
sizes_on_disk_px.push_back(bitmap.width());
}
std::sort(sizes_on_disk_px.begin(), sizes_on_disk_px.end());
EXPECT_EQ(overwritten_sizes_px, sizes_on_disk_px);
}
// Check that all IconPurpose::Maskable icons are now blue. Check that all red
// icons were deleted on disk (including the k32 size).
{
base::FilePath icons_dir = GetAppIconsMaskableDir(profile(), app_id);
std::vector<int> sizes_on_disk_px;
base::FileEnumerator enumerator_maskable(icons_dir, true,
base::FileEnumerator::FILES);
for (base::FilePath path = enumerator_maskable.Next(); !path.empty();
path = enumerator_maskable.Next()) {
EXPECT_TRUE(path.MatchesExtension(FILE_PATH_LITERAL(".png")));
SkBitmap bitmap;
EXPECT_TRUE(ReadBitmap(&file_utils(), path, &bitmap));
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(bitmap.width(), bitmap.height());
EXPECT_EQ(SK_ColorBLUE, bitmap.getColor(0, 0));
sizes_on_disk_px.push_back(bitmap.width());
}
std::sort(sizes_on_disk_px.begin(), sizes_on_disk_px.end());
EXPECT_EQ(overwritten_sizes_px, sizes_on_disk_px);
}
}
TEST_F(WebAppIconManagerTest, ReadAllIcons_AnyOnly) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
{
base::RunLoop run_loop;
icon_manager().ReadAllIcons(
app_id, base::BindLambdaForTesting([&](IconBitmaps icons_map) {
EXPECT_FALSE(icons_map.empty());
EXPECT_EQ(2u, icons_map.any.size());
EXPECT_EQ(colors[0], icons_map.any[sizes_px[0]].getColor(0, 0));
EXPECT_EQ(colors[1], icons_map.any[sizes_px[1]].getColor(0, 0));
EXPECT_EQ(0u, icons_map.maskable.size());
run_loop.Quit();
}));
run_loop.Run();
}
}
TEST_F(WebAppIconManagerTest, ReadAllIcons_AnyAndMaskable) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorYELLOW};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, sizes_px);
controller().RegisterApp(std::move(web_app));
{
base::RunLoop run_loop;
icon_manager().ReadAllIcons(
app_id, base::BindLambdaForTesting([&](IconBitmaps icons_map) {
EXPECT_FALSE(icons_map.empty());
EXPECT_EQ(2u, icons_map.any.size());
EXPECT_EQ(colors[0], icons_map.any[sizes_px[0]].getColor(0, 0));
EXPECT_EQ(colors[1], icons_map.any[sizes_px[1]].getColor(0, 0));
EXPECT_EQ(2u, icons_map.maskable.size());
EXPECT_EQ(colors[0], icons_map.maskable[sizes_px[0]].getColor(0, 0));
EXPECT_EQ(colors[1], icons_map.maskable[sizes_px[1]].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
}
TEST_F(WebAppIconManagerTest, ReadShortcutsMenuIconsFailed) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<SquareSizePx> sizes_px_any{icon_size::k96, icon_size::k256};
// Set shortcuts menu icons meta-info but don't write bitmaps to disk.
web_app->SetDownloadedShortcutsMenuIconsSizes(
CreateDownloadedShortcutsMenuIconsSizes(sizes_px_any,
/*sizes_maskable=*/{},
/*sizes_monochrome=*/{},
/*num_menu_items=*/10));
controller().RegisterApp(std::move(web_app));
// Request shortcuts menu icons which don't exist on disk.
ShortcutsMenuIconBitmaps shortcuts_menu_icons_map =
ReadAllShortcutsMenuIcons(app_id);
EXPECT_EQ(10u, shortcuts_menu_icons_map.size());
for (const auto& icon_map : shortcuts_menu_icons_map) {
EXPECT_TRUE(icon_map.empty());
}
}
TEST_F(WebAppIconManagerTest, WriteAndReadAllShortcutsMenuIcons) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const int num_menu_items = 3;
const std::vector<int> sizes_any = {icon_size::k64, icon_size::k128,
icon_size::k256};
const std::vector<SkColor> colors_any = {SK_ColorRED, SK_ColorWHITE,
SK_ColorBLUE};
const std::vector<int> sizes_maskable = {icon_size::k64, icon_size::k96,
icon_size::k128};
const std::vector<SkColor> colors_maskable = {SK_ColorCYAN, SK_ColorMAGENTA,
SK_ColorYELLOW};
const std::vector<int> sizes_monochrome = {icon_size::k64, icon_size::k96,
icon_size::k128};
const std::vector<SkColor> colors_monochrome = {SK_ColorGREEN, SK_ColorBLACK,
SK_ColorTRANSPARENT};
WriteGeneratedShortcutsMenuIcons(
app_id,
{{IconPurpose::ANY, sizes_any, colors_any},
{IconPurpose::MASKABLE, sizes_maskable, colors_maskable},
{IconPurpose::MONOCHROME, sizes_monochrome, colors_monochrome}},
num_menu_items);
web_app->SetDownloadedShortcutsMenuIconsSizes(
CreateDownloadedShortcutsMenuIconsSizes(
sizes_any, sizes_maskable, sizes_monochrome, num_menu_items));
controller().RegisterApp(std::move(web_app));
ShortcutsMenuIconBitmaps shortcuts_menu_icons_map =
ReadAllShortcutsMenuIcons(app_id);
EXPECT_EQ(3u, shortcuts_menu_icons_map.size());
for (int i = 0; i < num_menu_items; ++i) {
for (IconPurpose purpose : kIconPurposes) {
SCOPED_TRACE(purpose);
const std::vector<int>* expect_sizes;
const std::vector<SkColor>* expect_colors;
switch (purpose) {
case IconPurpose::ANY:
expect_sizes = &sizes_any;
expect_colors = &colors_any;
break;
case IconPurpose::MASKABLE:
expect_sizes = &sizes_maskable;
expect_colors = &colors_maskable;
break;
case IconPurpose::MONOCHROME:
expect_sizes = &sizes_monochrome;
expect_colors = &colors_monochrome;
break;
}
const std::map<SquareSizePx, SkBitmap>& icon_bitmaps =
shortcuts_menu_icons_map[i].GetBitmapsForPurpose(purpose);
ASSERT_EQ(expect_sizes->size(), expect_colors->size());
for (unsigned s = 0; s < expect_sizes->size(); ++s) {
const SquareSizePx size_px = (*expect_sizes)[s];
const auto& size_and_bitmap = icon_bitmaps.find(size_px);
ASSERT_TRUE(size_and_bitmap != icon_bitmaps.end());
EXPECT_EQ((*expect_colors)[s], size_and_bitmap->second.getColor(0, 0));
}
}
}
}
TEST_F(WebAppIconManagerTest, WriteShortcutsMenuIconsEmptyMap) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
web_app->SetDownloadedShortcutsMenuIconsSizes(std::vector<IconSizes>{});
controller().RegisterApp(std::move(web_app));
ShortcutsMenuIconBitmaps shortcuts_menu_icons;
base::RunLoop run_loop;
icon_manager().WriteShortcutsMenuIconsData(
app_id, std::move(shortcuts_menu_icons),
base::BindLambdaForTesting([&](bool success) {
EXPECT_FALSE(success);
run_loop.Quit();
}));
run_loop.Run();
// Make sure that nothing was written to disk.
ShortcutsMenuIconBitmaps shortcuts_menu_icons_map =
ReadAllShortcutsMenuIcons(app_id);
EXPECT_EQ(0u, shortcuts_menu_icons_map.size());
}
TEST_F(WebAppIconManagerTest, ReadIconsFailed) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<SquareSizePx> icon_sizes_px{icon_size::k256};
// Set icon meta-info but don't write bitmap to disk.
web_app->SetDownloadedIconSizes(IconPurpose::ANY, icon_sizes_px);
controller().RegisterApp(std::move(web_app));
EXPECT_FALSE(
icon_manager().HasIcons(app_id, IconPurpose::ANY, {icon_size::k96}));
EXPECT_TRUE(
icon_manager().HasIcons(app_id, IconPurpose::ANY, {icon_size::k256}));
EXPECT_FALSE(icon_manager().HasIcons(app_id, IconPurpose::ANY,
{icon_size::k96, icon_size::k256}));
// Request existing icon size which doesn't exist on disk.
base::RunLoop run_loop;
icon_manager().ReadIcons(
app_id, IconPurpose::ANY, icon_sizes_px,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_TRUE(icon_bitmaps.empty());
run_loop.Quit();
}));
run_loop.Run();
}
TEST_F(WebAppIconManagerTest, FindExact) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{10, 60, 50, 20, 30};
const std::vector<SkColor> colors{SK_ColorRED, SK_ColorYELLOW, SK_ColorGREEN,
SK_ColorBLUE, SK_ColorMAGENTA};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
EXPECT_FALSE(icon_manager().HasIcons(app_id, IconPurpose::ANY, {40}));
EXPECT_FALSE(icon_manager().HasIcons(app_id, IconPurpose::MASKABLE, {20}));
{
base::RunLoop run_loop;
EXPECT_TRUE(icon_manager().HasIcons(app_id, IconPurpose::ANY, {20}));
icon_manager().ReadIcons(
app_id, IconPurpose::ANY, {20},
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_EQ(1u, icon_bitmaps.size());
EXPECT_FALSE(icon_bitmaps[20].empty());
EXPECT_EQ(SK_ColorBLUE, icon_bitmaps[20].getColor(0, 0));
run_loop.Quit();
}));
run_loop.Run();
}
}
// Simple struct doesn't have an operator==.
bool operator==(const IconSizeAndPurpose& a, const IconSizeAndPurpose& b) {
return a.size_px == b.size_px && a.purpose == b.purpose;
}
TEST_F(WebAppIconManagerTest, FindSmallest) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{10, 60, 50, 20, 30};
const std::vector<SkColor> colors{SK_ColorRED, SK_ColorYELLOW, SK_ColorGREEN,
SK_ColorBLUE, SK_ColorMAGENTA};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
// Pretend we only have one size of maskable icon.
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, {20});
controller().RegisterApp(std::move(web_app));
EXPECT_FALSE(icon_manager().HasSmallestIcon(app_id, {IconPurpose::ANY}, 70));
EXPECT_EQ(absl::nullopt,
icon_manager().FindIconMatchBigger(app_id, {IconPurpose::ANY}, 70));
EXPECT_FALSE(icon_manager().HasSmallestIcon(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, 70));
EXPECT_EQ(absl::nullopt,
icon_manager().FindIconMatchBigger(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, 70));
EXPECT_FALSE(
icon_manager().HasSmallestIcon(app_id, {IconPurpose::MASKABLE}, 40));
EXPECT_EQ(absl::nullopt, icon_manager().FindIconMatchBigger(
app_id, {IconPurpose::MASKABLE}, 40));
EXPECT_TRUE(icon_manager().HasSmallestIcon(
app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, 40));
EXPECT_EQ((IconSizeAndPurpose{50, IconPurpose::ANY}),
icon_manager()
.FindIconMatchBigger(
app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, 40)
.value());
EXPECT_TRUE(icon_manager().HasSmallestIcon(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, 20));
EXPECT_EQ((IconSizeAndPurpose{20, IconPurpose::ANY}),
icon_manager()
.FindIconMatchBigger(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, 20)
.value());
EXPECT_TRUE(icon_manager().HasSmallestIcon(
app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, 10));
EXPECT_EQ((IconSizeAndPurpose{20, IconPurpose::MASKABLE}),
icon_manager()
.FindIconMatchBigger(
app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, 10)
.value());
{
EXPECT_TRUE(icon_manager().HasSmallestIcon(app_id, {IconPurpose::ANY}, 40));
SkBitmap bitmap = ReadSmallestIconAny(app_id, 40);
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(SK_ColorGREEN, bitmap.getColor(0, 0));
}
{
EXPECT_TRUE(icon_manager().HasSmallestIcon(app_id, {IconPurpose::ANY}, 20));
SkBitmap bitmap = ReadSmallestIconAny(app_id, 20);
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(SK_ColorBLUE, bitmap.getColor(0, 0));
}
{
PurposeAndBitmap result =
ReadSmallestIcon(app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, 20);
EXPECT_FALSE(result.bitmap.empty());
EXPECT_EQ(IconPurpose::ANY, result.purpose);
EXPECT_EQ(SK_ColorBLUE, result.bitmap.getColor(0, 0));
}
{
PurposeAndBitmap result =
ReadSmallestIcon(app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, 20);
EXPECT_FALSE(result.bitmap.empty());
EXPECT_EQ(IconPurpose::MASKABLE, result.purpose);
EXPECT_EQ(SK_ColorBLUE, result.bitmap.getColor(0, 0));
}
}
TEST_F(WebAppIconManagerTest, DeleteData_Success) {
const AppId app1_id = GenerateAppIdFromURL(GURL("https://example.com/"));
const AppId app2_id = GenerateAppIdFromURL(GURL("https://example.org/"));
const std::vector<int> sizes_px{icon_size::k128};
const std::vector<SkColor> colors{SK_ColorMAGENTA};
WriteGeneratedIcons(app1_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
WriteGeneratedIcons(app2_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
const base::FilePath web_apps_root_directory =
GetWebAppsRootDirectory(profile());
const base::FilePath app1_dir =
GetManifestResourcesDirectoryForApp(web_apps_root_directory, app1_id);
const base::FilePath app2_dir =
GetManifestResourcesDirectoryForApp(web_apps_root_directory, app2_id);
EXPECT_TRUE(file_utils().DirectoryExists(app1_dir));
EXPECT_FALSE(file_utils().IsDirectoryEmpty(app1_dir));
EXPECT_TRUE(file_utils().DirectoryExists(app2_dir));
EXPECT_FALSE(file_utils().IsDirectoryEmpty(app2_dir));
base::RunLoop run_loop;
icon_manager().DeleteData(app2_id,
base::BindLambdaForTesting([&](bool success) {
EXPECT_TRUE(success);
run_loop.Quit();
}));
run_loop.Run();
base::FilePath manifest_resources_directory =
GetManifestResourcesDirectory(web_apps_root_directory);
EXPECT_TRUE(file_utils().DirectoryExists(manifest_resources_directory));
EXPECT_TRUE(file_utils().DirectoryExists(app1_dir));
EXPECT_FALSE(file_utils().IsDirectoryEmpty(app1_dir));
EXPECT_FALSE(file_utils().DirectoryExists(app2_dir));
}
TEST_F(WebAppIconManagerTest, DeleteData_Failure) {
const AppId app_id = GenerateAppIdFromURL(GURL("https://example.com/"));
file_utils().SetNextDeleteFileRecursivelyResult(false);
base::RunLoop run_loop;
icon_manager().DeleteData(app_id,
base::BindLambdaForTesting([&](bool success) {
EXPECT_FALSE(success);
run_loop.Quit();
}));
run_loop.Run();
}
TEST_F(WebAppIconManagerTest, ReadSmallestCompressedIcon_Success_AnyOnly) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k128};
const std::vector<SkColor> colors{SK_ColorGREEN};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
{
PurposeAndData result =
ReadSmallestCompressedIcon(app_id, {IconPurpose::ANY}, sizes_px[0]);
EXPECT_EQ(IconPurpose::ANY, result.purpose);
EXPECT_FALSE(result.data.empty());
}
{
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, sizes_px[0]);
EXPECT_EQ(IconPurpose::ANY, result.purpose);
EXPECT_FALSE(result.data.empty());
}
{
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, sizes_px[0]);
EXPECT_EQ(IconPurpose::ANY, result.purpose);
EXPECT_FALSE(result.data.empty());
}
}
TEST_F(WebAppIconManagerTest, ReadSmallestCompressedIcon_Success) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k64, icon_size::k128};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorGREEN};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
int size_smaller = icon_size::k64;
int size_larger = icon_size::k128;
// Lie about available icon sizes so any/maskable have different sizes.
web_app->SetDownloadedIconSizes(IconPurpose::ANY, {size_smaller});
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, {size_larger});
controller().RegisterApp(std::move(web_app));
{
PurposeAndData result =
ReadSmallestCompressedIcon(app_id, {IconPurpose::ANY}, size_smaller);
EXPECT_EQ(IconPurpose::ANY, result.purpose);
EXPECT_FALSE(result.data.empty());
auto* data_ptr = reinterpret_cast<const char*>(result.data.data());
// Check that |compressed_data| starts with the 8-byte PNG magic string.
std::string png_magic_string{data_ptr, 8};
EXPECT_EQ(png_magic_string, "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a");
}
{
// Maskable returned when purpose specified.
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::MASKABLE}, size_larger);
EXPECT_EQ(IconPurpose::MASKABLE, result.purpose);
EXPECT_FALSE(result.data.empty());
}
{
// Maskable returned even though size doesn't exactly match.
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::MASKABLE}, size_smaller);
EXPECT_EQ(IconPurpose::MASKABLE, result.purpose);
EXPECT_FALSE(result.data.empty());
}
{
// Any returned because it is first in purposes.
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, size_smaller);
EXPECT_EQ(IconPurpose::ANY, result.purpose);
EXPECT_FALSE(result.data.empty());
}
{
// Maskable returned because it is the only one of sufficient size.
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, size_larger);
EXPECT_EQ(IconPurpose::MASKABLE, result.purpose);
EXPECT_FALSE(result.data.empty());
}
{
// Maskable returned because it is first in purposes.
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, size_smaller);
EXPECT_EQ(IconPurpose::MASKABLE, result.purpose);
EXPECT_FALSE(result.data.empty());
}
}
TEST_F(WebAppIconManagerTest, ReadSmallestCompressedIcon_Failure) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k64};
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, sizes_px);
controller().RegisterApp(std::move(web_app));
{
PurposeAndData result =
ReadSmallestCompressedIcon(app_id, {IconPurpose::ANY}, sizes_px[0]);
EXPECT_TRUE(result.data.empty());
}
{
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::MASKABLE}, sizes_px[0]);
EXPECT_TRUE(result.data.empty());
}
{
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::ANY, IconPurpose::MASKABLE}, sizes_px[0]);
EXPECT_TRUE(result.data.empty());
}
{
PurposeAndData result = ReadSmallestCompressedIcon(
app_id, {IconPurpose::MASKABLE, IconPurpose::ANY}, sizes_px[0]);
EXPECT_TRUE(result.data.empty());
}
}
TEST_F(WebAppIconManagerTest, ReadIconAndResize_Success_AnyOnly) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k32, icon_size::k64,
icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors{SK_ColorBLUE, SK_ColorGREEN, SK_ColorYELLOW,
SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
for (size_t i = 0; i < sizes_px.size(); ++i)
EXPECT_EQ(colors[i], ReadIconAndResize(app_id, sizes_px[i]));
// ReadIconAndResize should work for non-present icon sizes as long as an icon
// (with matching IconPurpose) is present. It should prefer shrinking over
// enlarging.
EXPECT_EQ(SK_ColorYELLOW, ReadIconAndResize(app_id, icon_size::k128));
EXPECT_EQ(SK_ColorBLUE, ReadIconAndResize(app_id, icon_size::k16));
EXPECT_EQ(SK_ColorRED, ReadIconAndResize(app_id, 1024));
// Maskable icons not found.
base::RunLoop run_loop;
icon_manager().ReadIconAndResize(
app_id, IconPurpose::MASKABLE, icon_size::k128,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_TRUE(icon_bitmaps.empty());
run_loop.Quit();
}));
run_loop.Run();
}
TEST_F(WebAppIconManagerTest, ReadIconAndResize_Success_AnyAndMaskable) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{icon_size::k32, icon_size::k64,
icon_size::k256, icon_size::k512};
const std::vector<SkColor> colors{SK_ColorBLUE, SK_ColorGREEN, SK_ColorYELLOW,
SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors},
{IconPurpose::MASKABLE, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE, sizes_px);
controller().RegisterApp(std::move(web_app));
for (size_t i = 0; i < sizes_px.size(); ++i) {
EXPECT_EQ(colors[i],
ReadIconAndResize(app_id, IconPurpose::ANY, sizes_px[i]));
}
for (size_t i = 0; i < sizes_px.size(); ++i) {
EXPECT_EQ(colors[i],
ReadIconAndResize(app_id, IconPurpose::MASKABLE, sizes_px[i]));
}
// ReadIconAndResize should work for non-present icon sizes as long as an icon
// (with matching IconPurpose) is present. It should prefer shrinking over
// enlarging.
EXPECT_EQ(SK_ColorYELLOW,
ReadIconAndResize(app_id, IconPurpose::ANY, icon_size::k128));
EXPECT_EQ(SK_ColorBLUE,
ReadIconAndResize(app_id, IconPurpose::ANY, icon_size::k16));
EXPECT_EQ(SK_ColorRED, ReadIconAndResize(app_id, IconPurpose::ANY, 1024));
EXPECT_EQ(SK_ColorYELLOW,
ReadIconAndResize(app_id, IconPurpose::MASKABLE, icon_size::k128));
EXPECT_EQ(SK_ColorBLUE,
ReadIconAndResize(app_id, IconPurpose::MASKABLE, icon_size::k16));
EXPECT_EQ(SK_ColorRED,
ReadIconAndResize(app_id, IconPurpose::MASKABLE, 1024));
}
TEST_F(WebAppIconManagerTest, ReadIconAndResize_Failure) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
web_app->SetDownloadedIconSizes(IconPurpose::ANY,
{icon_size::k32, icon_size::k64});
web_app->SetDownloadedIconSizes(IconPurpose::MASKABLE,
{icon_size::k32, icon_size::k64});
controller().RegisterApp(std::move(web_app));
{
base::RunLoop run_loop;
icon_manager().ReadIconAndResize(
app_id, IconPurpose::ANY, icon_size::k128,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_TRUE(icon_bitmaps.empty());
run_loop.Quit();
}));
run_loop.Run();
}
{
base::RunLoop run_loop;
icon_manager().ReadIconAndResize(
app_id, IconPurpose::MASKABLE, icon_size::k128,
base::BindLambdaForTesting(
[&](std::map<SquareSizePx, SkBitmap> icon_bitmaps) {
EXPECT_TRUE(icon_bitmaps.empty());
run_loop.Quit();
}));
run_loop.Run();
}
}
TEST_F(WebAppIconManagerTest, MatchSizes) {
EXPECT_EQ(kWebAppIconSmall, extension_misc::EXTENSION_ICON_SMALL);
}
TEST_F(WebAppIconManagerTest, CacheExistingAppFavicon) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{gfx::kFaviconSize, icon_size::k48};
const std::vector<SkColor> colors{SK_ColorGREEN, SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
SkBitmap bitmap = icon_manager().GetFavicon(app_id);
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(gfx::kFaviconSize, bitmap.width());
EXPECT_EQ(gfx::kFaviconSize, bitmap.height());
EXPECT_EQ(SK_ColorGREEN, bitmap.getColor(0, 0));
}
TEST_F(WebAppIconManagerTest, CacheAppFaviconWithResize) {
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
// App does not declare an icon of gfx::kFaviconSize, forcing a resize.
const std::vector<int> sizes_px{8, icon_size::k48, icon_size::k64};
ASSERT_FALSE(base::Contains(sizes_px, gfx::kFaviconSize));
const std::vector<SkColor> colors{SK_ColorBLACK, SK_ColorGREEN, SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
SkBitmap bitmap = icon_manager().GetFavicon(app_id);
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(gfx::kFaviconSize, bitmap.width());
EXPECT_EQ(gfx::kFaviconSize, bitmap.height());
// Correct size wasn't available so larger icon should be used.
EXPECT_EQ(SK_ColorGREEN, bitmap.getColor(0, 0));
}
TEST_F(WebAppIconManagerTest, CacheNewAppFavicon) {
icon_manager().Start();
auto web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
const std::vector<int> sizes_px{gfx::kFaviconSize, icon_size::k48};
const std::vector<SkColor> colors{SK_ColorBLUE, SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
base::RunLoop run_loop;
icon_manager().SetFaviconReadCallbackForTesting(
base::BindLambdaForTesting([&](const AppId& cached_app_id) {
EXPECT_EQ(cached_app_id, app_id);
run_loop.Quit();
}));
controller().RegisterApp(std::move(web_app));
registrar().NotifyWebAppInstalled(app_id);
run_loop.Run();
SkBitmap bitmap = icon_manager().GetFavicon(app_id);
EXPECT_FALSE(bitmap.empty());
EXPECT_EQ(gfx::kFaviconSize, bitmap.width());
EXPECT_EQ(gfx::kFaviconSize, bitmap.height());
EXPECT_EQ(SK_ColorBLUE, bitmap.getColor(0, 0));
}
TEST_F(WebAppIconManagerTest, CacheAppFavicon_UiScaleFactors_NoMissingIcons) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_200P, ui::SCALE_FACTOR_300P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
// App declares icons precisely matching suspported UI scale factors.
const std::vector<int> sizes_px{icon_size::k16, icon_size::k32,
icon_size::k64};
ASSERT_TRUE(base::Contains(sizes_px, gfx::kFaviconSize));
const std::vector<SkColor> colors{SK_ColorYELLOW, SK_ColorGREEN, SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
gfx::ImageSkia image_skia = icon_manager().GetFaviconImageSkia(app_id);
ASSERT_FALSE(image_skia.isNull());
EXPECT_EQ(gfx::kFaviconSize, image_skia.width());
EXPECT_EQ(gfx::kFaviconSize, image_skia.height());
{
SCOPED_TRACE(icon_size::k16);
ExpectImageSkiaRep(image_skia, /*scale=*/1.0f, /*size_px=*/icon_size::k16,
SK_ColorYELLOW);
}
{
SCOPED_TRACE(icon_size::k32);
ExpectImageSkiaRep(image_skia, /*scale=*/2.0f, /*size_px=*/icon_size::k32,
SK_ColorGREEN);
}
{
SCOPED_TRACE(icon_size::k48);
ExpectImageSkiaRep(image_skia, /*scale=*/3.0f, /*size_px=*/icon_size::k48,
SK_ColorRED);
}
}
TEST_F(WebAppIconManagerTest, CacheAppFavicon_UiScaleFactors_DownsizingIcons) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_200P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
// App declares only bigger icons, forcing a downsize to suspported UI scale
// factors.
const std::vector<int> sizes_px{icon_size::k24, icon_size::k48};
ASSERT_FALSE(base::Contains(sizes_px, gfx::kFaviconSize));
const std::vector<SkColor> colors{SK_ColorCYAN, SK_ColorMAGENTA};
WriteGeneratedIcons(app_id, {{IconPurpose::ANY, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
gfx::ImageSkia image_skia = icon_manager().GetFaviconImageSkia(app_id);
ASSERT_FALSE(image_skia.isNull());
EXPECT_EQ(gfx::kFaviconSize, image_skia.width());
EXPECT_EQ(gfx::kFaviconSize, image_skia.height());
{
SCOPED_TRACE(icon_size::k16);
ExpectImageSkiaRep(image_skia, /*scale=*/1.0f, /*size_px=*/icon_size::k16,
SK_ColorCYAN);
}
{
SCOPED_TRACE(icon_size::k32);
ExpectImageSkiaRep(image_skia, /*scale=*/2.0f, /*size_px=*/icon_size::k32,
SK_ColorMAGENTA);
}
}
TEST_F(WebAppIconManagerTest, CacheAppFavicon_UiScaleFactors_NoIcons) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_200P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
gfx::ImageSkia image_skia = icon_manager().GetFaviconImageSkia(app_id);
EXPECT_TRUE(image_skia.isNull());
}
TEST_F(WebAppIconManagerTest, CacheAppFavicon_UiScaleFactors_NoMatchSmaller) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_200P, ui::SCALE_FACTOR_300P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
// App declares only smaller icon and implementations ignore it: no upsizing.
const std::vector<int> sizes_px{icon_size::k16};
WriteGeneratedIcons(app_id,
{{IconPurpose::ANY, sizes_px, /*colors=*/{SK_ColorRED}}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
gfx::ImageSkia image_skia = icon_manager().GetFaviconImageSkia(app_id);
EXPECT_TRUE(image_skia.isNull());
}
TEST_F(WebAppIconManagerTest,
CacheAppFavicon_UiScaleFactors_DownsizingFromSingleIcon) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_200P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
// App declares only one jumbo icon.
const std::vector<int> sizes_px{icon_size::k512};
WriteGeneratedIcons(
app_id, {{IconPurpose::ANY, sizes_px, /*colors=*/{SK_ColorLTGRAY}}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
gfx::ImageSkia image_skia = icon_manager().GetFaviconImageSkia(app_id);
ASSERT_FALSE(image_skia.isNull());
EXPECT_EQ(gfx::kFaviconSize, image_skia.width());
EXPECT_EQ(gfx::kFaviconSize, image_skia.height());
{
SCOPED_TRACE(icon_size::k16);
ExpectImageSkiaRep(image_skia, /*scale=*/1.0f, /*size_px=*/icon_size::k16,
SK_ColorLTGRAY);
}
{
SCOPED_TRACE(icon_size::k32);
ExpectImageSkiaRep(image_skia, /*scale=*/2.0f, /*size_px=*/icon_size::k32,
SK_ColorLTGRAY);
}
}
TEST_F(WebAppIconManagerTest,
CacheAppFavicon_UiScaleFactors_BiggerUiScaleFactorIconMissing) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_300P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
// App declares the icon which is ok for 100P but small for 300P.
const std::vector<int> sizes_px{icon_size::k32};
WriteGeneratedIcons(
app_id, {{IconPurpose::ANY, sizes_px, /*colors=*/{SK_ColorDKGRAY}}});
web_app->SetDownloadedIconSizes(IconPurpose::ANY, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFavicon(app_id);
gfx::ImageSkia image_skia = icon_manager().GetFaviconImageSkia(app_id);
ASSERT_FALSE(image_skia.isNull());
EXPECT_EQ(gfx::kFaviconSize, image_skia.width());
EXPECT_EQ(gfx::kFaviconSize, image_skia.height());
{
SCOPED_TRACE(icon_size::k16);
ExpectImageSkiaRep(image_skia, /*scale=*/1.0f, /*size_px=*/icon_size::k16,
SK_ColorDKGRAY);
}
EXPECT_FALSE(image_skia.HasRepresentation(2.0f));
EXPECT_FALSE(image_skia.HasRepresentation(3.0f));
}
class WebAppIconManagerTest_NotificationIconAndTitle
: public WebAppIconManagerTest {
public:
WebAppIconManagerTest_NotificationIconAndTitle() {
scoped_feature_list_.InitAndEnableFeature(
features::kDesktopPWAsNotificationIconAndTitle);
}
base::test::ScopedFeatureList scoped_feature_list_;
};
TEST_F(WebAppIconManagerTest_NotificationIconAndTitle,
CacheAppMonochromeFavicon_NoMissingIcons) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_200P, ui::SCALE_FACTOR_300P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
web_app->SetThemeColor(absl::make_optional(SK_ColorBLUE));
const AppId app_id = web_app->app_id();
// App declares icons precisely matching suspported UI scale factors.
const std::vector<int> sizes_px{icon_size::k16, icon_size::k32,
icon_size::k64};
ASSERT_TRUE(base::Contains(sizes_px, gfx::kFaviconSize));
const std::vector<SkColor> colors{SK_ColorYELLOW, SK_ColorTRANSPARENT,
SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::MONOCHROME, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::MONOCHROME, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFaviconMonochrome(app_id);
gfx::ImageSkia monochrome_image = icon_manager().GetMonochromeFavicon(app_id);
ASSERT_FALSE(monochrome_image.isNull());
EXPECT_EQ(gfx::kFaviconSize, monochrome_image.width());
EXPECT_EQ(gfx::kFaviconSize, monochrome_image.height());
{
SCOPED_TRACE(icon_size::k16);
ExpectImageSkiaRep(monochrome_image, /*scale=*/1.0f,
/*size_px=*/icon_size::k16, SK_ColorBLUE);
}
{
SCOPED_TRACE(icon_size::k32);
ExpectImageSkiaRep(monochrome_image, /*scale=*/2.0f,
/*size_px=*/icon_size::k32, SK_ColorTRANSPARENT);
}
{
SCOPED_TRACE(icon_size::k48);
ExpectImageSkiaRep(monochrome_image, /*scale=*/3.0f,
/*size_px=*/icon_size::k48, SK_ColorBLUE);
}
}
TEST_F(WebAppIconManagerTest_NotificationIconAndTitle,
CacheAppMonochromeFavicon_CacheAfterAppInstall) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_200P, ui::SCALE_FACTOR_300P});
icon_manager().Start();
std::unique_ptr<WebApp> web_app = CreateWebApp();
web_app->SetThemeColor(absl::make_optional(SK_ColorGREEN));
const AppId app_id = web_app->app_id();
// App declares only one jumbo icon.
const std::vector<int> sizes_px{icon_size::k512};
const std::vector<SkColor> colors{SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::MONOCHROME, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::MONOCHROME, sizes_px);
base::RunLoop run_loop;
icon_manager().SetFaviconMonochromeReadCallbackForTesting(
base::BindLambdaForTesting([&](const AppId& cached_app_id) {
EXPECT_EQ(cached_app_id, app_id);
run_loop.Quit();
}));
controller().RegisterApp(std::move(web_app));
registrar().NotifyWebAppInstalled(app_id);
run_loop.Run();
gfx::ImageSkia monochrome_image = icon_manager().GetMonochromeFavicon(app_id);
ASSERT_FALSE(monochrome_image.isNull());
EXPECT_EQ(gfx::kFaviconSize, monochrome_image.width());
EXPECT_EQ(gfx::kFaviconSize, monochrome_image.height());
{
SCOPED_TRACE(icon_size::k32);
ExpectImageSkiaRep(monochrome_image, /*scale=*/2.0f,
/*size_px=*/icon_size::k32, SK_ColorGREEN);
}
{
SCOPED_TRACE(icon_size::k48);
ExpectImageSkiaRep(monochrome_image, /*scale=*/3.0f,
/*size_px=*/icon_size::k48, SK_ColorGREEN);
}
}
TEST_F(WebAppIconManagerTest_NotificationIconAndTitle,
CacheAppMonochromeFavicon_NoThemeColor) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_300P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
web_app->SetThemeColor(absl::nullopt);
const AppId app_id = web_app->app_id();
// Provides only SCALE_FACTOR_200P icon.
const std::vector<int> sizes_px{icon_size::k32};
const std::vector<SkColor> colors{SK_ColorRED};
WriteGeneratedIcons(app_id, {{IconPurpose::MONOCHROME, sizes_px, colors}});
web_app->SetDownloadedIconSizes(IconPurpose::MONOCHROME, sizes_px);
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFaviconMonochrome(app_id);
gfx::ImageSkia monochrome_image = icon_manager().GetMonochromeFavicon(app_id);
ASSERT_FALSE(monochrome_image.isNull());
EXPECT_EQ(gfx::kFaviconSize, monochrome_image.width());
EXPECT_EQ(gfx::kFaviconSize, monochrome_image.height());
{
SCOPED_TRACE(icon_size::k16);
ExpectImageSkiaRep(monochrome_image, /*scale=*/1.0f,
/*size_px=*/icon_size::k16, SK_ColorDKGRAY);
}
EXPECT_FALSE(monochrome_image.HasRepresentation(2.0));
EXPECT_FALSE(monochrome_image.HasRepresentation(3.0));
}
TEST_F(WebAppIconManagerTest_NotificationIconAndTitle,
CacheAppMonochromeFavicon_NoIcons) {
ui::test::ScopedSetSupportedScaleFactors scoped_scale_factors(
{ui::SCALE_FACTOR_100P, ui::SCALE_FACTOR_200P});
std::unique_ptr<WebApp> web_app = CreateWebApp();
const AppId app_id = web_app->app_id();
controller().RegisterApp(std::move(web_app));
StartIconManagerWaitFaviconMonochrome(app_id);
gfx::ImageSkia monochrome_image = icon_manager().GetMonochromeFavicon(app_id);
EXPECT_TRUE(monochrome_image.isNull());
}
} // namespace web_app
| 36.207395 | 82 | 0.678676 | [
"vector"
] |
a7ac9827f52fa10aed4ed717290b84c8df94d8ec | 1,362 | cpp | C++ | 15.cpp | zhangchbin/LeetRecord | 7f377b1a61e8f2a6fd86d028911c2722c1d03650 | [
"MIT"
] | 1 | 2020-09-12T07:38:23.000Z | 2020-09-12T07:38:23.000Z | 15.cpp | zhangchbin/LeetRecord | 7f377b1a61e8f2a6fd86d028911c2722c1d03650 | [
"MIT"
] | 1 | 2020-09-12T07:38:27.000Z | 2020-09-12T07:40:26.000Z | 15.cpp | zhangchbin/LeetRecord | 7f377b1a61e8f2a6fd86d028911c2722c1d03650 | [
"MIT"
] | null | null | null | class Solution {
public:
long long hash(vector<int>& pp){
return pp[0] * 100000LL + pp[1];
}
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n=nums.size();
vector<vector<int>>ans;
int dp[200100];
memset(dp, 0, sizeof(dp));
for(int i=0;i<n;i++) dp[nums[i]+100000] = 1;
map<long long, int> ma;
for(int i=0;i<n-2;i++){
if(nums[i] > 0) continue;
for(int j=i+1;j<n-1;j++){
int sum = nums[i] + nums[j];
if(sum > 0) continue;
if(-sum > nums[n-1]) continue;
if(-sum < nums[j+1]) continue;
int idx = -sum + 100000;
if(dp[idx]&&-sum>=nums[j]){
vector<int>tmp = vector<int>{nums[i], nums[j], -sum};
if(ma[hash(tmp)] == 0)
ans.push_back(tmp),
ma[hash(tmp)] = 1;
else continue;
}
//int pose = *lower_bound(nums.begin() + j+1, nums.end(), -sum);
//if(pose+sum == 0) ans.push_back(vector<int>{nums[i], nums[j], pose});
}
}
//sort(ans.begin(), ans.end());
//ans.erase(unique(ans.begin(), ans.end()), ans.end());
return ans;
}
};
| 34.923077 | 87 | 0.428781 | [
"vector"
] |
a7aecb87abba73b9cc5ff642e082bdf8828dae06 | 1,213 | cpp | C++ | src/LoggerAdapter.cpp | vitsh1974/fakranwallet | b368ba6dacc98e238cab3db445d54c579d795217 | [
"MIT"
] | null | null | null | src/LoggerAdapter.cpp | vitsh1974/fakranwallet | b368ba6dacc98e238cab3db445d54c579d795217 | [
"MIT"
] | null | null | null | src/LoggerAdapter.cpp | vitsh1974/fakranwallet | b368ba6dacc98e238cab3db445d54c579d795217 | [
"MIT"
] | null | null | null | // Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2015-2016 XDN developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "LoggerAdapter.h"
#include "Settings.h"
namespace WalletGui {
LoggerAdapter& LoggerAdapter::instance() {
static LoggerAdapter inst;
return inst;
}
void LoggerAdapter::init() {
Common::JsonValue loggerConfiguration(Common::JsonValue::OBJECT);
loggerConfiguration.insert("globalLevel", static_cast<int64_t>(Logging::INFO));
Common::JsonValue& cfgLoggers = loggerConfiguration.insert("loggers", Common::JsonValue::ARRAY);
Common::JsonValue& fileLogger = cfgLoggers.pushBack(Common::JsonValue::OBJECT);
fileLogger.insert("type", "file");
fileLogger.insert("filename", Settings::instance().getDataDir().absoluteFilePath("fakranwallet.log").toStdString());
fileLogger.insert("level", static_cast<int64_t>(Logging::INFO));
m_logManager.configure(loggerConfiguration);
}
LoggerAdapter::LoggerAdapter() : m_logManager() {
}
LoggerAdapter::~LoggerAdapter() {
}
Logging::LoggerManager& LoggerAdapter::getLoggerManager() {
return m_logManager;
}
}
| 31.921053 | 118 | 0.762572 | [
"object"
] |
a7af6ccbb65d183e528de018d85c6bfa155d7cdf | 16,666 | hpp | C++ | hibernation.hpp | FarbodHassani/nonlinear_kevolution | 16b408b01b73e75c993a15263769d0bef011644d | [
"MIT"
] | null | null | null | hibernation.hpp | FarbodHassani/nonlinear_kevolution | 16b408b01b73e75c993a15263769d0bef011644d | [
"MIT"
] | null | null | null | hibernation.hpp | FarbodHassani/nonlinear_kevolution | 16b408b01b73e75c993a15263769d0bef011644d | [
"MIT"
] | null | null | null | //////////////////////////
// hibernation.hpp
//////////////////////////
//
// Auxiliary functions for hibernation
//
// Author: Julian Adamek (Université de Genève & Observatoire de Paris)
//
// Last modified: December 2016
//
//////////////////////////
#ifndef HIBERNATION_HEADER
#define HIBERNATION_HEADER
//////////////////////////
// writeRestartSettings
//////////////////////////
// Description:
// writes a settings file containing all the relevant metadata for restarting
// a run from a hibernation point
//
// Arguments:
// sim simulation metadata structure
// ic settings for IC generation
// cosmo cosmological parameter structure
// a scale factor
// tau conformal coordinate time
// dtau time step
// cycle current main control loop cycle count
// restartcount restart counter aka number of hibernation point (default -1)
// if < 0 no number is associated to the hibernation point
//
// Returns:
//
//////////////////////////
void writeRestartSettings(metadata & sim, icsettings & ic, cosmology & cosmo, const double a, const double tau, const double dtau, const int cycle, const int restartcount = -1)
{
char buffer[2*PARAM_MAX_LENGTH+24];
FILE * outfile;
int i;
if (!parallel.isRoot()) return;
if (restartcount >= 0)
sprintf(buffer, "%s%s%03d.ini", sim.restart_path, sim.basename_restart, restartcount);
else
sprintf(buffer, "%s%s.ini", sim.restart_path, sim.basename_restart);
outfile = fopen(buffer, "w");
if (outfile == NULL)
{
cout << " error opening file for restart settings!" << endl;
}
else
{
fprintf(outfile, "# automatically generated settings for restart after hibernation ");
if (restartcount < 0)
fprintf(outfile, "due to wallclock limit ");
else
fprintf(outfile, "requested ");
fprintf(outfile, "at redshift z=%f\n\n", (1./a)-1.);
fprintf(outfile, "# info related to IC generation\n\n");
fprintf(outfile, "IC generator = restart\n");
if (restartcount >= 0)
sprintf(buffer, "%03d", restartcount);
else
buffer[0] = '\0';
fprintf(outfile, "particle file = %s%s%s_cdm.h5", sim.restart_path, sim.basename_restart, buffer);
if (sim.baryon_flag)
fprintf(outfile, ", %s%s%s_b.h5", sim.restart_path, sim.basename_restart, buffer);
for (i = 0; i < cosmo.num_ncdm; i++)
fprintf(outfile, ", %s%s%s_ncdm%d.h5", sim.restart_path, sim.basename_restart, buffer, i);
fprintf(outfile, "\n");
if (sim.gr_flag > 0)
{
fprintf(outfile, "metric file = %s%s%s_phi.h5", sim.restart_path, sim.basename_restart, buffer);
//Kessence
fprintf(outfile, "k-essence field = %s%s%s_pi_k.h5", sim.restart_path, sim.basename_restart, buffer);
fprintf(outfile, "k-essence field = %s%s%s_zeta_k.h5", sim.restart_path, sim.basename_restart, buffer);
fprintf(outfile, ", %s%s%s_chi.h5", sim.restart_path, sim.basename_restart, buffer);
if (sim.vector_flag == VECTOR_PARABOLIC)
fprintf(outfile, ", %s%s%s_B.h5\n", sim.restart_path, sim.basename_restart, buffer);
else
#ifdef CHECK_B
fprintf(outfile, ", %s%s%s_B_check.h5\n", sim.restart_path, sim.basename_restart, buffer);
#else
fprintf(outfile, "\n");
#endif
}
else if (sim.vector_flag == VECTOR_PARABOLIC)
fprintf(outfile, "metric file = %s%s%s_B.h5\n", sim.restart_path, sim.basename_restart, buffer);
#ifdef CHECK_B
else
fprintf(outfile, "metric file = %s%s%s_B_check.h5\n", sim.restart_path, sim.basename_restart, buffer);
#endif
fprintf(outfile, "restart redshift = %.15lf\n", (1./a) - 1.);
fprintf(outfile, "cycle = %d\n", cycle);
fprintf(outfile, "tau = %.15le\n", tau);
fprintf(outfile, "dtau = %.15le\n", dtau);
fprintf(outfile, "gevolution version = %g\n\n", GEVOLUTION_VERSION);
fprintf(outfile, "seed = %d\n", ic.seed);
if (ic.flags & ICFLAG_KSPHERE)
fprintf(outfile, "k-domain = sphere\n");
else
fprintf(outfile, "k-domain = cube\n");
fprintf(outfile, "\n\n# primordial power spectrum\n\n");
fprintf(outfile, "k_pivot = %lg\n", ic.k_pivot);
fprintf(outfile, "A_s = %lg\n", ic.A_s);
fprintf(outfile, "n_s = %lg\n", ic.n_s);
fprintf(outfile, "\n\n# cosmological parameters\n\n");
fprintf(outfile, "h = %lg\n", cosmo.h);
fprintf(outfile, "Omega_cdm = %.15le\n", cosmo.Omega_cdm);
fprintf(outfile, "Omega_b = %.15le\n", cosmo.Omega_b);
fprintf(outfile, "Omega_g = %.15le\n", cosmo.Omega_g);
fprintf(outfile, "Omega_ur = %.15le\n", cosmo.Omega_ur);
fprintf(outfile, "N_ncdm = %d\n", cosmo.num_ncdm);
//Kessence
fprintf(outfile, "Omega_kessence = %.15le\n", cosmo.w_kessence);
fprintf(outfile, "w_kessence = %.15le\n", cosmo.Omega_b);
fprintf(outfile, "cs2_kessence = %.15le\n", cosmo.cs2_kessence);
if (cosmo.num_ncdm > 0)
{
fprintf(outfile, "m_cdm = ");
for (i = 0; i < cosmo.num_ncdm - 1; i++)
fprintf(outfile, "%9lf, ", cosmo.m_ncdm[i]);
fprintf(outfile, "%9lf\n", cosmo.m_ncdm[i]);
fprintf(outfile, "T_cdm = ");
for (i = 0; i < cosmo.num_ncdm - 1; i++)
fprintf(outfile, "%9lf, ", cosmo.T_ncdm[i]);
fprintf(outfile, "%9lf\n", cosmo.T_ncdm[i]);
fprintf(outfile, "deg_cdm = ");
for (i = 0; i < cosmo.num_ncdm - 1; i++)
fprintf(outfile, "%lf, ", cosmo.deg_ncdm[i]);
fprintf(outfile, "%lg\n", cosmo.deg_ncdm[i]);
}
fprintf(outfile, "\n\n# simulation settings\n\n");
if (sim.baryon_flag > 0)
fprintf(outfile, "baryon treatment = sample\n");
if (sim.radiation_flag > 0)
{
fprintf(outfile, "radiation treatment = CLASS\n");
fprintf(outfile, "switch delta_rad = %lf\n", sim.z_switch_deltarad);
if (cosmo.num_ncdm > 0)
{
fprintf(outfile, "switch delta_ncdm = ");
for (i = 0; i < cosmo.num_ncdm - 1; i++)
fprintf(outfile, "%lf, ", sim.z_switch_deltancdm[i]);
fprintf(outfile, "%lf\n", sim.z_switch_deltancdm[i]);
}
fprintf(outfile, "switch linear chi = %lf\n", sim.z_switch_linearchi);
}
if (sim.gr_flag > 0)
fprintf(outfile, "gravity theory = GR\n");
else
fprintf(outfile, "gravity theory = N\n");
if (sim.vector_flag == VECTOR_ELLIPTIC)
fprintf(outfile, "vector method = elliptic\n");
else
fprintf(outfile, "vector method = parabolic\n");
fprintf(outfile, "\ninitial redshift = %lg\n", sim.z_in);
fprintf(outfile, "boxsize = %lg\n", sim.boxsize);
fprintf(outfile, "Ngrid = %d\n", sim.numpts);
fprintf(outfile, "Courant factor = %lg\n", sim.Cf);
fprintf(outfile, "time step limit = %lg\n", sim.steplimit);
if (cosmo.num_ncdm > 0)
fprintf(outfile, "move limit = %lg\n", sim.movelimit);
fprintf(outfile, "\n\n# output\n\n");
fprintf(outfile, "output path = %s\n", sim.output_path);
fprintf(outfile, "generic file base = %s\n", sim.basename_generic);
fprintf(outfile, "snapshot file base = %s\n", sim.basename_snapshot);
fprintf(outfile, "Pk file base = %s\n", sim.basename_pk);
if (sim.num_snapshot > 0)
{
fprintf(outfile, "snapshot redshifts = ");
for (i = 0; i < sim.num_snapshot - 1; i++)
fprintf(outfile, "%lg, ", sim.z_snapshot[i]);
fprintf(outfile, "%lg\n", sim.z_snapshot[i]);
}
if (sim.out_snapshot)
{
fprintf(outfile, "snapshot outputs = ");
if(sim.out_snapshot & MASK_PHI)
{
fprintf(outfile, "phi");
if (sim.out_snapshot > MASK_PI_K)
fprintf(outfile, ", ");
}
//Kessence
if(sim.out_snapshot & MASK_PI_K)
{
fprintf(outfile, "pi_k");
if (sim.out_snapshot > MASK_zeta)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_zeta)
{
fprintf(outfile, "zeta_k");
if (sim.out_snapshot > MASK_CHI)
fprintf(outfile, ", ");
}
//kessence end
if(sim.out_snapshot & MASK_CHI)
{
fprintf(outfile, "chi");
if (sim.out_snapshot > MASK_POT)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_POT)
{
fprintf(outfile, "psiN");
if (sim.out_snapshot > MASK_B)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_B)
{
fprintf(outfile, "B");
if (sim.out_snapshot > MASK_T00)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_T00)
{
fprintf(outfile, "T00");
if (sim.out_snapshot > MASK_TIJ)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_TIJ)
{
fprintf(outfile, "Tij");
if (sim.out_snapshot > MASK_RBARE)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_RBARE)
{
fprintf(outfile, "rhoN");
if (sim.out_snapshot > MASK_HIJ)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_HIJ)
{
fprintf(outfile, "hij");
if (sim.out_snapshot > MASK_P)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_P)
{
fprintf(outfile, "p");
if (sim.out_snapshot > MASK_GADGET)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_GADGET)
{
fprintf(outfile, "Gadget2");
if (sim.out_snapshot > MASK_PCLS)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_PCLS)
{
fprintf(outfile, "particles");
if (sim.out_snapshot > MASK_DELTA)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_DELTA)
{
fprintf(outfile, "delta");
if (sim.out_snapshot > MASK_DBARE)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_DBARE)
{
fprintf(outfile, "deltaN");
}
fprintf(outfile, "\n");
}
if (sim.out_snapshot & MASK_GADGET)
{
fprintf(outfile, "tracer factor = %d", sim.tracer_factor[0]);
for (i = 1; i <= sim.baryon_flag + cosmo.num_ncdm; i++)
fprintf(outfile, ", %d", sim.tracer_factor[i]);
fprintf(outfile, "\n");
}
if (sim.downgrade_factor > 1)
fprintf(outfile, "downgrade factor = %d", sim.downgrade_factor);
if (sim.num_pk > 0)
{
fprintf(outfile, "Pk redshifts = ");
for (i = 0; i < sim.num_pk - 1; i++)
fprintf(outfile, "%lg, ", sim.z_pk[i]);
fprintf(outfile, "%lg\n", sim.z_pk[i]);
}
if (sim.out_pk)
{
fprintf(outfile, "Pk outputs = ");
if(sim.out_pk & MASK_PHI)
{
//Kessence
fprintf(outfile, "phi");
if (sim.out_pk > MASK_PI_K)
fprintf(outfile, ", ");
}
//Kessence
if(sim.out_snapshot & MASK_PI_K)
{
fprintf(outfile, "pi_k");
if (sim.out_snapshot > MASK_zeta)
fprintf(outfile, ", ");
}
if(sim.out_snapshot & MASK_zeta)
{
fprintf(outfile, "zeta");
if (sim.out_snapshot > MASK_CHI)
fprintf(outfile, ", ");
}
//kessence end
if(sim.out_pk & MASK_CHI)
{
fprintf(outfile, "chi");
if (sim.out_pk > MASK_POT)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_POT)
{
fprintf(outfile, "psiN");
if (sim.out_pk > MASK_B)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_B)
{
fprintf(outfile, "B");
if (sim.out_pk > MASK_T00)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_T00)
{
fprintf(outfile, "T00");
if (sim.out_pk > MASK_TIJ)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_TIJ)
{
fprintf(outfile, "Tij");
if (sim.out_pk > MASK_RBARE)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_RBARE)
{
fprintf(outfile, "rhoN");
if (sim.out_pk > MASK_HIJ)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_HIJ)
{
fprintf(outfile, "hij");
if (sim.out_pk > MASK_P)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_P)
{
fprintf(outfile, "p");
if (sim.out_pk > MASK_XSPEC)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_XSPEC)
{
fprintf(outfile, "X-spectra");
if (sim.out_pk > MASK_DELTA)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_DELTA)
{
fprintf(outfile, "delta");
if (sim.out_pk > MASK_DBARE)
fprintf(outfile, ", ");
}
if(sim.out_pk & MASK_DBARE)
{
fprintf(outfile, "deltaN");
}
fprintf(outfile, "\n");
}
fprintf(outfile, "Pk bins = %d\n", sim.numbins);
fprintf(outfile, "\n\n# hibernations\n\n");
if (sim.num_restart > 0)
{
fprintf(outfile, "hibernation redshifts = ");
for (i = 0; i < sim.num_restart - 1; i++)
fprintf(outfile, "%lg, ", sim.z_restart[i]);
fprintf(outfile, "%lg\n", sim.z_restart[i]);
}
if (sim.wallclocklimit > 0.)
fprintf(outfile, "hibernation wallclock limit = %lg\n", sim.wallclocklimit);
if (sim.restart_path[0] != '\0')
fprintf(outfile, "hibernation path = %s\n", sim.restart_path);
fprintf(outfile, "hibernation file base = %s\n", sim.basename_restart);
fclose(outfile);
}
}
//////////////////////////
// hibernate
//////////////////////////
// Description:
// creates a hibernation point by writing snapshots of the simulation data and metadata
//
// Arguments:
// sim simulation metadata structure
// ic settings for IC generation
// cosmo cosmological parameter structure
// pcls_cdm pointer to particle handler for CDM
// pcls_b pointer to particle handler for baryons
// pcls_ncdm array of particle handlers for non-cold DM
// phi reference to field containing first Bardeen potential
// chi reference to field containing difference of Bardeen potentials
// Bi reference to vector field containing frame-dragging potential
// a scale factor
// tau conformal coordinate time
// dtau time step
// cycle current main control loop cycle count
// restartcount restart counter aka number of hibernation point (default -1)
// if < 0 no number is associated to the hibernation point
//
// Returns:
//
//////////////////////////
void hibernate(metadata & sim, icsettings & ic, cosmology & cosmo, Particles<part_simple,part_simple_info,part_simple_dataType> * pcls_cdm, Particles<part_simple,part_simple_info,part_simple_dataType> * pcls_b, Particles<part_simple,part_simple_info,part_simple_dataType> * pcls_ncdm, Field<Real> & phi, Field<Real> & pi_k,Field<Real> & zeta, Field<Real> & chi, Field<Real> & Bi, const double a, const double tau, const double dtau, const int cycle, const int restartcount = -1)
{
string h5filename;
char buffer[5];
int i;
Site x(Bi.lattice());
h5filename.reserve(2*PARAM_MAX_LENGTH);
h5filename.assign(sim.restart_path);
h5filename += sim.basename_restart;
if (restartcount >= 0)
{
sprintf(buffer, "%03d", restartcount);
h5filename += buffer;
}
writeRestartSettings(sim, ic, cosmo, a, tau, dtau, cycle, restartcount);
#ifndef CHECK_B
if (sim.vector_flag == VECTOR_PARABOLIC)
#endif
for (x.first(); x.test(); x.next())
{
Bi(x,0) /= a * a * sim.numpts;
Bi(x,1) /= a * a * sim.numpts;
Bi(x,2) /= a * a * sim.numpts;
}
#ifdef EXTERNAL_IO
while (ioserver.openOstream()== OSTREAM_FAIL);
pcls_cdm->saveHDF5_server_open(h5filename + "_cdm");
if (sim.baryon_flag)
pcls_b->saveHDF5_server_open(h5filename + "_b");
for (i = 0; i < cosmo.num_ncdm; i++)
{
sprintf(buffer, "%d", i);
pcls_ncdm[i].saveHDF5_server_open(h5filename + "_ncdm" + buffer);
}
if (sim.gr_flag > 0)
{
phi.saveHDF5_server_open(h5filename + "_phi");
//kessence
pi_k.saveHDF5_server_open(h5filename + "_pi_k");
zeta.saveHDF5_server_open(h5filename + "_zeta");
chi.saveHDF5_server_open(h5filename + "_chi");
}
if (sim.vector_flag == VECTOR_PARABOLIC)
Bi.saveHDF5_server_open(h5filename + "_B");
#ifdef CHECK_B
else
Bi.saveHDF5_server_open(h5filename + "_B_check");
#endif
pcls_cdm->saveHDF5_server_write();
if (sim.baryon_flag)
pcls_b->saveHDF5_server_write();
for (i = 0; i < cosmo.num_ncdm; i++)
pcls_ncdm[i].saveHDF5_server_write();
if (sim.gr_flag > 0)
{
phi.saveHDF5_server_write(NUMBER_OF_IO_FILES);
chi.saveHDF5_server_write(NUMBER_OF_IO_FILES);
}
#ifndef CHECK_B
if (sim.vector_flag == VECTOR_PARABOLIC)
#endif
Bi.saveHDF5_server_write(NUMBER_OF_IO_FILES);
ioserver.closeOstream();
#else
pcls_cdm->saveHDF5(h5filename + "_cdm", 1);
if (sim.baryon_flag)
pcls_b->saveHDF5(h5filename + "_b", 1);
for (i = 0; i < cosmo.num_ncdm; i++)
{
sprintf(buffer, "%d", i);
pcls_ncdm[i].saveHDF5(h5filename + "_ncdm" + buffer, 1);
}
if (sim.gr_flag > 0)
{
phi.saveHDF5(h5filename + "_phi.h5");
//kessence
pi_k.saveHDF5(h5filename + "_pi_k.h5");
zeta.saveHDF5(h5filename + "_zeta.h5");
chi.saveHDF5(h5filename + "_chi.h5");
}
if (sim.vector_flag == VECTOR_PARABOLIC)
Bi.saveHDF5(h5filename + "_B.h5");
#ifdef CHECK_B
else
Bi.saveHDF5(h5filename + "_B_check.h5");
#endif
#endif
}
#endif
| 31.093284 | 478 | 0.619345 | [
"vector"
] |
a7afd7a8274e987c17f90d3e939005d65463ad34 | 10,406 | cxx | C++ | IO/Export/vtkX3DExporterXMLWriter.cxx | stephansmit/VTK | caa1eabb4612a0253171723bd1f1ddc599d7eea8 | [
"BSD-3-Clause"
] | 3 | 2015-07-28T18:07:50.000Z | 2018-02-28T20:59:58.000Z | IO/Export/vtkX3DExporterXMLWriter.cxx | stephansmit/VTK | caa1eabb4612a0253171723bd1f1ddc599d7eea8 | [
"BSD-3-Clause"
] | null | null | null | IO/Export/vtkX3DExporterXMLWriter.cxx | stephansmit/VTK | caa1eabb4612a0253171723bd1f1ddc599d7eea8 | [
"BSD-3-Clause"
] | 4 | 2016-09-08T02:11:00.000Z | 2019-08-15T02:38:39.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkX3DExporterXMLWriter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen, Kristian Sons
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkX3DExporterXMLWriter.h"
#include "vtkX3D.h"
#include "vtkObjectFactory.h"
#include "vtkDataArray.h"
#include "vtkUnsignedCharArray.h"
#include "vtkPoints.h"
#include "vtkCellArray.h"
#include "vtkMath.h"
#include <sstream>
#include <fstream>
#include <iomanip>
#include <ios>
#include <limits>
#include <string>
#include <cassert>
using namespace vtkX3D;
struct XMLInfo {
XMLInfo(int _elementId)
{
this->elementId = _elementId;
this->endTagWritten = false;
}
int elementId;
bool endTagWritten;
};
typedef std::vector<XMLInfo> vtkX3DExporterXMLNodeInfoStackBase;
class vtkX3DExporterXMLNodeInfoStack: public vtkX3DExporterXMLNodeInfoStackBase
{};
//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkX3DExporterXMLWriter);
//-----------------------------------------------------------------------------
vtkX3DExporterXMLWriter::~vtkX3DExporterXMLWriter()
{
delete this->InfoStack;
delete this->OutputStream;
this->OutputStream = nullptr;
}
//-----------------------------------------------------------------------------
vtkX3DExporterXMLWriter::vtkX3DExporterXMLWriter()
{
this->OutputStream = nullptr;
this->InfoStack = new vtkX3DExporterXMLNodeInfoStack();
this->Depth = 0;
this->ActTab = "";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
//----------------------------------------------------------------------------
int vtkX3DExporterXMLWriter::OpenFile(const char* file)
{
this->CloseFile();
this->WriteToOutputString = 0;
std::fstream* fileStream = new std::fstream();
fileStream->open (file, ios::out);
if(fileStream->fail())
{
delete fileStream;
return 0;
}
else
{
this->OutputStream = fileStream;
*this->OutputStream << std::scientific << std::setprecision(std::numeric_limits<double>::max_digits10);
return 1;
}
}
//----------------------------------------------------------------------------
int vtkX3DExporterXMLWriter::OpenStream()
{
this->CloseFile();
this->WriteToOutputString = 1;
this->OutputStream = new std::ostringstream();
return 1;
}
//----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::CloseFile()
{
if(this->OutputStream != nullptr)
{
if(this->WriteToOutputString)
{
std::ostringstream *ostr =
static_cast<std::ostringstream*>(this->OutputStream);
delete [] this->OutputString;
this->OutputStringLength = static_cast<int>(ostr->str().size());
this->OutputString = new char[ostr->str().size()];
memcpy(this->OutputString, ostr->str().c_str(),
this->OutputStringLength);
}
delete this->OutputStream;
this->OutputStream = nullptr;
}
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::StartDocument()
{
this->Depth = 0;
*this->OutputStream << "<?xml version=\"1.0\" encoding =\"UTF-8\"?>"
<< endl << endl;
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::EndDocument()
{
assert(this->Depth == 0);
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::StartNode(int elementID)
{
// End last tag, if this is the first child
if (!this->InfoStack->empty())
{
if (!this->InfoStack->back().endTagWritten)
{
*this->OutputStream << ">" << this->GetNewline();
this->InfoStack->back().endTagWritten = true;
}
}
this->InfoStack->push_back(XMLInfo(elementID));
*this->OutputStream << this->ActTab << "<" << x3dElementString[elementID];
this->AddDepth();
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::EndNode()
{
assert(!this->InfoStack->empty());
this->SubDepth();
int elementID = this->InfoStack->back().elementId;
// There were no childs
if (!this->InfoStack->back().endTagWritten)
{
*this->OutputStream << "/>" << this->GetNewline();
}
else
{
*this->OutputStream << this->ActTab << "</" << x3dElementString[elementID]
<< ">" << this->GetNewline();
}
this->InfoStack->pop_back();
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, int type, const double* d)
{
*this->OutputStream << " " << x3dAttributeString[attributeID] << "=\"";
switch (type)
{
case(SFVEC3F):
case(SFCOLOR):
*this->OutputStream << d[0]
<< " "
<< d[1]
<< " "
<< d[2];
break;
case(SFROTATION):
*this->OutputStream << d[1]
<< " "
<< d[2]
<< " "
<< d[3]
<< " "
<< vtkMath::RadiansFromDegrees( -d[0] );
break;
default:
*this->OutputStream << "UNKNOWN DATATYPE";
}
*this->OutputStream << "\"";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, int type, vtkDataArray* a)
{
*this->OutputStream << " " << x3dAttributeString[attributeID] << "=\"" << this->GetNewline();
switch (type)
{
case(MFVEC3F):
for (vtkIdType i = 0; i < a->GetNumberOfTuples(); i++)
{
double* d = a->GetTuple(i);
*this->OutputStream << this->ActTab << d[0] << " " << d[1] << " " << d[2] << "," << this->GetNewline();
}
break;
case(MFVEC2F):
for (vtkIdType i = 0; i < a->GetNumberOfTuples(); i++)
{
double* d = a->GetTuple(i);
*this->OutputStream << this->ActTab << d[0] << " " << d[1] << "," << this->GetNewline();
}
break;
default:
*this->OutputStream << "UNKNOWN DATATYPE";
}
*this->OutputStream << this->ActTab << "\"";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, const double* values, size_t size)
{
*this->OutputStream << " " << x3dAttributeString[attributeID] << "=\"" << this->GetNewline() << this->ActTab;
unsigned int i = 0;
while (i < size)
{
*this->OutputStream << values[i];
if ((i+1)%3)
{
*this->OutputStream << " ";
}
else
{
*this->OutputStream << "," << this->GetNewline() << this->ActTab;
}
i++;
}
*this->OutputStream << "\"";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, const int* values, size_t size, bool image)
{
*this->OutputStream << " " << x3dAttributeString[attributeID] << "=\"" << this->GetNewline() << this->ActTab;
unsigned int i = 0;
if (image)
{
assert(size > 2);
char buffer[20];
*this->OutputStream << values[0] << " "; // width
*this->OutputStream << values[1] << " "; // height
int bpp = values[2]; *this->OutputStream << bpp << "\n"; // bpp
i = 3;
unsigned int j = 0;
while (i < size)
{
snprintf(buffer,sizeof(buffer),"0x%.8x",values[i]);
*this->OutputStream << buffer;
if (j%(8*bpp))
{
*this->OutputStream << " ";
}
else
{
*this->OutputStream << this->GetNewline();// << this->ActTab;
}
i++; j+=bpp;
}
*this->OutputStream << dec;
}
else
while (i < size)
{
*this->OutputStream << values[i] << " ";
if (values[i] == -1)
{
*this->OutputStream << this->GetNewline() << this->ActTab;
}
i++;
}
*this->OutputStream << "\"";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, int value)
{
*this->OutputStream << " " << x3dAttributeString[attributeID] << "=\"" << value << "\"";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, float value)
{
*this->OutputStream << " " << x3dAttributeString[attributeID] << "=\"" << value << "\"";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, double vtkNotUsed(value))
{
*this->OutputStream << " " << x3dAttributeString[attributeID] << "=\"" << "WHY DOUBLE?" << "\"";
assert(false);
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, bool value)
{
*this->OutputStream << " "
<< x3dAttributeString[attributeID] << "=\"" << (value ? "true" : "false" ) << "\"";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SetField(int attributeID, const char* value, bool mfstring)
{
if (mfstring)
{
*this->OutputStream << " "
<< x3dAttributeString[attributeID] << "='" << value << "'";
}
else
{
*this->OutputStream
<< " " << x3dAttributeString[attributeID] << "=\"" << value << "\"";
}
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::Flush()
{
this->OutputStream->flush();
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::AddDepth()
{
this->ActTab += " ";
}
//-----------------------------------------------------------------------------
void vtkX3DExporterXMLWriter::SubDepth()
{
this->ActTab.erase(0, 2);
}
| 28.666667 | 111 | 0.490486 | [
"vector"
] |
a7b4ed75e9f45f68968443e9d4e68f05ec986b31 | 30,831 | cpp | C++ | NMEA0183AISMessages.cpp | ronzeiller/NMEA0183-AIS | 29df9b3f7afde03b0a7907bfb9f0320fb4d8a925 | [
"Unlicense"
] | 5 | 2020-01-10T12:39:17.000Z | 2022-03-15T22:45:13.000Z | NMEA0183AISMessages.cpp | ronzeiller/NMEA0183-AIS | 29df9b3f7afde03b0a7907bfb9f0320fb4d8a925 | [
"Unlicense"
] | 2 | 2020-12-23T06:30:48.000Z | 2022-03-15T22:43:48.000Z | NMEA0183AISMessages.cpp | ronzeiller/NMEA0183-AIS | 29df9b3f7afde03b0a7907bfb9f0320fb4d8a925 | [
"Unlicense"
] | 2 | 2020-10-01T07:06:55.000Z | 2021-11-22T04:23:08.000Z | /*
NMEA0183AISMessages.cpp
Copyright (c) 2019 Ronnie Zeiller
Based on the works of Timo Lappalainen NMEA2000 and NMEA0183 Library
Thanks to Eric S. Raymond (https://gpsd.gitlab.io/gpsd/AIVDM.html)
and Kurt Schwehr for their informations on AIS encoding.
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 <NMEA0183AISMessages.h>
#include <N2kTypes.h>
#include <N2kMsg.h>
#include <string.h>
//#include <bitset>
//#include <unordered_map>
#include <sstream>
#include <math.h>
#include <NMEA0183AISMsg.h>
const double pi=3.1415926535897932384626433832795;
const double kmhToms=1000.0/3600.0;
const double knToms=1852.0/3600.0;
const double degToRad=pi/180.0;
const double radToDeg=180.0/pi;
const double msTokmh=3600.0/1000.0;
const double msTokn=3600.0/1852.0;
const double nmTom=1.852*1000;
const double mToFathoms=0.546806649;
const double mToFeet=3.2808398950131;
const double radsToDegMin = 60 * 360.0 / (2 * pi); // [rad/s -> degree/minute]
const char Prefix='!';
std::vector<ship *> vships;
// ************************ Helper for AIS ***********************************
static bool AddMessageType(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t MessageType);
static bool AddRepeat(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t Repeat);
static bool AddUserID(tNMEA0183AISMsg &NMEA0183AISMsg, uint32_t UserID);
static bool AddIMONumber(tNMEA0183AISMsg &NMEA0183AISMsg, uint32_t &IMONumber);
static bool AddText(tNMEA0183AISMsg &NMEA0183AISMsg, char *FieldVal, uint8_t length);
static bool AddVesselType(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t VesselType);
static bool AddDimensions(tNMEA0183AISMsg &NMEA0183AISMsg, double Length, double Beam, double PosRefStbd, double PosRefBow);
static bool AddNavStatus(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t &NavStatus);
static bool AddROT(tNMEA0183AISMsg &NMEA0183AISMsg, double &rot);
static bool AddSOG (tNMEA0183AISMsg &NMEA0183AISMsg, double &sog);
static bool AddLongitude(tNMEA0183AISMsg &NMEA0183AISMsg, double &Longitude);
static bool AddLatitude(tNMEA0183AISMsg &NMEA0183AISMsg, double &Latitude);
static bool AddHeading (tNMEA0183AISMsg &NMEA0183AISMsg, double &heading);
static bool AddCOG(tNMEA0183AISMsg &NMEA0183AISMsg, double cog);
static bool AddSeconds (tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t &Seconds);
static bool AddEPFDFixType(tNMEA0183AISMsg &NMEA0183AISMsg, tN2kGNSStype &GNSStype);
static bool AddStaticDraught(tNMEA0183AISMsg &NMEA0183AISMsg, double &Draught);
static bool AddETADateTime(tNMEA0183AISMsg &NMEA0183AISMsg, uint16_t &ETAdate, double &ETAtime);
//*****************************************************************************
// Types 1, 2 and 3: Position Report Class A or B -> https://gpsd.gitlab.io/gpsd/AIVDM.html
// total of 168 bits, occupying one AIVDM sentence
// Example: !AIVDM,1,1,,A,133m@ogP00PD;88MD5MTDww@2D7k,0*46
// Payload: Payload: 133m@ogP00PD;88MD5MTDww@2D7k
// Message type 1 has a payload length of 168 bits.
// because AIS encodes messages using a 6-bits ASCII mechanism and 168 divided by 6 is 28.
//
// Got values from: ParseN2kPGN129038()
bool SetAISClassABMessage1( tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t MessageType, uint8_t Repeat,
uint32_t UserID, double Latitude, double Longitude, bool Accuracy, bool RAIM, uint8_t Seconds,
double COG, double SOG, double Heading, double ROT, uint8_t NavStatus ) {
NMEA0183AISMsg.ClearAIS();
if ( !AddMessageType(NMEA0183AISMsg, MessageType) ) return false; // 0 - 5 | 6 Message Type -> Constant: 1
if ( !AddRepeat(NMEA0183AISMsg, Repeat) ) return false; // 6 - 7 | 2 Repeat Indicator: 0 = default; 3 = do not repeat any more
if ( !AddUserID(NMEA0183AISMsg, UserID) ) return false; // 8 - 37 | 30 MMSI
if ( !AddNavStatus(NMEA0183AISMsg, NavStatus) ) return false; // 38-41 | 4 Navigational Status e.g.: "Under way sailing"
if ( !AddROT(NMEA0183AISMsg, ROT) ) return false; // 42-49 | 8 Rate of Turn (ROT)
if ( !AddSOG(NMEA0183AISMsg, SOG) ) return false; // 50-59 | 10 [m/s -> kts] SOG with one digit x10, 1023 = N/A
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(Accuracy, 1) ) return false;// 60 | 1 GPS Accuracy 1 oder 0, Default 0
if ( !AddLongitude(NMEA0183AISMsg, Longitude) ) return false; // 61-88 | 28 Longitude in Minutes / 10000
if ( !AddLatitude(NMEA0183AISMsg, Latitude) ) return false; // 89-115 | 27 Latitude in Minutes / 10000
if ( !AddCOG(NMEA0183AISMsg, COG) ) return false; // 116-127 | 12 Course over ground will be 3600 (0xE10) if that data is not available.
if ( !AddHeading (NMEA0183AISMsg, Heading) ) return false; // 128-136 | 9 True Heading (HDG)
if ( !AddSeconds(NMEA0183AISMsg, Seconds) ) return false; // 137-142 | 6 Seconds in UTC timestamp)
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 2) ) return false; // 143-144 | 2 Maneuver Indicator: 0 (default) 1, 2 (not delivered within this PGN)
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 3) ) return false; // 145-147 | 3 Spare
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(RAIM, 1) ) return false; // 148-148 | 1 RAIM flag 0 = RAIM not in use (default), 1 = RAIM in use
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 19) ) return false; // 149-167 | 19 Radio Status (-> 0 NOT SENT WITH THIS PGN!!!!!)
if ( !NMEA0183AISMsg.Init("VDM","AI", Prefix) ) return false;
if ( !NMEA0183AISMsg.AddStrField("1") ) return false;
if ( !NMEA0183AISMsg.AddStrField("1") ) return false;
if ( !NMEA0183AISMsg.AddEmptyField() ) return false;
if ( !NMEA0183AISMsg.AddStrField("A") ) return false;
if ( !NMEA0183AISMsg.AddStrField( NMEA0183AISMsg.GetPayload() ) ) return false;
if ( !NMEA0183AISMsg.AddStrField("0") ) return false; // Message 1,2,3 has always Zero Padding
return true;
}
// *****************************************************************************
// https://www.navcen.uscg.gov/?pageName=AISMessagesAStatic#
// AIS class A Static and Voyage Related Data
// Values derived from ParseN2kPGN129794();
bool SetAISClassAMessage5(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t MessageID, uint8_t Repeat,
uint32_t UserID, uint32_t IMONumber, char *Callsign, char *Name,
uint8_t VesselType, double Length, double Beam, double PosRefStbd,
double PosRefBow, uint16_t ETAdate, double ETAtime, double Draught,
char *Destination, tN2kGNSStype GNSStype, uint8_t DTE ) {
// AIS Type 5 Message
NMEA0183AISMsg.ClearAIS();
if ( !AddMessageType(NMEA0183AISMsg, 5) ) return false; // 0 - 5 | 6 Message Type -> Constant: 5
if ( !AddRepeat(NMEA0183AISMsg, Repeat) ) return false; // 6 - 7 | 2 Repeat Indicator: 0 = default; 3 = do not repeat any more
if ( !AddUserID(NMEA0183AISMsg, UserID) ) return false; // 8 - 37 | 30 MMSI
if ( !NMEA0183AISMsg.AddIntToPayloadBin(1, 2) ) return false; // 38 - 39 | 2 AIS Version -> 0 oder 1 NOT DERIVED FROM N2k, Always 1!!!!
if ( !AddIMONumber(NMEA0183AISMsg, IMONumber) ) return false; // 40 - 69 | 30 IMO Number unisgned
if ( !AddText(NMEA0183AISMsg, Callsign, 42) ) return false; // 70 - 111 | 42 Call Sign WDE4178 -> 7 6-bit characters -> Ascii lt. Table)
if ( !AddText(NMEA0183AISMsg, Name, 120) ) return false; // 112-231 | 120 Vessel Name POINT FERMIN -> 20 6-bit characters -> Ascii lt. Table
if ( !NMEA0183AISMsg.AddIntToPayloadBin(VesselType, 8) ) return false; // 232-239 | 8 Ship Type 0....255 e.g. 31 Towing
if ( !AddDimensions(NMEA0183AISMsg, Length, Beam, PosRefStbd, PosRefBow) ) return false; // 240 - 269 | 30 Dimensions
if ( !AddEPFDFixType(NMEA0183AISMsg, GNSStype) ) return false; // 270-273 | 4 Position Fix Type, 0 (default)
if ( !AddETADateTime(NMEA0183AISMsg, ETAdate, ETAtime) ) return false; // 274 -293 | 20 Estimated time of arrival; MMDDHHMM UTC
if ( !AddStaticDraught(NMEA0183AISMsg, Draught) ) return false; // 294-301 | 8 Maximum Present Static Draught
if ( !AddText(NMEA0183AISMsg, Destination, 120) ) return false; // 302-421 | 120 | 20 Destination 20 6-bit characters
if ( !NMEA0183AISMsg.AddIntToPayloadBin(DTE, 1) ) return false; // 422 | 1 | Data terminal equipment (DTE) ready (0 = available, 1 = not available = default)
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 1) ) return false; // 423 | 1 | spare
return true;
}
// ****************************************************************************
// AIS position report (class B 129039) -> Type 18: Standard Class B CS Position Report
// ParseN2kPGN129039(const tN2kMsg &N2kMsg, uint8_t &MessageID, tN2kAISRepeat &Repeat, uint32_t &UserID,
// double &Latitude, double &Longitude, bool &Accuracy, bool &RAIM,
// uint8_t &Seconds, double &COG, double &SOG, double &Heading, tN2kAISUnit &Unit,
// bool &Display, bool &DSC, bool &Band, bool &Msg22, tN2kAISMode &Mode, bool &State)
// VDM, VDO (AIS VHF Data-link message 18)
bool SetAISClassBMessage18(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t MessageID, uint8_t Repeat, uint32_t UserID,
double Latitude, double Longitude, bool Accuracy, bool RAIM,
uint8_t Seconds, double COG, double SOG, double Heading, tN2kAISUnit Unit,
bool Display, bool DSC, bool Band, bool Msg22, bool Mode, bool State) {
//
NMEA0183AISMsg.ClearAIS();
if ( !AddMessageType(NMEA0183AISMsg, MessageID) ) return false; // 0 - 5 | 6 Message Type -> Constant: 18
if ( !AddRepeat(NMEA0183AISMsg, Repeat) ) return false; // 6 - 7 | 2 Repeat Indicator: 0 = default; 3 = do not repeat any more
if ( !AddUserID(NMEA0183AISMsg, UserID) ) return false; // 8 - 37 | 30 MMSI
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 8) ) return false; // 38-45 | 8 Regional Reserved
if ( !AddSOG(NMEA0183AISMsg, SOG) ) return false; // 46-55 | 10 [m/s -> kts] SOG with one digit x10, 1023 = N/A
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(Accuracy, 1)) return false; // 56 | 1 GPS Accuracy 1 oder 0, Default 0
if ( !AddLongitude(NMEA0183AISMsg, Longitude) ) return false; // 57-84 | 28 Longitude in Minutes / 10000
if ( !AddLatitude(NMEA0183AISMsg, Latitude) ) return false; // 85-111 | 27 Latitude in Minutes / 10000
if ( !AddCOG(NMEA0183AISMsg, COG) ) return false; // 112-123 | 12 Course over ground will be 3600 (0xE10) if that data is not available.
if ( !AddHeading (NMEA0183AISMsg, Heading) ) return false; // 124-132 | 9 True Heading (HDG)
if ( !AddSeconds(NMEA0183AISMsg, Seconds) ) return false; // 133-138 | 6 Seconds in UTC timestamp)
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 2) ) return false; // 139-140 | 2 Regional Reserved
if ( !NMEA0183AISMsg.AddIntToPayloadBin(Unit, 1) ) return false; // 141 | 1 0=Class B SOTDMA unit 1=Class B CS (Carrier Sense) unit
if ( !NMEA0183AISMsg.AddIntToPayloadBin(Display, 1) ) return false; // 142 | 1 0=No visual display, 1=Has display, (Probably not reliable).
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(DSC, 1) ) return false; // 143 | 1 If 1, unit is attached to a VHF voice radio with DSC capability.
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(Band, 1) ) return false; // 144 | 1 If this flag is 1, the unit can use any part of the marine channel.
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(Msg22, 1) ) return false; // 145 | 1 If 1, unit can accept a channel assignment via Message Type 22.
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(Mode, 1) ) return false; // 146 | 1 Assigned-mode flag: 0 = autonomous mode (default), 1 = assigned mode
if ( !NMEA0183AISMsg.AddBoolToPayloadBin(RAIM, 1) ) return false; // 147 | 1 as for Message Type 1,2,3
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 20) ) return false; // 148-167 | 20 Radio Status not in PGN 129039
if ( !NMEA0183AISMsg.Init("VDM","AI", Prefix) ) return false;
if ( !NMEA0183AISMsg.AddStrField("1") ) return false;
if ( !NMEA0183AISMsg.AddStrField("1") ) return false;
if ( !NMEA0183AISMsg.AddEmptyField() ) return false;
if ( !NMEA0183AISMsg.AddStrField("B") ) return false;
if ( !NMEA0183AISMsg.AddStrField( NMEA0183AISMsg.GetPayload() ) ) return false;
if ( !NMEA0183AISMsg.AddStrField("0") ) return false; // Message 18, has always Zero Padding
return true;
}
// ****************************************************************************
// Type 24: Static Data Report
// Equivalent of a Type 5 message for ships using Class B equipment. Also used to associate an MMSI
// with a name on either class A or class B equipment.
//
// A "Type 24" may be in part A or part B format; According to the standard, parts A and B are expected
// to be broadcast in adjacent pairs; in the real world they may (due to quirks in various aggregation methods)
// be separated by other sentences or even interleaved with different Type 24 pairs; decoders must cope with this.
// The interpretation of some fields in Type B format changes depending on the range of the Type B MMSI field.
//
// 160 bits for part A, 168 bits for part B.
// According to the standard, both the A and B parts are supposed to be 168 bits.
// However, in the wild, A parts are often transmitted with only 160 bits, omitting the spare 7 bits at the end.
// Implementers should be permissive about this.
//
// If the Part Number field is 0, the rest of the message is interpreted as a Part A;
// If it is 1, the rest of the message is interpreted as a Part B; values 2 and 3 are not allowed.
//
// PGN 129809 AIS Class B "CS" Static Data Report, Part A -> AIS VHF Data-link message 24
// PGN 129810 AIS Class B "CS" Static Data Report, Part B -> AIS VHF Data-link message 24
// ParseN2kPGN129809 (const tN2kMsg &N2kMsg, uint8_t &MessageID, tN2kAISRepeat &Repeat, uint32_t &UserID, char *Name) -> store to vector
// ParseN2kPGN129810(const tN2kMsg &N2kMsg, uint8_t &MessageID, tN2kAISRepeat &Repeat, uint32_t &UserID,
// uint8_t &VesselType, char *Vendor, char *Callsign, double &Length, double &Beam,
// double &PosRefStbd, double &PosRefBow, uint32_t &MothershipID);
//
// Part A: MessageID, Repeat, UserID, ShipName -> store in vector to call on Part B arrivals!!!
// Part B: MessageID, Repeat, UserID, VesselType (5), Callsign (5), Length & Beam, PosRefBow,.. (5)
bool SetAISClassBMessage24PartA(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t MessageID, uint8_t Repeat, uint32_t UserID, char *Name) {
bool found = false;
for (int i = 0; i < vships.size(); i++) {
if ( vships[i]->_userID == UserID ) {
found = true;
break;
}
}
if ( ! found ) {
std::string nm;
nm+= Name;
vships.push_back(new ship(UserID, nm));
}
return true;
}
// ***************************************************************************************************************
bool SetAISClassBMessage24(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t MessageID, uint8_t Repeat,
uint32_t UserID, uint8_t VesselType, char *VendorID, char *Callsign,
double Length, double Beam, double PosRefStbd, double PosRefBow, uint32_t MothershipID ) {
uint8_t PartNr = 0; // Identifier for the message part number; always 0 for Part A
char *ShipName = (char*)" "; // get from vector to look up for sent Messages Part A
uint8_t i;
for ( i = 0; i < vships.size(); i++) {
if ( vships[i]->_userID == UserID ) {
Serial.print("UserID gefunden: "); Serial.print(UserID);
ShipName = const_cast<char*>( vships[i]->_shipName.c_str() );
Serial.print(" / "); Serial.println( ShipName);
}
}
if ( i > MAX_SHIP_IN_VECTOR ) {
vships.erase(vships.begin());
}
// AIS Type 24 Message
NMEA0183AISMsg.ClearAIS();
// Common for PART A AND Part B Bit 0 - 39 / len 40
if ( !AddMessageType(NMEA0183AISMsg, 24) ) return false; // 0 - 5 | 6 Message Type -> Constant: 24
if ( !AddRepeat(NMEA0183AISMsg, Repeat) ) return false; // 6 - 7 | 2 Repeat Indicator: 0 = default; 3 = do not repeat any more
if ( !AddUserID(NMEA0183AISMsg, UserID) ) return false; // 8 - 37 | 30 MMSI
if ( !NMEA0183AISMsg.AddIntToPayloadBin(PartNr, 2) ) return false; // 38-39 | 2 Part Number 0-1 ->
// Part A: 40 + 128 = len 168
if ( !AddText(NMEA0183AISMsg, ShipName, 120) ) return false; // 40-159 | 120 Vessel Name 20 6-bit characters -> Ascii Table
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 8) ) return false; // 160-167 | 8 Spare
// https://www.navcen.uscg.gov/?pageName=AISMessagesB
// PART B: 40 + 128 = len 168
if ( !NMEA0183AISMsg.AddIntToPayloadBin(VesselType, 8) ) return false; // 168-175 | 40-47 | 8 Ship Type 0....99
if ( !AddText(NMEA0183AISMsg, VendorID, 42) ) return false; // 176-217 | 48-89 | 42 Vendor ID + Unit Model Code + Serial Number
if ( !AddText(NMEA0183AISMsg, Callsign, 42) ) return false; // 218-259 | 90-131 | 42 Call Sign WDE4178 -> 7 6-bit characters, as in Msg Type 5
if ( !AddDimensions(NMEA0183AISMsg, Length, Beam, PosRefStbd, PosRefBow) ) return false; // 260-289 | 132-161 | 30 Dimensions
if ( !NMEA0183AISMsg.AddIntToPayloadBin(0, 6) ) return false; // 290-295 | 162-167 | 6 Spare
return true;
}
//******************************************************************************
// Validations and Unit Transformations
//******************************************************************************
// *****************************************************************************
// 6bit Message Type -> Constant: 1 or 3, 5, 24 etc.
bool AddMessageType(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t MessageType) {
if (MessageType < 0 || MessageType > 24 ) MessageType = 1;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(MessageType, 6) ) return false;
return true;
}
// *****************************************************************************
// 2bit Repeat Indicator: 0 = default; 3 = do not repeat any more
bool AddRepeat(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t Repeat) {
if (Repeat < 0 || Repeat > 3) Repeat = 0;
if ( !NMEA0183AISMsg.AddIntToPayloadBin(Repeat, 2) ) return false;
return true;
}
// *****************************************************************************
// 30bit UserID = MMSI (9 decimal digits)
bool AddUserID(tNMEA0183AISMsg &NMEA0183AISMsg, uint32_t UserID) {
if (UserID < 0||UserID > 999999999) UserID = 0;
if ( !NMEA0183AISMsg.AddIntToPayloadBin(UserID, 30) ) return false;
return true;
}
// *****************************************************************************
// 30 bit IMO Number
// 0 = not available = default – Not applicable to SAR aircraft
// 0000000001-0000999999 not used
// 0001000000-0009999999 = valid IMO number;
// 0010000000-1073741823 = official flag state number.
bool AddIMONumber(tNMEA0183AISMsg &NMEA0183AISMsg, uint32_t &IMONumber) {
uint32_t iTemp;
( (IMONumber >= 999999 && IMONumber <= 9999999)||(IMONumber >= 10000000 && IMONumber <= 1073741823) )? iTemp = IMONumber : iTemp = 0;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 30) ) return false;
return true;
}
// *****************************************************************************
// 42bit Callsign alphanumeric value, max 7 six-bit characters
// 120bit Name or Destination
bool AddText(tNMEA0183AISMsg &NMEA0183AISMsg, char *FieldVal, uint8_t length) {
uint8_t len = length/6;
if ( strlen(FieldVal) > len ) FieldVal[len] = 0;
if ( !NMEA0183AISMsg.AddEncodedCharToPayloadBin(FieldVal, length) ) return false;
return true;
}
// *****************************************************************************
// Calculate Dimension A, B, C, D
// double PosRefBow 240-248 | 9 [m] Dimension to Bow, reference for pos. A
// Length - PosRefBow 249-257 | 9 [m] Dimension to Stern, reference for pos. B
// Beam - PosRefStbd 258-263 | 6 [m] Dimension to Port, reference for pos. C
// PosRefStbd 264-269 | 6 [m] Dimension to Starboard, reference for pos. D
// Ship dimensions will be 0 if not available. For the dimensions to bow and stern,
// the special value 511 indicates 511 meters or greater;
// for the dimensions to port and starboard, the special value 63 indicates 63 meters or greater.
// 30 Bit
bool AddDimensions(tNMEA0183AISMsg &NMEA0183AISMsg, double Length, double Beam, double PosRefStbd, double PosRefBow) {
uint16_t _PosRefBow = 0;
uint16_t _PosRefStern = 0;
uint16_t _PosRefStbd = 0;
uint16_t _PosRefPort = 0;
if ( PosRefBow >= 0.0 && PosRefBow <= 511.0 ) {
_PosRefBow = ceil(PosRefBow);
} else {
_PosRefBow = 511;
}
if ( PosRefStbd >= 0.0 && PosRefStbd <= 63.0 ) {
_PosRefStbd = ceil(PosRefStbd);
} else {
_PosRefStbd = 63;
}
if ( !N2kIsNA(Length) ) {
_PosRefStern = ceil( Length ) - _PosRefBow;
if ( _PosRefStern < 0 ) _PosRefStern = 0;
if ( _PosRefStern > 511 ) _PosRefStern = 511;
}
if ( !N2kIsNA(Beam) ) {
_PosRefPort = ceil( Beam ) - _PosRefStbd;
if ( _PosRefPort < 0 ) _PosRefPort = 0;
if ( _PosRefPort > 63 ) _PosRefPort = 63;
}
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(_PosRefBow, 9) ) return false;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(_PosRefStern, 9) ) return false;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(_PosRefPort, 6) ) return false;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(_PosRefStbd, 6) ) return false;
return true;
}
// *****************************************************************************
// 4 Bit Navigational Status e.g.: "Under way sailing"
// Same values used as in tN2kAISNavStatus, so we can use direct numbers
bool AddNavStatus(tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t &NavStatus) {
uint8_t iTemp;
(NavStatus >= 0 && NavStatus <= 15 )? iTemp = NavStatus : iTemp = 15;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 4) ) return false;
return true;
}
// *****************************************************************************
// 8bit [rad/s -> degree/minute] Rate of Turn ROT 128 = N/A
// 0 = not turning
// 1…126 = turning right at up to 708 degrees per minute or higher
// 1…-126 = turning left at up to 708 degrees per minute or higher
// 127 = turning right at more than 5deg/30s (No TI available)
// -127 = turning left at more than 5deg/30s (No TI available)
// 128 (80 hex) indicates no turn information available (default)
bool AddROT(tNMEA0183AISMsg &NMEA0183AISMsg, double &rot) {
int8_t iTemp;
if ( N2kIsNA(rot)) iTemp = 128;
else {
rot *= radsToDegMin;
(rot > -128.0 && rot < 128.0)? iTemp = aRoundToInt(rot) : iTemp = 128;
}
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 8) ) return false;
return true;
}
// *****************************************************************************
// 10 bit [m/s -> kts] SOG x10, 1023 = N/A
// Speed over ground is in 0.1-knot resolution from 0 to 102 knots.
// Value 1023 indicates speed is not available, value 1022 indicates 102.2 knots or higher.
bool AddSOG (tNMEA0183AISMsg &NMEA0183AISMsg, double &sog) {
int16_t iTemp;
if ( sog < 0.0 ) iTemp = 1023;
else {
sog *= msTokn;
if (sog > 102.2) iTemp = 1023;
else iTemp = aRoundToInt( 10 * sog );
}
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 10) ) return false;
return true;
}
// *****************************************************************************
// 28 bit @TODO check negative values
// Values up to plus or minus 180 degrees, East = positive, West = negative.
// A value of 181 degrees (0x6791AC0 hex) indicates that longitude is not available and is the default.
// AIS Longitude is given in in 1/10000 min; divide by 600000.0 to obtain degrees.
bool AddLongitude(tNMEA0183AISMsg &NMEA0183AISMsg, double &Longitude) {
int32_t iTemp;
(Longitude >= -180.0 && Longitude <= 180.0)? iTemp = (int) (Longitude * 600000) : iTemp = 181 * 600000;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 28) ) return false;
return true;
}
// *****************************************************************************
// 27 bit
// Values up to plus or minus 90 degrees, North = positive, South = negative.
// A value of 91 degrees (0x3412140 hex) indicates latitude is not available and is the default.
bool AddLatitude(tNMEA0183AISMsg &NMEA0183AISMsg, double &Latitude) {
int32_t iTemp;
(Latitude >= -90.0 && Latitude <= 90.0)? iTemp = (int) (Latitude * 600000) : iTemp = 91 * 600000;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 27) ) return false;
return true;
}
// ****************************************************************************
// 9 bit True Heading (HDG) 0 to 359 degrees, 511 = not available.
bool AddHeading (tNMEA0183AISMsg &NMEA0183AISMsg, double &heading) {
uint16_t iTemp;
if ( N2kIsNA(heading) ) iTemp = 511;
else {
heading *= radToDeg;
(heading >= 0.0 && heading <= 359.0 )? iTemp = aRoundToInt( heading ) : iTemp = 511;
}
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 9) ) return false;
return true;
}
// *****************************************************************************
// 12bit Relative to true north, to 0.1 degree precision
bool AddCOG(tNMEA0183AISMsg &NMEA0183AISMsg, double cog) {
int16_t iTemp;
cog *= radToDeg;
if ( cog >= 0.0 && cog < 360.0 ) { iTemp = aRoundToInt( cog * 10 ); } else { iTemp = 3600; }
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 12) ) return false;
return true;
}
// *****************************************************************************
// 6bit Seconds in UTC timestamp should be 0-59, except for these special values:
// 60 if time stamp is not available (default)
// 61 if positioning system is in manual input mode
// 62 if Electronic Position Fixing System operates in estimated (dead reckoning) mode,
// 63 if the positioning system is inoperative.
bool AddSeconds (tNMEA0183AISMsg &NMEA0183AISMsg, uint8_t &Seconds) {
uint8_t iTemp;
(Seconds >= 0 && Seconds <= 63 )? iTemp = Seconds : iTemp = 60;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(iTemp, 6) ) return false;
return true;
}
// *****************************************************************************
// 4 bit Position Fix Type, See "EPFD Fix Types" 0 (default)
bool AddEPFDFixType(tNMEA0183AISMsg &NMEA0183AISMsg, tN2kGNSStype &GNSStype) {
// Translate tN2kGNSStype to AIS conventions
// 3 & 4 not defined in AIS -> we take 1 for GPS
uint8_t fixType = 0;
switch (GNSStype) {
case 0: // GPS
case 3: // GPS+SBAS/WAAS
case 4: // GPS+SBAS/WAAS+GLONASS
fixType = 1; break;
case 1: // GLONASS
fixType = 2; break;
case 2: // GPS+GLONASS
fixType = 3; break;
case 5: // Chayka
fixType = 5; break;
case 6: // integrated
fixType = 6; break;
case 7: // surveyed
fixType = 7; break;
case 8: // Galileo
fixType = 8; break;
default:
fixType = 0;
}
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(fixType, 4) ) return false;
return true;
}
// *****************************************************************************
// 8 bit Maxiumum present static draught
// In 1/10 m, 255 = draught 25.5 m or greater, 0 = not available = default; in accordance with IMO Resolution A.851
bool AddStaticDraught(tNMEA0183AISMsg &NMEA0183AISMsg, double &Draught) {
uint8_t staticDraught;
if ( N2kIsNA(Draught) ) staticDraught = 0;
else if (Draught < 0.0) staticDraught = 0;
else if (Draught>25.5) staticDraught = 255;
else staticDraught = (int) ceil( 10.0 * Draught);
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(staticDraught, 8) ) return false;
return true;
}
// *****************************************************************************
// 20bit Estimated time of arrival; MMDDHHMM UTC
// 4 Bits 19-16: month; 1-12; 0 = not available = default
// 5 Bits 15-11: day; 1-31; 0 = not available = default
// 5 Bits 10-6: hour; 0-23; 24 = not available = default
// 6 Bits 5-0: minute; 0-59; 60 = not available = default
// N2k Field #7: ETA Time - Seconds since midnight Bits: 32 Units: s
// Type: Time Resolution: 0.0001 Signed: false e.g. 36000.00
// N2k Field #8: ETA Date - Days since January 1, 1970 Bits: 16
// Units: days Type: Date Resolution: 1 Signed: false e.g. 18184
bool AddETADateTime(tNMEA0183AISMsg &NMEA0183AISMsg, uint16_t &ETAdate, double &ETAtime) {
uint8_t month = 0;
uint8_t day = 0;
uint8_t hour = 24;
uint8_t minute = 60;
if (!N2kIsNA(ETAdate) && ETAdate > 0 ) {
tmElements_t tm;
#ifndef _Time_h
time_t t=NMEA0183AISMsg.daysToTime_t(ETAdate);
#else
time_t t=ETAdate*86400;
#endif
NMEA0183AISMsg.breakTime(t, tm);
month = (uint8_t) NMEA0183AISMsg.GetMonth(tm);
day = (uint8_t) NMEA0183AISMsg.GetDay(tm);
}
if ( !N2kIsNA(ETAtime) && ETAtime >= 0 ) {
double temp = ETAtime / 3600;
hour = (int) temp;
minute = (int) ((temp - hour) * 60);
} else {
hour = 24;
minute = 60;
}
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(month, 4) ) return false;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(day, 5) ) return false;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(hour, 5) ) return false;
if ( ! NMEA0183AISMsg.AddIntToPayloadBin(minute, 6) ) return false;
return true;
}
| 53.90035 | 174 | 0.632837 | [
"vector",
"model"
] |
a7b5cc7ff2c76f85e019513861abaf495dc4aa99 | 1,089 | cpp | C++ | src/transforms/linear.cpp | vorsselmansphilip/SenseEsp-Universal-Module | 41af4dca2f65c527551848f1246986d639d4fdfd | [
"Apache-2.0"
] | 1 | 2020-12-05T01:50:56.000Z | 2020-12-05T01:50:56.000Z | src/transforms/linear.cpp | vorsselmansphilip/SenseEsp-Universal-Module | 41af4dca2f65c527551848f1246986d639d4fdfd | [
"Apache-2.0"
] | null | null | null | src/transforms/linear.cpp | vorsselmansphilip/SenseEsp-Universal-Module | 41af4dca2f65c527551848f1246986d639d4fdfd | [
"Apache-2.0"
] | null | null | null | #include "linear.h"
// Linear
Linear::Linear(float k, float c, String config_path) :
NumericTransform(config_path),
k{ k },
c{ c } {
className = "Linear";
load_configuration();
}
void Linear::set_input(float input, uint8_t inputChannel) {
output = k * input + c;
notify();
}
JsonObject& Linear::get_configuration(JsonBuffer& buf) {
JsonObject& root = buf.createObject();
root["k"] = k;
root["c"] = c;
root["value"] = output;
return root;
}
static const char SCHEMA[] PROGMEM = R"({
"type": "object",
"properties": {
"k": { "title": "Multiplier", "type": "number" },
"c": { "title": "Constant offset", "type": "number" },
"value": { "title": "Last value", "type" : "number", "readOnly": true }
}
})";
String Linear::get_config_schema() {
return FPSTR(SCHEMA);
}
bool Linear::set_configuration(const JsonObject& config) {
String expected[] = {"k", "c" };
for (auto str : expected) {
if (!config.containsKey(str)) {
return false;
}
}
k = config["k"];
c = config["c"];
return true;
}
| 20.942308 | 79 | 0.58494 | [
"object"
] |
a7b6755686dc0fcc70a516c8dc706677c84afffe | 3,531 | hpp | C++ | include/dialogs/LoadNukeProjDialog.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 47 | 2016-07-27T07:22:06.000Z | 2021-08-17T13:08:19.000Z | include/dialogs/LoadNukeProjDialog.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 1 | 2016-09-24T06:04:39.000Z | 2016-09-25T10:34:19.000Z | include/dialogs/LoadNukeProjDialog.hpp | vinben/Rotopp | f0c25db5bd25074c55ff0f67539a2452d92aaf72 | [
"Unlicense"
] | 13 | 2016-07-27T10:44:35.000Z | 2020-07-01T21:08:33.000Z | /**************************************************************************
** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):
**
** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds
** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell
**
** w.li AT cs.ucl.ac.uk
** http://visual.cs.ucl.ac.uk/pubs/rotopp
**
** Copyright (c) 2016, Wenbin Li
** 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 and data must retain the above
** copyright notice, this list of conditions and the following disclaimer.
** -- Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA 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.
***************************************************************************/
#ifndef LOADNUKEPROJDIALOG_H
#define LOADNUKEPROJDIALOG_H
#include <QDialog>
#include <QLayout>
#include <QFormLayout>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QDebug>
#include <QComboBox>
class LoadNukeProjDialog : public QDialog
{
Q_OBJECT
public:
LoadNukeProjDialog();
// void display();
QString getFiles();
QString getName(){return nameEdit->text();}
QString getCurveName(){return curveNameEdit->text();}
QString getProjPath(){return projPathEdit->text();}
QString getNukeFileName(){return nukePathEdit->text();}
bool hasSrcImgs(){return flagLoadImgs;}
bool hasSrcVideo(){return flagLoadVideo;}
private slots:
void chooseImgFold();
void chooseProjFold();
void chooseNukeFile();
private:
bool flagLoadImgs;
bool flagLoadVideo;
QFormLayout *formLayout;
QVBoxLayout *globeLayout;
QHBoxLayout *videoLayout;
QHBoxLayout *NukeFileLayout;
QHBoxLayout *projPathLayout;
QHBoxLayout *nameLayout;
QLabel *pathLabel;
QLabel *projPathLabel;
QLabel *orLabel;
QLabel *nukeLabel;
QLineEdit *nameEdit;
QLineEdit *curveNameEdit;
QLineEdit *videoPathEdit;
QLineEdit *projPathEdit;
QLineEdit *nukePathEdit;
QPushButton *projPathButton;
QPushButton *loadVideoButton;
QPushButton *loadImgButton;
QPushButton *nukePathButton;
QPushButton *okButton;
QPushButton *cancelButton;
QDialogButtonBox *buttonBox;
QString projPath;
QString srcVideo;
QString srcImg;
int fpsFrequence;
};
#endif // LOADNUKEPROJDIALOG_H
| 32.394495 | 86 | 0.708864 | [
"shape"
] |
a7b71d30cb97a7a0c49bdeb3fa9c5cf2a62a2ee4 | 5,548 | cpp | C++ | CSPong/AppSource/Game/Camera/CameraTiltComponent.cpp | angelahnicole/Benchmarking-CSPong | 7efa0913410919291ea8de9ee4d0c4993b5d761e | [
"MIT"
] | null | null | null | CSPong/AppSource/Game/Camera/CameraTiltComponent.cpp | angelahnicole/Benchmarking-CSPong | 7efa0913410919291ea8de9ee4d0c4993b5d761e | [
"MIT"
] | null | null | null | CSPong/AppSource/Game/Camera/CameraTiltComponent.cpp | angelahnicole/Benchmarking-CSPong | 7efa0913410919291ea8de9ee4d0c4993b5d761e | [
"MIT"
] | null | null | null | //
// CameraTiltComponent.cpp
// CSPong
// Created by Scott Downie on 02/07/2014.
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Tag Games Limited
//
// 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 <Game/Camera/CameraTiltComponent.h>
#include <ChilliSource/Core/Base.h>
#include <ChilliSource/Core/Entity.h>
#include <ChilliSource/Core/Math.h>
#include <ChilliSource/Input/Accelerometer.h>
namespace CSPong
{
CS_DEFINE_NAMEDTYPE(CameraTiltComponent);
//----------------------------------------------------------
//----------------------------------------------------------
CameraTiltComponent::CameraTiltComponent(const CSCore::Vector3& in_viewDirection)
: m_restingViewDirection(in_viewDirection)
{
}
//----------------------------------------------------------
//----------------------------------------------------------
bool CameraTiltComponent::IsA(CSCore::InterfaceIDType in_interfaceId) const
{
return in_interfaceId == CameraTiltComponent::InterfaceID;
}
//----------------------------------------------------
//----------------------------------------------------
void CameraTiltComponent::OnAddedToScene()
{
m_accelerometer = CSCore::Application::Get()->GetSystem<CSInput::Accelerometer>();
if(m_accelerometer != nullptr)
{
m_accelerometer->StartUpdating();
}
}
//----------------------------------------------------
//----------------------------------------------------
void CameraTiltComponent::OnRemovedFromScene()
{
if(m_accelerometer != nullptr)
{
m_accelerometer->StopUpdating();
}
m_accelerometer = nullptr;
}
//----------------------------------------------------
//----------------------------------------------------
void CameraTiltComponent::OnFixedUpdate(f32 in_timeSinceLastUpdate)
{
if (m_accelerometer != nullptr)
{
const f32 k_angleFromFlat = -CSCore::MathUtils::k_pi * 0.25f;
const f32 k_accelerationFactor = 40.0f;
const f32 k_deadzoneLimit = 10.0f;
const f32 k_drag = 0.85f;
const f32 k_scale = 1.0f;
//calculate the offset from the perfect down vector from the accelerometer
CSCore::Matrix4 matZDownSpace;
matZDownSpace.RotateX(-k_angleFromFlat);
CSCore::Vector3 perfectDown = CSCore::Vector3::k_unitNegativeZ;
CSCore::Vector3 reading = m_accelerometer->GetAcceleration();
CSCore::Vector3 actualDown = reading * matZDownSpace;
CSCore::Vector3 offset = perfectDown - actualDown;
CSCore::Vector3 offsetXY = CSCore::Vector3(offset.x, offset.y, 0.0f);
CSCore::Vector3 offsetXYDirection = CSCore::Vector3::Normalise(offsetXY);
//calculate the angle and magnitude of the acceleration
f32 angle = -CSCore::MathUtils::k_pi / 2.0f - atan2(offsetXYDirection.y, offsetXYDirection.x);
f32 accelerationMagnitude = offsetXY.Length() * k_accelerationFactor * in_timeSinceLastUpdate;
//calulate the acceleration vector taking into account a small deadzone
f32 deadZoneMagnitude = k_deadzoneLimit * in_timeSinceLastUpdate;
CSCore::Vector3 acceleration;
if (accelerationMagnitude > deadZoneMagnitude)
{
acceleration.x = std::sin(angle) * (accelerationMagnitude - deadZoneMagnitude) * k_scale;
acceleration.z = 0.0f;
acceleration.y = std::cos(angle) * (accelerationMagnitude - deadZoneMagnitude) * k_scale;
}
else
{
acceleration = CSCore::Vector3::k_zero;
}
//calculate the velocity and offset and apply drag.
m_tiltVelocity += acceleration;
m_tiltVelocity *= k_drag;
m_unitTiltOffset += m_tiltVelocity * in_timeSinceLastUpdate;
m_unitTiltOffset *= k_drag;
CSCore::Vector3 position(GetEntity()->GetTransform().GetLocalPosition());
CSCore::Vector3 target(position + m_restingViewDirection);
target += m_unitTiltOffset * m_restingViewDirection.Length();
GetEntity()->GetTransform().SetLookAt(position, target, CSCore::Vector3::k_unitPositiveY);
}
}
}
| 43.007752 | 106 | 0.583814 | [
"vector"
] |
a7b98834ac4dc78eb0321b1d9c0aaab229230180 | 142,346 | cpp | C++ | libraries/ine-vm/tests/spec/const_tests.cpp | inery-blockchain/inery | 2823539f76a0debae22b6783781b1374c63a59d8 | [
"MIT"
] | null | null | null | libraries/ine-vm/tests/spec/const_tests.cpp | inery-blockchain/inery | 2823539f76a0debae22b6783781b1374c63a59d8 | [
"MIT"
] | null | null | null | libraries/ine-vm/tests/spec/const_tests.cpp | inery-blockchain/inery | 2823539f76a0debae22b6783781b1374c63a59d8 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <cmath>
#include <cstdlib>
#include <catch2/catch.hpp>
#include <utils.hpp>
#include <wasm_config.hpp>
#include <inery/vm/backend.hpp>
using namespace inery;
using namespace inery::vm;
extern wasm_allocator wa;
BACKEND_TEST_CASE( "Testing wasm <const_0_wasm>", "[const_0_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.0.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_1_wasm>", "[const_1_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.1.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_100_wasm>", "[const_100_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.100.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_101_wasm>", "[const_101_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.101.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_102_wasm>", "[const_102_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.102.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_103_wasm>", "[const_103_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.103.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_104_wasm>", "[const_104_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.104.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_105_wasm>", "[const_105_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.105.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_106_wasm>", "[const_106_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.106.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_107_wasm>", "[const_107_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.107.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_108_wasm>", "[const_108_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.108.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_109_wasm>", "[const_109_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.109.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_110_wasm>", "[const_110_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.110.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_111_wasm>", "[const_111_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.111.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_112_wasm>", "[const_112_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.112.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_113_wasm>", "[const_113_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.113.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_114_wasm>", "[const_114_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.114.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_115_wasm>", "[const_115_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.115.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_116_wasm>", "[const_116_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.116.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_117_wasm>", "[const_117_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.117.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_118_wasm>", "[const_118_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.118.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922819));
}
BACKEND_TEST_CASE( "Testing wasm <const_119_wasm>", "[const_119_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.119.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406467));
}
BACKEND_TEST_CASE( "Testing wasm <const_12_wasm>", "[const_12_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.12.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_120_wasm>", "[const_120_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.120.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922816));
}
BACKEND_TEST_CASE( "Testing wasm <const_121_wasm>", "[const_121_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.121.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406464));
}
BACKEND_TEST_CASE( "Testing wasm <const_122_wasm>", "[const_122_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.122.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_123_wasm>", "[const_123_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.123.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_124_wasm>", "[const_124_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.124.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_125_wasm>", "[const_125_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.125.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_126_wasm>", "[const_126_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.126.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_127_wasm>", "[const_127_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.127.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_128_wasm>", "[const_128_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.128.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783616));
}
BACKEND_TEST_CASE( "Testing wasm <const_129_wasm>", "[const_129_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.129.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267264));
}
BACKEND_TEST_CASE( "Testing wasm <const_13_wasm>", "[const_13_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.13.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_130_wasm>", "[const_130_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.130.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_131_wasm>", "[const_131_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.131.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_132_wasm>", "[const_132_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.132.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_133_wasm>", "[const_133_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.133.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_134_wasm>", "[const_134_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.134.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_135_wasm>", "[const_135_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.135.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_136_wasm>", "[const_136_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.136.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_137_wasm>", "[const_137_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.137.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_138_wasm>", "[const_138_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.138.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_139_wasm>", "[const_139_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.139.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_140_wasm>", "[const_140_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.140.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_141_wasm>", "[const_141_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.141.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_142_wasm>", "[const_142_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.142.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_143_wasm>", "[const_143_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.143.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_144_wasm>", "[const_144_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.144.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_145_wasm>", "[const_145_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.145.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_146_wasm>", "[const_146_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.146.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_147_wasm>", "[const_147_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.147.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_148_wasm>", "[const_148_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.148.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_149_wasm>", "[const_149_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.149.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_150_wasm>", "[const_150_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.150.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_151_wasm>", "[const_151_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.151.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_152_wasm>", "[const_152_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.152.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_153_wasm>", "[const_153_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.153.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_154_wasm>", "[const_154_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.154.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783619));
}
BACKEND_TEST_CASE( "Testing wasm <const_155_wasm>", "[const_155_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.155.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267267));
}
BACKEND_TEST_CASE( "Testing wasm <const_156_wasm>", "[const_156_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.156.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783616));
}
BACKEND_TEST_CASE( "Testing wasm <const_157_wasm>", "[const_157_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.157.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267264));
}
BACKEND_TEST_CASE( "Testing wasm <const_158_wasm>", "[const_158_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.158.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_159_wasm>", "[const_159_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.159.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_16_wasm>", "[const_16_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.16.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_160_wasm>", "[const_160_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.160.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_161_wasm>", "[const_161_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.161.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_162_wasm>", "[const_162_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.162.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_163_wasm>", "[const_163_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.163.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_164_wasm>", "[const_164_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.164.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_165_wasm>", "[const_165_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.165.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_166_wasm>", "[const_166_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.166.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_167_wasm>", "[const_167_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.167.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_168_wasm>", "[const_168_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.168.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_169_wasm>", "[const_169_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.169.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_17_wasm>", "[const_17_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.17.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_170_wasm>", "[const_170_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.170.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783616));
}
BACKEND_TEST_CASE( "Testing wasm <const_171_wasm>", "[const_171_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.171.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267264));
}
BACKEND_TEST_CASE( "Testing wasm <const_172_wasm>", "[const_172_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.172.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_173_wasm>", "[const_173_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.173.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_174_wasm>", "[const_174_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.174.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783617));
}
BACKEND_TEST_CASE( "Testing wasm <const_175_wasm>", "[const_175_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.175.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267265));
}
BACKEND_TEST_CASE( "Testing wasm <const_176_wasm>", "[const_176_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.176.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1484783618));
}
BACKEND_TEST_CASE( "Testing wasm <const_177_wasm>", "[const_177_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.177.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3632267266));
}
BACKEND_TEST_CASE( "Testing wasm <const_178_wasm>", "[const_178_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.178.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(0));
}
BACKEND_TEST_CASE( "Testing wasm <const_179_wasm>", "[const_179_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.179.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483648));
}
BACKEND_TEST_CASE( "Testing wasm <const_18_wasm>", "[const_18_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.18.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_180_wasm>", "[const_180_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.180.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_181_wasm>", "[const_181_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.181.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483649));
}
BACKEND_TEST_CASE( "Testing wasm <const_182_wasm>", "[const_182_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.182.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_183_wasm>", "[const_183_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.183.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483649));
}
BACKEND_TEST_CASE( "Testing wasm <const_184_wasm>", "[const_184_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.184.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_185_wasm>", "[const_185_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.185.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483649));
}
BACKEND_TEST_CASE( "Testing wasm <const_186_wasm>", "[const_186_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.186.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_187_wasm>", "[const_187_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.187.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483649));
}
BACKEND_TEST_CASE( "Testing wasm <const_188_wasm>", "[const_188_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.188.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_189_wasm>", "[const_189_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.189.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483649));
}
BACKEND_TEST_CASE( "Testing wasm <const_19_wasm>", "[const_19_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.19.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_190_wasm>", "[const_190_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.190.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_191_wasm>", "[const_191_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.191.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483650));
}
BACKEND_TEST_CASE( "Testing wasm <const_192_wasm>", "[const_192_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.192.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_193_wasm>", "[const_193_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.193.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483650));
}
BACKEND_TEST_CASE( "Testing wasm <const_194_wasm>", "[const_194_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.194.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_195_wasm>", "[const_195_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.195.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483650));
}
BACKEND_TEST_CASE( "Testing wasm <const_196_wasm>", "[const_196_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.196.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_197_wasm>", "[const_197_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.197.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483650));
}
BACKEND_TEST_CASE( "Testing wasm <const_198_wasm>", "[const_198_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.198.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_199_wasm>", "[const_199_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.199.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483650));
}
BACKEND_TEST_CASE( "Testing wasm <const_20_wasm>", "[const_20_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.20.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_200_wasm>", "[const_200_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.200.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_201_wasm>", "[const_201_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.201.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483650));
}
BACKEND_TEST_CASE( "Testing wasm <const_202_wasm>", "[const_202_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.202.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_203_wasm>", "[const_203_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.203.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483650));
}
BACKEND_TEST_CASE( "Testing wasm <const_204_wasm>", "[const_204_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.204.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(3));
}
BACKEND_TEST_CASE( "Testing wasm <const_205_wasm>", "[const_205_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.205.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2147483651));
}
BACKEND_TEST_CASE( "Testing wasm <const_206_wasm>", "[const_206_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.206.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2139095039));
}
BACKEND_TEST_CASE( "Testing wasm <const_207_wasm>", "[const_207_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.207.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(4286578687));
}
BACKEND_TEST_CASE( "Testing wasm <const_208_wasm>", "[const_208_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.208.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2139095039));
}
BACKEND_TEST_CASE( "Testing wasm <const_209_wasm>", "[const_209_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.209.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(4286578687));
}
BACKEND_TEST_CASE( "Testing wasm <const_21_wasm>", "[const_21_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.21.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_210_wasm>", "[const_210_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.210.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2139095039));
}
BACKEND_TEST_CASE( "Testing wasm <const_211_wasm>", "[const_211_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.211.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(4286578687));
}
BACKEND_TEST_CASE( "Testing wasm <const_212_wasm>", "[const_212_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.212.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719808));
}
BACKEND_TEST_CASE( "Testing wasm <const_213_wasm>", "[const_213_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.213.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495616));
}
BACKEND_TEST_CASE( "Testing wasm <const_214_wasm>", "[const_214_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.214.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_215_wasm>", "[const_215_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.215.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_216_wasm>", "[const_216_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.216.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_217_wasm>", "[const_217_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.217.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_218_wasm>", "[const_218_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.218.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_219_wasm>", "[const_219_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.219.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_22_wasm>", "[const_22_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.22.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_220_wasm>", "[const_220_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.220.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_221_wasm>", "[const_221_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.221.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_222_wasm>", "[const_222_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.222.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_223_wasm>", "[const_223_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.223.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_224_wasm>", "[const_224_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.224.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_225_wasm>", "[const_225_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.225.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_226_wasm>", "[const_226_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.226.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_227_wasm>", "[const_227_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.227.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_228_wasm>", "[const_228_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.228.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_229_wasm>", "[const_229_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.229.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_23_wasm>", "[const_23_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.23.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_230_wasm>", "[const_230_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.230.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_231_wasm>", "[const_231_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.231.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_232_wasm>", "[const_232_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.232.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_233_wasm>", "[const_233_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.233.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_234_wasm>", "[const_234_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.234.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_235_wasm>", "[const_235_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.235.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_236_wasm>", "[const_236_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.236.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719811));
}
BACKEND_TEST_CASE( "Testing wasm <const_237_wasm>", "[const_237_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.237.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495619));
}
BACKEND_TEST_CASE( "Testing wasm <const_238_wasm>", "[const_238_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.238.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719808));
}
BACKEND_TEST_CASE( "Testing wasm <const_239_wasm>", "[const_239_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.239.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495616));
}
BACKEND_TEST_CASE( "Testing wasm <const_24_wasm>", "[const_24_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.24.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_240_wasm>", "[const_240_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.240.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_241_wasm>", "[const_241_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.241.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_242_wasm>", "[const_242_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.242.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_243_wasm>", "[const_243_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.243.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_244_wasm>", "[const_244_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.244.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_245_wasm>", "[const_245_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.245.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_246_wasm>", "[const_246_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.246.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_247_wasm>", "[const_247_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.247.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_248_wasm>", "[const_248_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.248.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719809));
}
BACKEND_TEST_CASE( "Testing wasm <const_249_wasm>", "[const_249_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.249.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495617));
}
BACKEND_TEST_CASE( "Testing wasm <const_25_wasm>", "[const_25_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.25.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_250_wasm>", "[const_250_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.250.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_251_wasm>", "[const_251_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.251.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_252_wasm>", "[const_252_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.252.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_253_wasm>", "[const_253_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.253.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_254_wasm>", "[const_254_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.254.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_255_wasm>", "[const_255_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.255.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_256_wasm>", "[const_256_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.256.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_257_wasm>", "[const_257_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.257.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_258_wasm>", "[const_258_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.258.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_259_wasm>", "[const_259_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.259.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_260_wasm>", "[const_260_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.260.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719810));
}
BACKEND_TEST_CASE( "Testing wasm <const_261_wasm>", "[const_261_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.261.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495618));
}
BACKEND_TEST_CASE( "Testing wasm <const_262_wasm>", "[const_262_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.262.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1905022642377719811));
}
BACKEND_TEST_CASE( "Testing wasm <const_263_wasm>", "[const_263_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.263.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(11128394679232495619));
}
BACKEND_TEST_CASE( "Testing wasm <const_264_wasm>", "[const_264_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.264.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9106278446543142912));
}
BACKEND_TEST_CASE( "Testing wasm <const_265_wasm>", "[const_265_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.265.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(18329650483397918720));
}
BACKEND_TEST_CASE( "Testing wasm <const_266_wasm>", "[const_266_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.266.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9106278446543142913));
}
BACKEND_TEST_CASE( "Testing wasm <const_267_wasm>", "[const_267_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.267.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(18329650483397918721));
}
BACKEND_TEST_CASE( "Testing wasm <const_268_wasm>", "[const_268_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.268.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9106278446543142913));
}
BACKEND_TEST_CASE( "Testing wasm <const_269_wasm>", "[const_269_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.269.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(18329650483397918721));
}
BACKEND_TEST_CASE( "Testing wasm <const_270_wasm>", "[const_270_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.270.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9106278446543142914));
}
BACKEND_TEST_CASE( "Testing wasm <const_271_wasm>", "[const_271_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.271.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(18329650483397918722));
}
BACKEND_TEST_CASE( "Testing wasm <const_272_wasm>", "[const_272_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.272.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315008));
}
BACKEND_TEST_CASE( "Testing wasm <const_273_wasm>", "[const_273_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.273.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090816));
}
BACKEND_TEST_CASE( "Testing wasm <const_274_wasm>", "[const_274_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.274.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315009));
}
BACKEND_TEST_CASE( "Testing wasm <const_275_wasm>", "[const_275_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.275.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090817));
}
BACKEND_TEST_CASE( "Testing wasm <const_276_wasm>", "[const_276_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.276.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315009));
}
BACKEND_TEST_CASE( "Testing wasm <const_277_wasm>", "[const_277_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.277.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090817));
}
BACKEND_TEST_CASE( "Testing wasm <const_278_wasm>", "[const_278_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.278.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315009));
}
BACKEND_TEST_CASE( "Testing wasm <const_279_wasm>", "[const_279_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.279.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090817));
}
BACKEND_TEST_CASE( "Testing wasm <const_280_wasm>", "[const_280_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.280.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315009));
}
BACKEND_TEST_CASE( "Testing wasm <const_281_wasm>", "[const_281_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.281.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090817));
}
BACKEND_TEST_CASE( "Testing wasm <const_282_wasm>", "[const_282_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.282.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315009));
}
BACKEND_TEST_CASE( "Testing wasm <const_283_wasm>", "[const_283_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.283.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090817));
}
BACKEND_TEST_CASE( "Testing wasm <const_284_wasm>", "[const_284_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.284.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315010));
}
BACKEND_TEST_CASE( "Testing wasm <const_285_wasm>", "[const_285_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.285.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090818));
}
BACKEND_TEST_CASE( "Testing wasm <const_286_wasm>", "[const_286_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.286.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315010));
}
BACKEND_TEST_CASE( "Testing wasm <const_287_wasm>", "[const_287_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.287.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090818));
}
BACKEND_TEST_CASE( "Testing wasm <const_288_wasm>", "[const_288_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.288.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315010));
}
BACKEND_TEST_CASE( "Testing wasm <const_289_wasm>", "[const_289_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.289.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090818));
}
BACKEND_TEST_CASE( "Testing wasm <const_290_wasm>", "[const_290_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.290.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315010));
}
BACKEND_TEST_CASE( "Testing wasm <const_291_wasm>", "[const_291_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.291.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090818));
}
BACKEND_TEST_CASE( "Testing wasm <const_292_wasm>", "[const_292_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.292.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315010));
}
BACKEND_TEST_CASE( "Testing wasm <const_293_wasm>", "[const_293_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.293.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090818));
}
BACKEND_TEST_CASE( "Testing wasm <const_294_wasm>", "[const_294_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.294.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315010));
}
BACKEND_TEST_CASE( "Testing wasm <const_295_wasm>", "[const_295_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.295.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090818));
}
BACKEND_TEST_CASE( "Testing wasm <const_296_wasm>", "[const_296_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.296.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315010));
}
BACKEND_TEST_CASE( "Testing wasm <const_297_wasm>", "[const_297_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.297.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090818));
}
BACKEND_TEST_CASE( "Testing wasm <const_298_wasm>", "[const_298_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.298.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(7309342195222315011));
}
BACKEND_TEST_CASE( "Testing wasm <const_299_wasm>", "[const_299_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.299.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(16532714232077090819));
}
BACKEND_TEST_CASE( "Testing wasm <const_30_wasm>", "[const_30_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.30.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_300_wasm>", "[const_300_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.300.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955520));
}
BACKEND_TEST_CASE( "Testing wasm <const_301_wasm>", "[const_301_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.301.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731328));
}
BACKEND_TEST_CASE( "Testing wasm <const_302_wasm>", "[const_302_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.302.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955521));
}
BACKEND_TEST_CASE( "Testing wasm <const_303_wasm>", "[const_303_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.303.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731329));
}
BACKEND_TEST_CASE( "Testing wasm <const_304_wasm>", "[const_304_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.304.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955521));
}
BACKEND_TEST_CASE( "Testing wasm <const_305_wasm>", "[const_305_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.305.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731329));
}
BACKEND_TEST_CASE( "Testing wasm <const_306_wasm>", "[const_306_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.306.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955521));
}
BACKEND_TEST_CASE( "Testing wasm <const_307_wasm>", "[const_307_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.307.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731329));
}
BACKEND_TEST_CASE( "Testing wasm <const_308_wasm>", "[const_308_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.308.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955521));
}
BACKEND_TEST_CASE( "Testing wasm <const_309_wasm>", "[const_309_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.309.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731329));
}
BACKEND_TEST_CASE( "Testing wasm <const_31_wasm>", "[const_31_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.31.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_310_wasm>", "[const_310_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.310.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955521));
}
BACKEND_TEST_CASE( "Testing wasm <const_311_wasm>", "[const_311_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.311.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731329));
}
BACKEND_TEST_CASE( "Testing wasm <const_312_wasm>", "[const_312_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.312.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955522));
}
BACKEND_TEST_CASE( "Testing wasm <const_313_wasm>", "[const_313_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.313.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731330));
}
BACKEND_TEST_CASE( "Testing wasm <const_314_wasm>", "[const_314_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.314.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955522));
}
BACKEND_TEST_CASE( "Testing wasm <const_315_wasm>", "[const_315_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.315.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731330));
}
BACKEND_TEST_CASE( "Testing wasm <const_316_wasm>", "[const_316_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.316.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955522));
}
BACKEND_TEST_CASE( "Testing wasm <const_317_wasm>", "[const_317_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.317.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731330));
}
BACKEND_TEST_CASE( "Testing wasm <const_318_wasm>", "[const_318_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.318.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955522));
}
BACKEND_TEST_CASE( "Testing wasm <const_319_wasm>", "[const_319_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.319.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731330));
}
BACKEND_TEST_CASE( "Testing wasm <const_320_wasm>", "[const_320_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.320.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955522));
}
BACKEND_TEST_CASE( "Testing wasm <const_321_wasm>", "[const_321_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.321.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731330));
}
BACKEND_TEST_CASE( "Testing wasm <const_322_wasm>", "[const_322_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.322.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955522));
}
BACKEND_TEST_CASE( "Testing wasm <const_323_wasm>", "[const_323_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.323.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731330));
}
BACKEND_TEST_CASE( "Testing wasm <const_324_wasm>", "[const_324_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.324.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955522));
}
BACKEND_TEST_CASE( "Testing wasm <const_325_wasm>", "[const_325_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.325.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731330));
}
BACKEND_TEST_CASE( "Testing wasm <const_326_wasm>", "[const_326_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.326.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(5044031582654955523));
}
BACKEND_TEST_CASE( "Testing wasm <const_327_wasm>", "[const_327_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.327.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14267403619509731331));
}
BACKEND_TEST_CASE( "Testing wasm <const_328_wasm>", "[const_328_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.328.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(4877398396442247168));
}
BACKEND_TEST_CASE( "Testing wasm <const_329_wasm>", "[const_329_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.329.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14100770433297022976));
}
BACKEND_TEST_CASE( "Testing wasm <const_330_wasm>", "[const_330_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.330.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(4877398396442247169));
}
BACKEND_TEST_CASE( "Testing wasm <const_331_wasm>", "[const_331_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.331.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14100770433297022977));
}
BACKEND_TEST_CASE( "Testing wasm <const_332_wasm>", "[const_332_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.332.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(4877398396442247169));
}
BACKEND_TEST_CASE( "Testing wasm <const_333_wasm>", "[const_333_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.333.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14100770433297022977));
}
BACKEND_TEST_CASE( "Testing wasm <const_334_wasm>", "[const_334_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.334.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(4877398396442247170));
}
BACKEND_TEST_CASE( "Testing wasm <const_335_wasm>", "[const_335_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.335.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(14100770433297022978));
}
BACKEND_TEST_CASE( "Testing wasm <const_336_wasm>", "[const_336_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.336.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(0));
}
BACKEND_TEST_CASE( "Testing wasm <const_337_wasm>", "[const_337_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.337.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775808));
}
BACKEND_TEST_CASE( "Testing wasm <const_338_wasm>", "[const_338_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.338.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_339_wasm>", "[const_339_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.339.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775809));
}
BACKEND_TEST_CASE( "Testing wasm <const_34_wasm>", "[const_34_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.34.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_340_wasm>", "[const_340_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.340.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_341_wasm>", "[const_341_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.341.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775809));
}
BACKEND_TEST_CASE( "Testing wasm <const_342_wasm>", "[const_342_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.342.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_343_wasm>", "[const_343_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.343.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775809));
}
BACKEND_TEST_CASE( "Testing wasm <const_344_wasm>", "[const_344_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.344.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_345_wasm>", "[const_345_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.345.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775809));
}
BACKEND_TEST_CASE( "Testing wasm <const_346_wasm>", "[const_346_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.346.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(1));
}
BACKEND_TEST_CASE( "Testing wasm <const_347_wasm>", "[const_347_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.347.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775809));
}
BACKEND_TEST_CASE( "Testing wasm <const_348_wasm>", "[const_348_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.348.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_349_wasm>", "[const_349_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.349.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775810));
}
BACKEND_TEST_CASE( "Testing wasm <const_35_wasm>", "[const_35_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.35.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_350_wasm>", "[const_350_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.350.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_351_wasm>", "[const_351_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.351.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775810));
}
BACKEND_TEST_CASE( "Testing wasm <const_352_wasm>", "[const_352_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.352.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_353_wasm>", "[const_353_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.353.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775810));
}
BACKEND_TEST_CASE( "Testing wasm <const_354_wasm>", "[const_354_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.354.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_355_wasm>", "[const_355_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.355.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775810));
}
BACKEND_TEST_CASE( "Testing wasm <const_356_wasm>", "[const_356_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.356.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_357_wasm>", "[const_357_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.357.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775810));
}
BACKEND_TEST_CASE( "Testing wasm <const_358_wasm>", "[const_358_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.358.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_359_wasm>", "[const_359_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.359.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775810));
}
BACKEND_TEST_CASE( "Testing wasm <const_360_wasm>", "[const_360_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.360.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(2));
}
BACKEND_TEST_CASE( "Testing wasm <const_361_wasm>", "[const_361_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.361.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9223372036854775810));
}
BACKEND_TEST_CASE( "Testing wasm <const_362_wasm>", "[const_362_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.362.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(4503599627370499));
}
BACKEND_TEST_CASE( "Testing wasm <const_363_wasm>", "[const_363_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.363.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9227875636482146307));
}
BACKEND_TEST_CASE( "Testing wasm <const_364_wasm>", "[const_364_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.364.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9218868437227405311));
}
BACKEND_TEST_CASE( "Testing wasm <const_365_wasm>", "[const_365_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.365.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(18442240474082181119));
}
BACKEND_TEST_CASE( "Testing wasm <const_366_wasm>", "[const_366_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.366.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(9218868437227405311));
}
BACKEND_TEST_CASE( "Testing wasm <const_367_wasm>", "[const_367_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.367.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint64_t>(bkend.call_with_return(nullptr, "env", "f")->to_f64()) == UINT64_C(18442240474082181119));
}
BACKEND_TEST_CASE( "Testing wasm <const_38_wasm>", "[const_38_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.38.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_39_wasm>", "[const_39_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.39.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_4_wasm>", "[const_4_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.4.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_40_wasm>", "[const_40_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.40.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_41_wasm>", "[const_41_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.41.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_42_wasm>", "[const_42_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.42.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_43_wasm>", "[const_43_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.43.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_44_wasm>", "[const_44_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.44.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_45_wasm>", "[const_45_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.45.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_5_wasm>", "[const_5_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.5.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_50_wasm>", "[const_50_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.50.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_51_wasm>", "[const_51_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.51.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_54_wasm>", "[const_54_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.54.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_55_wasm>", "[const_55_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.55.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_58_wasm>", "[const_58_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.58.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_59_wasm>", "[const_59_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.59.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_60_wasm>", "[const_60_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.60.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_61_wasm>", "[const_61_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.61.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_68_wasm>", "[const_68_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.68.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922816));
}
BACKEND_TEST_CASE( "Testing wasm <const_69_wasm>", "[const_69_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.69.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406464));
}
BACKEND_TEST_CASE( "Testing wasm <const_70_wasm>", "[const_70_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.70.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_71_wasm>", "[const_71_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.71.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_72_wasm>", "[const_72_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.72.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_73_wasm>", "[const_73_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.73.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_74_wasm>", "[const_74_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.74.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_75_wasm>", "[const_75_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.75.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_76_wasm>", "[const_76_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.76.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_77_wasm>", "[const_77_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.77.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_78_wasm>", "[const_78_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.78.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_79_wasm>", "[const_79_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.79.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
BACKEND_TEST_CASE( "Testing wasm <const_8_wasm>", "[const_8_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.8.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_80_wasm>", "[const_80_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.80.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_81_wasm>", "[const_81_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.81.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_82_wasm>", "[const_82_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.82.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_83_wasm>", "[const_83_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.83.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_84_wasm>", "[const_84_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.84.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_85_wasm>", "[const_85_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.85.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_86_wasm>", "[const_86_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.86.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_87_wasm>", "[const_87_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.87.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_88_wasm>", "[const_88_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.88.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_89_wasm>", "[const_89_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.89.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_9_wasm>", "[const_9_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.9.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
}
BACKEND_TEST_CASE( "Testing wasm <const_90_wasm>", "[const_90_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.90.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_91_wasm>", "[const_91_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.91.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_92_wasm>", "[const_92_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.92.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922818));
}
BACKEND_TEST_CASE( "Testing wasm <const_93_wasm>", "[const_93_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.93.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406466));
}
BACKEND_TEST_CASE( "Testing wasm <const_94_wasm>", "[const_94_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.94.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922819));
}
BACKEND_TEST_CASE( "Testing wasm <const_95_wasm>", "[const_95_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.95.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406467));
}
BACKEND_TEST_CASE( "Testing wasm <const_96_wasm>", "[const_96_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.96.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922816));
}
BACKEND_TEST_CASE( "Testing wasm <const_97_wasm>", "[const_97_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.97.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406464));
}
BACKEND_TEST_CASE( "Testing wasm <const_98_wasm>", "[const_98_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.98.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(645922817));
}
BACKEND_TEST_CASE( "Testing wasm <const_99_wasm>", "[const_99_wasm_tests]" ) {
using backend_t = backend<std::nullptr_t, TestType>;
auto code = backend_t::read_wasm( std::string(wasm_directory) + "const.99.wasm");
backend_t bkend( code );
bkend.set_wasm_allocator( &wa );
bkend.initialize(nullptr);
CHECK(bit_cast<uint32_t>(bkend.call_with_return(nullptr, "env", "f")->to_f32()) == UINT32_C(2793406465));
}
| 42.390113 | 118 | 0.713592 | [
"vector"
] |
a7bb6e94c954e0ee074e1f2a010f559242faff4d | 5,828 | cc | C++ | src/sst/elements/simpleElementExample/basicClocks.cc | sudhanshu2/sst-elements | d658e5e4b26e5725488f9e93528506ddb22072ee | [
"BSD-3-Clause"
] | 58 | 2015-10-05T15:22:27.000Z | 2022-03-31T01:58:36.000Z | src/sst/elements/simpleElementExample/basicClocks.cc | sudhanshu2/sst-elements | d658e5e4b26e5725488f9e93528506ddb22072ee | [
"BSD-3-Clause"
] | 1,453 | 2015-10-07T14:51:06.000Z | 2022-03-31T22:22:28.000Z | src/sst/elements/simpleElementExample/basicClocks.cc | sudhanshu2/sst-elements | d658e5e4b26e5725488f9e93528506ddb22072ee | [
"BSD-3-Clause"
] | 109 | 2015-10-16T22:03:10.000Z | 2022-03-22T23:21:32.000Z | // Copyright 2009-2021 NTESS. Under the terms
// of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Copyright (c) 2009-2021, NTESS
// All rights reserved.
//
// Portions are copyright of other developers:
// See the file CONTRIBUTORS.TXT in the top level directory
// the distribution for more information.
//
// This file is part of the SST software package. For license
// information, see the LICENSE file in the top level directory of the
// distribution.
// This include is ***REQUIRED***
// for ALL SST implementation files
#include "sst_config.h"
#include "basicClocks.h"
using namespace SST;
using namespace SST::simpleElementExample;
/*
* During construction the basicClocks component should prepare for simulation
* - Read parameters
* - Register clocks
*/
basicClocks::basicClocks(ComponentId_t id, Params& params) : Component(id) {
// SST Output Object
out = new Output("", 1, 0, Output::STDOUT);
// Get parameters from the Python input
// Clocks can be specified by frequency or period
clock0Freq = params.find<std::string>("clock0", "1GHz");
clock1Freq = params.find<std::string>("clock1", "5ns");
clock2Freq = params.find<std::string>("clock2", "15ns");
cycleCount = params.find<Cycle_t>("clockTicks", "500");
// Use UnitAlgebra to error check the clock parameters
// Check that all frequencies have time units associated
UnitAlgebra clock0Freq_ua(clock0Freq);
UnitAlgebra clock1Freq_ua(clock1Freq);
UnitAlgebra clock2Freq_ua(clock2Freq);
if (! (clock0Freq_ua.hasUnits("Hz") || clock0Freq_ua.hasUnits("s") ) )
out->fatal(CALL_INFO, -1, "Error in %s: the 'clock0' parameter needs to have units of Hz or s\n", getName().c_str());
if (! (clock1Freq_ua.hasUnits("Hz") || clock1Freq_ua.hasUnits("s") ) )
out->fatal(CALL_INFO, -1, "Error in %s: the 'clock1' parameter needs to have units of Hz or s\n", getName().c_str());
if (! (clock2Freq_ua.hasUnits("Hz") || clock2Freq_ua.hasUnits("s") ) )
out->fatal(CALL_INFO, -1, "Error in %s: the 'clock2' parameter needs to have units of Hz or s\n", getName().c_str());
// Tell the simulation not to end until we're ready
registerAsPrimaryComponent();
primaryComponentDoNotEndSim();
// Register our clocks
// Main clock (clock 0)
// Clock can be registered with a string or UnitAlgebra, here we use the string
registerClock(clock0Freq, new Clock::Handler<basicClocks>(this, &basicClocks::mainTick));
out->output("Registering clock0 at %s\n", clock0Freq.c_str());
// Second clock, here we'll use the UnitAlgebra to register
// Clock handler can add a template parameter. In this example clock1 and clock2 share a handler but
// pass unique IDs in to it to differentiate
// We also save the registerClock return value (a TimeConverter) so that we can use it later (see mainTick)
clock1converter = registerClock(clock1Freq_ua,
new Clock::Handler<basicClocks, uint32_t>(this, &basicClocks::otherTick, 1));
out->output("Registering clock1 at %s (that's %s or %s if we convert the UnitAlgebra to string)\n",
clock1Freq.c_str(), clock1Freq_ua.toString().c_str(), clock1Freq_ua.toStringBestSI().c_str());
// Last clock, as with clock1, the handler has an extra parameter and we save the registerClock return parameter
Clock::HandlerBase* handler = new Clock::Handler<basicClocks, uint32_t>(this, &basicClocks::otherTick, 2);
clock2converter = registerClock(clock2Freq, handler);
out->output("Registering clock2 at %s\n", clock2Freq.c_str());
// This component prints the clock cycles & time every so often so calculate a print interval
// based on simulation time
printInterval = cycleCount / 10;
if (printInterval < 1)
printInterval = 1;
}
/*
* Destructor, clean up our output
*/
basicClocks::~basicClocks()
{
delete out;
}
/*
* Main clock (clock0) handler
* Every 'printInterval' cycles, this handler prints the time & cycle count for all clocks
* When cycleCount cycles have elapsed, this clock triggers the end of simulation
*/
bool basicClocks::mainTick( Cycle_t cycles)
{
// Print time in terms of clock cycles every so often
// Clock0 cycles: Number of elapsed cycles in terms of this clock
// Clock1 cycles: Number of elapsed cycles in terms of clock1 cycles, use the clock1converter to calculate this
// Clock2 cycles: Number of elapsed cycles in terms of clock2 cycles, use the clock2converter to calculate this
// Simulation cycles: Number of elapsed cycles in terms of SST Core cycles, get this from the simulator
// Simulation ns: Elapsed time in terms of nanoseconds, get this from the simulator
if (cycles % printInterval == 0) {
out->output("Clock0 cycles: %" PRIu64 ", Clock1 cycles: %" PRIu64 ", Clock2 cycles: %" PRIu64 ", SimulationCycles: %" PRIu64 ", Simulation ns: %" PRIu64 "\n",
cycles, getCurrentSimTime(clock1converter), getCurrentSimTime(clock2converter),
getCurrentSimCycle(), getCurrentSimTimeNano());
}
cycleCount--;
// Check if exit condition is met
// If so, tell the simulation it can end
if (cycleCount == 0) {
primaryComponentOKToEndSim();
return true;
} else {
return false;
}
}
/*
* Other clock (clock1 & clock2) handler
* Let both clocks run for 10 cycles
*/
bool basicClocks::otherTick( Cycle_t cycles, uint32_t id )
{
out->output("Clock #%d - TICK num: %" PRIu64 "\n", id, cycles);
if (cycles == 10) {
return true; // Stop calling this handler after 10 cycles
} else {
return false; // Keep calling this handler if it hasn't been 10 cycles yet
}
}
| 38.596026 | 166 | 0.688572 | [
"object"
] |
a7c0b55243f07cbc1e3673a04284851594ae9612 | 11,108 | cpp | C++ | demos/demo_scenerender_json/demo_scenerender_json.cpp | walkfish8/scenerender | 89518cbbcad38d2db5e586648025e772dcbbee42 | [
"MIT"
] | 3 | 2019-04-16T15:45:44.000Z | 2020-03-29T02:29:07.000Z | demos/demo_scenerender_json/demo_scenerender_json.cpp | walkfish8/scenerender | 89518cbbcad38d2db5e586648025e772dcbbee42 | [
"MIT"
] | null | null | null | demos/demo_scenerender_json/demo_scenerender_json.cpp | walkfish8/scenerender | 89518cbbcad38d2db5e586648025e772dcbbee42 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include "json\json.h"
#include "timer.h"
#include "logger.h"
#include "scenerender.h"
#include <chrono>
#include <Windows.h>
std::vector<std::string> FindFilesInDirectory(const std::string& _dir,
const std::string& _format);
std::string FileName(const std::string& _file_path)
{
return _file_path.substr(_file_path.rfind('/') + 1, std::string::npos);
}
std::string RemoveExtension(const std::string& _file_path)
{
return _file_path.substr(0, _file_path.rfind('.'));
}
void render_objs(Ruler::SceneRender& sr, const char* json_path, const char* obj_dir, float scale = 1.0f);
void render_images(Ruler::SceneRender& sr, const char* json_path, const char* picture_dir, float scale = 1.0f);
void main()
{
auto start = std::chrono::system_clock::now();
std::string out_dir = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\out)";
std::string pano_dir = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\pano)";
std::string picture_dir = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\pics)";
std::string json_path = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\json\sweeps.json)";
std::string scene_json_path = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\json\scene.json)";
std::string extobj_json_path = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\json\ExtObjs.json)";
std::string obj_dir = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\model)";
auto obj_paths = FindFilesInDirectory(obj_dir, ".obj");
std::string obj_path = R"(..\..\..\datas\fc43ad5c-4a78-02f4-be90-3a334224b3f7\model\75677dfc-a532-bc0c-cbb5-af7b1785dda0.obj)";
std::cout << "obj_paths : " << obj_paths.size() << std::endl;
std::cout << "obj_paths : " << obj_paths[0] << std::endl;
std::ifstream ifs;
ifs.open(json_path);
if (!ifs.is_open())
{
std::cout << "Reading json file failed!" << std::endl;
return;
}
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
return;
}
//float scale = 1000;
float scale = 1.0f;
char tmp[256];
Ruler::CameraD cameraparam;
Ruler::SceneRender sr(cameraparam, 2048, 9000, 4500, 1);
for (int index = 0; index < root.size(); ++index)
{
cameraparam.SetQuaternionRotation(
root[index]["rotation"]["x"].asDouble(),
root[index]["rotation"]["y"].asDouble(),
root[index]["rotation"]["z"].asDouble(),
root[index]["rotation"]["w"].asDouble());
cameraparam.SetTranslation(
root[index]["position"]["x"].asDouble() * scale,
root[index]["position"]["y"].asDouble() * scale,
root[index]["position"]["z"].asDouble() * scale);
sr.clearDepthAndImage();
sr.setCameraParam(cameraparam);
std::string sweep_uuid = root[index]["sweep_uuid"].asString();
std::string pano_box1 = pano_dir + "\\" + sweep_uuid + "_skybox1.jpg";
std::string pano_box2 = pano_dir + "\\" + sweep_uuid + "_skybox2.jpg";
std::string pano_box3 = pano_dir + "\\" + sweep_uuid + "_skybox3.jpg";
std::string pano_box4 = pano_dir + "\\" + sweep_uuid + "_skybox4.jpg";
std::string pano_box0 = pano_dir + "\\" + sweep_uuid + "_skybox0.jpg";
std::string pano_box5 = pano_dir + "\\" + sweep_uuid + "_skybox5.jpg";
const char *sixpath[6] = {
pano_box1.c_str(),
pano_box2.c_str(),
pano_box3.c_str(),
pano_box4.c_str(),
pano_box0.c_str(),
pano_box5.c_str() };
for (int i = 0; i < 6; ++i)
std::cout << sixpath[i] << std::endl;
sr.renderSixBox(sixpath);
sr.renderTrimesh(obj_path.c_str(), "", 0, true);
//for(int i=0;i <obj_paths.size(); ++i)
// sr.renderTrimesh(obj_paths[i].c_str(), "", 0, true);
render_objs(sr, extobj_json_path.c_str(), obj_dir.c_str(), scale);
render_images(sr, scene_json_path.c_str(), picture_dir.c_str(), scale);
std::cout << root[index]["sweep_uuid"].asString() << std::endl;
std::cout << root[index]["position"]["x"].asDouble() << std::endl;
std::cout << root[index]["position"]["y"].asDouble() << std::endl;
std::cout << root[index]["position"]["z"].asDouble() << std::endl;
std::cout << root[index]["rotation"]["x"].asDouble() << std::endl;
std::cout << root[index]["rotation"]["y"].asDouble() << std::endl;
std::cout << root[index]["rotation"]["z"].asDouble() << std::endl;
std::cout << root[index]["rotation"]["w"].asDouble() << std::endl;
sprintf_s(tmp, "%s\\%02d.jpg", out_dir.c_str(), index);
//sr.saveSixBoxSimulateImage(tmp);
sr.savePanoSimulateImage(tmp);
sprintf_s(tmp, "%s\\%02d.png", out_dir.c_str(), index);
sr.savePanoDepthImage(tmp, 1000.0f);
}
auto end = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "Spent" << double(duration.count()) * std::chrono::microseconds::period::num / std::chrono::microseconds::period::den << " seconds." << std::endl;
return;
}
void render_objs(Ruler::SceneRender& sr, const char* json_path, const char* obj_dir, float scale)
{
std::ifstream ifs;
ifs.open(json_path);
if (!ifs.is_open())
{
std::cout << "Reading json file failed!" << std::endl;
return;
}
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
return;
}
Ruler::CameraD objparam;
//std::cout << "scene " << root["data"]["extobjs"].size() << std::endl;
for (int index = 0; index < root.size(); ++index)
{
if (root[index]["type"].asInt() == 4)
{
//std::string obj_path = root[index]["obj"].asString();
//obj_path = std::string(obj_dir) + "\\" + RemoveExtension(FileName(obj_path)) + ".obj";
std::string obj_path = std::string(obj_dir) + "\\" + root[index]["id"].asString() + ".obj";
objparam.SetQuaternionRotation(
root[index]["quaternion"]["x"].asDouble(),
root[index]["quaternion"]["y"].asDouble(),
root[index]["quaternion"]["z"].asDouble(),
root[index]["quaternion"]["w"].asDouble());
objparam.SetTranslation(
root[index]["position"]["x"].asDouble()*scale,
root[index]["position"]["y"].asDouble()*scale,
root[index]["position"]["z"].asDouble()*scale);
std::cout << obj_path << std::endl;
sr.renderTrimesh(obj_path.c_str(), "", objparam, 0, true, root[index]["scale"]["x"].asFloat());
}
//std::cout << root[index]["type"].asInt() << std::endl;
//std::cout << root[index]["position"]["x"].asDouble() << std::endl;
//std::cout << root[index]["position"]["y"].asDouble() << std::endl;
//std::cout << root[index]["position"]["z"].asDouble() << std::endl;
//std::cout << root[index]["quaternion"]["x"].asDouble() << std::endl;
//std::cout << root[index]["quaternion"]["y"].asDouble() << std::endl;
//std::cout << root[index]["quaternion"]["z"].asDouble() << std::endl;
//std::cout << root[index]["quaternion"]["w"].asDouble() << std::endl;
////std::cout << root["data"]["extobjs"][index]["scale"]["x"].asDouble() << std::endl;
////std::cout << root["data"]["extobjs"][index]["scale"]["y"].asDouble() << std::endl;
////std::cout << root["data"]["extobjs"][index]["scale"]["z"].asDouble() << std::endl;
//std::string image_path = std::string(picture_dir) + "\\" + root["data"]["extobjs"][index]["id"].asString() + ".jpg";
//sr.renderRectangle(image_path.c_str(), rectparam,
// root["data"]["extobjs"][index]["scale"]["x"].asDouble()*scale / 2,
// root["data"]["extobjs"][index]["scale"]["y"].asDouble()*scale / 2, 1, true);
}
ifs.close();
}
void render_images(Ruler::SceneRender& sr, const char* json_path, const char* picture_dir, float scale)
{
std::ifstream ifs;
ifs.open(json_path);
if (!ifs.is_open())
{
std::cout << "Reading json file failed!" << std::endl;
return;
}
Json::Reader reader;
Json::Value root;
if (!reader.parse(ifs, root, false))
{
return;
}
Ruler::CameraD rectparam;
//std::cout << "scene " << root["data"]["extobjs"].size() << std::endl;
for (int index = 0; index < root["data"]["extobjs"].size(); ++index)
{
//std::cout << root["data"]["extobjs"][index]["id"].asString() << std::endl;
//std::cout << root["data"]["extobjs"][index]["position"]["x"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["position"]["y"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["position"]["z"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["quaternion"]["x"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["quaternion"]["y"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["quaternion"]["z"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["quaternion"]["w"].asDouble() << std::endl;
rectparam.SetQuaternionRotation(
root["data"]["extobjs"][index]["quaternion"]["x"].asDouble(),
root["data"]["extobjs"][index]["quaternion"]["y"].asDouble(),
root["data"]["extobjs"][index]["quaternion"]["z"].asDouble(),
root["data"]["extobjs"][index]["quaternion"]["w"].asDouble());
rectparam.SetTranslation(
root["data"]["extobjs"][index]["position"]["x"].asDouble()*scale,
root["data"]["extobjs"][index]["position"]["y"].asDouble()*scale,
root["data"]["extobjs"][index]["position"]["z"].asDouble()*scale);
//std::cout << root["data"]["extobjs"][index]["scale"]["x"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["scale"]["y"].asDouble() << std::endl;
//std::cout << root["data"]["extobjs"][index]["scale"]["z"].asDouble() << std::endl;
std::string image_path = std::string(picture_dir) + "\\" + root["data"]["extobjs"][index]["id"].asString() + ".jpg";
sr.renderRectangle(image_path.c_str(), rectparam,
root["data"]["extobjs"][index]["scale"]["x"].asDouble()*scale / 2,
root["data"]["extobjs"][index]["scale"]["y"].asDouble()*scale / 2, 1, true);
}
ifs.close();
}
std::vector<std::string> FindFilesInDirectory(const std::string& _dir,
const std::string& _format)
{
std::string name;
WIN32_FIND_DATA FindFileData;
std::vector<std::string> names;
std::string dir_path =
_dir.at(_dir.length() - 1) != '\\' ? _dir + "\\" : _dir;
std::string findstr =
dir_path + (!_format.empty() && _format[0] == '.' ? ("*" + _format)
: ("*." + _format));
HANDLE hFind = ::FindFirstFile(findstr.c_str(), &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) return std::move(names);
do
{
if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
names.push_back(
name.assign(dir_path).append(FindFileData.cFileName));
}
} while (::FindNextFile(hFind, &FindFileData));
return std::move(names);
} | 40.838235 | 163 | 0.593806 | [
"vector",
"model"
] |
a7c95b34a76a1b098a96c10fd63a64c84635a7ae | 2,504 | cpp | C++ | deps/libgeos/geos/src/index/sweepline/SweepLineEvent_index.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 42 | 2021-03-26T17:34:52.000Z | 2022-03-18T14:15:31.000Z | deps/libgeos/geos/src/index/sweepline/SweepLineEvent_index.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 29 | 2021-06-03T14:24:01.000Z | 2022-03-23T15:43:58.000Z | deps/libgeos/geos/src/index/sweepline/SweepLineEvent_index.cpp | khrushjing/node-gdal-async | 6546b0c8690f2db677d5385b40b407523503b314 | [
"Apache-2.0"
] | 8 | 2021-05-14T19:26:37.000Z | 2022-03-21T13:44:42.000Z | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************/
#include <geos/index/sweepline/SweepLineEvent.h>
namespace geos {
namespace index { // geos.index
namespace sweepline { // geos.index.sweepline
SweepLineEvent::SweepLineEvent(double x, SweepLineEvent* newInsertEvent,
SweepLineInterval* newSweepInt)
:
xValue(x),
eventType(SweepLineEvent::INSERT_EVENT),
insertEvent(newInsertEvent),
sweepInt(newSweepInt)
{
if(insertEvent != nullptr) {
eventType = SweepLineEvent::DELETE_EVENT;
}
}
bool
SweepLineEvent::isInsert()
{
return insertEvent == nullptr;
}
bool
SweepLineEvent::isDelete()
{
return insertEvent != nullptr;
}
SweepLineEvent*
SweepLineEvent::getInsertEvent()
{
return insertEvent;
}
size_t
SweepLineEvent::getDeleteEventIndex()
{
return deleteEventIndex;
}
void
SweepLineEvent::setDeleteEventIndex(std::size_t newDeleteEventIndex)
{
deleteEventIndex = newDeleteEventIndex;
}
SweepLineInterval*
SweepLineEvent::getInterval()
{
return sweepInt;
}
int
SweepLineEvent::compareTo(const SweepLineEvent* pe) const
{
if(xValue < pe->xValue) {
return -1;
}
if(xValue > pe->xValue) {
return 1;
}
if(eventType < pe->eventType) {
return -1;
}
if(eventType > pe->eventType) {
return 1;
}
return 0;
}
#if 0
int
SweepLineEvent::compareTo(void* o) const
{
SweepLineEvent* pe = (SweepLineEvent*) o;
if(xValue < pe->xValue) {
return -1;
}
if(xValue > pe->xValue) {
return 1;
}
if(eventType < pe->eventType) {
return -1;
}
if(eventType > pe->eventType) {
return 1;
}
return 0;
}
#endif // 0
bool
SweepLineEventLessThen::operator()(const SweepLineEvent* first, const SweepLineEvent* second) const
{
if(first->compareTo(second) < 0) {
return true;
}
else {
return false;
}
}
} // namespace geos.index.sweepline
} // namespace geos.index
} // namespace geos
| 19.873016 | 99 | 0.618211 | [
"geometry"
] |
a7cc1a6e1d08a16d879c7f5d39b75cc93b189abc | 2,811 | cc | C++ | engine/collision/planeExtractor.cc | ClayHanson/B4v21-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | 1 | 2020-08-18T19:45:34.000Z | 2020-08-18T19:45:34.000Z | engine/collision/planeExtractor.cc | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | engine/collision/planeExtractor.cc | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#include "platform/platform.h"
#include "dgl/dgl.h"
#include "math/mMath.h"
#include "console/console.h"
#include "collision/planeExtractor.h"
//----------------------------------------------------------------------------
// Plane matching parameters
static F32 NormalEpsilon = 0.93969; // 20 deg.
static F32 DistanceEpsilon = 100;
//----------------------------------------------------------------------------
PlaneExtractorPolyList::PlaneExtractorPolyList()
{
VECTOR_SET_ASSOCIATION(mVertexList);
VECTOR_SET_ASSOCIATION(mPolyPlaneList);
}
PlaneExtractorPolyList::~PlaneExtractorPolyList()
{
}
//----------------------------------------------------------------------------
void PlaneExtractorPolyList::clear()
{
mVertexList.clear();
mPolyPlaneList.clear();
}
U32 PlaneExtractorPolyList::addPoint(const Point3F& p)
{
mVertexList.increment();
Point3F& v = mVertexList.last();
v.x = p.x * mScale.x;
v.y = p.y * mScale.y;
v.z = p.z * mScale.z;
mMatrix.mulP(v);
return mVertexList.size() - 1;
}
U32 PlaneExtractorPolyList::addPlane(const PlaneF& plane)
{
mPolyPlaneList.increment();
mPlaneTransformer.transform(plane, mPolyPlaneList.last());
return mPolyPlaneList.size() - 1;
}
//----------------------------------------------------------------------------
void PlaneExtractorPolyList::plane(U32 v1,U32 v2,U32 v3)
{
mPlaneList->last().set(mVertexList[v1],
mVertexList[v2],mVertexList[v3]);
}
void PlaneExtractorPolyList::plane(const PlaneF& p)
{
mPlaneTransformer.transform(p, mPlaneList->last());
}
void PlaneExtractorPolyList::plane(const U32 index)
{
AssertFatal(index < mPolyPlaneList.size(), "Out of bounds index!");
mPlaneList->last() = mPolyPlaneList[index];
}
const PlaneF& PlaneExtractorPolyList::getIndexedPlane(const U32 index)
{
AssertFatal(index < mPolyPlaneList.size(), "Out of bounds index!");
return mPolyPlaneList[index];
}
//----------------------------------------------------------------------------
bool PlaneExtractorPolyList::isEmpty() const
{
return true;
}
void PlaneExtractorPolyList::begin(U32,U32)
{
mPlaneList->increment();
}
void PlaneExtractorPolyList::end()
{
// See if there are any duplicate planes
PlaneF &plane = mPlaneList->last();
PlaneF *ptr = mPlaneList->begin();
for (; ptr != &plane; ptr++)
if (mFabs(ptr->d - plane.d) < DistanceEpsilon &&
mDot(*ptr,plane) > NormalEpsilon) {
mPlaneList->decrement();
return;
}
}
void PlaneExtractorPolyList::vertex(U32)
{
}
void PlaneExtractorPolyList::render()
{
}
| 23.822034 | 79 | 0.563501 | [
"render",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.