hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1642c9fbf7d569e9760f9e78a9124aa1bd2816c7 | 105,166 | cpp | C++ | src/coreclr/src/vm/gdbjit.cpp | patricksadowski/runtime | aa5b2041471d7687dbddb1d275ea8a93943c43bf | [
"MIT"
] | 2 | 2020-03-28T13:38:11.000Z | 2020-12-18T15:00:04.000Z | src/coreclr/src/vm/gdbjit.cpp | patricksadowski/runtime | aa5b2041471d7687dbddb1d275ea8a93943c43bf | [
"MIT"
] | 1 | 2020-04-24T10:03:11.000Z | 2020-04-24T10:03:11.000Z | src/coreclr/src/vm/gdbjit.cpp | patricksadowski/runtime | aa5b2041471d7687dbddb1d275ea8a93943c43bf | [
"MIT"
] | 3 | 2021-02-10T16:20:05.000Z | 2021-03-12T07:55:36.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//*****************************************************************************
// File: gdbjit.cpp
//
//
// NotifyGdb implementation.
//
//*****************************************************************************
#include "common.h"
#include "formattype.h"
#include "gdbjit.h"
#include "gdbjithelpers.h"
thread_local bool tls_isSymReaderInProgress = false;
#ifdef _DEBUG
static void DumpElf(const char* methodName, const char *addr, size_t size)
{
char dump[1024] = { 0, };
strcat(dump, methodName);
strcat(dump, ".o");
FILE *f = fopen(dump, "wb");
fwrite(addr, sizeof(char), size, f);
fclose(f);
}
#endif
TypeInfoBase*
GetTypeInfoFromTypeHandle(TypeHandle typeHandle,
NotifyGdb::PTK_TypeInfoMap pTypeMap,
FunctionMemberPtrArrayHolder &method)
{
TypeInfoBase *foundTypeInfo = nullptr;
TypeKey key = typeHandle.GetTypeKey();
PTR_MethodTable pMT = typeHandle.GetMethodTable();
if (pTypeMap->Lookup(&key, &foundTypeInfo))
{
return foundTypeInfo;
}
CorElementType corType = typeHandle.GetSignatureCorElementType();
switch (corType)
{
case ELEMENT_TYPE_I1:
case ELEMENT_TYPE_U1:
case ELEMENT_TYPE_CHAR:
case ELEMENT_TYPE_VOID:
case ELEMENT_TYPE_BOOLEAN:
case ELEMENT_TYPE_I2:
case ELEMENT_TYPE_U2:
case ELEMENT_TYPE_I4:
case ELEMENT_TYPE_U4:
case ELEMENT_TYPE_I8:
case ELEMENT_TYPE_U8:
case ELEMENT_TYPE_R4:
case ELEMENT_TYPE_R8:
case ELEMENT_TYPE_U:
case ELEMENT_TYPE_I:
{
NewHolder<PrimitiveTypeInfo> typeInfo = new PrimitiveTypeInfo(typeHandle);
pTypeMap->Add(typeInfo->GetTypeKey(), typeInfo);
typeInfo.SuppressRelease();
return typeInfo;
}
case ELEMENT_TYPE_VALUETYPE:
case ELEMENT_TYPE_CLASS:
{
ApproxFieldDescIterator fieldDescIterator(pMT,
pMT->IsString() ? ApproxFieldDescIterator::INSTANCE_FIELDS : ApproxFieldDescIterator::ALL_FIELDS);
ULONG cFields = fieldDescIterator.Count();
NewHolder<ClassTypeInfo> typeInfo = new ClassTypeInfo(typeHandle, cFields, method);
NewHolder<RefTypeInfo> refTypeInfo = nullptr;
if (!typeHandle.IsValueType())
{
refTypeInfo = new NamedRefTypeInfo(typeHandle, typeInfo);
typeInfo.SuppressRelease();
pTypeMap->Add(refTypeInfo->GetTypeKey(), refTypeInfo);
refTypeInfo.SuppressRelease();
}
else
{
pTypeMap->Add(typeInfo->GetTypeKey(), typeInfo);
typeInfo.SuppressRelease();
}
//
// Now fill in the array
//
FieldDesc *pField;
for (ULONG i = 0; i < cFields; i++)
{
pField = fieldDescIterator.Next();
LPCUTF8 szName = pField->GetName();
typeInfo->members[i].m_member_name = new char[strlen(szName) + 1];
strcpy(typeInfo->members[i].m_member_name, szName);
if (!pField->IsStatic())
{
typeInfo->members[i].m_member_offset = (ULONG)pField->GetOffset();
if (!typeHandle.IsValueType())
typeInfo->members[i].m_member_offset += Object::GetOffsetOfFirstField();
}
else
{
PTR_BYTE base = 0;
MethodTable* pMT = pField->GetEnclosingMethodTable();
base = pField->GetBase();
// TODO: add support of generics with static fields
if (pField->IsRVA() || !pMT->IsDynamicStatics())
{
PTR_VOID pAddress = pField->GetStaticAddressHandle((PTR_VOID)dac_cast<TADDR>(base));
typeInfo->members[i].m_static_member_address = dac_cast<TADDR>(pAddress);
}
}
typeInfo->members[i].m_member_type =
GetTypeInfoFromTypeHandle(pField->GetExactFieldType(typeHandle), pTypeMap, method);
// handle the System.String case:
// coerce type of the second field into array type
if (pMT->IsString() && i == 1)
{
TypeInfoBase* elemTypeInfo = typeInfo->members[1].m_member_type;
typeInfo->m_array_type = new ArrayTypeInfo(typeHandle.MakeSZArray(), 1, elemTypeInfo);
typeInfo->members[1].m_member_type = typeInfo->m_array_type;
}
}
// Ignore inheritance from System.Object and System.ValueType classes.
if (!typeHandle.IsValueType() &&
pMT->GetParentMethodTable() && pMT->GetParentMethodTable()->GetParentMethodTable())
{
typeInfo->m_parent = GetTypeInfoFromTypeHandle(typeHandle.GetParent(), pTypeMap, method);
}
if (refTypeInfo)
return refTypeInfo;
else
return typeInfo;
}
case ELEMENT_TYPE_PTR:
case ELEMENT_TYPE_BYREF:
{
TypeInfoBase* valTypeInfo = GetTypeInfoFromTypeHandle(typeHandle.GetTypeParam(), pTypeMap, method);
NewHolder<RefTypeInfo> typeInfo = new RefTypeInfo(typeHandle, valTypeInfo);
typeInfo->m_type_offset = valTypeInfo->m_type_offset;
pTypeMap->Add(typeInfo->GetTypeKey(), typeInfo);
typeInfo.SuppressRelease();
return typeInfo;
}
case ELEMENT_TYPE_ARRAY:
case ELEMENT_TYPE_SZARRAY:
{
NewHolder<ClassTypeInfo> info = new ClassTypeInfo(typeHandle, pMT->GetRank() == 1 ? 2 : 3, method);
NewHolder<RefTypeInfo> refTypeInfo = new NamedRefTypeInfo(typeHandle, info);
info.SuppressRelease();
pTypeMap->Add(refTypeInfo->GetTypeKey(), refTypeInfo);
refTypeInfo.SuppressRelease();
TypeInfoBase* lengthTypeInfo = GetTypeInfoFromTypeHandle(
TypeHandle(MscorlibBinder::GetElementType(ELEMENT_TYPE_I4)), pTypeMap, method);
TypeInfoBase* valTypeInfo = GetTypeInfoFromTypeHandle(typeHandle.GetArrayElementTypeHandle(), pTypeMap, method);
info->m_array_type = new ArrayTypeInfo(typeHandle, 1, valTypeInfo);
info->members[0].m_member_name = new char[16];
strcpy(info->members[0].m_member_name, "m_NumComponents");
info->members[0].m_member_offset = ArrayBase::GetOffsetOfNumComponents();
info->members[0].m_member_type = lengthTypeInfo;
info->members[1].m_member_name = new char[7];
strcpy(info->members[1].m_member_name, "m_Data");
info->members[1].m_member_offset = ArrayBase::GetDataPtrOffset(pMT);
info->members[1].m_member_type = info->m_array_type;
if (pMT->GetRank() != 1)
{
TypeHandle dwordArray(MscorlibBinder::GetElementType(ELEMENT_TYPE_I4));
info->m_array_bounds_type = new ArrayTypeInfo(dwordArray.MakeSZArray(), pMT->GetRank(), lengthTypeInfo);
info->members[2].m_member_name = new char[9];
strcpy(info->members[2].m_member_name, "m_Bounds");
info->members[2].m_member_offset = ArrayBase::GetBoundsOffset(pMT);
info->members[2].m_member_type = info->m_array_bounds_type;
}
return refTypeInfo;
}
default:
COMPlusThrowHR(COR_E_NOTSUPPORTED);
}
}
TypeInfoBase* GetArgTypeInfo(MethodDesc* methodDescPtr,
NotifyGdb::PTK_TypeInfoMap pTypeMap,
unsigned ilIndex,
FunctionMemberPtrArrayHolder &method)
{
MetaSig sig(methodDescPtr);
TypeHandle th;
if (ilIndex == 0)
{
th = sig.GetRetTypeHandleNT();
}
else
{
while (--ilIndex)
sig.SkipArg();
sig.NextArg();
th = sig.GetLastTypeHandleNT();
}
return GetTypeInfoFromTypeHandle(th, pTypeMap, method);
}
TypeInfoBase* GetLocalTypeInfo(MethodDesc *methodDescPtr,
NotifyGdb::PTK_TypeInfoMap pTypeMap,
unsigned ilIndex,
FunctionMemberPtrArrayHolder &funcs)
{
COR_ILMETHOD_DECODER method(methodDescPtr->GetILHeader());
if (method.GetLocalVarSigTok())
{
DWORD cbSigLen;
PCCOR_SIGNATURE pComSig;
if (FAILED(methodDescPtr->GetMDImport()->GetSigFromToken(method.GetLocalVarSigTok(), &cbSigLen, &pComSig)))
{
printf("\nInvalid record");
return nullptr;
}
_ASSERTE(*pComSig == IMAGE_CEE_CS_CALLCONV_LOCAL_SIG);
SigTypeContext typeContext(methodDescPtr, TypeHandle());
MetaSig sig(pComSig, cbSigLen, methodDescPtr->GetModule(), &typeContext, MetaSig::sigLocalVars);
if (ilIndex > 0)
{
while (ilIndex--)
sig.SkipArg();
}
sig.NextArg();
TypeHandle th = sig.GetLastTypeHandleNT();
return GetTypeInfoFromTypeHandle(th, pTypeMap, funcs);
}
return nullptr;
}
HRESULT GetArgNameByILIndex(MethodDesc* methodDescPtr, unsigned index, NewArrayHolder<char> ¶mName)
{
IMDInternalImport* mdImport = methodDescPtr->GetMDImport();
mdParamDef paramToken;
USHORT seq;
DWORD attr;
HRESULT status;
// Param indexing is 1-based.
ULONG32 mdIndex = index + 1;
MetaSig sig(methodDescPtr);
if (sig.HasThis())
{
mdIndex--;
}
status = mdImport->FindParamOfMethod(methodDescPtr->GetMemberDef(), mdIndex, ¶mToken);
if (status == S_OK)
{
LPCSTR name;
status = mdImport->GetParamDefProps(paramToken, &seq, &attr, &name);
paramName = new char[strlen(name) + 1];
strcpy(paramName, name);
}
return status;
}
// Copy-pasted from src/debug/di/module.cpp
HRESULT FindNativeInfoInILVariable(DWORD dwIndex,
SIZE_T ip,
ICorDebugInfo::NativeVarInfo* nativeInfoList,
unsigned int nativeInfoCount,
ICorDebugInfo::NativeVarInfo** ppNativeInfo)
{
_ASSERTE(ppNativeInfo != NULL);
*ppNativeInfo = NULL;
int lastGoodOne = -1;
for (unsigned int i = 0; i < (unsigned)nativeInfoCount; i++)
{
if (nativeInfoList[i].varNumber == dwIndex)
{
if ((lastGoodOne == -1) || (nativeInfoList[lastGoodOne].startOffset < nativeInfoList[i].startOffset))
{
lastGoodOne = i;
}
if ((nativeInfoList[i].startOffset <= ip) &&
(nativeInfoList[i].endOffset > ip))
{
*ppNativeInfo = &(nativeInfoList[i]);
return S_OK;
}
}
}
if ((lastGoodOne > -1) && (nativeInfoList[lastGoodOne].endOffset == ip))
{
*ppNativeInfo = &(nativeInfoList[lastGoodOne]);
return S_OK;
}
return CORDBG_E_IL_VAR_NOT_AVAILABLE;
}
BYTE* DebugInfoStoreNew(void * pData, size_t cBytes)
{
return new BYTE[cBytes];
}
/* Get IL to native offsets map */
HRESULT
GetMethodNativeMap(MethodDesc* methodDesc,
ULONG32* numMap,
NewArrayHolder<DebuggerILToNativeMap> &map,
ULONG32* pcVars,
ICorDebugInfo::NativeVarInfo** ppVars)
{
// Use the DebugInfoStore to get IL->Native maps.
// It doesn't matter whether we're jitted, ngenned etc.
DebugInfoRequest request;
TADDR nativeCodeStartAddr = PCODEToPINSTR(methodDesc->GetNativeCode());
request.InitFromStartingAddr(methodDesc, nativeCodeStartAddr);
// Bounds info.
ULONG32 countMapCopy;
NewHolder<ICorDebugInfo::OffsetMapping> mapCopy(NULL);
BOOL success = DebugInfoManager::GetBoundariesAndVars(request,
DebugInfoStoreNew,
NULL, // allocator
&countMapCopy,
&mapCopy,
pcVars,
ppVars);
if (!success)
{
return E_FAIL;
}
// Need to convert map formats.
*numMap = countMapCopy;
map = new DebuggerILToNativeMap[countMapCopy];
ULONG32 i;
for (i = 0; i < *numMap; i++)
{
map[i].ilOffset = mapCopy[i].ilOffset;
map[i].nativeStartOffset = mapCopy[i].nativeOffset;
if (i > 0)
{
map[i - 1].nativeEndOffset = map[i].nativeStartOffset;
}
map[i].source = mapCopy[i].source;
}
if (*numMap >= 1)
{
map[i - 1].nativeEndOffset = 0;
}
return S_OK;
}
HRESULT FunctionMember::GetLocalsDebugInfo(NotifyGdb::PTK_TypeInfoMap pTypeMap,
LocalsInfo& locals,
int startNativeOffset,
FunctionMemberPtrArrayHolder &method)
{
ICorDebugInfo::NativeVarInfo* nativeVar = NULL;
int thisOffs = 0;
if (!md->IsStatic())
{
thisOffs = 1;
}
int i;
for (i = 0; i < m_num_args - thisOffs; i++)
{
if (FindNativeInfoInILVariable(i + thisOffs, startNativeOffset, locals.vars, locals.countVars, &nativeVar) == S_OK)
{
vars[i + thisOffs].m_var_type = GetArgTypeInfo(md, pTypeMap, i + 1, method);
GetArgNameByILIndex(md, i + thisOffs, vars[i + thisOffs].m_var_name);
vars[i + thisOffs].m_il_index = i;
vars[i + thisOffs].m_native_offset = nativeVar->loc.vlStk.vlsOffset;
vars[i + thisOffs].m_var_abbrev = 6;
}
}
//Add info about 'this' as first argument
if (thisOffs == 1)
{
if (FindNativeInfoInILVariable(0, startNativeOffset, locals.vars, locals.countVars, &nativeVar) == S_OK)
{
TypeHandle th = TypeHandle(md->GetMethodTable());
if (th.IsValueType())
th = th.MakePointer();
vars[0].m_var_type = GetTypeInfoFromTypeHandle(th, pTypeMap, method);
vars[0].m_var_name = new char[strlen("this") + 1];
strcpy(vars[0].m_var_name, "this");
vars[0].m_il_index = 0;
vars[0].m_native_offset = nativeVar->loc.vlStk.vlsOffset;
vars[0].m_var_abbrev = 13;
}
i++;
}
for (; i < m_num_vars; i++)
{
if (FindNativeInfoInILVariable(
i, startNativeOffset, locals.vars, locals.countVars, &nativeVar) == S_OK)
{
int ilIndex = i - m_num_args;
vars[i].m_var_type = GetLocalTypeInfo(md, pTypeMap, ilIndex, method);
vars[i].m_var_name = new char[strlen(locals.localsName[ilIndex]) + 1];
strcpy(vars[i].m_var_name, locals.localsName[ilIndex]);
vars[i].m_il_index = ilIndex;
vars[i].m_native_offset = nativeVar->loc.vlStk.vlsOffset;
vars[i].m_var_abbrev = 5;
TADDR nativeStart;
TADDR nativeEnd;
int ilLen = locals.localsScope[ilIndex].ilEndOffset - locals.localsScope[ilIndex].ilStartOffset;
if (GetBlockInNativeCode(locals.localsScope[ilIndex].ilStartOffset, ilLen, &nativeStart, &nativeEnd))
{
vars[i].m_low_pc = md->GetNativeCode() + nativeStart;
vars[i].m_high_pc = nativeEnd - nativeStart;
}
}
}
return S_OK;
}
MethodDebugInfo::MethodDebugInfo(int numPoints, int numLocals)
{
points = (SequencePointInfo*) CoTaskMemAlloc(sizeof(SequencePointInfo) * numPoints);
if (points == nullptr)
{
COMPlusThrowOM();
}
memset(points, 0, sizeof(SequencePointInfo) * numPoints);
size = numPoints;
if (numLocals == 0)
{
locals = nullptr;
localsSize = 0;
return;
}
locals = (LocalVarInfo*) CoTaskMemAlloc(sizeof(LocalVarInfo) * numLocals);
if (locals == nullptr)
{
CoTaskMemFree(points);
COMPlusThrowOM();
}
memset(locals, 0, sizeof(LocalVarInfo) * numLocals);
localsSize = numLocals;
}
MethodDebugInfo::~MethodDebugInfo()
{
if (locals)
{
for (int i = 0; i < localsSize; i++)
CoTaskMemFree(locals[i].name);
CoTaskMemFree(locals);
}
for (int i = 0; i < size; i++)
CoTaskMemFree(points[i].fileName);
CoTaskMemFree(points);
}
/* Get mapping of IL offsets to source line numbers */
HRESULT
GetDebugInfoFromPDB(MethodDesc* methodDescPtr,
NewArrayHolder<SymbolsInfo> &symInfo,
unsigned int &symInfoLen,
LocalsInfo &locals)
{
NewArrayHolder<DebuggerILToNativeMap> map;
ULONG32 numMap;
if (!getInfoForMethodDelegate)
return E_FAIL;
if (GetMethodNativeMap(methodDescPtr, &numMap, map, &locals.countVars, &locals.vars) != S_OK)
return E_FAIL;
const Module* mod = methodDescPtr->GetMethodTable()->GetModule();
SString modName = mod->GetFile()->GetPath();
if (modName.IsEmpty())
return E_FAIL;
StackScratchBuffer scratch;
const char* szModName = modName.GetUTF8(scratch);
MethodDebugInfo methodDebugInfo(numMap, locals.countVars);
if (getInfoForMethodDelegate(szModName, methodDescPtr->GetMemberDef(), methodDebugInfo) == FALSE)
return E_FAIL;
symInfoLen = numMap;
symInfo = new SymbolsInfo[numMap];
locals.size = methodDebugInfo.localsSize;
locals.localsName = new NewArrayHolder<char>[locals.size];
locals.localsScope = new LocalsInfo::Scope [locals.size];
for (ULONG32 i = 0; i < locals.size; i++)
{
size_t sizeRequired = WideCharToMultiByte(CP_UTF8, 0, methodDebugInfo.locals[i].name, -1, NULL, 0, NULL, NULL);
locals.localsName[i] = new char[sizeRequired];
int len = WideCharToMultiByte(
CP_UTF8, 0, methodDebugInfo.locals[i].name, -1, locals.localsName[i], sizeRequired, NULL, NULL);
locals.localsScope[i].ilStartOffset = methodDebugInfo.locals[i].startOffset;
locals.localsScope[i].ilEndOffset = methodDebugInfo.locals[i].endOffset;
}
for (ULONG32 j = 0; j < numMap; j++)
{
SymbolsInfo& s = symInfo[j];
if (j == 0) {
s.fileName[0] = 0;
s.lineNumber = 0;
s.fileIndex = 0;
} else {
s = symInfo[j - 1];
}
s.nativeOffset = map[j].nativeStartOffset;
s.ilOffset = map[j].ilOffset;
s.source = map[j].source;
s.lineNumber = 0;
for (ULONG32 i = 0; i < methodDebugInfo.size; i++)
{
const SequencePointInfo& sp = methodDebugInfo.points[i];
if (methodDebugInfo.points[i].ilOffset == map[j].ilOffset)
{
s.fileIndex = 0;
int len = WideCharToMultiByte(CP_UTF8, 0, sp.fileName, -1, s.fileName, sizeof(s.fileName), NULL, NULL);
s.fileName[len] = 0;
s.lineNumber = sp.lineNumber;
break;
}
}
}
return S_OK;
}
/* LEB128 for 32-bit unsigned integer */
int Leb128Encode(uint32_t num, char* buf, int size)
{
int i = 0;
do
{
uint8_t byte = num & 0x7F;
if (i >= size)
break;
num >>= 7;
if (num != 0)
byte |= 0x80;
buf[i++] = byte;
}
while (num != 0);
return i;
}
/* LEB128 for 32-bit signed integer */
int Leb128Encode(int32_t num, char* buf, int size)
{
int i = 0;
bool hasMore = true, isNegative = num < 0;
while (hasMore && i < size)
{
uint8_t byte = num & 0x7F;
num >>= 7;
if ((num == 0 && (byte & 0x40) == 0) || (num == -1 && (byte & 0x40) == 0x40))
hasMore = false;
else
byte |= 0x80;
buf[i++] = byte;
}
return i;
}
int GetFrameLocation(int nativeOffset, char* bufVarLoc)
{
char cnvBuf[16] = {0};
int len = Leb128Encode(static_cast<int32_t>(nativeOffset), cnvBuf, sizeof(cnvBuf));
bufVarLoc[0] = len + 1;
bufVarLoc[1] = DW_OP_fbreg;
for (int j = 0; j < len; j++)
{
bufVarLoc[j + 2] = cnvBuf[j];
}
return len + 2; // We add '2' because first 2 bytes contain length of expression and DW_OP_fbreg operation.
}
// GDB JIT interface
typedef enum
{
JIT_NOACTION = 0,
JIT_REGISTER_FN,
JIT_UNREGISTER_FN
} jit_actions_t;
struct jit_code_entry
{
struct jit_code_entry *next_entry;
struct jit_code_entry *prev_entry;
const char *symfile_addr;
UINT64 symfile_size;
};
struct jit_descriptor
{
UINT32 version;
/* This type should be jit_actions_t, but we use uint32_t
to be explicit about the bitwidth. */
UINT32 action_flag;
struct jit_code_entry *relevant_entry;
struct jit_code_entry *first_entry;
};
// GDB puts a breakpoint in this function.
// To prevent from inlining we add noinline attribute and inline assembler statement.
extern "C"
void __attribute__((noinline)) __jit_debug_register_code() { __asm__(""); };
/* Make sure to specify the version statically, because the
debugger may check the version before we can set it. */
struct jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
static CrstStatic g_jitDescriptorCrst;
// END of GDB JIT interface
class DebugStringsCU
{
public:
DebugStringsCU(const char *module, const char *path)
: m_producerName("CoreCLR"),
m_moduleName(module),
m_moduleDir(path),
m_producerOffset(0),
m_moduleNameOffset(0),
m_moduleDirOffset(0)
{
}
int GetProducerOffset() const { return m_producerOffset; }
int GetModuleNameOffset() const { return m_moduleNameOffset; }
int GetModuleDirOffset() const { return m_moduleDirOffset; }
void DumpStrings(char *ptr, int &offset)
{
m_producerOffset = offset;
DumpString(m_producerName, ptr, offset);
m_moduleNameOffset = offset;
DumpString(m_moduleName, ptr, offset);
m_moduleDirOffset = offset;
DumpString(m_moduleDir, ptr, offset);
}
private:
const char* m_producerName;
const char* m_moduleName;
const char* m_moduleDir;
int m_producerOffset;
int m_moduleNameOffset;
int m_moduleDirOffset;
static void DumpString(const char *str, char *ptr, int &offset)
{
if (ptr != nullptr)
{
strcpy(ptr + offset, str);
}
offset += strlen(str) + 1;
}
};
/* Static data for .debug_abbrev */
const unsigned char AbbrevTable[] = {
1, DW_TAG_compile_unit, DW_CHILDREN_yes,
DW_AT_producer, DW_FORM_strp, DW_AT_language, DW_FORM_data2, DW_AT_name, DW_FORM_strp, DW_AT_comp_dir, DW_FORM_strp,
DW_AT_stmt_list, DW_FORM_sec_offset, 0, 0,
2, DW_TAG_base_type, DW_CHILDREN_no,
DW_AT_name, DW_FORM_strp, DW_AT_encoding, DW_FORM_data1, DW_AT_byte_size, DW_FORM_data1, 0, 0,
3, DW_TAG_typedef, DW_CHILDREN_no, DW_AT_name, DW_FORM_strp,
DW_AT_type, DW_FORM_ref4, 0, 0,
4, DW_TAG_subprogram, DW_CHILDREN_yes,
DW_AT_name, DW_FORM_strp, DW_AT_linkage_name, DW_FORM_strp, DW_AT_decl_file, DW_FORM_data1, DW_AT_decl_line, DW_FORM_data1,
DW_AT_type, DW_FORM_ref4, DW_AT_external, DW_FORM_flag_present,
DW_AT_low_pc, DW_FORM_addr, DW_AT_high_pc, DW_FORM_size,
DW_AT_frame_base, DW_FORM_exprloc, 0, 0,
5, DW_TAG_variable, DW_CHILDREN_no,
DW_AT_name, DW_FORM_strp, DW_AT_decl_file, DW_FORM_data1, DW_AT_decl_line, DW_FORM_data1, DW_AT_type,
DW_FORM_ref4, DW_AT_location, DW_FORM_exprloc, 0, 0,
6, DW_TAG_formal_parameter, DW_CHILDREN_no,
DW_AT_name, DW_FORM_strp, DW_AT_decl_file, DW_FORM_data1, DW_AT_decl_line, DW_FORM_data1, DW_AT_type,
DW_FORM_ref4, DW_AT_location, DW_FORM_exprloc, 0, 0,
7, DW_TAG_class_type, DW_CHILDREN_yes,
DW_AT_name, DW_FORM_strp, DW_AT_byte_size, DW_FORM_data4, 0, 0,
8, DW_TAG_member, DW_CHILDREN_no,
DW_AT_name, DW_FORM_strp, DW_AT_type, DW_FORM_ref4, DW_AT_data_member_location, DW_FORM_data4, 0, 0,
9, DW_TAG_pointer_type, DW_CHILDREN_no,
DW_AT_type, DW_FORM_ref4, DW_AT_byte_size, DW_FORM_data1, 0, 0,
10, DW_TAG_array_type, DW_CHILDREN_yes,
DW_AT_type, DW_FORM_ref4, 0, 0,
11, DW_TAG_subrange_type, DW_CHILDREN_no,
DW_AT_upper_bound, DW_FORM_exprloc, 0, 0,
12, DW_TAG_subprogram, DW_CHILDREN_yes,
DW_AT_name, DW_FORM_strp, DW_AT_linkage_name, DW_FORM_strp, DW_AT_decl_file, DW_FORM_data1, DW_AT_decl_line, DW_FORM_data1,
DW_AT_type, DW_FORM_ref4, DW_AT_external, DW_FORM_flag_present,
DW_AT_low_pc, DW_FORM_addr, DW_AT_high_pc, DW_FORM_size,
DW_AT_frame_base, DW_FORM_exprloc, DW_AT_object_pointer, DW_FORM_ref4, 0, 0,
13, DW_TAG_formal_parameter, DW_CHILDREN_no,
DW_AT_name, DW_FORM_strp, DW_AT_decl_file, DW_FORM_data1, DW_AT_decl_line, DW_FORM_data1, DW_AT_type,
DW_FORM_ref4, DW_AT_location, DW_FORM_exprloc, DW_AT_artificial, DW_FORM_flag_present, 0, 0,
14, DW_TAG_member, DW_CHILDREN_no,
DW_AT_name, DW_FORM_strp, DW_AT_type, DW_FORM_ref4, DW_AT_external, DW_FORM_flag_present, 0, 0,
15, DW_TAG_variable, DW_CHILDREN_no, DW_AT_specification, DW_FORM_ref4, DW_AT_location, DW_FORM_exprloc,
0, 0,
16, DW_TAG_try_block, DW_CHILDREN_no,
DW_AT_low_pc, DW_FORM_addr, DW_AT_high_pc, DW_FORM_size,
0, 0,
17, DW_TAG_catch_block, DW_CHILDREN_no,
DW_AT_low_pc, DW_FORM_addr, DW_AT_high_pc, DW_FORM_size,
0, 0,
18, DW_TAG_inheritance, DW_CHILDREN_no, DW_AT_type, DW_FORM_ref4, DW_AT_data_member_location, DW_FORM_data1,
0, 0,
19, DW_TAG_subrange_type, DW_CHILDREN_no,
DW_AT_upper_bound, DW_FORM_udata, 0, 0,
20, DW_TAG_lexical_block, DW_CHILDREN_yes,
DW_AT_low_pc, DW_FORM_addr, DW_AT_high_pc, DW_FORM_size,
0, 0,
0
};
const int AbbrevTableSize = sizeof(AbbrevTable);
/* Static data for .debug_line, including header */
#define DWARF_LINE_BASE (-5)
#define DWARF_LINE_RANGE 14
#define DWARF_OPCODE_BASE 13
#ifdef FEATURE_GDBJIT_LANGID_CS
/* TODO: use corresponding constant when it will be added to llvm */
#define DW_LANG_MICROSOFT_CSHARP 0x9e57
#endif
DwarfLineNumHeader LineNumHeader = {
0, 2, 0, 1, 1, DWARF_LINE_BASE, DWARF_LINE_RANGE, DWARF_OPCODE_BASE, {0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1}
};
/* Static data for .debug_info */
struct __attribute__((packed)) DebugInfoCU
{
uint8_t m_cu_abbrev;
uint32_t m_prod_off;
uint16_t m_lang;
uint32_t m_cu_name;
uint32_t m_cu_dir;
uint32_t m_line_num;
} debugInfoCU = {
#ifdef FEATURE_GDBJIT_LANGID_CS
1, 0, DW_LANG_MICROSOFT_CSHARP, 0, 0
#else
1, 0, DW_LANG_C89, 0, 0
#endif
};
struct __attribute__((packed)) DebugInfoTryCatchSub
{
uint8_t m_sub_abbrev;
uintptr_t m_sub_low_pc, m_sub_high_pc;
};
struct __attribute__((packed)) DebugInfoSub
{
uint8_t m_sub_abbrev;
uint32_t m_sub_name;
uint32_t m_linkage_name;
uint8_t m_file, m_line;
uint32_t m_sub_type;
uintptr_t m_sub_low_pc, m_sub_high_pc;
uint8_t m_sub_loc[2];
};
struct __attribute__((packed)) DebugInfoSubMember
{
DebugInfoSub sub;
uint32_t m_obj_ptr;
};
struct __attribute__((packed)) DebugInfoLexicalBlock
{
uint8_t m_abbrev;
uintptr_t m_low_pc, m_high_pc;
};
// Holder for array of pointers to FunctionMember objects
class FunctionMemberPtrArrayHolder : public NewArrayHolder<NewHolder<FunctionMember>>
{
private:
int m_cElements;
public:
explicit FunctionMemberPtrArrayHolder(int cElements) :
NewArrayHolder<NewHolder<FunctionMember>>(new NewHolder<FunctionMember>[cElements]),
m_cElements(cElements)
{
}
int GetCount() const
{
return m_cElements;
}
};
struct __attribute__((packed)) DebugInfoType
{
uint8_t m_type_abbrev;
uint32_t m_type_name;
uint8_t m_encoding;
uint8_t m_byte_size;
};
struct __attribute__((packed)) DebugInfoVar
{
uint8_t m_var_abbrev;
uint32_t m_var_name;
uint8_t m_var_file, m_var_line;
uint32_t m_var_type;
};
struct __attribute__((packed)) DebugInfoTypeDef
{
uint8_t m_typedef_abbrev;
uint32_t m_typedef_name;
uint32_t m_typedef_type;
};
struct __attribute__((packed)) DebugInfoClassType
{
uint8_t m_type_abbrev;
uint32_t m_type_name;
uint32_t m_byte_size;
};
struct __attribute__((packed)) DebugInfoInheritance
{
uint8_t m_abbrev;
uint32_t m_type;
uint8_t m_data_member_location;
};
struct __attribute__((packed)) DebugInfoClassMember
{
uint8_t m_member_abbrev;
uint32_t m_member_name;
uint32_t m_member_type;
};
struct __attribute__((packed)) DebugInfoStaticMember
{
uint8_t m_member_abbrev;
uint32_t m_member_specification;
};
struct __attribute__((packed)) DebugInfoRefType
{
uint8_t m_type_abbrev;
uint32_t m_ref_type;
uint8_t m_byte_size;
};
struct __attribute__((packed)) DebugInfoArrayType
{
uint8_t m_abbrev;
uint32_t m_type;
};
void TypeInfoBase::DumpStrings(char* ptr, int& offset)
{
if (ptr != nullptr)
{
strcpy(ptr + offset, m_type_name);
m_type_name_offset = offset;
}
offset += strlen(m_type_name) + 1;
}
void TypeInfoBase::CalculateName()
{
// name the type
SString sName;
const TypeString::FormatFlags formatFlags = static_cast<TypeString::FormatFlags>(
TypeString::FormatNamespace |
TypeString::FormatAngleBrackets);
TypeString::AppendType(sName, typeHandle, formatFlags);
StackScratchBuffer buffer;
const UTF8 *utf8 = sName.GetUTF8(buffer);
if (typeHandle.IsValueType())
{
m_type_name = new char[strlen(utf8) + 1];
strcpy(m_type_name, utf8);
}
else
{
m_type_name = new char[strlen(utf8) + 1 + 2];
strcpy(m_type_name, "__");
strcpy(m_type_name + 2, utf8);
}
// Fix nested names
for (char *p = m_type_name; *p; ++p)
{
if (*p == '+')
*p = '.';
}
}
void TypeInfoBase::SetTypeHandle(TypeHandle handle)
{
typeHandle = handle;
typeKey = handle.GetTypeKey();
}
TypeHandle TypeInfoBase::GetTypeHandle()
{
return typeHandle;
}
TypeKey* TypeInfoBase::GetTypeKey()
{
return &typeKey;
}
void TypeDefInfo::DumpStrings(char *ptr, int &offset)
{
if (ptr != nullptr)
{
strcpy(ptr + offset, m_typedef_name);
m_typedef_name_offset = offset;
}
offset += strlen(m_typedef_name) + 1;
}
void TypeDefInfo::DumpDebugInfo(char *ptr, int &offset)
{
if (m_is_visited && m_base_ptr == ptr)
{
return;
}
m_base_ptr = ptr;
m_is_visited = true;
if (ptr != nullptr)
{
DebugInfoTypeDef buf;
buf.m_typedef_abbrev = 3;
buf.m_typedef_name = m_typedef_name_offset;
buf.m_typedef_type = offset + sizeof(DebugInfoTypeDef);
m_typedef_type_offset = offset;
memcpy(ptr + offset,
&buf,
sizeof(DebugInfoTypeDef));
}
offset += sizeof(DebugInfoTypeDef);
}
static const char *GetCSharpTypeName(TypeInfoBase *typeInfo)
{
switch(typeInfo->GetTypeHandle().GetSignatureCorElementType())
{
case ELEMENT_TYPE_I1: return "sbyte";
case ELEMENT_TYPE_U1: return "byte";
case ELEMENT_TYPE_CHAR: return "char";
case ELEMENT_TYPE_VOID: return "void";
case ELEMENT_TYPE_BOOLEAN: return "bool";
case ELEMENT_TYPE_I2: return "short";
case ELEMENT_TYPE_U2: return "ushort";
case ELEMENT_TYPE_I4: return "int";
case ELEMENT_TYPE_U4: return "uint";
case ELEMENT_TYPE_I8: return "long";
case ELEMENT_TYPE_U8: return "ulong";
case ELEMENT_TYPE_R4: return "float";
case ELEMENT_TYPE_R8: return "double";
default: return typeInfo->m_type_name;
}
}
PrimitiveTypeInfo::PrimitiveTypeInfo(TypeHandle typeHandle)
: TypeInfoBase(typeHandle),
m_typedef_info(new TypeDefInfo(nullptr, 0))
{
CorElementType corType = typeHandle.GetSignatureCorElementType();
m_type_encoding = CorElementTypeToDWEncoding[corType];
m_type_size = CorTypeInfo::Size(corType);
if (corType == ELEMENT_TYPE_CHAR)
{
m_type_name = new char[9];
strcpy(m_type_name, "WCHAR");
}
else
{
CalculateName();
}
}
void PrimitiveTypeInfo::DumpStrings(char* ptr, int& offset)
{
TypeInfoBase::DumpStrings(ptr, offset);
if (!m_typedef_info->m_typedef_name)
{
const char *typeName = GetCSharpTypeName(this);
m_typedef_info->m_typedef_name = new char[strlen(typeName) + 1];
strcpy(m_typedef_info->m_typedef_name, typeName);
}
m_typedef_info->DumpStrings(ptr, offset);
}
void PrimitiveTypeInfo::DumpDebugInfo(char *ptr, int &offset)
{
if (m_is_visited && m_base_ptr == ptr)
{
return;
}
m_base_ptr = ptr;
m_is_visited = true;
m_typedef_info->DumpDebugInfo(ptr, offset);
if (ptr != nullptr)
{
DebugInfoType bufType;
bufType.m_type_abbrev = 2;
bufType.m_type_name = m_type_name_offset;
bufType.m_encoding = m_type_encoding;
bufType.m_byte_size = m_type_size;
memcpy(ptr + offset,
&bufType,
sizeof(DebugInfoType));
// Replace offset from real type to typedef
m_type_offset = m_typedef_info->m_typedef_type_offset;
}
offset += sizeof(DebugInfoType);
}
ClassTypeInfo::ClassTypeInfo(TypeHandle typeHandle, int num_members, FunctionMemberPtrArrayHolder &method)
: TypeInfoBase(typeHandle),
m_num_members(num_members),
members(new TypeMember[num_members]),
m_parent(nullptr),
m_method(method),
m_array_type(nullptr)
{
CorElementType corType = typeHandle.GetSignatureCorElementType();
PTR_MethodTable pMT = typeHandle.GetMethodTable();
switch (corType)
{
case ELEMENT_TYPE_VALUETYPE:
case ELEMENT_TYPE_CLASS:
m_type_size = pMT->IsValueType() ? typeHandle.GetSize() : typeHandle.AsMethodTable()->GetBaseSize();
break;
case ELEMENT_TYPE_ARRAY:
case ELEMENT_TYPE_SZARRAY:
m_type_size = typeHandle.AsMethodTable()->GetBaseSize();
break;
default:
m_type_size = 0;
}
CalculateName();
}
void TypeMember::DumpStrings(char* ptr, int& offset)
{
if (ptr != nullptr)
{
strcpy(ptr + offset, m_member_name);
m_member_name_offset = offset;
}
offset += strlen(m_member_name) + 1;
}
void TypeMember::DumpDebugInfo(char* ptr, int& offset)
{
if (ptr != nullptr)
{
DebugInfoClassMember memberEntry;
if (m_static_member_address == 0)
memberEntry.m_member_abbrev = 8;
else
{
memberEntry.m_member_abbrev = 14;
m_member_offset = offset;
}
memberEntry.m_member_name = m_member_name_offset;
memberEntry.m_member_type = m_member_type->m_type_offset;
memcpy(ptr + offset, &memberEntry, sizeof(DebugInfoClassMember));
if (m_static_member_address == 0)
memcpy(ptr + offset + sizeof(DebugInfoClassMember), &m_member_offset, sizeof(m_member_offset));
}
offset += sizeof(DebugInfoClassMember);
if (m_static_member_address == 0)
offset += sizeof(m_member_offset);
}
void TypeMember::DumpStaticDebugInfo(char* ptr, int& offset)
{
const int ptrSize = sizeof(TADDR);
const int valueTypeBufSize = ptrSize + 6;
const int refTypeBufSize = ptrSize + 2;
bool isValueType = m_member_type->GetTypeHandle().GetSignatureCorElementType() ==
ELEMENT_TYPE_VALUETYPE;
int bufSize;
if (isValueType)
{
bufSize = valueTypeBufSize;
}
else
{
bufSize = refTypeBufSize;
}
if (ptr != nullptr)
{
DebugInfoStaticMember memberEntry;
memberEntry.m_member_abbrev = 15;
memberEntry.m_member_specification = m_member_offset;
memcpy(ptr + offset, &memberEntry, sizeof(DebugInfoStaticMember));
// for value type static fields compute address as:
// addr = (*addr+sizeof(OBJECTREF))
if (isValueType)
{
char buf[valueTypeBufSize] = {0};
buf[0] = ptrSize + 5;
buf[1] = DW_OP_addr;
for (int i = 0; i < ptrSize; i++)
{
buf[i + 2] = m_static_member_address >> (i * 8);
}
buf[ptrSize + 2] = DW_OP_deref;
buf[ptrSize + 3] = DW_OP_const1u;
buf[ptrSize + 4] = sizeof(OBJECTREF);
buf[ptrSize + 5] = DW_OP_plus;
memcpy(ptr + offset + sizeof(DebugInfoStaticMember), &buf, bufSize);
}
else
{
char buf[refTypeBufSize] = {0};
buf[0] = ptrSize + 1;
buf[1] = DW_OP_addr;
for (int i = 0; i < ptrSize; i++)
{
buf[i + 2] = m_static_member_address >> (i * 8);
}
memcpy(ptr + offset + sizeof(DebugInfoStaticMember), &buf, bufSize);
}
}
offset += sizeof(DebugInfoStaticMember);
offset += bufSize;
}
void FunctionMember::MangleName(char *buf, int &buf_offset, const char *name)
{
int name_length = strlen(name);
char tmp[20];
int tmp_len = sprintf_s(tmp, _countof(tmp), "%i", name_length);
if (tmp_len <= 0)
return;
if (buf)
strncpy(buf + buf_offset, tmp, tmp_len);
buf_offset += tmp_len;
if (buf)
{
for (int i = 0; i < name_length; i++)
{
char c = name[i];
bool valid = (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9');
*(buf + buf_offset + i) = valid ? c : '_';
}
}
buf_offset += name_length;
}
void FunctionMember::DumpMangledNamespaceAndMethod(char *buf, int &offset, const char *nspace, const char *mname)
{
static const char *begin_mangled = "_ZN";
static const char *end_mangled = "Ev";
static const int begin_mangled_len = strlen(begin_mangled);
static const int end_mangled_len = strlen(end_mangled);
if (buf)
strncpy(buf + offset, begin_mangled, begin_mangled_len);
offset += begin_mangled_len;
MangleName(buf, offset, nspace);
MangleName(buf, offset, mname);
if (buf)
strncpy(buf + offset, end_mangled, end_mangled_len);
offset += end_mangled_len;
if (buf)
buf[offset] = '\0';
++offset;
}
void FunctionMember::DumpLinkageName(char* ptr, int& offset)
{
SString namespaceOrClassName;
SString methodName;
md->GetMethodInfoNoSig(namespaceOrClassName, methodName);
SString utf8namespaceOrClassName;
SString utf8methodName;
namespaceOrClassName.ConvertToUTF8(utf8namespaceOrClassName);
methodName.ConvertToUTF8(utf8methodName);
const char *nspace = utf8namespaceOrClassName.GetUTF8NoConvert();
const char *mname = utf8methodName.GetUTF8NoConvert();
if (!nspace || !mname)
{
m_linkage_name_offset = 0;
return;
}
m_linkage_name_offset = offset;
DumpMangledNamespaceAndMethod(ptr, offset, nspace, mname);
}
void FunctionMember::DumpStrings(char* ptr, int& offset)
{
TypeMember::DumpStrings(ptr, offset);
for (int i = 0; i < m_num_vars; ++i)
{
vars[i].DumpStrings(ptr, offset);
}
DumpLinkageName(ptr, offset);
}
bool FunctionMember::GetBlockInNativeCode(int blockILOffset, int blockILLen, TADDR *startOffset, TADDR *endOffset)
{
PCODE pCode = md->GetNativeCode();
const int blockILEnd = blockILOffset + blockILLen;
*startOffset = 0;
*endOffset = 0;
bool inBlock = false;
for (int i = 0; i < nlines; ++i)
{
TADDR nativeOffset = lines[i].nativeOffset + pCode;
// Limit block search to current function addresses
if (nativeOffset < m_sub_low_pc)
continue;
if (nativeOffset >= m_sub_low_pc + m_sub_high_pc)
break;
// Skip invalid IL offsets
switch(lines[i].ilOffset)
{
case ICorDebugInfo::PROLOG:
case ICorDebugInfo::EPILOG:
case ICorDebugInfo::NO_MAPPING:
continue;
default:
break;
}
// Check if current IL is within block
if (blockILOffset <= lines[i].ilOffset && lines[i].ilOffset < blockILEnd)
{
if (!inBlock)
{
*startOffset = lines[i].nativeOffset;
inBlock = true;
}
}
else
{
if (inBlock)
{
*endOffset = lines[i].nativeOffset;
inBlock = false;
break;
}
}
}
if (inBlock)
{
*endOffset = m_sub_low_pc + m_sub_high_pc - pCode;
}
return *endOffset != *startOffset;
}
void FunctionMember::DumpTryCatchBlock(char* ptr, int& offset, int ilOffset, int ilLen, int abbrev)
{
TADDR startOffset;
TADDR endOffset;
if (!GetBlockInNativeCode(ilOffset, ilLen, &startOffset, &endOffset))
return;
if (ptr != nullptr)
{
DebugInfoTryCatchSub subEntry;
subEntry.m_sub_abbrev = abbrev;
subEntry.m_sub_low_pc = md->GetNativeCode() + startOffset;
subEntry.m_sub_high_pc = endOffset - startOffset;
memcpy(ptr + offset, &subEntry, sizeof(DebugInfoTryCatchSub));
}
offset += sizeof(DebugInfoTryCatchSub);
}
void FunctionMember::DumpTryCatchDebugInfo(char* ptr, int& offset)
{
if (!md)
return;
COR_ILMETHOD *pHeader = md->GetILHeader();
COR_ILMETHOD_DECODER header(pHeader);
unsigned ehCount = header.EHCount();
for (unsigned e = 0; e < ehCount; e++)
{
IMAGE_COR_ILMETHOD_SECT_EH_CLAUSE_FAT ehBuff;
const IMAGE_COR_ILMETHOD_SECT_EH_CLAUSE_FAT* ehInfo;
ehInfo = header.EH->EHClause(e, &ehBuff);
DumpTryCatchBlock(ptr, offset, ehInfo->TryOffset, ehInfo->TryLength, 16);
DumpTryCatchBlock(ptr, offset, ehInfo->HandlerOffset, ehInfo->HandlerLength, 17);
}
}
void FunctionMember::DumpVarsWithScopes(char *ptr, int &offset)
{
NewArrayHolder<DebugInfoLexicalBlock> scopeStack = new DebugInfoLexicalBlock[m_num_vars];
int scopeStackSize = 0;
for (int i = 0; i < m_num_vars; ++i)
{
if (vars[i].m_high_pc == 0) // no scope info
{
vars[i].DumpDebugInfo(ptr, offset);
continue;
}
// Try to step out to enclosing scope, finilizing scopes on the way
while (scopeStackSize > 0 &&
vars[i].m_low_pc >= (scopeStack[scopeStackSize - 1].m_low_pc +
scopeStack[scopeStackSize - 1].m_high_pc))
{
// Finalize scope
if (ptr != nullptr)
{
memset(ptr + offset, 0, 1);
}
offset += 1;
scopeStackSize--;
}
// Continue adding to prev scope?
if (scopeStackSize > 0 &&
scopeStack[scopeStackSize - 1].m_low_pc == vars[i].m_low_pc &&
scopeStack[scopeStackSize - 1].m_high_pc == vars[i].m_high_pc)
{
vars[i].DumpDebugInfo(ptr, offset);
continue;
}
// Start new scope
scopeStackSize++;
scopeStack[scopeStackSize - 1].m_abbrev = 20;
scopeStack[scopeStackSize - 1].m_low_pc = vars[i].m_low_pc;
scopeStack[scopeStackSize - 1].m_high_pc = vars[i].m_high_pc;
if (ptr != nullptr)
{
memcpy(ptr + offset, scopeStack + (scopeStackSize - 1), sizeof(DebugInfoLexicalBlock));
}
offset += sizeof(DebugInfoLexicalBlock);
vars[i].DumpDebugInfo(ptr, offset);
}
// Finalize any remaining scopes
while (scopeStackSize > 0)
{
if (ptr != nullptr)
{
memset(ptr + offset, 0, 1);
}
offset += 1;
scopeStackSize--;
}
}
void FunctionMember::DumpDebugInfo(char* ptr, int& offset)
{
if (ptr != nullptr)
{
DebugInfoSub subEntry;
subEntry.m_sub_abbrev = 4;
subEntry.m_sub_name = m_member_name_offset;
subEntry.m_linkage_name = m_linkage_name_offset;
subEntry.m_file = m_file;
subEntry.m_line = m_line;
subEntry.m_sub_type = m_member_type->m_type_offset;
subEntry.m_sub_low_pc = m_sub_low_pc;
subEntry.m_sub_high_pc = m_sub_high_pc;
subEntry.m_sub_loc[0] = m_sub_loc[0];
subEntry.m_sub_loc[1] = m_sub_loc[1];
if (!md->IsStatic())
{
DebugInfoSubMember subMemberEntry;
subEntry.m_sub_abbrev = 12;
subMemberEntry.sub = subEntry;
subMemberEntry.m_obj_ptr = offset+sizeof(DebugInfoSubMember);
memcpy(ptr + offset, &subMemberEntry, sizeof(DebugInfoSubMember));
}
else
{
memcpy(ptr + offset, &subEntry, sizeof(DebugInfoSub));
}
m_entry_offset = offset;
dumped = true;
}
if (!md->IsStatic())
{
offset += sizeof(DebugInfoSubMember);
}
else
{
offset += sizeof(DebugInfoSub);
}
DumpVarsWithScopes(ptr, offset);
DumpTryCatchDebugInfo(ptr, offset);
// terminate children
if (ptr != nullptr)
{
ptr[offset] = 0;
}
offset++;
}
int FunctionMember::GetArgsAndLocalsLen()
{
int locSize = 0;
char tmpBuf[16];
// Format for DWARF location expression: [expression length][operation][offset in SLEB128 encoding]
for (int i = 0; i < m_num_vars; i++)
{
locSize += 2; // First byte contains expression length, second byte contains operation (DW_OP_fbreg).
locSize += Leb128Encode(static_cast<int32_t>(vars[i].m_native_offset), tmpBuf, sizeof(tmpBuf));
}
return locSize;
}
void ClassTypeInfo::DumpStrings(char* ptr, int& offset)
{
TypeInfoBase::DumpStrings(ptr, offset);
for (int i = 0; i < m_num_members; ++i)
{
members[i].DumpStrings(ptr, offset);
}
if (m_parent != nullptr)
{
m_parent->DumpStrings(ptr, offset);
}
}
void RefTypeInfo::DumpStrings(char* ptr, int& offset)
{
TypeInfoBase::DumpStrings(ptr, offset);
m_value_type->DumpStrings(ptr, offset);
}
void RefTypeInfo::DumpDebugInfo(char* ptr, int& offset)
{
if (m_is_visited && m_base_ptr == ptr)
{
return;
}
m_base_ptr = ptr;
m_is_visited = true;
m_type_offset = offset;
offset += sizeof(DebugInfoRefType);
m_value_type->DumpDebugInfo(ptr, offset);
if (ptr != nullptr)
{
DebugInfoRefType refType;
refType.m_type_abbrev = 9;
refType.m_ref_type = m_value_type->m_type_offset;
refType.m_byte_size = m_type_size;
memcpy(ptr + m_type_offset, &refType, sizeof(DebugInfoRefType));
}
else
{
m_type_offset = 0;
}
}
void NamedRefTypeInfo::DumpDebugInfo(char* ptr, int& offset)
{
if (m_is_visited && m_base_ptr == ptr)
{
return;
}
m_base_ptr = ptr;
m_is_visited = true;
m_type_offset = offset;
offset += sizeof(DebugInfoRefType) + sizeof(DebugInfoTypeDef);
m_value_type->DumpDebugInfo(ptr, offset);
if (ptr != nullptr)
{
DebugInfoRefType refType;
refType.m_type_abbrev = 9;
refType.m_ref_type = m_value_type->m_type_offset;
refType.m_byte_size = m_type_size;
memcpy(ptr + m_type_offset, &refType, sizeof(DebugInfoRefType));
DebugInfoTypeDef bugTypeDef;
bugTypeDef.m_typedef_abbrev = 3;
bugTypeDef.m_typedef_name = m_value_type->m_type_name_offset + 2;
bugTypeDef.m_typedef_type = m_type_offset;
memcpy(ptr + m_type_offset + sizeof(DebugInfoRefType), &bugTypeDef, sizeof(DebugInfoTypeDef));
m_type_offset += sizeof(DebugInfoRefType);
}
else
{
m_type_offset = 0;
}
}
void ClassTypeInfo::DumpDebugInfo(char* ptr, int& offset)
{
if (m_is_visited && m_base_ptr == ptr)
{
return;
}
m_base_ptr = ptr;
m_is_visited = true;
if (m_parent != nullptr)
{
m_parent->DumpDebugInfo(ptr, offset);
}
// make sure that types of all members are dumped
for (int i = 0; i < m_num_members; ++i)
{
if (members[i].m_member_type != this)
{
members[i].m_member_type->DumpDebugInfo(ptr, offset);
}
}
if (ptr != nullptr)
{
DebugInfoClassType bufType;
bufType.m_type_abbrev = 7;
bufType.m_type_name = m_type_name_offset;
bufType.m_byte_size = m_type_size;
memcpy(ptr + offset, &bufType, sizeof(DebugInfoClassType));
m_type_offset = offset;
}
offset += sizeof(DebugInfoClassType);
for (int i = 0; i < m_num_members; ++i)
{
members[i].DumpDebugInfo(ptr, offset);
}
for (int i = 0; i < m_method.GetCount(); ++i)
{
if (m_method[i]->md->GetMethodTable() == GetTypeHandle().GetMethodTable())
{
// our method is part of this class, we should dump it now before terminating members
m_method[i]->DumpDebugInfo(ptr, offset);
}
}
if (m_parent != nullptr)
{
if (ptr != nullptr)
{
DebugInfoInheritance buf;
buf.m_abbrev = 18;
if (RefTypeInfo *m_p = dynamic_cast<RefTypeInfo*>(m_parent))
buf.m_type = m_p->m_value_type->m_type_offset;
else
buf.m_type = m_parent->m_type_offset;
buf.m_data_member_location = 0;
memcpy(ptr + offset, &buf, sizeof(DebugInfoInheritance));
}
offset += sizeof(DebugInfoInheritance);
}
// members terminator
if (ptr != nullptr)
{
ptr[offset] = 0;
}
offset++;
for (int i = 0; i < m_num_members; ++i)
{
if (members[i].m_static_member_address != 0)
members[i].DumpStaticDebugInfo(ptr, offset);
}
}
void ArrayTypeInfo::DumpDebugInfo(char* ptr, int& offset)
{
if (m_is_visited && m_base_ptr == ptr)
{
return;
}
m_base_ptr = ptr;
m_is_visited = true;
m_elem_type->DumpDebugInfo(ptr, offset);
if (ptr != nullptr)
{
DebugInfoArrayType arrType;
arrType.m_abbrev = 10; // DW_TAG_array_type abbrev
arrType.m_type = m_elem_type->m_type_offset;
memcpy(ptr + offset, &arrType, sizeof(DebugInfoArrayType));
m_type_offset = offset;
}
offset += sizeof(DebugInfoArrayType);
char tmp[16] = { 0 };
int len = Leb128Encode(static_cast<uint32_t>(m_count - 1), tmp + 1, sizeof(tmp) - 1);
if (ptr != nullptr)
{
tmp[0] = 19; // DW_TAG_subrange_type abbrev with const upper bound
memcpy(ptr + offset, tmp, len + 1);
}
offset += len + 1;
if (ptr != nullptr)
{
memset(ptr + offset, 0, 1);
}
offset += 1;
}
void VarDebugInfo::DumpStrings(char *ptr, int& offset)
{
if (ptr != nullptr)
{
strcpy(ptr + offset, m_var_name);
m_var_name_offset = offset;
}
offset += strlen(m_var_name) + 1;
}
void VarDebugInfo::DumpDebugInfo(char* ptr, int& offset)
{
char bufVarLoc[16];
int len = GetFrameLocation(m_native_offset, bufVarLoc);
if (ptr != nullptr)
{
DebugInfoVar bufVar;
bufVar.m_var_abbrev = m_var_abbrev;
bufVar.m_var_name = m_var_name_offset;
bufVar.m_var_file = 1;
bufVar.m_var_line = 1;
bufVar.m_var_type = m_var_type->m_type_offset;
memcpy(ptr + offset, &bufVar, sizeof(DebugInfoVar));
memcpy(ptr + offset + sizeof(DebugInfoVar), bufVarLoc, len);
}
offset += sizeof(DebugInfoVar);
offset += len;
}
/* static data for symbol strings */
struct Elf_Symbol {
const char* m_name;
int m_off;
TADDR m_value;
int m_section, m_size;
NewArrayHolder<char> m_symbol_name;
Elf_Symbol() : m_name(nullptr), m_off(0), m_value(0), m_section(0), m_size(0) {}
};
template <class T>
static int countFuncs(T &arr, int n)
{
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i].ilOffset == ICorDebugInfo::PROLOG)
{
count++;
}
}
return count;
}
template <class T>
static int getNextPrologueIndex(int from, T &arr, int n)
{
for (int i = from; i < n; ++i) {
if (arr[i].ilOffset == ICorDebugInfo::PROLOG)
{
return i;
}
}
return -1;
}
static NewArrayHolder<WCHAR> g_wszModuleNames;
static DWORD g_cBytesNeeded;
static inline bool isListedModule(const WCHAR *wszModuleFile)
{
if (g_wszModuleNames == nullptr)
{
return false;
}
_ASSERTE(g_cBytesNeeded > 0);
BOOL isUserDebug = FALSE;
NewArrayHolder<WCHAR> wszModuleName = new WCHAR[g_cBytesNeeded];
LPWSTR pComma = wcsstr(g_wszModuleNames, W(","));
LPWSTR tmp = g_wszModuleNames;
while (pComma != NULL)
{
wcsncpy(wszModuleName, tmp, pComma - tmp);
wszModuleName[pComma - tmp] = W('\0');
if (wcscmp(wszModuleName, wszModuleFile) == 0)
{
isUserDebug = TRUE;
break;
}
tmp = pComma + 1;
pComma = wcsstr(tmp, W(","));
}
if (isUserDebug == FALSE)
{
wcsncpy(wszModuleName, tmp, wcslen(tmp));
wszModuleName[wcslen(tmp)] = W('\0');
if (wcscmp(wszModuleName, wszModuleFile) == 0)
{
isUserDebug = TRUE;
}
}
return isUserDebug;
}
static NotifyGdb::AddrSet g_codeAddrs;
static CrstStatic g_codeAddrsCrst;
class Elf_SectionTracker
{
private:
unsigned int m_Flag;
private:
NewArrayHolder<char> m_NamePtr;
unsigned int m_NameLen;
private:
unsigned int m_Ind;
unsigned int m_Off;
unsigned int m_Len;
private:
Elf_Shdr m_Hdr;
private:
Elf_SectionTracker *m_Next;
public:
Elf_SectionTracker(const char *name, unsigned ind, unsigned off, uint32_t type, uint64_t flags);
~Elf_SectionTracker();
public:
bool NeedHeaderUpdate() const;
void DisableHeaderUpdate();
public:
unsigned int GetIndex() const { return m_Ind; }
unsigned int GetOffset() const { return m_Off; }
unsigned int GetSize() const { return m_Len; }
public:
const char *GetName() const { return m_NamePtr; }
unsigned int GetNameLen() const { return m_NameLen; }
public:
Elf_SectionTracker *GetNext(void);
void SetNext(Elf_SectionTracker *next);
public:
void Forward(unsigned int len);
public:
Elf_Shdr *Header(void);
const Elf_Shdr *Header(void) const;
};
Elf_SectionTracker::Elf_SectionTracker(const char *name,
unsigned ind, unsigned off,
uint32_t type, uint64_t flags)
: m_Flag(0),
m_NamePtr(nullptr),
m_NameLen(0),
m_Ind(ind),
m_Off(off),
m_Len(0),
m_Next(nullptr)
{
if (name)
{
unsigned int len = strlen(name);
char *ptr = new char[len + 1];
strncpy(ptr, name, len + 1);
m_NamePtr = ptr;
m_NameLen = len;
}
m_Hdr.sh_type = type;
m_Hdr.sh_flags = flags;
m_Hdr.sh_name = 0;
m_Hdr.sh_addr = 0;
m_Hdr.sh_offset = 0;
m_Hdr.sh_size = 0;
m_Hdr.sh_link = SHN_UNDEF;
m_Hdr.sh_info = 0;
m_Hdr.sh_addralign = 1;
m_Hdr.sh_entsize = 0;
}
Elf_SectionTracker::~Elf_SectionTracker()
{
}
#define ESTF_NO_HEADER_UPDATE 0x00000001
bool Elf_SectionTracker::NeedHeaderUpdate() const
{
return !(m_Flag & ESTF_NO_HEADER_UPDATE);
}
void Elf_SectionTracker::DisableHeaderUpdate()
{
m_Flag |= ESTF_NO_HEADER_UPDATE;
}
void Elf_SectionTracker::Forward(unsigned int len)
{
m_Len += len;
}
void Elf_SectionTracker::SetNext(Elf_SectionTracker *next)
{
m_Next = next;
}
Elf_SectionTracker *Elf_SectionTracker::GetNext(void)
{
return m_Next;
}
Elf_Shdr *Elf_SectionTracker::Header(void)
{
return &m_Hdr;
}
const Elf_Shdr *Elf_SectionTracker::Header(void) const
{
return &m_Hdr;
}
class Elf_Buffer
{
private:
NewArrayHolder<char> m_Ptr;
unsigned int m_Len;
unsigned int m_Pos;
public:
Elf_Buffer(unsigned int len);
private:
char *Ensure(unsigned int len);
void Forward(unsigned int len);
public:
unsigned int GetPos() const
{
return m_Pos;
}
char *GetPtr(unsigned int off = 0)
{
return m_Ptr.GetValue() + off;
}
public:
char *Reserve(unsigned int len);
template <typename T> T *ReserveT(unsigned int len = sizeof(T))
{
_ASSERTE(len >= sizeof(T));
return reinterpret_cast<T *>(Reserve(len));
}
public:
void Append(const char *src, unsigned int len);
template <typename T> void AppendT(T *src)
{
Append(reinterpret_cast<const char *>(src), sizeof(T));
}
};
Elf_Buffer::Elf_Buffer(unsigned int len)
: m_Ptr(new char[len])
, m_Len(len)
, m_Pos(0)
{
}
char *Elf_Buffer::Ensure(unsigned int len)
{
bool bAdjusted = false;
while (m_Pos + len > m_Len)
{
m_Len *= 2;
bAdjusted = true;
}
if (bAdjusted)
{
char *ptr = new char [m_Len * 2];
memcpy(ptr, m_Ptr.GetValue(), m_Pos);
m_Ptr = ptr;
}
return GetPtr(m_Pos);
}
void Elf_Buffer::Forward(unsigned int len)
{
m_Pos += len;
}
char *Elf_Buffer::Reserve(unsigned int len)
{
char *ptr = Ensure(len);
Forward(len);
return ptr;
}
void Elf_Buffer::Append(const char *src, unsigned int len)
{
char *dst = Reserve(len);
memcpy(dst, src, len);
}
#define ELF_BUILDER_TEXT_SECTION_INDEX 1
class Elf_Builder
{
private:
Elf_Buffer m_Buffer;
private:
unsigned int m_SectionCount;
Elf_SectionTracker *m_First;
Elf_SectionTracker *m_Last;
Elf_SectionTracker *m_Curr;
public:
Elf_Builder();
~Elf_Builder();
public:
unsigned int GetSectionCount(void) { return m_SectionCount; }
public:
void Initialize(PCODE codePtr, TADDR codeLen);
public:
Elf_SectionTracker *OpenSection(const char *name, uint32_t type, uint64_t flags);
void CloseSection();
public:
char *Reserve(unsigned int len);
template <typename T> T *ReserveT(unsigned int len = sizeof(T))
{
_ASSERTE(len >= sizeof(T));
return reinterpret_cast<T *>(Reserve(len));
}
public:
void Append(const char *src, unsigned int len);
template <typename T> void AppendT(T *src)
{
Append(reinterpret_cast<const char *>(src), sizeof(T));
}
public:
void Finalize(void);
public:
char *Export(size_t *len);
};
Elf_Builder::Elf_Builder()
: m_Buffer(128),
m_SectionCount(0),
m_First(nullptr),
m_Last(nullptr),
m_Curr(nullptr)
{
}
Elf_Builder::~Elf_Builder()
{
Elf_SectionTracker *curr = m_First;
while (curr)
{
Elf_SectionTracker *next = curr->GetNext();
delete curr;
curr = next;
}
}
void Elf_Builder::Initialize(PCODE codePtr, TADDR codeLen)
{
//
// Reserve ELF Header
//
m_Buffer.Reserve(sizeof(Elf_Ehdr));
//
// Create NULL section
//
Elf_SectionTracker *null = OpenSection("", SHT_NULL, 0);
{
null->DisableHeaderUpdate();
null->Header()->sh_addralign = 0;
}
CloseSection();
//
// Create '.text' section
//
Elf_SectionTracker *text = OpenSection(".text", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
{
text->DisableHeaderUpdate();
text->Header()->sh_addr = codePtr;
text->Header()->sh_size = codeLen;
_ASSERTE(text->GetIndex() == ELF_BUILDER_TEXT_SECTION_INDEX);
}
CloseSection();
}
char *Elf_Builder::Reserve(unsigned int len)
{
_ASSERTE(m_Curr != nullptr && "Section should be opened before");
char *ptr = m_Buffer.Reserve(len);
m_Curr->Forward(len);
return ptr;
}
void Elf_Builder::Append(const char *src, unsigned int len)
{
_ASSERTE(m_Curr != nullptr && "Section should be opened before");
char *dst = Reserve(len);
memcpy(dst, src, len);
}
Elf_SectionTracker *Elf_Builder::OpenSection(const char *name, uint32_t type, uint64_t flags)
{
_ASSERTE(m_Curr == nullptr && "Section should be closed before");
Elf_SectionTracker *next = new Elf_SectionTracker(name, m_SectionCount, m_Buffer.GetPos(), type, flags);
if (m_First == NULL)
{
m_First = next;
}
if (m_Last != NULL)
{
m_Last->SetNext(next);
}
m_SectionCount++;
m_Last = next;
m_Curr = next;
return next;
}
void Elf_Builder::CloseSection()
{
_ASSERTE(m_Curr != nullptr && "Section should be opened before");
m_Curr = nullptr;
}
char *Elf_Builder::Export(size_t *pLen)
{
unsigned int len = m_Buffer.GetPos();
const char *src = m_Buffer.GetPtr();
char *dst = new char[len];
memcpy(dst, src, len);
if (pLen)
{
*pLen = len;
}
return dst;
}
void Elf_Builder::Finalize()
{
//
// Create '.shstrtab'
//
Elf_SectionTracker *shstrtab = OpenSection(".shstrtab", SHT_STRTAB, 0);
{
Elf_SectionTracker *curr = m_First;
while (curr)
{
unsigned int off = shstrtab->GetSize();
unsigned int len = curr->GetNameLen();
char *dst = Reserve(len + 1);
memcpy(dst, curr->GetName(), len);
dst[len] = '\0';
curr->Header()->sh_name = off;
curr = curr->GetNext();
}
}
CloseSection();
//
// Create Section Header(s) Table
//
unsigned int shtOffset = m_Buffer.GetPos();
{
Elf_SectionTracker *curr = m_First;
while (curr)
{
if (curr->NeedHeaderUpdate())
{
curr->Header()->sh_offset = curr->GetOffset();
curr->Header()->sh_size = curr->GetSize();
}
m_Buffer.AppendT(curr->Header());
curr = curr->GetNext();
}
}
//
// Update ELF Header
//
Elf_Ehdr *elfHeader = new (m_Buffer.GetPtr()) Elf_Ehdr;
#ifdef TARGET_ARM
elfHeader->e_flags = EF_ARM_EABI_VER5;
#ifdef ARM_SOFTFP
elfHeader->e_flags |= EF_ARM_SOFT_FLOAT;
#else
elfHeader->e_flags |= EF_ARM_VFP_FLOAT;
#endif
#endif
elfHeader->e_shoff = shtOffset;
elfHeader->e_shentsize = sizeof(Elf_Shdr);
elfHeader->e_shnum = m_SectionCount;
elfHeader->e_shstrndx = shstrtab->GetIndex();
}
#ifdef FEATURE_GDBJIT_FRAME
struct __attribute__((packed)) Length
{
UINT32 value;
Length &operator=(UINT32 n)
{
value = n;
return *this;
}
Length()
{
value = 0;
}
};
struct __attribute__((packed)) CIE
{
Length length;
UINT32 id;
UINT8 version;
UINT8 augmentation;
UINT8 code_alignment_factor;
INT8 data_alignment_factor;
UINT8 return_address_register;
UINT8 instructions[0];
};
struct __attribute__((packed)) FDE
{
Length length;
UINT32 cie;
PCODE initial_location;
TADDR address_range;
UINT8 instructions[0];
};
static void BuildDebugFrame(Elf_Builder &elfBuilder, PCODE pCode, TADDR codeSize)
{
#if defined(TARGET_ARM)
const unsigned int code_alignment_factor = 2;
const int data_alignment_factor = -4;
UINT8 cieCode[] = {
// DW_CFA_def_cfa 13[sp], 0
0x0c, 0x0d, 0x00,
};
UINT8 fdeCode[] = {
// DW_CFA_advance_loc 1
0x02, 0x01,
// DW_CFA_def_cfa_offset 8
0x0e, 0x08,
// DW_CFA_offset 11(r11), -8(= -4 * 2)
(0x02 << 6) | 0x0b, 0x02,
// DW_CFA_offset 14(lr), -4(= -4 * 1)
(0x02 << 6) | 0x0e, 0x01,
// DW_CFA_def_cfa_register 11(r11)
0x0d, 0x0b,
};
#elif defined(TARGET_X86)
const unsigned int code_alignment_factor = 1;
const int data_alignment_factor = -4;
UINT8 cieCode[] = {
// DW_CFA_def_cfa 4(esp), 4
0x0c, 0x04, 0x04,
// DW_CFA_offset 8(eip), -4(= -4 * 1)
(0x02 << 6) | 0x08, 0x01,
};
UINT8 fdeCode[] = {
// DW_CFA_advance_loc 1
0x02, 0x01,
// DW_CFA_def_cfa_offset 8
0x0e, 0x08,
// DW_CFA_offset 5(ebp), -8(= -4 * 2)
(0x02 << 6) | 0x05, 0x02,
// DW_CFA_def_cfa_register 5(ebp)
0x0d, 0x05,
};
#elif defined(TARGET_AMD64)
const unsigned int code_alignment_factor = 1;
const int data_alignment_factor = -8;
UINT8 cieCode[] = {
// DW_CFA_def_cfa 7(rsp), 8
0x0c, 0x07, 0x08,
// DW_CFA_offset 16, -16 (= -8 * 2)
(0x02 << 6) | 0x10, 0x01,
};
UINT8 fdeCode[] = {
// DW_CFA_advance_loc(1)
0x02, 0x01,
// DW_CFA_def_cfa_offset(16)
0x0e, 0x10,
// DW_CFA_offset 6, -16 (= -8 * 2)
(0x02 << 6) | 0x06, 0x02,
// DW_CFA_def_cfa_register(6)
0x0d, 0x06,
};
#elif defined(TARGET_ARM64)
const unsigned int code_alignment_factor = 1;
const int data_alignment_factor = -4;
UINT8 cieCode[] = {
// DW_CFA_def_cfa 31(sp), 0
0x0c, 0x1f, 0x00,
};
UINT8 fdeCode[] = {
// DW_CFA_advance_loc(1)
0x02, 0x01,
// DW_CFA_def_cfa_offset 16
0x0e, 0x10,
// DW_CFA_def_cfa_register 29(r29/fp)
0x0d, 0x1d,
// DW_CFA_offset: r30 (x30) at cfa-8
(0x02 << 6) | 0x1e, 0x02,
// DW_CFA_offset: r29 (x29) at cfa-16
(0x02 << 6) | 0x1d, 0x04,
};
#else
#error "Unsupported architecture"
#endif
elfBuilder.OpenSection(".debug_frame", SHT_PROGBITS, 0);
//
// Common Information Entry
//
int cieLen = ALIGN_UP(sizeof(CIE) + sizeof(cieCode), ADDRESS_SIZE) + sizeof(Length);
CIE *pCIE = elfBuilder.ReserveT<CIE>(cieLen);
memset(pCIE, 0, cieLen);
pCIE->length = cieLen - sizeof(Length);
pCIE->id = 0xffffffff;
pCIE->version = 3;
pCIE->augmentation = 0;
Leb128Encode(code_alignment_factor, reinterpret_cast<char *>(&pCIE->code_alignment_factor), 1);
Leb128Encode(data_alignment_factor, reinterpret_cast<char *>(&pCIE->data_alignment_factor), 1);
pCIE->return_address_register = 0;
memcpy(&pCIE->instructions, cieCode, sizeof(cieCode));
//
// Frame Description Entry
//
int fdeLen = ALIGN_UP((sizeof(FDE) + sizeof(fdeCode)), ADDRESS_SIZE) + sizeof(Length);
FDE *pFDE = elfBuilder.ReserveT<FDE>(fdeLen);
memset(pFDE, 0, fdeLen);
pFDE->length = fdeLen - sizeof(Length);
pFDE->cie = 0;
pFDE->initial_location = pCode;
pFDE->address_range = codeSize;
memcpy(&pFDE->instructions, fdeCode, sizeof(fdeCode));
elfBuilder.CloseSection();
}
#endif // FEATURE_GDBJIT_FRAME
void NotifyGdb::Initialize()
{
g_jitDescriptorCrst.Init(CrstNotifyGdb);
g_codeAddrsCrst.Init(CrstNotifyGdb);
// Get names of interesting modules from environment
if (g_wszModuleNames == nullptr && g_cBytesNeeded == 0)
{
DWORD cCharsNeeded = GetEnvironmentVariableW(W("CORECLR_GDBJIT"), NULL, 0);
if (cCharsNeeded == 0)
{
g_cBytesNeeded = 0xffffffff;
return;
}
WCHAR *wszModuleNamesBuf = new WCHAR[cCharsNeeded+1];
cCharsNeeded = GetEnvironmentVariableW(W("CORECLR_GDBJIT"), wszModuleNamesBuf, cCharsNeeded);
if (cCharsNeeded == 0)
{
delete[] wszModuleNamesBuf;
g_cBytesNeeded = 0xffffffff;
return;
}
g_wszModuleNames = wszModuleNamesBuf;
g_cBytesNeeded = cCharsNeeded + 1;
}
}
/* Create ELF/DWARF debug info for jitted method */
void NotifyGdb::MethodPrepared(MethodDesc* methodDescPtr)
{
EX_TRY
{
if (!tls_isSymReaderInProgress)
{
tls_isSymReaderInProgress = true;
NotifyGdb::OnMethodPrepared(methodDescPtr);
tls_isSymReaderInProgress = false;
}
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
}
void NotifyGdb::OnMethodPrepared(MethodDesc* methodDescPtr)
{
PCODE pCode = methodDescPtr->GetNativeCode();
if (pCode == NULL)
return;
/* Get method name & size of jitted code */
EECodeInfo codeInfo(pCode);
if (!codeInfo.IsValid())
{
return;
}
TADDR codeSize = codeInfo.GetCodeManager()->GetFunctionSize(codeInfo.GetGCInfoToken());
pCode = PCODEToPINSTR(pCode);
/* Get module name */
const Module* mod = methodDescPtr->GetMethodTable()->GetModule();
SString modName = mod->GetFile()->GetPath();
StackScratchBuffer scratch;
const char* szModName = modName.GetUTF8(scratch);
const char* szModuleFile = SplitFilename(szModName);
int length = MultiByteToWideChar(CP_UTF8, 0, szModuleFile, -1, NULL, 0);
if (length == 0)
return;
NewArrayHolder<WCHAR> wszModuleFile = new WCHAR[length+1];
length = MultiByteToWideChar(CP_UTF8, 0, szModuleFile, -1, wszModuleFile, length);
if (length == 0)
return;
bool bNotify = false;
Elf_Builder elfBuilder;
elfBuilder.Initialize(pCode, codeSize);
#ifdef FEATURE_GDBJIT_FRAME
if (g_pConfig->ShouldEmitDebugFrame())
{
bool bEmitted = EmitFrameInfo(elfBuilder, pCode, codeSize);
bNotify = bNotify || bEmitted;
}
#endif
// remove '.ni.dll' or '.ni.exe' suffix from wszModuleFile
LPWSTR pNIExt = const_cast<LPWSTR>(wcsstr(wszModuleFile, W(".ni.exe"))); // where '.ni.exe' start at
if (!pNIExt)
{
pNIExt = const_cast<LPWSTR>(wcsstr(wszModuleFile, W(".ni.dll"))); // where '.ni.dll' start at
}
if (pNIExt)
{
wcscpy(pNIExt, W(".dll"));
}
if (isListedModule(wszModuleFile))
{
bool bEmitted = EmitDebugInfo(elfBuilder, methodDescPtr, pCode, codeSize);
bNotify = bNotify || bEmitted;
}
#ifdef FEATURE_GDBJIT_SYMTAB
else
{
bool bEmitted = EmitSymtab(elfBuilder, methodDescPtr, pCode, codeSize);
bNotify = bNotify || bEmitted;
}
#endif
if (!bNotify)
{
return;
}
elfBuilder.Finalize();
char *symfile_addr = NULL;
size_t symfile_size = 0;
symfile_addr = elfBuilder.Export(&symfile_size);
#ifdef _DEBUG
LPCUTF8 methodName = methodDescPtr->GetName();
if (g_pConfig->ShouldDumpElfOnMethod(methodName))
{
DumpElf(methodName, symfile_addr, symfile_size);
}
#endif
/* Create GDB JIT structures */
NewHolder<jit_code_entry> jit_symbols = new jit_code_entry;
/* Fill the new entry */
jit_symbols->next_entry = jit_symbols->prev_entry = 0;
jit_symbols->symfile_addr = symfile_addr;
jit_symbols->symfile_size = symfile_size;
{
CrstHolder crst(&g_jitDescriptorCrst);
/* Link into list */
jit_code_entry *head = __jit_debug_descriptor.first_entry;
__jit_debug_descriptor.first_entry = jit_symbols;
if (head != 0)
{
jit_symbols->next_entry = head;
head->prev_entry = jit_symbols;
}
jit_symbols.SuppressRelease();
/* Notify the debugger */
__jit_debug_descriptor.relevant_entry = jit_symbols;
__jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
__jit_debug_register_code();
}
}
#ifdef FEATURE_GDBJIT_FRAME
bool NotifyGdb::EmitFrameInfo(Elf_Builder &elfBuilder, PCODE pCode, TADDR codeSize)
{
BuildDebugFrame(elfBuilder, pCode, codeSize);
return true;
}
#endif // FEATURE_GDBJIT_FRAME
#ifdef FEATURE_GDBJIT_SYMTAB
bool NotifyGdb::EmitSymtab(Elf_Builder &elfBuilder, MethodDesc* methodDescPtr, PCODE pCode, TADDR codeSize)
{
NewArrayHolder<DebuggerILToNativeMap> map = nullptr;
NewArrayHolder<Elf_Symbol> symbols = nullptr;
NewArrayHolder<NewArrayHolder<char>> symbolNames = nullptr;
ULONG32 numMap;
int symbolCount;
LPCUTF8 methodName = methodDescPtr->GetName();
if (GetMethodNativeMap(methodDescPtr, &numMap, map, NULL, NULL) == S_OK)
{
int methodCount = countFuncs(map, numMap);
symbolCount = methodCount + 1;
symbols = new Elf_Symbol[symbolCount];
if (methodCount > 1)
symbolNames = new NewArrayHolder<char>[methodCount - 1];
int startIndex = getNextPrologueIndex(0, map, numMap);
int methodNameSize = strlen(methodName) + 10;
for (int i = 1; i < symbolCount; ++i)
{
int endIndex = getNextPrologueIndex(startIndex + 1, map, numMap);
PCODE methodStart = map[startIndex].nativeStartOffset;
TADDR methodSize = endIndex == -1 ? codeSize - methodStart : map[endIndex].nativeStartOffset - methodStart;
if (i == 1)
{
symbols[i].m_name = methodName;
}
else
{
int symbolNameIndex = i - 2;
symbolNames[symbolNameIndex] = new char[methodNameSize];
sprintf_s(symbolNames[symbolNameIndex], methodNameSize, "%s_%d", methodName, symbolNameIndex + 1);
symbols[i].m_name = symbolNames[symbolNameIndex];
}
symbols[i].m_value = pCode + methodStart;
symbols[i].m_size = methodSize;
startIndex = endIndex;
}
}
else
{
symbolCount = 2;
symbols = new Elf_Symbol[symbolCount];
symbols[1].m_name = methodName;
symbols[1].m_value = pCode;
symbols[1].m_size = codeSize;
}
symbols[0].m_name = "";
MemBuf sectSymTab, sectStrTab;
if (!BuildStringTableSection(sectStrTab, symbols, symbolCount))
{
return false;
}
if (!BuildSymbolTableSection(sectSymTab, pCode, codeSize, symbolCount - 1, symbols, symbolCount, 0))
{
return false;
}
Elf_SectionTracker *strtab = elfBuilder.OpenSection(".strtab", SHT_STRTAB, 0);
elfBuilder.Append(sectStrTab.MemPtr, sectStrTab.MemSize);
elfBuilder.CloseSection();
Elf_SectionTracker *symtab = elfBuilder.OpenSection(".symtab", SHT_SYMTAB, 0);
elfBuilder.Append(sectSymTab.MemPtr, sectSymTab.MemSize);
symtab->Header()->sh_link = strtab->GetIndex();
symtab->Header()->sh_entsize = sizeof(Elf_Sym);
elfBuilder.CloseSection();
return true;
}
#endif // FEATURE_GDBJIT_SYMTAB
bool NotifyGdb::EmitDebugInfo(Elf_Builder &elfBuilder, MethodDesc* methodDescPtr, PCODE pCode, TADDR codeSize)
{
unsigned int thunkIndexBase = elfBuilder.GetSectionCount();
LPCUTF8 methodName = methodDescPtr->GetName();
int symbolCount = 0;
NewArrayHolder<Elf_Symbol> symbolNames;
unsigned int symInfoLen = 0;
NewArrayHolder<SymbolsInfo> symInfo = nullptr;
LocalsInfo locals;
NewHolder<TK_TypeInfoMap> pTypeMap = new TK_TypeInfoMap();
/* Get debug info for method from portable PDB */
HRESULT hr = GetDebugInfoFromPDB(methodDescPtr, symInfo, symInfoLen, locals);
if (FAILED(hr) || symInfoLen == 0)
{
return false;
}
int method_count = countFuncs(symInfo, symInfoLen);
FunctionMemberPtrArrayHolder method(method_count);
CodeHeader* pCH = (CodeHeader*)pCode - 1;
CalledMethod* pCalledMethods = reinterpret_cast<CalledMethod*>(pCH->GetCalledMethods());
/* Collect addresses of thunks called by method */
if (!CollectCalledMethods(pCalledMethods, (TADDR)methodDescPtr->GetNativeCode(), method, symbolNames, symbolCount))
{
return false;
}
pCH->SetCalledMethods(NULL);
MetaSig sig(methodDescPtr);
int nArgsCount = sig.NumFixedArgs();
if (sig.HasThis())
nArgsCount++;
unsigned int firstLineIndex = 0;
for (;firstLineIndex < symInfoLen; firstLineIndex++) {
if (symInfo[firstLineIndex].lineNumber != 0 && symInfo[firstLineIndex].lineNumber != HiddenLine) break;
}
if (firstLineIndex >= symInfoLen)
{
return false;
}
int start_index = getNextPrologueIndex(0, symInfo, symInfoLen);
for (int method_index = 0; method_index < method.GetCount(); ++method_index)
{
method[method_index] = new FunctionMember(methodDescPtr, locals.size, nArgsCount);
int end_index = getNextPrologueIndex(start_index + 1, symInfo, symInfoLen);
PCODE method_start = symInfo[start_index].nativeOffset;
TADDR method_size = end_index == -1 ? codeSize - method_start : symInfo[end_index].nativeOffset - method_start;
// method return type
method[method_index]->m_member_type = GetArgTypeInfo(methodDescPtr, pTypeMap, 0, method);
method[method_index]->m_sub_low_pc = pCode + method_start;
method[method_index]->m_sub_high_pc = method_size;
method[method_index]->lines = symInfo;
method[method_index]->nlines = symInfoLen;
method[method_index]->GetLocalsDebugInfo(pTypeMap, locals, symInfo[firstLineIndex].nativeOffset, method);
size_t methodNameSize = strlen(methodName) + 10;
method[method_index]->m_member_name = new char[methodNameSize];
if (method_index == 0)
sprintf_s(method[method_index]->m_member_name, methodNameSize, "%s", methodName);
else
sprintf_s(method[method_index]->m_member_name, methodNameSize, "%s_%i", methodName, method_index);
// method's class
GetTypeInfoFromTypeHandle(TypeHandle(method[method_index]->md->GetMethodTable()), pTypeMap, method);
start_index = end_index;
}
MemBuf sectSymTab, sectStrTab, dbgInfo, dbgAbbrev, dbgPubname, dbgPubType, dbgLine,
dbgStr;
/* Build .debug_abbrev section */
if (!BuildDebugAbbrev(dbgAbbrev))
{
return false;
}
const char *cuPath = "";
/* Build .debug_line section */
if (!BuildLineTable(dbgLine, pCode, codeSize, symInfo, symInfoLen, cuPath))
{
return false;
}
// Split full path to compile unit into file name and directory path
const char *fileName = SplitFilename(cuPath);
int dirLen = fileName - cuPath;
NewArrayHolder<char> dirPath;
if (dirLen != 0)
{
dirPath = new char[dirLen];
memcpy(dirPath, cuPath, dirLen - 1);
dirPath[dirLen - 1] = '\0';
}
DebugStringsCU debugStringsCU(fileName, dirPath ? (const char *)dirPath : "");
/* Build .debug_str section */
if (!BuildDebugStrings(dbgStr, pTypeMap, method, debugStringsCU))
{
return false;
}
/* Build .debug_info section */
if (!BuildDebugInfo(dbgInfo, pTypeMap, method, debugStringsCU))
{
return false;
}
for (int i = 0; i < method.GetCount(); ++i)
{
method[i]->lines = nullptr;
method[i]->nlines = 0;
}
/* Build .debug_pubname section */
if (!BuildDebugPub(dbgPubname, methodName, dbgInfo.MemSize, 0x28))
{
return false;
}
/* Build debug_pubtype section */
if (!BuildDebugPub(dbgPubType, "int", dbgInfo.MemSize, 0x1a))
{
return false;
}
/* Build .strtab section */
symbolNames[0].m_name = "";
for (int i = 0; i < method.GetCount(); ++i)
{
symbolNames[1 + i].m_name = method[i]->m_member_name;
symbolNames[1 + i].m_value = method[i]->m_sub_low_pc;
symbolNames[1 + i].m_section = 1;
symbolNames[1 + i].m_size = method[i]->m_sub_high_pc;
}
if (!BuildStringTableSection(sectStrTab, symbolNames, symbolCount))
{
return false;
}
/* Build .symtab section */
if (!BuildSymbolTableSection(sectSymTab, pCode, codeSize, method.GetCount(), symbolNames, symbolCount, thunkIndexBase))
{
return false;
}
for (int i = 1 + method.GetCount(); i < symbolCount; i++)
{
char name[256];
sprintf_s(name, _countof(name), ".thunk_%i", i);
Elf_SectionTracker *thunk = elfBuilder.OpenSection(name, SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR);
thunk->DisableHeaderUpdate();
elfBuilder.CloseSection();
}
elfBuilder.OpenSection(".debug_str", SHT_PROGBITS, SHF_MERGE | SHF_STRINGS);
elfBuilder.Append(dbgStr.MemPtr, dbgStr.MemSize);
elfBuilder.CloseSection();
elfBuilder.OpenSection(".debug_abbrev", SHT_PROGBITS, 0);
elfBuilder.Append(dbgAbbrev.MemPtr, dbgAbbrev.MemSize);
elfBuilder.CloseSection();
elfBuilder.OpenSection(".debug_info", SHT_PROGBITS, 0);
elfBuilder.Append(dbgInfo.MemPtr, dbgInfo.MemSize);
elfBuilder.CloseSection();
elfBuilder.OpenSection(".debug_pubnames", SHT_PROGBITS, 0);
elfBuilder.Append(dbgPubname.MemPtr, dbgPubname.MemSize);
elfBuilder.CloseSection();
elfBuilder.OpenSection(".debug_pubtypes", SHT_PROGBITS, 0);
elfBuilder.Append(dbgPubType.MemPtr, dbgPubType.MemSize);
elfBuilder.CloseSection();
elfBuilder.OpenSection(".debug_line", SHT_PROGBITS, 0);
elfBuilder.Append(dbgLine.MemPtr, dbgLine.MemSize);
elfBuilder.CloseSection();
Elf_SectionTracker *strtab = elfBuilder.OpenSection(".strtab", SHT_STRTAB, 0);
elfBuilder.Append(sectStrTab.MemPtr, sectStrTab.MemSize);
elfBuilder.CloseSection();
Elf_SectionTracker *symtab = elfBuilder.OpenSection(".symtab", SHT_SYMTAB, 0);
elfBuilder.Append(sectSymTab.MemPtr, sectSymTab.MemSize);
symtab->Header()->sh_link = strtab->GetIndex();
symtab->Header()->sh_entsize = sizeof(Elf_Sym);
elfBuilder.CloseSection();
return true;
}
void NotifyGdb::MethodPitched(MethodDesc* methodDescPtr)
{
PCODE pCode = methodDescPtr->GetNativeCode();
if (pCode == NULL)
return;
CrstHolder crst(&g_jitDescriptorCrst);
/* Find relevant entry */
for (jit_code_entry* jit_symbols = __jit_debug_descriptor.first_entry; jit_symbols != 0; jit_symbols = jit_symbols->next_entry)
{
const char* ptr = jit_symbols->symfile_addr;
uint64_t size = jit_symbols->symfile_size;
const Elf_Ehdr* pEhdr = reinterpret_cast<const Elf_Ehdr*>(ptr);
const Elf_Shdr* pShdr = reinterpret_cast<const Elf_Shdr*>(ptr + pEhdr->e_shoff);
pShdr += ELF_BUILDER_TEXT_SECTION_INDEX; // bump to .text section
if (pShdr->sh_addr == pCode)
{
/* Notify the debugger */
__jit_debug_descriptor.relevant_entry = jit_symbols;
__jit_debug_descriptor.action_flag = JIT_UNREGISTER_FN;
__jit_debug_register_code();
/* Free memory */
delete[] ptr;
/* Unlink from list */
if (jit_symbols->prev_entry == 0)
__jit_debug_descriptor.first_entry = jit_symbols->next_entry;
else
jit_symbols->prev_entry->next_entry = jit_symbols->next_entry;
delete jit_symbols;
break;
}
}
}
/* Build the DWARF .debug_line section */
bool NotifyGdb::BuildLineTable(MemBuf& buf, PCODE startAddr, TADDR codeSize, SymbolsInfo* lines, unsigned nlines,
const char * &cuPath)
{
MemBuf fileTable, lineProg;
/* Build file table */
if (!BuildFileTable(fileTable, lines, nlines, cuPath))
return false;
/* Build line info program */
if (!BuildLineProg(lineProg, startAddr, codeSize, lines, nlines))
{
return false;
}
buf.MemSize = sizeof(DwarfLineNumHeader) + fileTable.MemSize + lineProg.MemSize;
buf.MemPtr = new char[buf.MemSize];
/* Fill the line info header */
DwarfLineNumHeader* header = reinterpret_cast<DwarfLineNumHeader*>(buf.MemPtr.GetValue());
memcpy(buf.MemPtr, &LineNumHeader, sizeof(DwarfLineNumHeader));
header->m_length = buf.MemSize - sizeof(header->m_length);
// Set m_hdr_field to the number of bytes following the m_hdr_field field to the beginning of the first byte of
// the line number program itself.
header->m_hdr_length = sizeof(DwarfLineNumHeader)
- sizeof(header->m_length)
- sizeof(header->m_version)
- sizeof(header->m_hdr_length)
+ fileTable.MemSize;
/* copy file table */
memcpy(buf.MemPtr + sizeof(DwarfLineNumHeader), fileTable.MemPtr, fileTable.MemSize);
/* copy line program */
memcpy(buf.MemPtr + sizeof(DwarfLineNumHeader) + fileTable.MemSize, lineProg.MemPtr, lineProg.MemSize);
return true;
}
// A class for building Directory Table and File Table (in .debug_line section) from a list of files
class NotifyGdb::FileTableBuilder
{
int m_capacity;
NewArrayHolder< NewArrayHolder<char> > m_dirs;
int m_dirs_count;
struct FileEntry
{
const char* path;
const char* name;
int dir;
};
NewArrayHolder<FileEntry> m_files;
int m_files_count;
int FindDir(const char *name) const
{
for (int i = 0; i < m_dirs_count; ++i)
{
if (strcmp(m_dirs[i], name) == 0)
return i;
}
return -1;
}
int FindFile(const char *path) const
{
for (int i = 0; i < m_files_count; ++i)
{
if (strcmp(m_files[i].path, path) == 0)
return i;
}
return -1;
}
public:
FileTableBuilder(int capacity) :
m_capacity(capacity),
m_dirs(new NewArrayHolder<char>[capacity]),
m_dirs_count(0),
m_files(new FileEntry[capacity]),
m_files_count(0)
{
}
int Add(const char *path)
{
// Already exists?
int i = FindFile(path);
if (i != -1)
return i;
if (m_files_count >= m_capacity)
return -1;
// Add new file entry
m_files[m_files_count].path = path;
const char *filename = SplitFilename(path);
m_files[m_files_count].name = filename;
int dirLen = filename - path;
if (dirLen == 0)
{
m_files[m_files_count].dir = 0;
return m_files_count++;
}
// Construct directory path
NewArrayHolder<char> dirName = new char[dirLen + 1];
int delimiterDelta = dirLen == 1 ? 0 : 1; // Avoid empty dir entry when file is at Unix root /
memcpy(dirName, path, dirLen - delimiterDelta);
dirName[dirLen - delimiterDelta] = '\0';
// Try to find existing directory entry
i = FindDir(dirName);
if (i != -1)
{
m_files[m_files_count].dir = i + 1;
return m_files_count++;
}
// Create new directory entry
if (m_dirs_count >= m_capacity)
return -1;
m_dirs[m_dirs_count++] = dirName.Extract();
m_files[m_files_count].dir = m_dirs_count;
return m_files_count++;
}
void Build(MemBuf& buf)
{
unsigned totalSize = 0;
// Compute buffer size
for (unsigned i = 0; i < m_dirs_count; ++i)
totalSize += strlen(m_dirs[i]) + 1;
totalSize += 1;
char cnv_buf[16];
for (unsigned i = 0; i < m_files_count; ++i)
{
int len = Leb128Encode(static_cast<uint32_t>(m_files[i].dir), cnv_buf, sizeof(cnv_buf));
totalSize += strlen(m_files[i].name) + 1 + len + 2;
}
totalSize += 1;
// Fill the buffer
buf.MemSize = totalSize;
buf.MemPtr = new char[buf.MemSize];
char *ptr = buf.MemPtr;
for (unsigned i = 0; i < m_dirs_count; ++i)
{
strcpy(ptr, m_dirs[i]);
ptr += strlen(m_dirs[i]) + 1;
}
// final zero byte for directory table
*ptr++ = 0;
for (unsigned i = 0; i < m_files_count; ++i)
{
strcpy(ptr, m_files[i].name);
ptr += strlen(m_files[i].name) + 1;
// Index in directory table
int len = Leb128Encode(static_cast<uint32_t>(m_files[i].dir), cnv_buf, sizeof(cnv_buf));
memcpy(ptr, cnv_buf, len);
ptr += len;
// Two LEB128 entries which we don't care
*ptr++ = 0;
*ptr++ = 0;
}
// final zero byte
*ptr = 0;
}
};
/* Buid the source files table for DWARF source line info */
bool NotifyGdb::BuildFileTable(MemBuf& buf, SymbolsInfo* lines, unsigned nlines, const char * &cuPath)
{
FileTableBuilder fileTable(nlines);
cuPath = "";
for (unsigned i = 0; i < nlines; ++i)
{
const char* fileName = lines[i].fileName;
if (fileName[0] == '\0')
continue;
if (*cuPath == '\0') // Use first non-empty filename as compile unit
cuPath = fileName;
lines[i].fileIndex = fileTable.Add(fileName);
}
fileTable.Build(buf);
return true;
}
/* Command to set absolute address */
void NotifyGdb::IssueSetAddress(char*& ptr, PCODE addr)
{
*ptr++ = 0;
*ptr++ = ADDRESS_SIZE + 1;
*ptr++ = DW_LNE_set_address;
*reinterpret_cast<PCODE*>(ptr) = addr;
ptr += ADDRESS_SIZE;
}
/* End of line program */
void NotifyGdb::IssueEndOfSequence(char*& ptr)
{
*ptr++ = 0;
*ptr++ = 1;
*ptr++ = DW_LNE_end_sequence;
}
/* Command w/o parameters */
void NotifyGdb::IssueSimpleCommand(char*& ptr, uint8_t command)
{
*ptr++ = command;
}
/* Command with one LEB128 parameter */
void NotifyGdb::IssueParamCommand(char*& ptr, uint8_t command, char* param, int param_size)
{
*ptr++ = command;
while (param_size-- > 0)
{
*ptr++ = *param++;
}
}
static void fixLineMapping(SymbolsInfo* lines, unsigned nlines)
{
// Fix EPILOGUE line mapping
int prevLine = 0;
for (int i = 0; i < nlines; ++i)
{
if (lines[i].lineNumber == HiddenLine)
continue;
if (lines[i].ilOffset == ICorDebugInfo::PROLOG) // will be fixed in next step
{
prevLine = 0;
}
else
{
if (lines[i].lineNumber == 0)
{
lines[i].lineNumber = prevLine;
}
else
{
prevLine = lines[i].lineNumber;
}
}
}
// Fix PROLOGUE line mapping
prevLine = lines[nlines - 1].lineNumber;
for (int i = nlines - 1; i >= 0; --i)
{
if (lines[i].lineNumber == HiddenLine)
continue;
if (lines[i].lineNumber == 0)
lines[i].lineNumber = prevLine;
else
prevLine = lines[i].lineNumber;
}
// Skip HiddenLines
for (int i = 0; i < nlines; ++i)
{
if (lines[i].lineNumber == HiddenLine)
{
lines[i].lineNumber = 0;
if (i + 1 < nlines && lines[i + 1].ilOffset == ICorDebugInfo::NO_MAPPING)
lines[i + 1].lineNumber = 0;
}
}
}
/* Build program for DWARF source line section */
bool NotifyGdb::BuildLineProg(MemBuf& buf, PCODE startAddr, TADDR codeSize, SymbolsInfo* lines, unsigned nlines)
{
char cnv_buf[16];
/* reserve memory assuming worst case: set address, advance line command, set proglogue/epilogue and copy for each line */
buf.MemSize =
+ 6 /* set file command */
+ nlines * 6 /* advance line commands */
+ nlines * (3 + ADDRESS_SIZE) /* set address commands */
+ nlines * 1 /* set prologue end or epilogue begin commands */
+ nlines * 1 /* copy commands */
+ 6 /* advance PC command */
+ 3; /* end of sequence command */
buf.MemPtr = new char[buf.MemSize];
char* ptr = buf.MemPtr;
if (buf.MemPtr == nullptr)
return false;
fixLineMapping(lines, nlines);
int prevLine = 1, prevFile = 0;
for (int i = 0; i < nlines; ++i)
{
/* different source file */
if (lines[i].fileIndex != prevFile)
{
int len = Leb128Encode(static_cast<uint32_t>(lines[i].fileIndex+1), cnv_buf, sizeof(cnv_buf));
IssueParamCommand(ptr, DW_LNS_set_file, cnv_buf, len);
prevFile = lines[i].fileIndex;
}
// GCC don't use the is_prologue_end flag to mark the first instruction after the prologue.
// Instead of it it is issueing a line table entry for the first instruction of the prologue
// and one for the first instruction after the prologue.
// We do not want to confuse the debugger so we have to avoid adding a line in such case.
if (i > 0 && lines[i - 1].nativeOffset == lines[i].nativeOffset)
continue;
IssueSetAddress(ptr, startAddr + lines[i].nativeOffset);
if (lines[i].lineNumber != prevLine) {
int len = Leb128Encode(static_cast<int32_t>(lines[i].lineNumber - prevLine), cnv_buf, sizeof(cnv_buf));
IssueParamCommand(ptr, DW_LNS_advance_line, cnv_buf, len);
prevLine = lines[i].lineNumber;
}
if (lines[i].ilOffset == ICorDebugInfo::EPILOG)
IssueSimpleCommand(ptr, DW_LNS_set_epilogue_begin);
else if (i > 0 && lines[i - 1].ilOffset == ICorDebugInfo::PROLOG)
IssueSimpleCommand(ptr, DW_LNS_set_prologue_end);
IssueParamCommand(ptr, DW_LNS_copy, NULL, 0);
}
int lastAddr = nlines > 0 ? lines[nlines - 1].nativeOffset : 0;
// Advance PC to the end of function
if (lastAddr < codeSize) {
int len = Leb128Encode(static_cast<uint32_t>(codeSize - lastAddr), cnv_buf, sizeof(cnv_buf));
IssueParamCommand(ptr, DW_LNS_advance_pc, cnv_buf, len);
}
IssueEndOfSequence(ptr);
buf.MemSize = ptr - buf.MemPtr;
return true;
}
/* Build the DWARF .debug_str section */
bool NotifyGdb::BuildDebugStrings(MemBuf& buf,
PTK_TypeInfoMap pTypeMap,
FunctionMemberPtrArrayHolder &method,
DebugStringsCU &debugStringsCU)
{
int totalLength = 0;
/* calculate total section size */
debugStringsCU.DumpStrings(nullptr, totalLength);
for (int i = 0; i < method.GetCount(); ++i)
{
method[i]->DumpStrings(nullptr, totalLength);
}
{
auto iter = pTypeMap->Begin();
while (iter != pTypeMap->End())
{
TypeInfoBase *typeInfo = iter->Value();
typeInfo->DumpStrings(nullptr, totalLength);
iter++;
}
}
buf.MemSize = totalLength;
buf.MemPtr = new char[totalLength];
/* copy strings */
char* bufPtr = buf.MemPtr;
int offset = 0;
debugStringsCU.DumpStrings(bufPtr, offset);
for (int i = 0; i < method.GetCount(); ++i)
{
method[i]->DumpStrings(bufPtr, offset);
}
{
auto iter = pTypeMap->Begin();
while (iter != pTypeMap->End())
{
TypeInfoBase *typeInfo = iter->Value();
typeInfo->DumpStrings(bufPtr, offset);
iter++;
}
}
return true;
}
/* Build the DWARF .debug_abbrev section */
bool NotifyGdb::BuildDebugAbbrev(MemBuf& buf)
{
buf.MemPtr = new char[AbbrevTableSize];
buf.MemSize = AbbrevTableSize;
memcpy(buf.MemPtr, AbbrevTable, AbbrevTableSize);
return true;
}
/* Build tge DWARF .debug_info section */
bool NotifyGdb::BuildDebugInfo(MemBuf& buf,
PTK_TypeInfoMap pTypeMap,
FunctionMemberPtrArrayHolder &method,
DebugStringsCU &debugStringsCU)
{
int totalTypeVarSubSize = 0;
{
auto iter = pTypeMap->Begin();
while (iter != pTypeMap->End())
{
TypeInfoBase *typeInfo = iter->Value();
typeInfo->DumpDebugInfo(nullptr, totalTypeVarSubSize);
iter++;
}
}
for (int i = 0; i < method.GetCount(); ++i)
{
method[i]->DumpDebugInfo(nullptr, totalTypeVarSubSize);
}
//int locSize = GetArgsAndLocalsLen(argsDebug, argsDebugSize, localsDebug, localsDebugSize);
buf.MemSize = sizeof(DwarfCompUnit) + sizeof(DebugInfoCU) + totalTypeVarSubSize + 2;
buf.MemPtr = new char[buf.MemSize];
int offset = 0;
/* Compile uint header */
DwarfCompUnit* cu = reinterpret_cast<DwarfCompUnit*>(buf.MemPtr.GetValue());
cu->m_length = buf.MemSize - sizeof(uint32_t);
cu->m_version = 4;
cu->m_abbrev_offset = 0;
cu->m_addr_size = ADDRESS_SIZE;
offset += sizeof(DwarfCompUnit);
DebugInfoCU* diCU =
reinterpret_cast<DebugInfoCU*>(buf.MemPtr + offset);
memcpy(buf.MemPtr + offset, &debugInfoCU, sizeof(DebugInfoCU));
offset += sizeof(DebugInfoCU);
diCU->m_prod_off = debugStringsCU.GetProducerOffset();
diCU->m_cu_name = debugStringsCU.GetModuleNameOffset();
diCU->m_cu_dir = debugStringsCU.GetModuleDirOffset();
{
auto iter = pTypeMap->Begin();
while (iter != pTypeMap->End())
{
TypeInfoBase *typeInfo = iter->Value();
typeInfo->DumpDebugInfo(buf.MemPtr, offset);
iter++;
}
}
for (int i = 0; i < method.GetCount(); ++i)
{
if (!method[i]->IsDumped())
{
method[i]->DumpDebugInfo(buf.MemPtr, offset);
}
else
{
method[i]->DumpDebugInfo(buf.MemPtr, method[i]->m_entry_offset);
}
}
memset(buf.MemPtr + offset, 0, buf.MemSize - offset);
return true;
}
/* Build the DWARF lookup section */
bool NotifyGdb::BuildDebugPub(MemBuf& buf, const char* name, uint32_t size, uint32_t die_offset)
{
uint32_t length = sizeof(DwarfPubHeader) + sizeof(uint32_t) + strlen(name) + 1 + sizeof(uint32_t);
buf.MemSize = length;
buf.MemPtr = new char[buf.MemSize];
DwarfPubHeader* header = reinterpret_cast<DwarfPubHeader*>(buf.MemPtr.GetValue());
header->m_length = length - sizeof(uint32_t);
header->m_version = 2;
header->m_debug_info_off = 0;
header->m_debug_info_len = size;
*reinterpret_cast<uint32_t*>(buf.MemPtr + sizeof(DwarfPubHeader)) = die_offset;
strcpy(buf.MemPtr + sizeof(DwarfPubHeader) + sizeof(uint32_t), name);
*reinterpret_cast<uint32_t*>(buf.MemPtr + length - sizeof(uint32_t)) = 0;
return true;
}
/* Store addresses and names of the called methods into symbol table */
bool NotifyGdb::CollectCalledMethods(CalledMethod* pCalledMethods,
TADDR nativeCode,
FunctionMemberPtrArrayHolder &method,
NewArrayHolder<Elf_Symbol> &symbolNames,
int &symbolCount)
{
AddrSet tmpCodeAddrs;
CrstHolder crst(&g_codeAddrsCrst);
if (!g_codeAddrs.Contains(nativeCode))
g_codeAddrs.Add(nativeCode);
CalledMethod* pList = pCalledMethods;
/* count called methods */
while (pList != NULL)
{
TADDR callAddr = (TADDR)pList->GetCallAddr();
if (!tmpCodeAddrs.Contains(callAddr) && !g_codeAddrs.Contains(callAddr)) {
tmpCodeAddrs.Add(callAddr);
}
pList = pList->GetNext();
}
symbolCount = 1 + method.GetCount() + tmpCodeAddrs.GetCount();
symbolNames = new Elf_Symbol[symbolCount];
pList = pCalledMethods;
int i = 1 + method.GetCount();
while (i < symbolCount && pList != NULL)
{
TADDR callAddr = (TADDR)pList->GetCallAddr();
if (!g_codeAddrs.Contains(callAddr))
{
MethodDesc* pMD = pList->GetMethodDesc();
LPCUTF8 methodName = pMD->GetName();
int symbolNameLength = strlen(methodName) + sizeof("__thunk_");
symbolNames[i].m_symbol_name = new char[symbolNameLength];
symbolNames[i].m_name = symbolNames[i].m_symbol_name;
sprintf_s((char*)symbolNames[i].m_name, symbolNameLength, "__thunk_%s", methodName);
symbolNames[i].m_value = callAddr;
++i;
g_codeAddrs.Add(callAddr);
}
pList = pList->GetNext();
}
symbolCount = i;
return true;
}
/* Build ELF .strtab section */
bool NotifyGdb::BuildStringTableSection(MemBuf& buf, NewArrayHolder<Elf_Symbol> &symbolNames, int symbolCount)
{
int len = 0;
for (int i = 0; i < symbolCount; ++i)
len += strlen(symbolNames[i].m_name) + 1;
len++; // end table with zero-length string
buf.MemSize = len;
buf.MemPtr = new char[buf.MemSize];
char* ptr = buf.MemPtr;
for (int i = 0; i < symbolCount; ++i)
{
symbolNames[i].m_off = ptr - buf.MemPtr;
strcpy(ptr, symbolNames[i].m_name);
ptr += strlen(symbolNames[i].m_name) + 1;
}
buf.MemPtr[buf.MemSize-1] = 0;
return true;
}
/* Build ELF .symtab section */
bool NotifyGdb::BuildSymbolTableSection(MemBuf& buf, PCODE addr, TADDR codeSize, int methodCount,
NewArrayHolder<Elf_Symbol> &symbolNames, int symbolCount,
unsigned int thunkIndexBase)
{
buf.MemSize = symbolCount * sizeof(Elf_Sym);
buf.MemPtr = new char[buf.MemSize];
Elf_Sym *sym = reinterpret_cast<Elf_Sym*>(buf.MemPtr.GetValue());
sym[0].st_name = 0;
sym[0].st_info = 0;
sym[0].st_other = 0;
sym[0].st_value = 0;
sym[0].st_size = 0;
sym[0].st_shndx = SHN_UNDEF;
for (int i = 1; i < 1 + methodCount; ++i)
{
sym[i].st_name = symbolNames[i].m_off;
sym[i].setBindingAndType(STB_GLOBAL, STT_FUNC);
sym[i].st_other = 0;
sym[i].st_value = PINSTRToPCODE(symbolNames[i].m_value - addr);
sym[i].st_shndx = ELF_BUILDER_TEXT_SECTION_INDEX;
sym[i].st_size = symbolNames[i].m_size;
}
for (int i = 1 + methodCount; i < symbolCount; ++i)
{
sym[i].st_name = symbolNames[i].m_off;
sym[i].setBindingAndType(STB_GLOBAL, STT_FUNC);
sym[i].st_other = 0;
sym[i].st_shndx = thunkIndexBase + (i - (1 + methodCount)); // .thunks section index
sym[i].st_size = 8;
#ifdef TARGET_ARM
sym[i].st_value = 1; // for THUMB code
#else
sym[i].st_value = 0;
#endif
}
return true;
}
/* Split file name part from the full path */
const char * NotifyGdb::SplitFilename(const char* path)
{
// Search for the last directory delimiter (Windows or Unix)
const char *pSlash = nullptr;
for (const char *p = path; *p != '\0'; p++)
{
if (*p == '/' || *p == '\\')
pSlash = p;
}
return pSlash ? pSlash + 1 : path;
}
/* ELF 32bit header */
Elf32_Ehdr::Elf32_Ehdr()
{
e_ident[EI_MAG0] = ElfMagic[0];
e_ident[EI_MAG1] = ElfMagic[1];
e_ident[EI_MAG2] = ElfMagic[2];
e_ident[EI_MAG3] = ElfMagic[3];
e_ident[EI_CLASS] = ELFCLASS32;
e_ident[EI_DATA] = ELFDATA2LSB;
e_ident[EI_VERSION] = EV_CURRENT;
e_ident[EI_OSABI] = ELFOSABI_NONE;
e_ident[EI_ABIVERSION] = 0;
for (int i = EI_PAD; i < EI_NIDENT; ++i)
e_ident[i] = 0;
e_type = ET_REL;
#if defined(TARGET_X86)
e_machine = EM_386;
#elif defined(TARGET_ARM)
e_machine = EM_ARM;
#endif
e_flags = 0;
e_version = 1;
e_entry = 0;
e_phoff = 0;
e_ehsize = sizeof(Elf32_Ehdr);
e_phentsize = 0;
e_phnum = 0;
}
/* ELF 64bit header */
Elf64_Ehdr::Elf64_Ehdr()
{
e_ident[EI_MAG0] = ElfMagic[0];
e_ident[EI_MAG1] = ElfMagic[1];
e_ident[EI_MAG2] = ElfMagic[2];
e_ident[EI_MAG3] = ElfMagic[3];
e_ident[EI_CLASS] = ELFCLASS64;
e_ident[EI_DATA] = ELFDATA2LSB;
e_ident[EI_VERSION] = EV_CURRENT;
e_ident[EI_OSABI] = ELFOSABI_NONE;
e_ident[EI_ABIVERSION] = 0;
for (int i = EI_PAD; i < EI_NIDENT; ++i)
e_ident[i] = 0;
e_type = ET_REL;
#if defined(TARGET_AMD64)
e_machine = EM_X86_64;
#elif defined(TARGET_ARM64)
e_machine = EM_AARCH64;
#endif
e_flags = 0;
e_version = 1;
e_entry = 0;
e_phoff = 0;
e_ehsize = sizeof(Elf64_Ehdr);
e_phentsize = 0;
e_phnum = 0;
}
| 28.461705 | 131 | 0.607582 | patricksadowski |
164339c376cb9c28c3736418ae65755eb33fc2d1 | 3,034 | cc | C++ | src/core/tests/determinant.cc | revorg7/beliefbox | ba974b17fbb46ac98960f31dea66115be470000e | [
"OLDAP-2.3"
] | 4 | 2015-12-02T23:16:44.000Z | 2018-01-07T10:54:36.000Z | src/core/tests/determinant.cc | revorg7/beliefbox | ba974b17fbb46ac98960f31dea66115be470000e | [
"OLDAP-2.3"
] | 2 | 2015-12-02T19:47:57.000Z | 2018-10-14T13:08:40.000Z | src/core/tests/determinant.cc | revorg7/beliefbox | ba974b17fbb46ac98960f31dea66115be470000e | [
"OLDAP-2.3"
] | 4 | 2018-01-14T14:23:18.000Z | 2018-10-29T12:46:41.000Z | /* -*- Mode: c++ -*- */
/* VER: $Id: MathFunctions.h,v 1.2 2006/11/06 15:48:53 cdimitrakakis Exp cdimitrakakis $ */
// copyright (c) 2006 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifdef MAKE_MAIN
#include "Matrix.h"
#include "Distribution.h"
#include "NormalDistribution.h"
#include "EasyClock.h"
#include <cstdlib>
#include <cstdio>
#include <exception>
#include <stdexcept>
void compute_determinants_both_ways(Matrix A, bool show = true)
{
real det;
if (show) {
A.print(stdout);
}
Matrix B = A;
double cpu_time = GetCPU();
real det_sign = A.gaussian_elimination_forward();
real det_gaus_el = det_sign * A.compute_det_triangular();
cpu_time = GetCPU() - cpu_time;
printf ("# det(A):%f (%f ms)\n", det_gaus_el, 1000.0*cpu_time);
if (show) {
printf ("# G:\n"); A.print(stdout);
}
cpu_time = GetCPU();
std::vector<Matrix> LU = B.LUDecomposition(det);
real det_lu_dec = det * LU[0].compute_det_triangular() * LU[1].compute_det_triangular();
cpu_time = GetCPU() - cpu_time;
if (show) {
printf ("# L:\n"); LU[0].print(stdout);
printf ("# U:\n"); LU[1].print(stdout);
}
printf ("# det(A)=%f (%f ms)\n", det_lu_dec, 1000.0*cpu_time);
real delta = fabs(det_lu_dec - det_gaus_el);
printf ("# delta = %f : ", delta);
if (delta < 0.000001) {
printf ("OK\n");
} else {
printf ("ERR\n");
}
}
int main(void)
{
Matrix Q(2,2);
Matrix I = Matrix::Unity(2, 2);
Q(0,0)=0.0; Q(0,1)=1.0;
Q(1,0)=1.0; Q(1,1)=0.0;
Matrix W(2,2);
W(0,0)=1.0; W(0,1)=2.0;
W(1,0)=3.0; W(1,1)=4.0;
printf ("I\n");
compute_determinants_both_ways(I);
printf ("--------\n");
printf ("Q\n");
compute_determinants_both_ways(Q);
printf ("--------\n");
printf ("W\n");
compute_determinants_both_ways(W);
printf ("--------\n");
for (int N=2; N<=1024; N*=2) {
Matrix X = Matrix(N,N);
NormalDistribution gaussian;
real N2 = (real) (N);
printf ("# N=%d\n", N);
for (int i=0; i<N; ++i) {
for (int j=0; j<N; ++j) {
X(i,j) = gaussian.generate() / N2;
if(i==j) X(i,j)+=1.0;
}
}
compute_determinants_both_ways(X, false);
printf ("------------------------------\n\n");
}
return 0;
}
#endif
| 29.456311 | 92 | 0.488794 | revorg7 |
16436957f8231aba3e04fd20fac6f2b0790ae28e | 1,267 | cpp | C++ | foobar2000/helpers/packet_decoder_mp3_common.cpp | jpbattaille/foobar2000 | 9b057e21fee0a185d09d520de9bb7bce27cb264b | [
"Unlicense"
] | 147 | 2017-11-19T22:22:09.000Z | 2019-06-24T11:57:40.000Z | foobar_sdk/foobar2000/helpers/packet_decoder_mp3_common.cpp | izilzty/foo_usbhid_m202md28a | b4d6df8baa290fe2ad33c57ec8acd77dcd82500a | [
"Unlicense"
] | 28 | 2018-05-22T19:57:58.000Z | 2019-06-21T23:31:50.000Z | fb2k/foobar2000/helpers/packet_decoder_mp3_common.cpp | hozuki/foo_input_nemuc | 884fc8d7c1af2ac7eb8235cd5691d156109db94a | [
"MIT"
] | 14 | 2017-11-22T01:53:31.000Z | 2019-04-04T18:45:18.000Z | #include "stdafx.h"
#include "packet_decoder_mp3_common.h"
#include "mp3_utils.h"
unsigned packet_decoder_mp3_common::parseDecoderSetup( const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size )
{
if (p_owner == owner_MP3) return 3;
else if (p_owner == owner_MP2) return 2;
else if (p_owner == owner_MP1) return 1;
else if (p_owner == owner_MP4)
{
switch(p_param1)
{
case 0x6B:
return 3;
break;
case 0x69:
return 3;
break;
default:
return 0;
}
}
else if (p_owner == owner_matroska)
{
if (p_param2size==sizeof(matroska_setup))
{
const matroska_setup * setup = (const matroska_setup*) p_param2;
if (!strcmp(setup->codec_id,"A_MPEG/L3")) return 3;
else if (!strcmp(setup->codec_id,"A_MPEG/L2")) return 2;
else if (!strcmp(setup->codec_id,"A_MPEG/L1")) return 1;
else return 0;
}
else return 0;
}
else return 0;
}
unsigned packet_decoder_mp3_common::layer_from_frame(const void * frame, size_t size) {
using namespace mp3_utils;
TMPEGFrameInfo info;
if (!ParseMPEGFrameHeader(info, frame, size)) throw exception_io_data();
return info.m_layer;
} | 28.795455 | 135 | 0.632202 | jpbattaille |
f37d2b1eee108d835a8f06035f13ca1abbaf0d69 | 6,398 | cc | C++ | paddle/fluid/operators/distributed_ops/distributed_lookup_table_op.cc | Sand3r-/Paddle | 1217a521554d63caa1381b8716910d0268dfc22d | [
"Apache-2.0"
] | 2 | 2017-05-15T06:52:18.000Z | 2017-06-13T11:55:11.000Z | paddle/fluid/operators/distributed_ops/distributed_lookup_table_op.cc | Sand3r-/Paddle | 1217a521554d63caa1381b8716910d0268dfc22d | [
"Apache-2.0"
] | null | null | null | paddle/fluid/operators/distributed_ops/distributed_lookup_table_op.cc | Sand3r-/Paddle | 1217a521554d63caa1381b8716910d0268dfc22d | [
"Apache-2.0"
] | 4 | 2020-07-27T13:24:03.000Z | 2020-08-06T08:20:32.000Z | /* Copyright (c) 2016 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 <algorithm>
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/operators/distributed/parameter_prefetch.h"
#include "paddle/fluid/operators/math/math_function.h"
namespace paddle {
namespace operators {
class DistributedLookupTableOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInputs("Ids"),
"Input(Ids) of LookupTableOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("W"),
"Input(W) of LookupTableOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutputs("Outputs"),
"Output(Outs) of LookupTableOp should not be null.");
auto ids_dims = ctx->GetInputsDim("Ids");
auto table_dims = ctx->GetInputDim("W");
PADDLE_ENFORCE_EQ(table_dims.size(), 2,
"Only 2 dimensions of the 'Embedding' is supported.");
for (auto &ids_dim : ids_dims) {
PADDLE_ENFORCE_EQ(ids_dim.size(), 2,
"The dimension of the 'Ids' tensor must be 2.");
PADDLE_ENFORCE_EQ(ids_dim[1], 1,
"The last dimension of the 'Ids' tensor must be 1.");
}
auto lookup_tables =
ctx->Attrs().Get<std::vector<std::string>>("table_names");
auto height_sections =
ctx->Attrs().Get<std::vector<int64_t>>("height_sections");
auto endpoints = ctx->Attrs().Get<std::vector<std::string>>("endpoints");
PADDLE_ENFORCE(lookup_tables.size() == height_sections.size() &&
lookup_tables.size() == endpoints.size() &&
lookup_tables.size() != 0,
"Attrs lookup_tables/height_sections/endpoints must have "
"save size and can not be 0.");
auto outputs_dims = std::vector<framework::DDim>();
for (auto &ids_dim : ids_dims) {
outputs_dims.push_back(framework::make_ddim({ids_dim[0], table_dims[1]}));
}
ctx->SetOutputsDim("Outputs", outputs_dims);
ctx->ShareLoD("Ids", /*->*/ "Outputs");
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
return framework::OpKernelType(
framework::proto::VarType::Type(ctx.Attr<int>("dtype")),
ctx.GetPlace());
}
};
template <typename T>
class DistributedLookupTableKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext &context) const override {
auto ids_vars = context.MultiInputVar("Ids");
auto emb_vars = context.MultiOutput<framework::Tensor>("Embeddings");
auto id_names = context.InputNames("Ids");
auto embedding_name = context.InputNames("W").front();
auto out_names = context.OutputNames("Outputs");
auto lookup_tables = context.Attr<std::vector<std::string>>("table_names");
auto height_sections =
context.Attr<std::vector<int64_t>>("height_sections");
auto endpoints = context.Attr<std::vector<std::string>>("endpoints");
operators::distributed::prefetchs(
id_names, out_names, embedding_name, false, lookup_tables, endpoints,
height_sections, context, context.scope());
}
};
class DistributedLookupTableOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("Ids",
"(LoDTensor) Ids's type should be LoDTensor"
"THe ids to be looked up in W.")
.AsDuplicable();
AddInput("W",
"(Tensor) The input represents embedding tensors, "
"which is a learnable parameter.");
AddOutput("Outputs",
"(LoDTensor) The lookup results, which have the same type as W.")
.AsDuplicable();
AddAttr<std::vector<std::string>>(
"table_names",
"(string vector, such as emb_block0, emb_block1)"
"Server endpoints in the order of input variables for mapping")
.SetDefault({""});
AddAttr<std::vector<int64_t>>("height_sections",
"Height for each output SelectedRows.")
.SetDefault(std::vector<int64_t>({}));
AddAttr<std::vector<std::string>>(
"endpoints",
"(string vector, default 127.0.0.1:6164)"
"Server endpoints in the order of input variables for mapping")
.SetDefault({"127.0.0.1:6164"});
AddAttr<int>("trainer_id", "trainer id from 0 ~ worker_num.").SetDefault(0);
AddAttr<int64_t>("padding_idx",
"(int64, default -1) "
"If the value is -1, it makes no effect to lookup. "
"Otherwise the given value indicates padding the output "
"with zeros whenever lookup encounters it in Ids.")
.SetDefault(distributed::kNoPadding);
AddAttr<int>("dtype",
"(int, default 5 (FP32)) "
"Output data type")
.SetDefault(framework::proto::VarType::FP32);
AddComment(R"DOC(
Lookup Tablel Prefetch Operator.
This operator is used to perform lookup on parameter W,
then concatenated into a sparse tensor.
The type of Ids(Input) is SelectedRows, the rows of Ids contains
the ids to be looked up in W;
if the Id is not in the sparse table, this operator will return a
random value and set the value into the table for the next looking up.
)DOC");
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(distributed_lookup_table, ops::DistributedLookupTableOp,
ops::DistributedLookupTableOpMaker);
REGISTER_OP_CPU_KERNEL(distributed_lookup_table,
ops::DistributedLookupTableKernel<float>);
| 37.197674 | 80 | 0.659894 | Sand3r- |
f383c0a84332316ad240b8065e7dcb7684adea08 | 2,860 | cpp | C++ | clang/test/Cilk/opencilk-spawn.cpp | tkf/opencilk-project | 48265098754b785d1b06cb08d8e22477a003efcd | [
"MIT"
] | null | null | null | clang/test/Cilk/opencilk-spawn.cpp | tkf/opencilk-project | 48265098754b785d1b06cb08d8e22477a003efcd | [
"MIT"
] | null | null | null | clang/test/Cilk/opencilk-spawn.cpp | tkf/opencilk-project | 48265098754b785d1b06cb08d8e22477a003efcd | [
"MIT"
] | null | null | null | // RUN: %clang_cc1 -std=c++1z -fexceptions -fcxx-exceptions -fcilkplus -ftapir=none -triple x86_64-unknown-linux-gnu -emit-llvm %s -o - | FileCheck %s
int return_stuff(int i);
int return_spawn_test(int i){
return _Cilk_spawn return_stuff(i); // expected-warning{{no parallelism from a '_Cilk_spawn' in a return statement}}
}
// CHECK-LABEL: define {{(dso_local )?}}i32 @_Z17return_spawn_testi(i32 %i)
// CHECK: detach within %[[SYNCREG:.+]], label %[[DETACHED:.+]], label %[[CONTINUE:.+]]
// CHECK: [[DETACHED]]
// CHECK: %[[CALL:.+]] = call i32 @_Z12return_stuffi(i32
// CHECK-NEXT: store i32 %[[CALL]]
// CHECK-NEXT: reattach within %[[SYNCREG]], label %[[CONTINUE]]
// CHECK: [[CONTINUE]]
// CHECK-NEXT: sync within %[[SYNCREG]], label %[[SYNCCONT:.+]]
// CHECK: [[SYNCCONT]]
// CHECK-NEXT: call void @llvm.sync.unwind(token %[[SYNCREG]])
// CHECK-NEXT: %[[RETVALLOAD:.+]] = load i32
// CHECK: ret i32 %[[RETVALLOAD]]
class Bar {
int val[4] = {0,0,0,0};
public:
Bar();
~Bar();
Bar(const Bar &that);
Bar(Bar &&that);
Bar &operator=(Bar that);
friend void swap(Bar &left, Bar &right);
const int getValSpawn(int i) const { return _Cilk_spawn return_stuff(val[i]); } // expected-warning{{no parallelism from a '_Cilk_spawn' in a return statement}}
};
int foo(const Bar &b);
void spawn_infinite_loop() {
_Cilk_spawn {
label1: Bar().getValSpawn(0);
label2: foo(Bar());
goto label1;
};
}
// CHECK-LABEL: define {{(dso_local )?}}void @_Z19spawn_infinite_loopv()
// CHECK: detach within %[[SYNCREG:.+]], label %[[DETACHED:.+]], label %[[CONTINUE:.+]] unwind
// CHECK: [[DETACHED]]
// CHECK: %[[REFTMP:.+]] = alloca %class.Bar
// CHECK: %[[REFTMP2:.+]] = alloca %class.Bar
// CHECK: br label %[[LABEL1:.+]]
// CHECK: [[LABEL1]]
// CHECK: call void @_ZN3BarC1Ev(%class.Bar* %[[REFTMP]])
// CHECK: %[[CALL:.+]] = invoke i32 @_ZNK3Bar11getValSpawnEi(%class.Bar* %[[REFTMP]], i32 0)
// CHECK: call void @_ZN3BarD1Ev(%class.Bar* %[[REFTMP]])
// CHECK: call void @_ZN3BarC1Ev(%class.Bar* %[[REFTMP2]])
// CHECK: %[[CALL:.+]] = invoke i32 @_Z3fooRK3Bar(%class.Bar* {{.+}}%[[REFTMP2]])
// CHECK: call void @_ZN3BarD1Ev(%class.Bar* %[[REFTMP2]])
// CHECK-NEXT: br label %[[LABEL1]]
// CHECK: [[CONTINUE]]
// CHECK: ret void
// CHECK-LABEL: define linkonce_odr {{(dso_local )?}}i32 @_ZNK3Bar11getValSpawnEi(%class.Bar
// CHECK: detach within %[[SYNCREG:.+]], label %[[DETACHED:.+]], label %[[CONTINUE:.+]]
// CHECK: [[DETACHED]]
// CHECK: %[[CALL:.+]] = call i32 @_Z12return_stuffi(i32
// CHECK-NEXT: store i32 %[[CALL]]
// CHECK-NEXT: reattach within %[[SYNCREG]], label %[[CONTINUE]]
// CHECK: [[CONTINUE]]
// CHECK-NEXT: sync within %[[SYNCREG]], label %[[SYNCCONT:.+]]
// CHECK: [[SYNCCONT]]
// CHECK-NEXT: call void @llvm.sync.unwind(token %[[SYNCREG]])
// CHECK-NEXT: %[[RETVALLOAD:.+]] = load i32
// CHECK: ret i32 %[[RETVALLOAD]]
| 38.648649 | 162 | 0.63986 | tkf |
f3875ca502ce1a8c341c94f9a4a4e0791c319f74 | 3,127 | cpp | C++ | source/skyland/entity/projectile/missile.cpp | evanbowman/skyland | a62827a0dbcab705ba8ddf75cb74e975ceadec39 | [
"MIT"
] | 24 | 2021-07-03T02:27:25.000Z | 2022-03-29T05:21:32.000Z | source/skyland/entity/projectile/missile.cpp | evanbowman/skyland | a62827a0dbcab705ba8ddf75cb74e975ceadec39 | [
"MIT"
] | 3 | 2021-09-24T18:52:49.000Z | 2021-11-13T00:16:47.000Z | source/skyland/entity/projectile/missile.cpp | evanbowman/skyland | a62827a0dbcab705ba8ddf75cb74e975ceadec39 | [
"MIT"
] | 1 | 2021-07-11T08:05:59.000Z | 2021-07-11T08:05:59.000Z | #include "missile.hpp"
#include "skyland/entity/explosion/explosion.hpp"
#include "skyland/room.hpp"
#include "skyland/room_metatable.hpp"
#include "skyland/rooms/forcefield.hpp"
#include "skyland/rooms/missileSilo.hpp"
#include "skyland/skyland.hpp"
namespace skyland {
Missile::Missile(const Vec2<Float>& position,
const Vec2<Float>& target,
Island* source)
: Projectile({{10, 10}, {8, 8}}), target_x_(target.x), source_(source)
{
sprite_.set_position(position);
sprite_.set_size(Sprite::Size::w16_h32);
sprite_.set_texture_index(25);
sprite_.set_origin({8, 16});
}
void Missile::update(Platform& pfrm, App& app, Microseconds delta)
{
timer_ += delta;
// FIXME: Most entities in the game do not move far enough offscreen for the
// gba's sprite display wrapping to be a problem. But for this particular
// missile projectile, I threw in this little hack. Really, we should be
// creating a bounding box for the view and testing intersection with the
// missile entity. TODO. Unitl then...
if (sprite_.get_position().y < 450) {
sprite_.set_alpha(Sprite::Alpha::transparent);
} else {
sprite_.set_alpha(Sprite::Alpha::opaque);
}
switch (state_) {
case State::rising: {
if (timer_ > milliseconds(400)) {
timer_ = 0;
state_ = State::wait;
}
auto pos = sprite_.get_position();
pos.y -= delta * 0.0003f;
sprite_.set_position(pos);
break;
}
case State::wait:
if (timer_ > seconds(2)) {
timer_ = 0;
state_ = State::falling;
auto pos = sprite_.get_position();
pos.x = target_x_;
if (not pfrm.network_peer().is_connected() and
not app.tutorial_mode()) {
pos.x = rng::sample<5>(pos.x, rng::critical_state);
}
sprite_.set_position(pos);
sprite_.set_flip({false, true});
}
break;
case State::falling:
if (timer_ > milliseconds(700)) {
timer_ = 0;
kill();
}
auto pos = sprite_.get_position();
pos.y += delta * 0.00041f;
sprite_.set_position(pos);
break;
}
}
void Missile::on_collision(Platform& pfrm, App& app, Room& room)
{
if (source_ == room.parent() and room.metaclass() == missile_silo_mt) {
return;
}
if (source_ == room.parent() and room.metaclass() == forcefield_mt) {
return;
}
kill();
app.camera().shake(18);
big_explosion(pfrm, app, sprite_.get_position());
auto metac = room.metaclass();
if (str_cmp((*metac)->name(), "hull") == 0) {
room.apply_damage(pfrm, app, Missile::deals_damage * 0.9f);
} else {
room.apply_damage(pfrm, app, Missile::deals_damage);
}
}
void Missile::on_collision(Platform& pfrm, App& app, Entity& entity)
{
kill();
app.camera().shake(18);
big_explosion(pfrm, app, sprite_.get_position());
entity.apply_damage(Missile::deals_damage);
}
} // namespace skyland
| 25.842975 | 80 | 0.596098 | evanbowman |
f3876d43438b47cf5a242d7df5c8da3aa37fa4ad | 29,080 | cpp | C++ | Source/API/D3D12/SwapChainD3D12.cpp | KawBuma/Buma3D | 73b1c7a99c979492f072d4ead89f2d357d5e048a | [
"MIT"
] | 5 | 2020-11-25T05:05:13.000Z | 2022-02-09T09:35:21.000Z | Source/API/D3D12/SwapChainD3D12.cpp | KawBuma/Buma3D | 73b1c7a99c979492f072d4ead89f2d357d5e048a | [
"MIT"
] | 5 | 2020-11-11T09:52:59.000Z | 2021-12-15T13:27:37.000Z | Source/API/D3D12/SwapChainD3D12.cpp | KawBuma/Buma3D | 73b1c7a99c979492f072d4ead89f2d357d5e048a | [
"MIT"
] | null | null | null | #include "Buma3DPCH.h"
#include "SwapChainD3D12.h"
namespace buma3d
{
namespace /*anonymous*/
{
DXGI_USAGE GetNativeBufferFlags(SWAP_CHAIN_BUFFER_FLAGS _flags)
{
DXGI_USAGE result = 0;
if (_flags & SWAP_CHAIN_BUFFER_FLAG_SHADER_RESOURCE)
result |= DXGI_USAGE_SHADER_INPUT;
if (_flags & SWAP_CHAIN_BUFFER_FLAG_COLOR_ATTACHMENT)
result |= DXGI_USAGE_RENDER_TARGET_OUTPUT;
if (_flags & SWAP_CHAIN_BUFFER_FLAG_UNORDERED_ACCESS)
result |= DXGI_USAGE_UNORDERED_ACCESS;
// TODO: GetNativeBufferFlags
//if (_flags & SWAP_CHAIN_BUFFER_FLAG_ALLOW_SIMULTANEOUS_ACCESS)
// result |= ;
return result;
}
DXGI_ALPHA_MODE GetNativeAlphaMode(SWAP_CHAIN_ALPHA_MODE _mode)
{
switch (_mode)
{
case SWAP_CHAIN_ALPHA_MODE_DEFAULT : return DXGI_ALPHA_MODE_UNSPECIFIED;
case SWAP_CHAIN_ALPHA_MODE_IGNORE : return DXGI_ALPHA_MODE_IGNORE;
case SWAP_CHAIN_ALPHA_MODE_STRAIGHT : return DXGI_ALPHA_MODE_STRAIGHT;
case SWAP_CHAIN_ALPHA_MODE_PRE_MULTIPLIED : return DXGI_ALPHA_MODE_STRAIGHT;
default:
break;
}
return DXGI_ALPHA_MODE_UNSPECIFIED;
}
DEFINE_ENUM_FLAG_OPERATORS(DXGI_SWAP_CHAIN_FLAG);
DXGI_SWAP_CHAIN_FLAG GetNativeSwapChainFlags(SWAP_CHAIN_FLAGS _flags)
{
//DXGI_SWAP_CHAIN_FLAG result = (DXGI_SWAP_CHAIN_FLAG)0;
// 以下のフラグはデフォルトで使用します。
DXGI_SWAP_CHAIN_FLAG result = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH | DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT;
if (_flags & SWAP_CHAIN_FLAG_FULLSCREEN_EXCLUSIVE)
result |= DXGI_SWAP_CHAIN_FLAG_NONPREROTATED;
if (_flags & SWAP_CHAIN_FLAG_DISABLE_VERTICAL_SYNC)
result |= DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING;
if (_flags & SWAP_CHAIN_FLAG_PROTECT_CONTENTS)
result |= DXGI_SWAP_CHAIN_FLAG_HW_PROTECTED;
return result;
}
}
B3D_APIENTRY SwapChainD3D12::SwapChainD3D12()
: ref_count { 1 }
, name {}
, desc {}
, desc_data {}
, surface {}
, device {}
, present_queues {}
, present_queues_head {}
, swapchain_buffers {}
, current_buffer_index {}
, is_enabled_fullscreen {}
, swapchain {}
, prev_present_completion_event {}
, present_info {}
, fences_data {}
, is_acquired {}
{
}
B3D_APIENTRY SwapChainD3D12::~SwapChainD3D12()
{
Uninit();
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::Init(DeviceD3D12* _device, const SWAP_CHAIN_DESC& _desc)
{
(device = _device)->AddRef();
fences_data = B3DNewArgs(SWAPCHAIN_FENCES_DATA);
B3D_RET_IF_FAILED(CopyDesc(_desc));
B3D_RET_IF_FAILED(CheckValidity());
B3D_RET_IF_FAILED(CreateDXGISwapChain());
B3D_RET_IF_FAILED(PreparePresentInfo());
B3D_RET_IF_FAILED(GetSwapChainBuffers());
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::CopyDesc(const SWAP_CHAIN_DESC& _desc)
{
desc = _desc;
// _desc.present_queuesに全て同じキューが指定されている場合通常のスワップチェインとして扱う
if (_desc.num_present_queues > 1)
{
uint32_t same_queue_count = 0;
ICommandQueue* queue0 = _desc.present_queues[0];
for (uint32_t i = 0; i < _desc.num_present_queues; i++)
{
if (_desc.present_queues[i] == queue0)
same_queue_count++;
}
if (_desc.num_present_queues == same_queue_count)
{
desc.num_present_queues = 1;
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_WARNING, DEBUG_MESSAGE_CATEGORY_FLAG_INITIALIZATION
, "SWAP_CHAIN_DESC::present_queuesの全ての要素に同一のコマンドキューが指定されています。SWAP_CHAIN_DESC::num_present_queuesは1に設定されました。");
}
}
hlp::SafeRelease(surface);
(surface = _desc.surface->As<SurfaceD3D12>())->AddRef();
// コマンドキューをキャッシュ
if (_desc.present_queues == RCAST<ICommandQueue**>(present_queues_head)&&
_desc.buffer.count == (uint32_t)present_queues.size())
{
// Recreateの場合にGetDescから返された値が使用され、バックバッファ数に変更がない場合、何もしません。
}
else
{
util::DyArray<CommandQueueD3D12*> present_queues_tmp(_desc.buffer.count);
auto present_queues_tmp_data = present_queues_tmp.data();
for (uint32_t i = 0; i < _desc.buffer.count; i++)
{
// バックバッファの数だけキャッシュするので、num_present_queuesが1の場合インデックス0のキューを複数セットします。
present_queues_tmp_data[i] = _desc.present_queues[_desc.num_present_queues == 1 ? 0 : i]->As<CommandQueueD3D12>();
present_queues_tmp_data[i]->AddRef();
}
// Recreateの場合、以前のコマンドキューを開放
for (auto& i : present_queues)
hlp::SafeRelease(i);
present_queues.swap(present_queues_tmp);
present_queues_head = present_queues.data();
desc.present_queues = RCAST<ICommandQueue**>(present_queues_head);
}
// TEXTURE_FORMAT_DESC
auto&& tfd = desc.buffer.format_desc;
if (util::IsTypelessFormat(tfd.format))
{
auto&& fc = device->GetFormatCompatibilityChecker();
auto dd = B3DMakeUnique(DESC_DATA);
if (tfd.num_mutable_formats == 0)// default
{
dd->mutable_formats = fc.GetTypelessCompatibleFormats().at(tfd.format)->compatible_formats;
dd->is_shared_from_typeless_compatible_formats = true;
}
else
{
auto&& f = fc.CheckCompatibility(tfd);
if (f == nullptr)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_INITIALIZATION
, "TEXTURE_FORMAT_DESC::mutable_formatsに、TYPELESSフォーマットと互換性が無い、または現在のデバイスでは対応していないフォーマットが含まれています。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
auto&& mf = dd->mutable_formats = B3DMakeShared(util::DyArray<RESOURCE_FORMAT>);
dd->is_shared_from_typeless_compatible_formats = false;
mf->resize(tfd.num_mutable_formats);
util::MemCopyArray(mf->data(), tfd.mutable_formats, tfd.num_mutable_formats);
}
dd.swap(desc_data);
tfd.mutable_formats = desc_data->mutable_formats->data();
}
else
{
tfd.num_mutable_formats = 0;
tfd.mutable_formats = nullptr;
}
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::CheckValidity()
{
// プレゼント操作のサポートを確認
{
size_t index = 0;
auto adapter = device->GetDeviceAdapter();
for (auto& i : present_queues)
{
if (hlp::IsFailed(adapter->QueryPresentationSupport(i->GetDesc().type, surface)))
{
B3D_ADD_DEBUG_MSG2(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_INITIALIZATION
, __FUNCTION__": SWAP_CHAIN_DESC::present_queues[", index, "]はプレゼント操作をサポートしていません。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
index++;
}
}
// NOTE: D3D12では、FLIPスワップ効果が必須で、加えてFLIPスワップ効果を使用する場合DXGI_SWAP_CHAIN_DESC1::BufferCountに少なくとも2以上の値が必要です。
if (desc.buffer.count < 2)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_INITIALIZATION
, __FUNCTION__": SWAP_CHAIN_BUFFER_DESC::countは少なくとも2以上である必要があります。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
// 排他フルスクリーンのサポートを確認
if (desc.flags & SWAP_CHAIN_FLAG_FULLSCREEN_EXCLUSIVE &&
desc.flags & SWAP_CHAIN_FLAG_DISABLE_VERTICAL_SYNC)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_INITIALIZATION
, __FUNCTION__": 現在の内部APIでは、排他フルスクリーン機能を有効にする場合SWAP_CHAIN_FLAG_DISABLE_VERTICAL_SYNCが指定されない必要があります。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::CreateDXGISwapChain()
{
// Recreateの場合以前のバッファを開放し破棄
if (swapchain)
{
// スワップチェーンを破棄前にフルスクリーンを解除
auto hr = swapchain->SetFullscreenState(FALSE, nullptr);
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
is_enabled_fullscreen = false;
// NOTE: D3D12ではスワップチェーン作成時に渡すhWnd毎に1つ以上のスワップチェインを作成出来ずエラーとなるので予め破棄します。
auto count = swapchain->Release();
B3D_ASSERT(count == 0 && __FUNCTION__": swapchain->Release() != 0");
swapchain = nullptr;
}
desc.buffer.flags |= SWAP_CHAIN_BUFFER_FLAG_COPY_SRC | SWAP_CHAIN_BUFFER_FLAG_COPY_DST;
DXGI_SWAP_CHAIN_DESC1 scdesc{};
scdesc.Width = desc.buffer.width;
scdesc.Height = desc.buffer.height;
scdesc.Format = util::GetNativeFormat(desc.buffer.format_desc.format);
scdesc.Stereo = FALSE;
scdesc.SampleDesc.Count = 1;
scdesc.SampleDesc.Quality = 0;
scdesc.BufferUsage = GetNativeBufferFlags(desc.buffer.flags);
scdesc.BufferCount = desc.buffer.count;
scdesc.Scaling = DXGI_SCALING_NONE;
scdesc.SwapEffect = desc.flags & SWAP_CHAIN_FLAG_ALLOW_DISCARD_AFTER_PRESENT ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
scdesc.AlphaMode = GetNativeAlphaMode(desc.alpha_mode);
scdesc.Flags = GetNativeSwapChainFlags(desc.flags);
DXGI_SWAP_CHAIN_FULLSCREEN_DESC fsdesc{};
fsdesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
fsdesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
fsdesc.Windowed = desc.flags & SWAP_CHAIN_FLAG_FULLSCREEN_EXCLUSIVE ? FALSE : TRUE;
// TODO: ストアアプリの対応。
// スワップチェインの作成
auto hwnd = RCAST<HWND>(RCAST<const SURFACE_PLATFORM_DATA_WINDOWS*>(desc.surface->GetDesc().platform_data.data)->hwnd);
util::ComPtr<IDXGISwapChain1> sc;
auto&& f = device->GetDeviceFactory()->GetDXGIFactory();
auto hr = f->CreateSwapChainForHwnd(desc.present_queues[0]->As<CommandQueueD3D12>()->GetD3D12CommandQueue()
, hwnd
, &scdesc, &fsdesc
, nullptr/*出力先を制限しない。TODO: 共通化可能な機能を見つける。*/
, &sc);
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
// プリローテーション
if (!(desc.flags & SWAP_CHAIN_FLAG_FULLSCREEN_EXCLUSIVE))
{
// SetRotationを使用できるのは、ウィンドウモードで表示するフリップモデルスワップチェーンのバックバッファーを回転する場合のみです。
hr = sc->SetRotation(util::GetNativeRotationMode(desc.pre_roration));
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
}
// DXGI側が、hwndを所有するアプリケーションのメッセージキューを監視しないようにする
{
util::ComPtr<IDXGIFactory2> sc_parent;
hr = sc->GetParent(IID_PPV_ARGS(&sc_parent));
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
hr = sc_parent->MakeWindowAssociation(hwnd, DXGI_MWA_NO_WINDOW_CHANGES | DXGI_MWA_NO_ALT_ENTER | DXGI_MWA_NO_PRINT_SCREEN);
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
}
// IDXGISwapChain4を取得
hr = sc->QueryInterface(&swapchain);
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
// 色空間は作成時から固定する
hr = swapchain->SetColorSpace1(util::GetNativeColorSpace(desc.color_space));
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
// フレームレイテンシ
if (desc.flags & SWAP_CHAIN_FLAG_DISABLE_VERTICAL_SYNC)
{
hr = swapchain->SetMaximumFrameLatency(desc.buffer.count);
}
else
{
// 垂直同期が有効の場合、フレームレイテンシは1に設定します。
// 直近のPresent操作をIDXGISwapChain::Present1前に待機します。
hr = swapchain->SetMaximumFrameLatency(1);
}
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
prev_present_completion_event = swapchain->GetFrameLatencyWaitableObject();
// 排他フルスクリーン
if (desc.flags & SWAP_CHAIN_FLAG_FULLSCREEN_EXCLUSIVE)
{
hr = sc->SetFullscreenState(TRUE, nullptr/*出力先はデフォルト*/);
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
is_enabled_fullscreen = true;
}
// 複数ノードを用いたプレゼント操作
if (desc.num_present_queues > 1)
{
// ノードマスクを取得
util::DyArray<NodeMask> queue_node_masks(desc.buffer.count);
NodeMask* queue_node_masks_head = queue_node_masks.data();
for (uint32_t i = 0; i < desc.buffer.count; i++)
{
auto&& present_queue_index = std::min(i, desc.num_present_queues);
auto mask = present_queues_head[present_queue_index]->GetDesc().node_mask;
queue_node_masks_head[i] = mask;
}
// D3D12コマンドキューを取得
util::DyArray<ID3D12CommandQueue*> q12(desc.buffer.count);
auto q12_data = q12.data();
for (uint32_t i = 0; i < desc.buffer.count; i++)
{
auto&& present_queue_index = std::min(i, desc.num_present_queues);
q12_data[i] = present_queues_head[present_queue_index]->GetD3D12CommandQueue();
}
// NOTE: null以外のpCreationNodeMask配列でResizeBuffers1を使用して作成されたバッファーはすべてのノードに可視(visible)です。(visibleNodeMaskの(デバイスに含まれるノード数の範囲内の)ビットが全て有効)
hr = swapchain->ResizeBuffers1(scdesc.BufferCount
, scdesc.Width, scdesc.Height
, scdesc.Format
, scdesc.Flags
, queue_node_masks_head, RCAST<IUnknown**>(q12_data));
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
}
else if (is_enabled_fullscreen)
{
// NOTE: Full-Screen Issues: https://docs.microsoft.com/en-us/windows/win32/direct3darticles/dxgi-best-practices#full-screen-issues
hr = swapchain->ResizeBuffers(scdesc.BufferCount
, scdesc.Width, scdesc.Height
, scdesc.Format
, scdesc.Flags);
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
}
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::PreparePresentInfo()
{
if (desc.flags & SWAP_CHAIN_FLAG_DISABLE_VERTICAL_SYNC)
{
present_info.flags |= DXGI_PRESENT_ALLOW_TEARING;
present_info.sync_interval = 0; // 垂直同期を行わない。
present_info.params = {}; // 矩形は指定不可。
}
else
{
// DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT フラグが指定されたスワップチェインでは、垂直同期の待機が FrameLatencyWaitableObject にオフロードされます。
// DXGI_PRESENT_DO_NOT_WAIT フラグは上記の動作によって無効化されます。
present_info.sync_interval = 1;
if (present_info.dirty_rects.empty())
present_info.dirty_rects.resize(3); // default
present_info.params = {}; // 矩形を指定可能。
present_info.params.pDirtyRects = present_info.dirty_rects.data();
}
auto&& fd = *fences_data;
fd.dummy_fence_value = 0;
fd.fence_submit.num_fences = 1;
fd.fence_submit.fence_values = &fd.dummy_fence_value;
B3D_RET_IF_FAILED(fd.ResizeFences(device, desc.buffer.count));
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::GetSwapChainBuffers()
{
swapchain_buffers.resize(desc.buffer.count);
auto b3d_buffers = swapchain_buffers.data();
for (uint32_t i = 0; i < desc.buffer.count; i++)
{
util::ComPtr<ID3D12Resource> buffer;
auto hr = swapchain->GetBuffer(i, IID_PPV_ARGS(&buffer));
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
B3D_RET_IF_FAILED(TextureD3D12::CreateForSwapChain(this, buffer, &b3d_buffers[i]));
}
current_buffer_index = swapchain->GetCurrentBackBufferIndex();
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::ReleaseSwapChainBuffers()
{
//if (is_acquired)
//{
// B3D_ADD_DEBUG_MSG2(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_CLEANUP
// , __FUNCTION__": スワップチェインを再作成、または破棄する前に、AcquireNextBufferから取得したバックバッファのプレゼントを完了する必要があります。");
// return BMRESULT_FAILED_INVALID_CALL;
//}
size_t count = 0;
BMRESULT bmr = BMRESULT_SUCCEED;
for (auto& i : swapchain_buffers)
{
auto rc = i->GetRefCount();
if (rc != 1)
{
B3D_ADD_DEBUG_MSG2(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_CLEANUP
, __FUNCTION__": バックバッファ [", count, "]はまだ参照されています(カウント数: ", (rc - 1)
, ")。 スワップチェーンが破棄または再作成される前に、GetBuffers()から取得した全てのバッファは解放されている必要があります。");
bmr = BMRESULT_FAILED_INVALID_CALL;
}
count++;
}
if (hlp::IsSucceed(bmr))
{
for (auto& i : swapchain_buffers)
{
i->Release();
i = nullptr;
}
swapchain_buffers.clear();
}
return bmr;
}
void
B3D_APIENTRY SwapChainD3D12::Uninit()
{
if (prev_present_completion_event != NULL)
CloseHandle(prev_present_completion_event);
prev_present_completion_event = NULL;
ReleaseSwapChainBuffers();
hlp::SwapClear(swapchain_buffers);
present_info = {};
B3DSafeDelete(fences_data)
hlp::SafeRelease(swapchain);
is_enabled_fullscreen = {};
current_buffer_index = {};
desc_data.reset();
desc = {};
for (auto& i : present_queues)
hlp::SafeRelease(i);
present_queues_head = {};
hlp::SafeRelease(surface);
hlp::SafeRelease(device);
name.reset();
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::Create(DeviceD3D12* _device, const SWAP_CHAIN_DESC& _desc, SwapChainD3D12** _dst)
{
util::Ptr<SwapChainD3D12> ptr;
ptr.Attach(B3DCreateImplementationClass(SwapChainD3D12));
B3D_RET_IF_FAILED(ptr->Init(_device, _desc));
*_dst = ptr.Detach();
return BMRESULT_SUCCEED;
}
void
B3D_APIENTRY SwapChainD3D12::AddRef()
{
++ref_count;
B3D_REFCOUNT_DEBUG(ref_count);
}
uint32_t
B3D_APIENTRY SwapChainD3D12::Release()
{
B3D_REFCOUNT_DEBUG(ref_count - 1);
auto count = --ref_count;
if (count == 0)
B3DDestroyImplementationClass(this);
return count;
}
uint32_t
B3D_APIENTRY SwapChainD3D12::GetRefCount() const
{
return ref_count;
}
const char*
B3D_APIENTRY SwapChainD3D12::GetName() const
{
return name ? name->c_str() : nullptr;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::SetName(const char* _name)
{
if (!util::IsEnabledDebug(this))
return BMRESULT_FAILED;
if (swapchain)
{
auto hr = D3D_SET_OBJECT_NAME_W(swapchain, hlp::to_wstring(_name).c_str());
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
}
if (name && !_name)
name.reset();
else
name = B3DMakeUniqueArgs(util::NameableObjStr, _name);
return BMRESULT_SUCCEED;
}
IDevice*
B3D_APIENTRY SwapChainD3D12::GetDevice() const
{
return device;
}
const SWAP_CHAIN_DESC&
B3D_APIENTRY SwapChainD3D12::GetDesc() const
{
return desc;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::GetBuffer(uint32_t _buffer_idnex, ITexture** _dst)
{
if (_buffer_idnex >= desc.buffer.count)
return BMRESULT_FAILED_OUT_OF_RANGE;
(*_dst = swapchain_buffers.data()[_buffer_idnex])->AddRef();
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::AcquireNextBuffer(const SWAP_CHAIN_ACQUIRE_NEXT_BUFFER_INFO& _info, uint32_t* _buffer_index)
{
if (is_acquired)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_EXECUTION
, __FUNCTION__": 以前にAcquireNextBufferが呼び出されてから、プレゼント操作が実行されていません。 次のバックバッファインデックスを取得するにはISwapChain::Presentを呼び出す必要があります。");
return BMRESULT_FAILED_INVALID_CALL;
}
if (util::IsEnabledDebug(this))
{
if (!(_info.signal_fence || _info.signal_fence_to_cpu))
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_EXECUTION, __FUNCTION__": _info.signal_fenceとsignal_fence_to_cpuの両方がnullptrであってはなりません。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
if (_info.signal_fence && _info.signal_fence->GetDesc().type != FENCE_TYPE_BINARY_GPU_TO_GPU)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_EXECUTION, __FUNCTION__": _info.signal_fence はFENCE_TYPE_BINARY_GPU_TO_GPUである必要があります。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
if (_info.signal_fence_to_cpu && _info.signal_fence_to_cpu->GetDesc().type != FENCE_TYPE_BINARY_GPU_TO_CPU)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_EXECUTION, __FUNCTION__": _info.signal_fence_to_cpu はFENCE_TYPE_BINARY_GPU_TO_CPUである必要があります。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
}
/* NOTE: SwapPayloadについて
引数のシグナルフェンスにスワップチェインフェンスとその時のフェンス値を渡します。
引数のシグナルフェンスのペイロード(impl)をスワップして、自身(スワップチェインのフェンスペイロード)が元のペイロードであるかのように擬態します。この時元のペイロードは保持しておきます。
これにより、引数のシグナルフェンスへスワップチェインフェンスのシグナルをクローンすることが可能です。次に、Reset時またはWait時に元のペイロードに再び戻します。
D3D12フェンスの特徴として、全て値ベース(TIMELINE)であり、スワップチェインのフェンスペイロードを複数のフェンスにクローンしてもWaitまたはResetによる非シグナル化は実際には発生しません。
これにより、クローン時のシグナル値のみ保持しておけば、スワップチェインフェンスのシグナルを複数FenceD3D12に共有し、それぞれが任意のシグナル値で待機できます。
問題としては、スワップチェインのフェンスを保持したフェンスが存在したままISwapChainが開放されてしまった場合があります。
ペイロードはISwapChainが保有するため、ISwapChainが開放される前にペイロードを元に戻す必要があります。
適当に行うならば、ペイロードのスワップ毎に参照カウントを増加させれば良いが、AcquireNextBufferは毎フレーム呼び出される処理のため、このコストは回避すべきです。
内部でこれらを管理するコストが、アプリケーションによってペイロードを元に戻すコストと実装の複雑さを上回るため、新たに制約を追加する必要があります。 (SWAP_CHAIN_ACQUIRE_NEXT_BUFFER_INFO)
別の問題として、グラフィックスAPIをまたぐフェンスのエクスポート、インポートが困難になります。 これについても追加の調査が必要です。
*/
auto next_buffer_index = swapchain->GetCurrentBackBufferIndex();
// Presentでシグナルされたフェンス値を待機
fences_data->SetForWait(next_buffer_index);
auto&& present_complete_fence = fences_data->present_fences_head[next_buffer_index];
auto present_complete_fence_val = fences_data->present_fence_values_head[next_buffer_index];
BMRESULT result = present_complete_fence->Wait(present_complete_fence_val, _info.timeout_millisec);
B3D_RET_IF_FAILED(result);
// 引数のフェンスをプレゼント完了通知用フェンスのペイロードにすり替え
if (_info.signal_fence)
{
auto bmr = _info.signal_fence->As<FenceD3D12>()->SwapPayload(present_complete_fence, present_complete_fence_val);
B3D_RET_IF_FAILED(bmr);
}
if (_info.signal_fence_to_cpu)
{
auto bmr = _info.signal_fence_to_cpu->As<FenceD3D12>()->SwapPayload(present_complete_fence, present_complete_fence_val);
B3D_RET_IF_FAILED(bmr);
}
is_acquired = true;
current_buffer_index = next_buffer_index;
*_buffer_index = next_buffer_index;
return result;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::Present(const SWAP_CHAIN_PRESENT_INFO& _info)
{
if (!is_acquired)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_EXECUTION
, __FUNCTION__": AcquireNextBufferが呼び出されていません。 プレゼントを実行する前にISwapChain::AcquireNextBufferを呼び出す必要があります。");
return BMRESULT_FAILED_INVALID_CALL;
}
if (_info.wait_fence)
{
if (util::IsEnabledDebug(this))
{
if (_info.wait_fence->GetDesc().type != FENCE_TYPE_BINARY_GPU_TO_GPU)
{
B3D_ADD_DEBUG_MSG(DEBUG_MESSAGE_SEVERITY_ERROR, DEBUG_MESSAGE_CATEGORY_FLAG_EXECUTION, __FUNCTION__": _info.wait_fence はFENCE_TYPE_BINARY_GPU_TO_GPUである必要があります。");
return BMRESULT_FAILED_INVALID_PARAMETER;
}
}
// 引数のフェンス待機操作を送信
auto fence12 = _info.wait_fence->As<FenceD3D12>();
fence12->SubmitWait(present_queues_head[current_buffer_index]->GetD3D12CommandQueue(), nullptr);
}
// 矩形を設定
present_info.Set(_info.num_present_regions, _info.present_regions);
if (!(desc.flags & SWAP_CHAIN_FLAG_DISABLE_VERTICAL_SYNC))
{
// 前のPresent操作が完了するまで、今回のPresent操作をここで待機します。
// 初回フレームの場合に待機を避ける必要はありません: https://docs.microsoft.com/en-us/windows/win32/api/dxgi1_3/nf-dxgi1_3-idxgiswapchain2-getframelatencywaitableobject#:~:text=Note%20that%20this%20requirement%20includes%20the%20first%20frame%20the%20app%20renders%20with%20the%20swap%20chain.
auto wait_result = WaitForSingleObjectEx(prev_present_completion_event, INFINITE, FALSE);
if (wait_result != WAIT_OBJECT_0)
return BMRESULT_FAILED;
}
auto hr = swapchain->Present1(present_info.sync_interval, present_info.flags, &present_info.params);
auto bmr = HR_TRACE_IF_FAILED(hr);
// プレゼント完了通知用フェンスのシグナル操作を送信
fences_data->SetForSignal(current_buffer_index);
present_queues_head[current_buffer_index]->SubmitSignal(fences_data->fence_submit);
is_acquired = false;
return bmr;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::Recreate(const SWAP_CHAIN_DESC& _desc)
{
B3D_RET_IF_FAILED(ReleaseSwapChainBuffers());
current_buffer_index = 0;
if (prev_present_completion_event)
{
CloseHandle(prev_present_completion_event);
prev_present_completion_event = NULL;
}
B3D_RET_IF_FAILED(CopyDesc(_desc));
B3D_RET_IF_FAILED(CheckValidity());
B3D_RET_IF_FAILED(CreateDXGISwapChain());
B3D_RET_IF_FAILED(PreparePresentInfo());
B3D_RET_IF_FAILED(GetSwapChainBuffers());
return BMRESULT_SUCCEED;
}
BMRESULT
B3D_APIENTRY SwapChainD3D12::SetHDRMetaData(const SWAP_CHAIN_HDR_METADATA& _metadata)
{
DXGI_HDR_METADATA_HDR10 metadata = {
{ SCAST<UINT16>(50000.f * _metadata.primary_red.x) , SCAST<UINT16>(50000.f * _metadata.primary_red.y) } // RedPrimary[2]
, { SCAST<UINT16>(50000.f * _metadata.primary_green.x), SCAST<UINT16>(50000.f * _metadata.primary_green.y) } // GreenPrimary[2]
, { SCAST<UINT16>(50000.f * _metadata.primary_blue.x) , SCAST<UINT16>(50000.f * _metadata.primary_blue.y) } // BluePrimary[2]
, { SCAST<UINT16>(50000.f * _metadata.white_point.x) , SCAST<UINT16>(50000.f * _metadata.white_point.y) } // WhitePoint[2]
, SCAST<UINT> (10000.f * _metadata.max_luminance) // MaxMasteringLuminance
, SCAST<UINT> (10000.f * _metadata.min_luminance) // MinMasteringLuminance
, SCAST<UINT16>(_metadata.max_content_light_level) // MaxContentLightLevel
, SCAST<UINT16>(_metadata.max_frame_average_light_level) // MaxFrameAverageLightLevel
};
auto hr = swapchain->SetHDRMetaData(DXGI_HDR_METADATA_TYPE_HDR10, sizeof(metadata), &metadata);
B3D_RET_IF_FAILED(HR_TRACE_IF_FAILED(hr));
return BMRESULT_SUCCEED;
}
IDXGISwapChain4*
B3D_APIENTRY SwapChainD3D12::GetDXGISwapChain() const
{
return swapchain;
}
void SwapChainD3D12::PRESENT_INFO::Set(size_t _num_rects, const SCISSOR_RECT* _rects)
{
if (_num_rects > dirty_rects.size())
{
dirty_rects.resize(_num_rects);
params.pDirtyRects = dirty_rects.data();
}
params.DirtyRectsCount = (UINT)_num_rects;
for (uint32_t i = 0; i < _num_rects; i++)
{
util::ConvertNativeScissorRect(_rects[i], ¶ms.pDirtyRects[i]);
}
}
SwapChainD3D12::SWAPCHAIN_FENCES_DATA::~SWAPCHAIN_FENCES_DATA()
{
for (auto& i : present_fences)
hlp::SafeRelease(i);
present_fences = {};
present_fences_head = {};
fence_submit = {};
dummy_fence_value = {};
present_fence_values = {};
present_fence_values_head = {};
}
void SwapChainD3D12::SWAPCHAIN_FENCES_DATA::SetForSignal(uint32_t _current_buffer_index)
{
fence_submit.fences = RCAST<IFence**>(present_fences_head + _current_buffer_index);
fence_submit.fence_values = &(++present_fence_values_head[_current_buffer_index]);
}
void SwapChainD3D12::SWAPCHAIN_FENCES_DATA::SetForWait(uint32_t _current_buffer_index)
{
fence_submit.fences = RCAST<IFence**>(present_fences_head + _current_buffer_index);
fence_submit.fence_values = &present_fence_values_head[_current_buffer_index];
}
BMRESULT SwapChainD3D12::SWAPCHAIN_FENCES_DATA::ResizeFences(DeviceD3D12* _device, uint32_t _buffer_count)
{
auto prev_size = (uint32_t)present_fences.size();
if (_buffer_count > prev_size)
{
fence_results .resize(_buffer_count, BMRESULT_SUCCEED_NOT_READY);
present_fences .resize(_buffer_count);
present_fence_values .resize(_buffer_count);
fence_results_head = fence_results .data();
present_fences_head = present_fences .data();
present_fence_values_head = present_fence_values.data();
FENCE_DESC fdesc{ FENCE_TYPE_TIMELINE, 0 ,FENCE_FLAG_NONE };
for (size_t i = prev_size; i < _buffer_count; i++)
{
util::Ptr<FenceD3D12> f;
B3D_RET_IF_FAILED(FenceD3D12::Create(_device, fdesc, &f, /*for swapchain*/true));
present_fences_head[i] = f.Detach();
}
}
return BMRESULT_SUCCEED;
}
}// namespace buma3d
| 35.856967 | 277 | 0.676135 | KawBuma |
f38a25b2323e428bda5cdaf2c98cb9992ce9c881 | 9,396 | hpp | C++ | libstark-tests/lightCircLib/lightCircGate.hpp | ddsvetlov/libSTARK | 38aeda615864346dc1ff4c290e0d0d12ea324dfb | [
"MIT"
] | 399 | 2018-02-28T17:11:54.000Z | 2022-03-24T07:41:39.000Z | libstark-tests/lightCircLib/lightCircGate.hpp | ddsvetlov/libSTARK | 38aeda615864346dc1ff4c290e0d0d12ea324dfb | [
"MIT"
] | 18 | 2018-03-02T14:53:53.000Z | 2022-02-14T21:30:03.000Z | libstark-tests/lightCircLib/lightCircGate.hpp | ddsvetlov/libSTARK | 38aeda615864346dc1ff4c290e0d0d12ea324dfb | [
"MIT"
] | 90 | 2018-03-01T01:18:44.000Z | 2022-02-23T00:28:50.000Z | #ifndef LIGHT_CIRCUIT_GATES_HPP_
#define LIGHT_CIRCUIT_GATES_HPP_
#include "common/Infrastructure/Infrastructure.hpp"
#include "common/Utils/ErrorHandling.hpp"
#include <algebraLib/FieldElement.hpp>
#include <algebraLib/PolynomialDegree.hpp>
#include "common/langCommon/Sequence.hpp"
#include <vector>
#include <map>
#include <set>
#include <functional>
namespace libstark {
namespace LightCircLib {
/******************************************************************************/
/*************************** Various Gate Classes *****************************/
/******************************************************************************/
typedef enum {UNKNOWN, GENERIC, ADDITION, TIMES, DIVISION, EXPO, CONSTANT, CONSTANT_0, CONSTANT_1, NEG, VANISHING, PHI, PHI_INVERSE, INPUT_G, OUTPUT, NAND} GateType;
class lightCircGate {
protected:
std::vector<lightCircGate*> m_inputs; ///A list of input gates.
/**
* @brief Calculates the value of the gate from its inputs evaluations vector
* @param inputVals inputs evaluations
* @return value of gate
*/
virtual Algebra::FieldElement calculateEvaluation(const LazyVector<Algebra::FieldElement>& inputVals)const = 0;
virtual Algebra::PolynomialDegree calculateDegree(const std::vector<Algebra::PolynomialDegree>& inputDegrees)const = 0;
public:
typedef std::map<lightCircGate const*,Algebra::FieldElement> evaluationMap_t;
typedef std::map<lightCircGate const*,Algebra::PolynomialDegree> degreeCalcMap_t;
/****************************************/
/******* Constructors and Getters *******/
/****************************************/
/** Adds a new gate as input for this gate. */
void addInputGate(lightCircGate* newInput);
/** Adds a new gate as input for this gate. */
void setInputGate(lightCircGate* newInput);
/** Returns the list of gates that are the input of this gate */
const std::vector<lightCircGate*>& getInputsVector() const { return m_inputs; }
/** Returns the amount of gates that are the input of this gate */
uint64_t getInputsAmount() const { return m_inputs.size(); }
/*******************************/
/***** Abstract Functions ******/
/*******************************/
/** Returns a copy of a gate itself, not including its neighbors! */
virtual lightCircGate* shallowCopy() const = 0;
/** Returns the gate type */
virtual GateType getType() const = 0;
/**
* @brief Evaluates the gate according to its functionality and goal (this one is thread safe)
* @param evaluations a mapping between gate addresses and there evaluated values
* (if already evaluated). At evaluation request a gate will first check if it
* was already evaluated by checking if its address mapped to any value, if it does
* that value is returned, otherwise it will be calculated
* @return The value the gate outputs
*/
Algebra::FieldElement evaluateGate(lightCircGate::evaluationMap_t& evaluations)const;
Algebra::PolynomialDegree getDegree(lightCircGate::degreeCalcMap_t& degrees)const;
/*********************************************/
/***** Gate Profiling and Manipulations ******/
/*********************************************/
/** Class Destructor */
virtual ~lightCircGate(){};
};
/**************************************************/
/********** lightAdditionGate Class *************/
/**************************************************/
/**
* Addition gate. Its value equals the summation of its inputs.
*/
class lightAdditionGate : public lightCircGate{
protected:
/**
* @brief Calculates the value of the gate from its inputs evaluations vector
* @param inputVals inputs evaluations
* @return value of gate
*/
Algebra::FieldElement calculateEvaluation(const LazyVector<Algebra::FieldElement>& inputVals)const;
Algebra::PolynomialDegree calculateDegree(const std::vector<Algebra::PolynomialDegree>& inputDegrees)const;
public:
/** Returns a copy of a gate itself, not including its neighbors! */
lightCircGate* shallowCopy()const{ return new lightAdditionGate();}
/** Returns the gate type */
GateType getType() const{return ADDITION;}
};
/**************************************************/
/************ lightMultiplicationGate Class **************/
/**************************************************/
/**
* Times gate. Its value equals the multiplication of its inputs.
*/
class lightMultiplicationGate : public lightCircGate {
protected:
/**
* @brief Calculates the value of the gate from its inputs evaluations vector
* @param inputVals inputs evaluations
* @return value of gate
*/
Algebra::FieldElement calculateEvaluation(const LazyVector<Algebra::FieldElement>& inputVals)const;
Algebra::PolynomialDegree calculateDegree(const std::vector<Algebra::PolynomialDegree>& inputDegrees)const;
public:
/** Returns a copy of a gate itself, not including its neighbors! */
lightCircGate* shallowCopy()const {return new lightMultiplicationGate();}
/** Returns the gate type */
GateType getType() const{return TIMES;}
};
/**************************************************/
/************ lightExpoGate Class ***************/
/**************************************************/
/**
* Exponentiation gate. Its value equals its SINGLE input in some power (m_expo).
*/
class lightExpoGate : public lightCircGate {
private:
unsigned long m_expo; //The exponent of the gate
protected:
/**
* @brief Calculates the value of the gate from its inputs evaluations vector
* @param inputVals inputs evaluations
* @return value of gate
*/
Algebra::FieldElement calculateEvaluation(const LazyVector<Algebra::FieldElement>& inputVals)const;
Algebra::PolynomialDegree calculateDegree(const std::vector<Algebra::PolynomialDegree>& inputDegrees)const;
public:
/** Class Constructor */
lightExpoGate(const unsigned long expo) : m_expo(expo){};
/** Returns a copy of a gate itself, not including its neighbors! */
lightCircGate* shallowCopy()const{return new lightExpoGate(m_expo);}
/** Returns the exponent defined for this gate */
unsigned long getExpo() const { return m_expo; }
/** Returns the gate type */
GateType getType() const{return EXPO;}
};
/**************************************************/
/********* lightConstGate Class **************/
/**************************************************/
/**
* Constant gate. Has no input gates, and a constant value.
*/
class lightConstGate : public lightCircGate {
private:
Algebra::FieldElement m_value; ///The constant value
protected:
/**
* @brief Calculates the value of the gate from its inputs evaluations vector
* @param inputVals inputs evaluations
* @return value of gate
*/
Algebra::FieldElement calculateEvaluation(const LazyVector<Algebra::FieldElement>& inputVals)const{return m_value;}
Algebra::PolynomialDegree calculateDegree(const std::vector<Algebra::PolynomialDegree>& inputDegrees)const;
public:
/** Class Constructor */
lightConstGate(const Algebra::FieldElement& value):m_value(value){};
/** Returns a copy of a gate itself, not including its neighbors! */
lightCircGate* shallowCopy()const{return new lightConstGate(m_value);}
/** Returns the constant value of this gate. */
Algebra::FieldElement getValue() const { return m_value; }
/** Returns the gate type */
GateType getType() const{return CONSTANT;}
};
/**************************************************/
/********** lightInputGate Class ****************/
/**************************************************/
class lightInputGate : public lightCircGate {
private:
std::function<Algebra::FieldElement (const typename lightCircGate::evaluationMap_t& evaluations)> m_lazyValue;
protected:
/**
* @brief Calculates the value of the gate from its inputs evaluations vector
* @param inputVals inputs evaluations
* @return value of gate
*/
Algebra::FieldElement calculateEvaluation(const LazyVector<Algebra::FieldElement>& inputVals)const{
_COMMON_FATAL("No evaluation for light input gate");
}
Algebra::PolynomialDegree calculateDegree(const std::vector<Algebra::PolynomialDegree>& inputDegrees)const{
_COMMON_FATAL("No degree query for light input gate");
}
public:
/** Returns a copy of a gate itself, not including its neighbors! */
lightCircGate* shallowCopy()const{return new lightInputGate();}
/** Returns the gate type */
GateType getType() const{return INPUT_G;}
};
/**************************************************/
/********** lightOutGate Class ***************/
/**************************************************/
/**
* An output gate. Has a SINGLE input, with the same value as him.
*/
class lightOutGate : public lightCircGate {
protected:
/**
* @brief Calculates the value of the gate from its inputs evaluations vector
* @param inputVals inputs evaluations
* @return value of gate
*/
Algebra::FieldElement calculateEvaluation(const LazyVector<Algebra::FieldElement>& inputVals)const;
Algebra::PolynomialDegree calculateDegree(const std::vector<Algebra::PolynomialDegree>& inputDegrees)const;
public:
/** Returns a copy of a gate itself, not including its neighbors! */
lightCircGate* shallowCopy()const{return new lightOutGate();}
/** Returns the gate type */
GateType getType() const{return OUTPUT;}
};
} //namespace LightCircLib
} //namespace libstark
#endif //LIGHT_CIRCUIT_GATES_HPP_
| 34.417582 | 165 | 0.64421 | ddsvetlov |
f38a8492276ba557207ae4c80336eaba88c62678 | 33,635 | cpp | C++ | native/dll/DShowCapture-2/Crossbar.cpp | OpenSageTV/sagetv | 3a452dbab2d57990a2b9a5976d17b97d0c00cf79 | [
"Apache-2.0"
] | 3 | 2016-07-01T13:17:12.000Z | 2018-10-30T09:03:00.000Z | native/dll/DShowCapture-2/Crossbar.cpp | OpenSageTV/sagetv | 3a452dbab2d57990a2b9a5976d17b97d0c00cf79 | [
"Apache-2.0"
] | null | null | null | native/dll/DShowCapture-2/Crossbar.cpp | OpenSageTV/sagetv | 3a452dbab2d57990a2b9a5976d17b97d0c00cf79 | [
"Apache-2.0"
] | 2 | 2020-06-20T10:26:08.000Z | 2022-02-21T20:33:34.000Z | /*
* Copyright 2015 The SageTV 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 "stdafx.h"
#include "DShowCapture.h"
#include "../../include/guids.h"
#include "../../include/sage_DShowCaptureDevice.h"
#include "DShowUtilities.h"
#include "FilterGraphTools.h"
#include "../ax/TSSplitter2.0/iTSSplitter.h"
#include "Channel.h"
#include "QAMCtrl.h"
#include "TunerPlugin.h"
#include "uniapi.h"
extern FilterGraphTools graphTools;
TV_TYPE GetTVType( DShowCaptureInfo *pCapInfo );
char * TVTypeString( TV_TYPE BDATVType );
TV_TYPE String2TVType( char* szTvType );
HRESULT RetreveBDAChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, long *plId1, long* plId2, long* plId3 );
void BDAGraphConnectFilter( JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph );
void AddBDAVideoCaptureFilters(JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph, int devCaps );
void BDAGraphConnectDumpSink( JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph );
void BDAGraphDisconnectDumpSink( JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph );
void ClearUpDebugFileSource( JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph );
HRESULT TurnBDAChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, const char* cnum );
HRESULT ChannelSinalStrength( JNIEnv *env, DShowCaptureInfo* pCapInfo, long *strength, long* quality, bool* locked );
void BDAGraphConnectDebugRawDumpSink( JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph );
void BDAGraphSetDebugRawDumpFileName( JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph, char* Channel );
void BDAGraphSetDebugFileSource( JNIEnv* env, DShowCaptureInfo *pCapInfo, IGraphBuilder* pGraph );
HRESULT SetupBDAStreamOutFormat( JNIEnv *env, DShowCaptureInfo* pCapInfo, int streamType );
int LoadTuningEntryTable( JNIEnv* env, DShowCaptureInfo *pCapInfo );
void SetupDefaultDVBTuningTable( DShowCaptureInfo *pCapInfo );
void SetupDefaultATSCTuningTable( DShowCaptureInfo *pCapInfo );
int GetTuningProgramNum( DShowCaptureInfo* pCapInfo, long channel );
int GetTuningProgramNumByMajorMinor( DShowCaptureInfo* pCapInfo, int lMajor, int lMinor );
int GetTuningProgramNumByPhysicalMajorMinor( DShowCaptureInfo* pCapInfo, int lPhyscal, int lMajor, int lMinor );
bool IsFullTuningData( DShowCaptureInfo* pCapInfo, long channel );
void SetupCAM( JNIEnv* env, DShowCaptureInfo *pCapInfo );
int SetupSatelliteLNB( DShowCaptureInfo* pCapInfo, int bReload );
int LoadTuneTable( JNIEnv* env, DShowCaptureInfo *pCapInfo, TV_TYPE BDATVType );
int BDATypeNum( DWORD dwBDACap );
char* TVTypeString( TV_TYPE BDATVType );
extern "C" { int SwitchCamChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, int serviceId, int encryptionFlag ); }
#define INSTANCE_DATA_OF_PROPERTY_PTR(x) ( (PKSPROPERTY((x)) ) + 1 )
#define INSTANCE_DATA_OF_PROPERTY_SIZE(x) ( sizeof((x)) - sizeof(KSPROPERTY) )
HRESULT SetVboxFrequency( JNIEnv *env, DShowCaptureInfo* pCapInfo, ULONG ulFrequency );
unsigned long USA_AIR_FREQ[];
/*
* Class: sage_DShowCaptureDevice
* Method: switchToConnector0
* Signature: (JIILjava/lang/String;II)V
*/
JNIEXPORT void JNICALL Java_sage_DShowCaptureDevice_switchToConnector0
(JNIEnv *env, jobject jo, jlong capInfo, jint crossType, jint crossIndex, jstring tuningMode,
jint countryCode, jint videoFormatCode)
{
char szTuningMode[16];
if (!capInfo) return;
DShowCaptureInfo* pCapInfo = (DShowCaptureInfo*) capInfo;
pCapInfo->videoFormatCode = videoFormatCode;
const char* pTuningMode = env->GetStringUTFChars(tuningMode, NULL);
strncpy( szTuningMode, pTuningMode, sizeof(szTuningMode) );
env->ReleaseStringUTFChars(tuningMode, pTuningMode);
slog((env, "switchToConnector0 tuningMode:%s.\r\n", szTuningMode ));
if ( String2TVType( szTuningMode ) && BDATypeNum( pCapInfo->captureConfig ) > 0 ) //ZQ REMOVE ME
{
TV_TYPE newBDAType = String2TVType( szTuningMode );
if ( pCapInfo->dwBDAType != newBDAType && pCapInfo->dwBDAType > 0 )
{
int i, CaptureNum = pCapInfo->captureNum;
for ( i = 0; i < CaptureNum; i++ )
if ( pCapInfo->captures[i] && pCapInfo->captures[i]->dwBDAType == pCapInfo->dwBDAType )
break;
if ( i >= CaptureNum )
{
slog((env, "switchToConnector0 ERROR: Orignal BDA Capture :%d is not found\r\n", pCapInfo->dwBDAType ));
ASSERT( 0 );
return;
}
//save back
memcpy( pCapInfo->captures[i], pCapInfo, sizeof(DShowCaptureInfo) );
for ( i = 0; i < CaptureNum; i++ )
if ( pCapInfo->captures[i] && pCapInfo->captures[i]->dwBDAType == newBDAType )
break;
if ( i >= CaptureNum )
{
slog((env, "switchToConnector0 ERROR: BDA Capture :%s is not found\r\n", szTuningMode ));
ASSERT( 0 );
return;
}
memcpy( pCapInfo, pCapInfo->captures[i], sizeof(DShowCaptureInfo) );
setChannelDev( (CHANNEL_DATA*)pCapInfo->channel, (void*)pCapInfo );
slog((env, "switchToConnector0 BDA Capture :%s is switched.\r\n", szTuningMode ));
}
//strncpy( pCapInfo->tvType, szTuningMode, sizeof(pCapInfo->tvType) );
return;
}
if (!pCapInfo->pCrossbar)
return;
slog((env, "switchToConnector0 %d type:%d index:%d country:%d format:%d Mode:%s\r\n",
(int)capInfo, crossType, crossIndex, countryCode, videoFormatCode, szTuningMode ));
strncpy( pCapInfo->TuningMode, szTuningMode, sizeof(pCapInfo->TuningMode) );
// Setup the tuner first since it's upstream from the crossbar
if (crossType == 1 && pCapInfo->pTVTuner)
{
IAMTVTuner* pTunerProps = NULL;
HRESULT hr = pCapInfo->pTVTuner->QueryInterface(IID_IAMTVTuner, (void**)&pTunerProps);
if (SUCCEEDED(hr))
{
HRESULT ccHr = S_OK;
if (countryCode)
{
long currCountry = 0;
hr = pTunerProps->get_CountryCode(&currCountry);
if (FAILED(hr) || currCountry != countryCode)
{
hr = ccHr = pTunerProps->put_CountryCode(countryCode);
HTESTPRINT(hr);
}
hr = pTunerProps->put_TuningSpace(countryCode);
HTESTPRINT(hr);
}
AMTunerModeType currMode;
TunerInputType currTuneType;
HRESULT currModehr = pTunerProps->get_Mode(&currMode);
HTESTPRINT(currModehr);
HRESULT currTypehr = pTunerProps->get_InputType(0, &currTuneType);
HTESTPRINT(currTypehr);
AMTunerModeType newMode;
TunerInputType tuneType;
slog((env, "Tuning mode:%s; current tuning type:%d current tuning model:%d\r\n", pCapInfo->TuningMode, currTuneType, currMode ));
if (!strcmp(pCapInfo->TuningMode, "Air"))
{
newMode = AMTUNER_MODE_TV;
tuneType = TunerInputAntenna;
}
else if (!strcmp(pCapInfo->TuningMode, "FM Radio"))
{
newMode = AMTUNER_MODE_FM_RADIO;
tuneType = TunerInputAntenna;
}
else
if (!strcmp(pCapInfo->TuningMode, "HRC"))
{
newMode = AMTUNER_MODE_TV;
tuneType = (TunerInputType)2;
} else
{
newMode = AMTUNER_MODE_TV;
tuneType = TunerInputCable;
}
if (FAILED(currModehr) || newMode != currMode)
{
hr = pTunerProps->put_Mode(newMode);
HTESTPRINT(hr);
}
if (FAILED(currTypehr) || tuneType != currTuneType)
{
hr = pTunerProps->put_InputType(0, tuneType);
HTESTPRINT(hr);
}
long currConnInput = 0;
hr = pTunerProps->get_ConnectInput(&currConnInput);
if (FAILED(hr) || currConnInput != 0)
{
hr = pTunerProps->put_ConnectInput(0);
HTESTPRINT(hr);
}
//long tvFormat;
//hr = pTunerProps->get_TVFormat(&tvFormat);
//ZQ test
/*
{
IKsPropertySet *pKSProp=NULL;
KSPROPERTY_TUNER_STANDARD_S Standard;
hr = pCapInfo->pTVTuner->QueryInterface(IID_IKsPropertySet, (PVOID *)&pKSProp);
if ( SUCCEEDED(hr) )
{
memset(&Standard,0,sizeof(KSPROPERTY_TUNER_STANDARD_S));
Standard.Standard=videoFormatCode;
HRESULT hr=pKSProp->Set(PROPSETID_TUNER,
KSPROPERTY_TUNER_STANDARD,
INSTANCE_DATA_OF_PROPERTY_PTR(&Standard),
INSTANCE_DATA_OF_PROPERTY_SIZE(Standard),
&Standard, sizeof(Standard));
if(FAILED(hr))
{
slog(( env, "Failed set Video Format:%d on TVTuner hr=0x%x \r\n", videoFormatCode, hr ));
} else
{
slog(( env, "Force to set Video Format:%d on TVTuner hr=0x%x \r\n", videoFormatCode, hr ));
}
SAFE_RELEASE( pKSProp );
} else
{
slog(( env, "Failed to get IKsPropertySet to set Video Format:%d on TVTuner hr=0x%x \r\n", videoFormatCode, hr ));
}
}*/
SAFE_RELEASE(pTunerProps);
}
if (pCapInfo->pTVAudio)
{
IAMTVAudio* pAudioProps = NULL;
hr = pCapInfo->pTVAudio->QueryInterface(IID_IAMTVAudio, (void**)&pAudioProps);
if (SUCCEEDED(hr))
{
// For Vista+; there's the 'PRESET' flags which we want to use instead for setting the TV audio
// selections.
OSVERSIONINFOEX osInfo;
ZeroMemory(&osInfo, sizeof(OSVERSIONINFOEX));
osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
DWORD vistaPlus = 0;
if (GetVersionEx((LPOSVERSIONINFO)&osInfo))
{
if (osInfo.dwMajorVersion >= 6)
vistaPlus = 1;
}
if (vistaPlus)
hr = pAudioProps->put_TVAudioMode(AMTVAUDIO_PRESET_STEREO | AMTVAUDIO_PRESET_LANG_A);
else
hr = pAudioProps->put_TVAudioMode(AMTVAUDIO_MODE_STEREO | AMTVAUDIO_MODE_LANG_A);
HTESTPRINT(hr);
}
SAFE_RELEASE(pAudioProps);
}
}
// Setup the crossbar for the graph
IAMCrossbar *pXBar1 = NULL;
HRESULT hr = pCapInfo->pCrossbar->QueryInterface(IID_IAMCrossbar, (void**)&pXBar1);
HTESTPRINT(hr);
// Look through the pins on the crossbar and find the correct one for the type of
// connector we're routing. Also find the aligned audio pin and set that too.
int tempCrossIndex = crossIndex;
long i;
long videoOutNum = -1;
long audioOutNum = -1;
long numIn, numOut;
hr = pXBar1->get_PinCounts(&numOut, &numIn);
HTESTPRINT(hr);
long relatedPin, pinType;
for (i = 0; i < numOut; i++)
{
hr = pXBar1->get_CrossbarPinInfo(FALSE, i, &relatedPin, &pinType);
HTESTPRINT(hr);
if (pinType == PhysConn_Video_VideoDecoder)
videoOutNum = i;
else if (pinType == PhysConn_Audio_AudioDecoder)
audioOutNum = i;
}
for (i = 0; i < numIn; i++)
{
hr = pXBar1->get_CrossbarPinInfo(TRUE, i, &relatedPin, &pinType);
HTESTPRINT(hr);
if (pinType == crossType || (pinType == PhysConn_Video_YRYBY && crossType == 90)) // 90 is Component+SPDIF
{
if ((crossType != 1 && tempCrossIndex > 0) ||
tempCrossIndex == 1)
{
tempCrossIndex--;
continue;
}
// Route the video
long currRoute = -1;
// hr = pXBar1->get_IsRoutedTo(videoOutNum, &currRoute);
// if (FAILED(hr) || currRoute != i)
{
hr = pXBar1->Route(videoOutNum, i);
HTESTPRINT(hr);
}
if (audioOutNum >= 0)
{
if (crossType == PhysConn_Video_YRYBY || crossType == 90)
{
long relatedPinType = 0;
long junk = 0;
pXBar1->get_CrossbarPinInfo(TRUE, relatedPin, &junk, &relatedPinType);
if ((relatedPinType != PhysConn_Audio_SPDIFDigital && crossType == 90) ||
(relatedPinType == PhysConn_Audio_SPDIFDigital && crossType == PhysConn_Video_YRYBY))
{
// Find the other audio input pin that's related to the component input and use that
int j;
long otherRelatedPin = 0;
for (j = 0; j < numIn; j++)
{
if (j == relatedPin) continue;
otherRelatedPin = 0;
pXBar1->get_CrossbarPinInfo(TRUE, j, &otherRelatedPin, &junk);
if (otherRelatedPin == i)
{
slog(( env, "Crossbar swapping related audio pins on component video input old:%d new:%d\r\n", relatedPin, j));
relatedPin = j;
break;
}
}
}
}
// Route any related audio
// hr = pXBar1->get_IsRoutedTo(audioOutNum, &currRoute);
// if (FAILED(hr) || currRoute != relatedPin)
{
hr = pXBar1->Route(audioOutNum, relatedPin);
HTESTPRINT(hr);
}
}
slog(( env, "Crossbar route: video:%d, auido:%d\r\n", i, relatedPin ));
break;
}
}
SAFE_RELEASE(pXBar1);
if (audioOutNum == -1)
{
// It may have 2 crossbars, like ATI. Search for the second one.
hr = pCapInfo->pBuilder->FindInterface(&LOOK_UPSTREAM_ONLY, NULL, pCapInfo->pCrossbar,
IID_IAMCrossbar, (void**)&pXBar1);
if (SUCCEEDED(hr))
{
slog((env, "Found secondary audio crossbar, routing it\r\n"));
tempCrossIndex = crossIndex;
hr = pXBar1->get_PinCounts(&numOut, &numIn);
HTESTPRINT(hr);
for (i = 0; i < numOut; i++)
{
hr = pXBar1->get_CrossbarPinInfo(FALSE, i, &relatedPin, &pinType);
HTESTPRINT(hr);
if (pinType == PhysConn_Audio_AudioDecoder)
{
audioOutNum = i;
break;
}
}
for (i = 0; i < numIn && audioOutNum >= 0; i++)
{
hr = pXBar1->get_CrossbarPinInfo(TRUE, i, &relatedPin, &pinType);
HTESTPRINT(hr);
if (pinType == crossType)
{
if ((crossType != 1 && tempCrossIndex > 0) ||
tempCrossIndex == 1)
{
tempCrossIndex--;
continue;
}
// Route any related audio
hr = pXBar1->Route(audioOutNum, relatedPin);
HTESTPRINT(hr);
break;
}
}
SAFE_RELEASE(pXBar1);
}
}
IAMAnalogVideoDecoder *vidDec = NULL;
hr = pCapInfo->pVideoCaptureFilter->QueryInterface(IID_IAMAnalogVideoDecoder, (void**)&vidDec);
if (SUCCEEDED(hr))
{
/*if (FAILED(ccHr) && countryCode == 54)
{
tvFormat = AnalogVideo_PAL_N;
}*/
hr = vidDec->put_TVFormat(videoFormatCode);
HTESTPRINT(hr);
/*if (FAILED(hr) && tvFormat == AnalogVideo_PAL_N)
{
hr = vidDec->put_TVFormat(AnalogVideo_PAL_B);
} */
SAFE_RELEASE(vidDec);
}
slog((env, "DONE: switchToConnector0 %d type=%d index=%d\r\n", (int)capInfo, crossType, crossIndex));
}
/*
* Class: sage_DShowCaptureDevice
* Method: tuneToChannel0
* Signature: (JLjava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_sage_DShowCaptureDevice_tuneToChannel0
(JNIEnv *env, jobject jo, jlong capInfo, jstring jnum, jint streamType)
{
if (!capInfo) return;
DShowCaptureInfo* pCapInfo = (DShowCaptureInfo*) capInfo;
//ZQ
if (capMask(pCapInfo->captureConfig, sage_DShowCaptureDevice_BDA_VIDEO_CAPTURE_MASK ))
{
const char* cnum = env->GetStringUTFChars(jnum, NULL);
slog((env, "tuneToChannel0 digital tuner '%s-%d' num=%s (ver 3.1)\r\n", pCapInfo->videoCaptureFilterName,
pCapInfo->videoCaptureFilterNum, cnum ));
SetupBDAStreamOutFormat( env, pCapInfo, streamType );
HRESULT hr = TurnBDAChannel( env, pCapInfo, cnum );
env->ReleaseStringUTFChars(jnum, cnum);
}else //ZQ
{
if (!pCapInfo->pTVTuner) return;
const char* cnum = env->GetStringUTFChars(jnum, NULL);
int numericChannel = atoi(cnum);
long lFreq = 0, lTVFormat;
env->ReleaseStringUTFChars(jnum, cnum);
if ( numericChannel == 0 || numericChannel < 0 )
return ;
IAMTVTuner* pTunerProps = NULL;
HRESULT hr = pCapInfo->pTVTuner->QueryInterface(IID_IAMTVTuner, (void**)&pTunerProps);
slog((env, "tuneToChannel0 %d hr=0x%x num=%d\r\n", (int) capInfo, hr, numericChannel));
if (SUCCEEDED(hr))
{
pTunerProps->put_Channel(numericChannel, AMTUNER_SUBCHAN_DEFAULT, AMTUNER_SUBCHAN_DEFAULT);
HRESULT hr2 = pTunerProps->get_VideoFrequency( &lFreq );
hr2 = pTunerProps->get_TVFormat( &lTVFormat );
SAFE_RELEASE(pTunerProps);
pCapInfo->dwTuneState = 0x01;
}
slog((env, "DONE: tuneToChannel0 %d hr=0x%x freq:%d TVFormat:%d\r\n",
(int)capInfo, hr, lFreq, lTVFormat ));
}
}
/*
* Class: sage_DShowCaptureDevice
* Method: autoTuneChannel0
* Signature: (JLjava/lang/String;I)Z
*/
JNIEXPORT jboolean JNICALL Java_sage_DShowCaptureDevice_autoTuneChannel0
(JNIEnv *env, jobject jo, jlong capInfo, jstring jnum, jint streamType )
{
if (!capInfo) return JNI_FALSE;
DShowCaptureInfo* pCapInfo = (DShowCaptureInfo*)capInfo;
////ZQ audio leaking
//pCapInfo->pMC->Run();
//slog((env, ">>>> Start (capture:%s) \r\n"));
//ZQ
if (capMask(pCapInfo->captureConfig, sage_DShowCaptureDevice_BDA_VIDEO_CAPTURE_MASK ))
{
HRESULT hr;
const char* cnum = env->GetStringUTFChars(jnum, NULL);
if ( cnum == NULL || *cnum == 0x0 ) cnum = "0";
slog((env, "autotune0 digital tuner '%s-%d' num=%s (ver 3.1)\r\n", pCapInfo->videoCaptureFilterName,
pCapInfo->videoCaptureFilterNum, cnum ));
//setup output format
hr = SetupBDAStreamOutFormat( env, pCapInfo, streamType );
hr = TurnBDAChannel( env, pCapInfo, cnum );
env->ReleaseStringUTFChars(jnum, cnum);
int locked = SageCheckLocked( pCapInfo );
slog((env, "DONE: autotune0 hr=0x%x locked:%d\r\n", hr, locked ));
return hr == S_OK ? JNI_TRUE : JNI_FALSE;
}else //ZQ
{
if (!pCapInfo->pTVTuner) return JNI_FALSE;
const char* cnum = env->GetStringUTFChars(jnum, NULL);
int numericChannel = atoi(cnum);
env->ReleaseStringUTFChars(jnum, cnum);
IAMTVTuner* pTunerProps = NULL;
long tuneResult = 0;
if ( numericChannel == 0 || numericChannel < 0 )
return JNI_FALSE;
long lFreq = 0;
HRESULT hr = pCapInfo->pTVTuner->QueryInterface(IID_IAMTVTuner, (void**)&pTunerProps);
slog((env, "autotune0 analog tuner '%s-%d' hr=0x%x num=%d\r\n", pCapInfo->videoCaptureFilterName,
pCapInfo->videoCaptureFilterNum, hr, numericChannel));
if (SUCCEEDED(hr))
{
hr = pTunerProps->AutoTune(numericChannel, &tuneResult);
HRESULT hr2 = pTunerProps->get_VideoFrequency( &lFreq );
//if ( tuneResult )
// pTunerProps->StoreAutoTune();
pCapInfo->dwTuneState = 0x01;
//Fusion Card, FIX: after ATSC tune, fail to tune TV
if ( strstr( pCapInfo->videoCaptureFilterName, "Fusion" ) )
pTunerProps->put_Mode( AMTUNER_MODE_FM_RADIO );
pTunerProps->put_Mode( AMTUNER_MODE_TV ); //ZQ.
SAFE_RELEASE(pTunerProps);
}
slog((env, "DONE: autotune0 %d hr=0x%x result=%d freq:%d.\r\n",
(int)capInfo, hr, tuneResult, lFreq ));
return (SUCCEEDED(hr) && (tuneResult != 0));
}
return JNI_FALSE;
}
/*
* Class: sage_DShowCaptureDevice
* Method: getChannel0
* Signature: (JI)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_sage_DShowCaptureDevice_getChannel0
(JNIEnv *env, jobject jo, jlong capInfo, jint chanType)
{
DShowCaptureInfo* pCapInfo = (DShowCaptureInfo*) capInfo;
if (!pCapInfo )
return env->NewStringUTF("0");
if (capMask(pCapInfo->captureConfig, sage_DShowCaptureDevice_BDA_VIRTUAL_TUNER_MASK ))
return env->NewStringUTF("0");
//ZQ
if (capMask(pCapInfo->captureConfig, sage_DShowCaptureDevice_BDA_VIDEO_CAPTURE_MASK ))
{
HRESULT hr;
long lPhysicalChannel, lMinorChannel, lMajorChannel;
char rvBuf[32];
hr = RetreveBDAChannel( env, pCapInfo, &lPhysicalChannel, &lMinorChannel, &lMajorChannel );
if ( FAILED( hr ) )
return env->NewStringUTF("0");
if ( lMajorChannel > 0 && lMinorChannel > 0 )
{
SPRINTF(rvBuf, sizeof(rvBuf), "%d-%d-%d", lPhysicalChannel, lMajorChannel, lMinorChannel );
return env->NewStringUTF(rvBuf);
} else
if ( lMinorChannel > 0 )
{
SPRINTF(rvBuf, sizeof(rvBuf), "%d-%d", lPhysicalChannel, lMinorChannel );
return env->NewStringUTF(rvBuf);
} else
{
SPRINTF(rvBuf, sizeof(rvBuf), "%d", lPhysicalChannel );
return env->NewStringUTF(rvBuf);
}
} else
try
{
if ( !pCapInfo->pTVTuner )
return env->NewStringUTF("0");
CComPtr<IAMTVTuner> pTunerProps = NULL;
HRESULT hr = pCapInfo->pTVTuner->QueryInterface(IID_IAMTVTuner, (void**)&(pTunerProps.p));
if (FAILED(hr))
return env->NewStringUTF("0");
long currChan, videoSub, audioSub;
if (chanType == 0)
hr = pTunerProps->get_Channel(&currChan, &videoSub, &audioSub);
else if (chanType == 1)
hr = pTunerProps->ChannelMinMax(&videoSub, &currChan);
else // chanType == -1
hr = pTunerProps->ChannelMinMax(&currChan, &videoSub);
if (FAILED(hr))
return env->NewStringUTF("0");
else
{
char rvBuf[8];
SPRINTF(rvBuf, sizeof(rvBuf), "%d", (int)currChan);
return env->NewStringUTF(rvBuf);
}
}
catch (...)
{
slog((env, "NATIVE EXCEPTION getting current channel capInfo=%d chanType=%d\r\n",
(int) capInfo, (int) chanType));
return env->NewStringUTF("0");
}
//ZQ
}
/*
* Class: sage_DShowCaptureDevice
* Method: getSignalStrength0
* Signature: (J)I
*/
JNIEXPORT jint JNICALL Java_sage_DShowCaptureDevice_getSignalStrength0
(JNIEnv *env, jobject jo, jlong capInfo)
{
if (!capInfo) return JNI_FALSE;
DShowCaptureInfo* pCapInfo = (DShowCaptureInfo*) capInfo;
//ZQ
if (capMask(pCapInfo->captureConfig, sage_DShowCaptureDevice_BDA_VIDEO_CAPTURE_MASK ))
{
if (capMask(pCapInfo->captureConfig, sage_DShowCaptureDevice_BDA_VIRTUAL_TUNER_MASK ))
return 100;
long strength =0, quality = 0;
HRESULT hr = ChannelSinalStrength(env, pCapInfo, &strength, &quality, NULL);
slog((env, "DTV Signal Strength=%d %d\r\n", strength, quality));
return hr == S_OK ? quality: 0;
}
else
{
return 100;
}
}
HRESULT TuneStandardBDAChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, int physical, int major_ch, int minor_ch );
HRESULT TuneScanningBDAChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, long lMajorChannel, long lMinorChannel, long lProgram );
HRESULT TunePhysicalBDAChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, int physical_ch );
HRESULT ChangeATSCChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, long lPhysicalChannel,long lMajorChannel, long lMinorChannel );
HRESULT TurnBDAChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, const char* cnum )
{
//if ( pCapInfo->pBDANetworkProvider == NULL ) //ZQ. should call setup setupEncoder0 first! before call autoTuneChannel0. buf ???
if (capMask(pCapInfo->captureConfig, sage_DShowCaptureDevice_BDA_VIDEO_CAPTURE_MASK )) //ZQ. should call setup setupEncoder0 first! before call autoTuneChannel0. buf ???
{
if ( pCapInfo->pSink == NULL )
{
HRESULT hr = CoCreateInstance(CLSID_MPEG2Dump, NULL, CLSCTX_INPROC_SERVER,
IID_IBaseFilter, (void**)&(pCapInfo->pSink));
if ( FAILED( hr ) )
return hr;
hr = pCapInfo->pGraph->AddFilter(pCapInfo->pSink, L"MPEG Dump");
if ( FAILED( hr ) )
return hr;
}
AddBDAVideoCaptureFilters( env, pCapInfo, pCapInfo->pGraph, 0 );
BDAGraphSetDebugFileSource( env, pCapInfo, pCapInfo->pGraph );
BDAGraphConnectFilter( env, pCapInfo, pCapInfo->pGraph );
SetupCAM( env, pCapInfo );
SetupTunerPlugin( env, pCapInfo, GetTVType( pCapInfo ) );
BDAGraphConnectDebugRawDumpSink( env, pCapInfo, pCapInfo->pGraph );
BDAGraphConnectDumpSink( env, pCapInfo, pCapInfo->pGraph );
ClearUpDebugFileSource( env, pCapInfo, pCapInfo->pGraph );
TV_TYPE BDATVType = GetTVType( pCapInfo );
if ( BDATVType == DVBS ) SetupSatelliteLNB( pCapInfo, 0 );
//if user changed mode, reload tune table
if ( BDATVType == ATSC && !stricmp( pCapInfo->TuningMode, "Cable" ) && QAMTunerType( env, pCapInfo ) == 1 )
BDATVType = QAM;
if ( strcmp( getSourceType( (CHANNEL_DATA*)pCapInfo->channel ), TVTypeString( BDATVType ) ) )
{
LoadTuneTable( env, pCapInfo, BDATVType );
if ( BDATVType == DVBS ) SetupSatelliteLNB( pCapInfo, 1 );
}
}
BDAGraphSetDebugRawDumpFileName( env, pCapInfo, pCapInfo->pGraph, (char*)cnum );
//$NEW
int ret = tuneChannel( (CHANNEL_DATA*)pCapInfo->channel, cnum );
return ret>0 ? S_OK : E_FAIL;
//$NEW
}
HRESULT RetreveATSCChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, long *lPhysicalChannel, long* lMinorChannel, long* lMajorChannel )
{
HRESULT hr = S_OK;
CComPtr <ITuneRequest> pTuneRequest;
if (FAILED(hr = pCapInfo->pTuner->get_TuneRequest(&pTuneRequest)))
{
slog( ( env, "Cannot retreve ATSC tune request\r\n" ) );
return hr;
}
CComQIPtr <IATSCChannelTuneRequest> piATSCTuneRequest(pTuneRequest);
piATSCTuneRequest->get_MinorChannel(lMinorChannel);
piATSCTuneRequest->get_Channel(lMajorChannel);
CComPtr <ILocator> piLocator;
pTuneRequest->get_Locator( &piLocator );
CComQIPtr <IATSCLocator> piATSCLocator(piLocator);
piATSCLocator->get_PhysicalChannel( lPhysicalChannel );
return hr;
}
HRESULT RetreveDVBChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, long *plOid, long* plSid, long* plTsid )
{
HRESULT hr = S_OK;
CComPtr <ITuneRequest> pTuneRequest;
if (FAILED(hr = pCapInfo->pTuner->get_TuneRequest(&pTuneRequest)))
{
slog( ( env, "Cannot retreve DVB tune request\r\n" ) );
return hr;
}
CComQIPtr <IDVBTuneRequest> piDVBTuneRequest(pTuneRequest);
piDVBTuneRequest->get_ONID( plOid );
piDVBTuneRequest->get_SID( plSid );
piDVBTuneRequest->get_TSID( plTsid );
return hr;
}
HRESULT RetreveBDAChannel( JNIEnv *env, DShowCaptureInfo* pCapInfo, long *plId1, long* plId2, long* plId3 )
{
HRESULT hr = S_OK;
TV_TYPE TVType = GetTVType( pCapInfo );
if ( TVType == ATSC )
hr = RetreveATSCChannel( env, pCapInfo, plId1, plId2, plId3 );
else
if ( TVType == DVBT || TVType == DVBC || TVType == DVBS )
hr = RetreveDVBChannel( env, pCapInfo, plId1, plId2, plId3 );
else
{
slog( (env, "unknow network type %s for retreving\r\n", TVTypeString(TVType) ) );
hr = E_FAIL;
}
return hr;
}
HRESULT ChannelSinalStrength( JNIEnv *env, DShowCaptureInfo* pCapInfo, long *strength, long* quality, bool* locked )
{
HRESULT hr;
CComPtr <IBDA_Topology> bdaNetTop;
BOOL bBadNetTopFound = FALSE;
//Get IID_IBDA_Topology
if ( pCapInfo->pBDATuner == NULL && pCapInfo->pBDACapture == NULL )
return E_FAIL;
if ( pCapInfo->pBDATuner && !FAILED(hr = pCapInfo->pBDATuner->QueryInterface(&bdaNetTop)) )
{
bBadNetTopFound = TRUE;
}
if ( !bBadNetTopFound )
{
if ( pCapInfo->pBDACapture && !FAILED(hr = pCapInfo->pBDACapture->QueryInterface(&bdaNetTop)) )
bBadNetTopFound = TRUE;
}
if ( !bBadNetTopFound )
return E_FAIL;
ULONG NodeTypes;
ULONG NodeType[32];
ULONG Interfaces;
GUID Interface[32];
CComPtr <IUnknown> iNode;
long longVal = 0;
BYTE byteVal = 0;
if (strength)
*strength = 0;
if (quality)
*quality = 0;
if (locked)
*locked = 0;
if (FAILED(hr = bdaNetTop->GetNodeTypes(&NodeTypes, 32, NodeType)))
{
bdaNetTop.Release();
return hr;
}
for ( ULONG i=0 ; i<NodeTypes ; i++ )
{
hr = bdaNetTop->GetNodeInterfaces(NodeType[i], &Interfaces, 32, Interface);
if (hr == S_OK)
{
for ( ULONG j=0 ; j<Interfaces ; j++ )
{
if (Interface[j] == IID_IBDA_SignalStatistics)
{
hr = bdaNetTop->GetControlNode(0, 1, NodeType[i], &iNode);
if (hr == S_OK)
{
CComPtr <IBDA_SignalStatistics> pSigStats;
hr = iNode.QueryInterface(&pSigStats);
if (hr == S_OK)
{
if (strength && SUCCEEDED(hr = pSigStats->get_SignalStrength(&longVal)))
*strength = longVal;
if (quality && SUCCEEDED(hr = pSigStats->get_SignalQuality(&longVal)))
*quality = longVal;
if (locked && SUCCEEDED(hr = pSigStats->get_SignalLocked(&byteVal)))
*locked = byteVal != 0;
pSigStats.Release();
}
iNode.Release();
}
break;
}
}
}
}
bdaNetTop.Release();
return S_OK;
}
HRESULT SetupBDAStreamOutFormat( JNIEnv *env, DShowCaptureInfo* pCapInfo, int streamType )
{
ITSParser2 *pTSParser = NULL;
HRESULT hr = pCapInfo->pSplitter->QueryInterface(IID_ITSParser2, (void**)&pTSParser);
if ( FAILED( hr ) )
{
slog((env, "get TS Splitter interface failed\r\n" ));
} else
{
if ( streamType == 31 )
{
slog( (env,"Splitter Filter set output mpeg2 format \r\n") );
pTSParser->SetOutputFormat( 1 );
setOutputFormat( (CHANNEL_DATA*)pCapInfo->channel, 1 );
} else
if ( streamType == 32 )
{
slog( (env,"Splitter Filter output transport stream format \r\n") );
pTSParser->SetOutputFormat( 0 );
setOutputFormat( (CHANNEL_DATA*)pCapInfo->channel, 0 );
}
}
SAFE_RELEASE(pTSParser);
return hr;
}
//VBOX ATSC customize code for setting channel over 69
#define INSTANCEDATA_OF_PROPERTY_PTR(x) ((PKSPROPERTY((x))) + 1)
#define INSTANCEDATA_OF_PROPERTY_SIZE(x) (sizeof((x)) - sizeof(KSPROPERTY))
HRESULT SetVboxFrequency( JNIEnv *env, DShowCaptureInfo* pCapInfo, ULONG ulFrequency )
{
HRESULT hr;
DWORD dwSupported=0;
IEnumPins* pEnumPin;
IPin* pInputPin;
ULONG ulFetched;
PIN_INFO infoPin;
if ( pCapInfo->pBDATuner == NULL )
return E_FAIL;
if( ulFrequency == 0 )
{
slog( (env,"VOX tuner skips frequency 0\r\n") );
return S_OK;
}
IBaseFilter* pTunerDevice = pCapInfo->pBDATuner;
pTunerDevice->EnumPins(&pEnumPin);
if( SUCCEEDED( hr = pEnumPin->Reset() ) )
{
while((hr = pEnumPin->Next( 1, &pInputPin, &ulFetched )) == S_OK)
{
pInputPin->QueryPinInfo(&infoPin);
// Release AddRef'd filter, we don't need it
if( infoPin.pFilter != NULL )
infoPin.pFilter->Release();
if(infoPin.dir == PINDIR_INPUT)
break;
}
if(hr != S_OK)
{
slog( (env,"Vbox tuner input pin query failed \r\n") );
return hr;
}
}
else
{
slog( (env,"Vbox tuner reset failed \r\n") );
return E_FAIL;
}
IKsPropertySet *pKsPropertySet;
pInputPin->QueryInterface(&pKsPropertySet);
if (!pKsPropertySet)
{
slog( (env,"Vbox tuner input pin's QueryInterface failed \r\n") );
return E_FAIL;
}
KSPROPERTY_TUNER_MODE_CAPS_S ModeCaps;
KSPROPERTY_TUNER_FREQUENCY_S Frequency;
memset(&ModeCaps,0,sizeof(KSPROPERTY_TUNER_MODE_CAPS_S));
memset(&Frequency,0,sizeof(KSPROPERTY_TUNER_FREQUENCY_S));
ModeCaps.Mode = AMTUNER_MODE_TV;
// Check either the Property is supported or not by the Tuner drivers
hr = pKsPropertySet->QuerySupported(PROPSETID_TUNER,
KSPROPERTY_TUNER_MODE_CAPS,&dwSupported);
if(SUCCEEDED(hr) && dwSupported&KSPROPERTY_SUPPORT_GET)
{
DWORD cbBytes=0;
hr = pKsPropertySet->Get(PROPSETID_TUNER,KSPROPERTY_TUNER_MODE_CAPS,
INSTANCEDATA_OF_PROPERTY_PTR(&ModeCaps),
INSTANCEDATA_OF_PROPERTY_SIZE(ModeCaps),
&ModeCaps,
sizeof(ModeCaps),
&cbBytes);
}
else
{
SAFE_RELEASE(pKsPropertySet);
slog( (env,"Vbox tuner input pin's not support GET query \r\n") );
return E_FAIL;
}
Frequency.Frequency=ulFrequency; // in Hz
if(ModeCaps.Strategy==KS_TUNER_STRATEGY_DRIVER_TUNES)
Frequency.TuningFlags=KS_TUNER_TUNING_FINE;
else
Frequency.TuningFlags=KS_TUNER_TUNING_EXACT;
// Here the real magic starts
//if(ulFrequency>=ModeCaps.MinFrequency && ulFrequency<=ModeCaps.MaxFrequency)
{
hr = pKsPropertySet->Set(PROPSETID_TUNER,
KSPROPERTY_TUNER_FREQUENCY,
INSTANCEDATA_OF_PROPERTY_PTR(&Frequency),
INSTANCEDATA_OF_PROPERTY_SIZE(Frequency),
&Frequency,
sizeof(Frequency));
if(FAILED(hr))
{
slog( (env,"Vbox tuner input pin's set frequency %d failed hr=0x%x\r\n", Frequency.Frequency, hr ) );
SAFE_RELEASE(pKsPropertySet);
return E_FAIL;
}
}
// else
// {
//slog( (env,"Vbox tuning frequency %d is out of range (%d %d)\r\n",
// ulFrequency, ModeCaps.MinFrequency, ModeCaps.MaxFrequency ) );
// return E_FAIL;
// }
SAFE_RELEASE(pKsPropertySet);
slog( (env,"Vbox tuner tuning overider frequency %d successful. \r\n", ulFrequency) );
return S_OK;
}
unsigned long USA_AIR_FREQ[]=
{ /* 0 */ 0L, /* 1 */ 0L,
/* 2 */ 55250000L, /* 3 */ 61250000L, /* 4 */ 67250000L, /* 5 */ 77250000L,
/* 6 */ 83250000L, /* 7 */ 175250000L, /* 8 */ 181250000L, /* 9 */ 187250000L,
/* 10 */ 193250000L, /* 11 */ 199250000L, /* 12 */ 205250000L, /* 13 */ 211250000L,
/* 14 */ 471250000L, /* 15 */ 477250000L, /* 16 */ 483250000L, /* 17 */ 489250000L,
/* 18 */ 495250000L, /* 19 */ 501250000L, /* 20 */ 507250000L, /* 21 */ 513250000L,
/* 22 */ 519250000L, /* 23 */ 525250000L, /* 24 */ 531250000L, /* 25 */ 537250000L,
/* 26 */ 543250000L, /* 27 */ 549250000L, /* 28 */ 555250000L, /* 29 */ 561250000L,
/* 30 */ 567250000L, /* 31 */ 573250000L, /* 32 */ 579250000L, /* 33 */ 585250000L,
/* 34 */ 591250000L, /* 35 */ 597250000L, /* 36 */ 603250000L, /* 37 */ 609250000L,
/* 38 */ 615250000L, /* 39 */ 621250000L, /* 40 */ 627250000L, /* 41 */ 633250000L,
/* 42 */ 639250000L, /* 43 */ 645250000L, /* 44 */ 651250000L, /* 45 */ 657250000L,
/* 46 */ 663250000L, /* 47 */ 669250000L, /* 48 */ 675250000L, /* 49 */ 681250000L,
/* 50 */ 687250000L, /* 51 */ 693250000L, /* 52 */ 699250000L, /* 53 */ 705250000L,
/* 54 */ 711250000L, /* 55 */ 717250000L, /* 56 */ 723250000L, /* 57 */ 729250000L,
/* 58 */ 735250000L, /* 59 */ 741250000L, /* 60 */ 747250000L, /* 61 */ 753250000L,
/* 62 */ 759250000L, /* 63 */ 765250000L, /* 64 */ 771250000L, /* 65 */ 777250000L,
/* 66 */ 783250000L, /* 67 */ 789250000L, /* 68 */ 795250000L, /* 69 */ 801250000L,
/* 71 */ 807250000L, /* 71 */ 813250000L, /* 72 */ 819250000L, /* 73 */ 825250000L,
/* 74 */ 831250000L, /* 75 */ 837250000L, /* 76 */ 843250000L, /* 77 */ 849250000L,
/* 78 */ 855250000L, /* 79 */ 861250000L, /* 80 */ 867250000L, /* 81 */ 873250000L,
/* 82 */ 879250000L, /* 83 */ 885250000L };
| 33.137931 | 174 | 0.673138 | OpenSageTV |
f38bb5977380800b089c0fbada5e8059f606682e | 1,049 | cpp | C++ | code/leetcode/src/0025.Reverse-Nodes-in-k-Group.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | 1 | 2021-09-01T14:39:12.000Z | 2021-09-01T14:39:12.000Z | code/leetcode/src/0025.Reverse-Nodes-in-k-Group.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | code/leetcode/src/0025.Reverse-Nodes-in-k-Group.cpp | taseikyo/til | 8f703e69a49cbd9854062b102ba307c775d43a56 | [
"MIT"
] | null | null | null | /**
* @authors Lewis Tian (taseikyo@gmail.com)
* @date 2020-06-20 12:46:25
* @link github.com/taseikyo
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!head || !head->next) {
return head;
}
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* pre, * cur, *next;
pre = dummy;
cur = pre->next;
int n = length(head);
int times = n/k;
while (cur && cur->next && times--) {
for (int i = 1; i < k && cur->next; ++i) {
next = cur->next;
cur->next = next->next;
next->next = pre->next;
pre->next = next;
}
pre = cur;
cur = cur->next;
}
return dummy->next;
}
int length(ListNode* head) {
int ans = 0;
while(head){
head=head->next;
ans++;
}
return ans;
}
}; | 20.98 | 62 | 0.551001 | taseikyo |
f38c23aae6c334dab4632f2c183a401cd169e464 | 106 | cpp | C++ | qt_course/examples/01_trivial/01_hello_console/main.cpp | matus-chochlik/various | 2a9f5eddd964213f7d1e1ce8328e2e0b2a8e998b | [
"MIT"
] | 1 | 2020-10-25T12:28:50.000Z | 2020-10-25T12:28:50.000Z | qt_course/examples/01_trivial/01_hello_console/main.cpp | matus-chochlik/various | 2a9f5eddd964213f7d1e1ce8328e2e0b2a8e998b | [
"MIT"
] | null | null | null | qt_course/examples/01_trivial/01_hello_console/main.cpp | matus-chochlik/various | 2a9f5eddd964213f7d1e1ce8328e2e0b2a8e998b | [
"MIT"
] | null | null | null | #include <QTextStream>
int main(void)
{
QTextStream(stdout) << "Hello, console!" << endl;
return 0;
}
| 13.25 | 50 | 0.650943 | matus-chochlik |
f38c375991b9e958cc50caeee3781df7ce52eda5 | 1,951 | cpp | C++ | microNode/libraries/FRAM/fram.cpp | loranodes/arduino-core | 256eaf15e8a6bef67174fb162c54f1c73854c11c | [
"MIT"
] | null | null | null | microNode/libraries/FRAM/fram.cpp | loranodes/arduino-core | 256eaf15e8a6bef67174fb162c54f1c73854c11c | [
"MIT"
] | null | null | null | microNode/libraries/FRAM/fram.cpp | loranodes/arduino-core | 256eaf15e8a6bef67174fb162c54f1c73854c11c | [
"MIT"
] | null | null | null | #include "Arduino.h"
#include "fram.h"
#include "Wire.h"
void FRAMinit(){
Wire.begin();
}
void FRAMwrite(uint16_t address, uint8_t data){
Wire.beginTransmission(pageAddress(address));
Wire.write(wordAddress(address));
Wire.write(data);
Wire.endTransmission(true);
}
void FRAMwriteblock(uint16_t startAddress, uint8_t data[], uint16_t length){
Wire.beginTransmission(pageAddress(startAddress));
Wire.write(wordAddress(startAddress));
Wire.write(data, length);
Wire.endTransmission(true);
}
uint8_t FRAMread(uint16_t address){
Wire.beginTransmission(pageAddress(address));
Wire.write(wordAddress(address));
Wire.endTransmission(false);
Wire.requestFrom(pageAddress(address), 1);
uint8_t data = Wire.read();
return data;
}
void FRAMreadblock(uint16_t startAddress, uint8_t buffer[], uint16_t number){
Wire.beginTransmission(pageAddress(startAddress));
Wire.write(wordAddress(startAddress));
Wire.endTransmission(false);
Wire.requestFrom(pageAddress(startAddress), number);
for(int i = 0; i < number; i++){
buffer[i] = Wire.read();
}
}
void FRAMpack(uint16_t address, void* data, uint8_t len){
Wire.beginTransmission(pageAddress(address));
Wire.write(wordAddress(address));
Wire.write((uint8_t*)data, len);
Wire.endTransmission(true);
}
uint8_t FRAMunpack(uint16_t address, void* data, uint8_t len){
uint8_t rc;
uint8_t *p = (uint8_t*)data;
Wire.beginTransmission(pageAddress(address));
Wire.write(wordAddress(address));
Wire.endTransmission(false);
Wire.requestFrom(pageAddress(address), len);
for(rc = 0, p; rc < len ; rc++, p++){
*p = (uint8_t)Wire.read();
}
return rc;
}
uint8_t pageAddress(uint16_t dataAddress){
uint8_t page = dataAddress >> 8;
return (BASEADDR | page);
}
uint8_t wordAddress(uint16_t dataAddress){
return (dataAddress & 0b11111111);
}
| 20.978495 | 77 | 0.689903 | loranodes |
f38e1b5ecc76db040c7c1718ad0849b193e6d30b | 545 | cpp | C++ | Source/ActorRenderNode.cpp | obeezzy/Nima-Cpp | 12142f3db24760749d7db9301e7971398a342d99 | [
"MIT"
] | 7 | 2019-02-27T20:16:53.000Z | 2020-10-11T12:50:39.000Z | Source/ActorRenderNode.cpp | obeezzy/Nima-Cpp | 12142f3db24760749d7db9301e7971398a342d99 | [
"MIT"
] | 2 | 2019-09-09T17:09:25.000Z | 2020-03-11T08:47:43.000Z | Source/ActorRenderNode.cpp | obeezzy/Nima-Cpp | 12142f3db24760749d7db9301e7971398a342d99 | [
"MIT"
] | 9 | 2018-10-31T03:07:11.000Z | 2021-08-06T08:53:21.000Z | #include "ActorRenderNode.hpp"
#include "Actor.hpp"
using namespace nima;
ActorRenderNode::ActorRenderNode(ComponentType type) :
ActorNode(type),
m_DrawOrder(0)
{
}
void ActorRenderNode::copy(ActorRenderNode* node, Actor* resetActor)
{
Base::copy(node, resetActor);
m_DrawOrder = node->m_DrawOrder;
}
int ActorRenderNode::drawOrder() const
{
return m_DrawOrder;
}
void ActorRenderNode::drawOrder(int order)
{
if (m_DrawOrder != order)
{
m_DrawOrder = order;
if(m_Actor != nullptr)
{
m_Actor->markDrawOrderDirty();
}
}
} | 15.571429 | 68 | 0.724771 | obeezzy |
f38ea185dffc2d98f18b3a6f76d766369afc1af5 | 393 | cpp | C++ | GPM/MathTestProject/src/main.cpp | Hukunaa/GPM_Maths_Library | 7b2515a6a5fec5bfe213e1d503d4607c753e9cf3 | [
"MIT"
] | null | null | null | GPM/MathTestProject/src/main.cpp | Hukunaa/GPM_Maths_Library | 7b2515a6a5fec5bfe213e1d503d4607c753e9cf3 | [
"MIT"
] | null | null | null | GPM/MathTestProject/src/main.cpp | Hukunaa/GPM_Maths_Library | 7b2515a6a5fec5bfe213e1d503d4607c753e9cf3 | [
"MIT"
] | null | null | null | #include <iostream>
#include <GPM/GPM.h>
int main(const int p_argc, char** p_argv)
{
try
{
// Try stuff here
Matrix4F rot = GPM::Matrix4F::LookAt(GPM::Vector3F(0, 0, 0), GPM::Vector3F(0, 0, 3), GPM::Vector3F(0, 1, 0));
std::cout << rot;
}
catch (const std::exception & e)
{
std::cerr << "Exception thrown: " << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | 20.684211 | 111 | 0.615776 | Hukunaa |
f38ff80ab6fed64a9b95d6412c4a20cd785a495e | 379 | cpp | C++ | code/nastyhacks.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 8 | 2020-02-21T22:21:01.000Z | 2022-02-16T05:30:54.000Z | code/nastyhacks.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | null | null | null | code/nastyhacks.cpp | matthewReff/Kattis-Problems | 848628af630c990fb91bde6256a77afad6a3f5f6 | [
"MIT"
] | 3 | 2020-08-05T05:42:35.000Z | 2021-08-30T05:39:51.000Z | #include <iostream>
#include <string>
using namespace std;
int main(){
int dataSets = 0;
int rev, exp, adv;
cin >> dataSets;
for (int i = 0; i < dataSets; i++){
cin >> rev >> exp >> adv;
if (rev > (exp - adv)){
cout << "do not advertise\n";
}
else if (rev == (exp - adv)){
cout << "does not matter\n";
}
else{
cout << "advertise\n";
}
}
return 0;
} | 16.478261 | 36 | 0.540897 | matthewReff |
f3924603c429f148672ae1a81d3a5add96606e9f | 469 | cpp | C++ | @DOC by DIPTA/dipta007_final/Number Theory/sieve_bitwise.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 6 | 2018-10-15T18:45:05.000Z | 2022-03-29T04:30:10.000Z | @DOC by DIPTA/dipta007_final/Number Theory/sieve_bitwise.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | null | null | null | @DOC by DIPTA/dipta007_final/Number Theory/sieve_bitwise.cpp | dipta007/Competitive-Programming | 998d47f08984703c5b415b98365ddbc84ad289c4 | [
"MIT"
] | 4 | 2018-01-07T06:20:07.000Z | 2019-08-21T15:45:59.000Z | const int MX = 1e7
int status[(MX/32)+2];
void sieve()
{
int i, j, sqrtN;
sqrtN = int( sqrt( N ) );
for( i = 3; i <= sqrtN; i += 2 )
{
if( bitCheck(status[i>>5],i&31)==0)
{
for( j = i*i; j <= N; j += (i<<1) )
{
status[j>>5] = bitOn(status[j>>5],j & 31);
}
}
}
puts("2");
for(i=3; i<=N; i+=2)
if( Check(status[i>>5],i&31)==0)
printf("%d\n",i);
}
| 21.318182 | 58 | 0.364606 | dipta007 |
f3941ed6817872126382884d637645ecee3207a7 | 57,751 | cpp | C++ | ros/src/util/packages/kitti_pkg/kitti_player/src/kitti_player.cpp | filiperinaldi/Autoware | 9fae6cc7cb8253586578dbb62a2f075b52849e6e | [
"Apache-2.0"
] | 64 | 2018-11-19T02:34:05.000Z | 2021-12-27T06:19:48.000Z | ros/src/util/packages/kitti_pkg/kitti_player/src/kitti_player.cpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 18 | 2019-04-08T16:09:37.000Z | 2019-06-05T15:24:40.000Z | ros/src/util/packages/kitti_pkg/kitti_player/src/kitti_player.cpp | anhnv3991/autoware | d5b2ed9dc309193c8a2a7c77a2b6c88104c28328 | [
"Apache-2.0"
] | 34 | 2018-11-27T08:57:32.000Z | 2022-02-18T08:06:04.000Z | // redmine usage: This commit refs #388 @2h
// ###############################################################################################
// ###############################################################################################
// ###############################################################################################
/*
* KITTI_PLAYER v2.
*
* Augusto Luis Ballardini, ballardini@disco.unimib.it
*
* https://github.com/iralabdisco/kitti_player
*
* WARNING: this package is using some C++11
*
*/
// ###############################################################################################
// ###############################################################################################
// ###############################################################################################
#include <iostream>
#include <fstream>
#include <limits>
#include <sstream>
#include <string>
#include <ros/ros.h>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
//#include <boost/locale.hpp>
#include <boost/program_options.hpp>
#include <boost/progress.hpp>
#include <boost/tokenizer.hpp>
#include <boost/tokenizer.hpp>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <sensor_msgs/distortion_models.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/NavSatFix.h>
#include <sensor_msgs/PointCloud2.h>
#include <stereo_msgs/DisparityImage.h>
#include <tf/LinearMath/Transform.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <time.h>
/// EXTRA messages, not from KITTI
/// Inser here further detectors & features to be published
//#include <road_layout_estimation/msg_lines.h>
//#include <road_layout_estimation/msg_lineInfo.h>
using namespace std;
using namespace pcl;
using namespace ros;
using namespace tf;
namespace po = boost::program_options;
struct kitti_player_options
{
string path;
float frequency; // publisher frequency. 1 > Kitti default 10Hz
bool all_data; // publish everything
bool velodyne; // publish velodyne point clouds /as PCL
bool gps; // publish GPS sensor_msgs/NavSatFix message
bool imu; // publish IMU sensor_msgs/Imu Message message
bool grayscale; // publish
bool color; // publish
bool viewer; // enable CV viewer
bool timestamps; // use KITTI timestamps;
bool sendTransform; // publish velodyne TF IMU 3DOF orientation wrt fixed frame
bool stereoDisp; // use precalculated stereoDisparities
bool viewDisparities; // view use precalculated stereoDisparities
unsigned int startFrame; // start the replay at frame ...
/// Extra parameters
bool laneDetections; // send laneDetections;
};
/**
* @brief publish_velodyne
* @param pub The ROS publisher as reference
* @param infile file with data to publish
* @param header Header to use to publish the message
* @return 1 if file is correctly readed, 0 otherwise
*/
int publish_velodyne(ros::Publisher &pub, string infile, std_msgs::Header *header)
{
fstream input(infile.c_str(), ios::in | ios::binary);
if(!input.good())
{
ROS_ERROR_STREAM ( "Could not read file: " << infile );
return 0;
}
else
{
ROS_DEBUG_STREAM ("reading " << infile);
input.seekg(0, ios::beg);
pcl::PointCloud<pcl::PointXYZI>::Ptr points (new pcl::PointCloud<pcl::PointXYZI>);
int i;
for (i=0; input.good() && !input.eof(); i++) {
pcl::PointXYZI point;
input.read((char *) &point.x, 3*sizeof(float));
input.read((char *) &point.intensity, sizeof(float));
points->push_back(point);
}
input.close();
//workaround for the PCL headers... http://wiki.ros.org/hydro/Migration#PCL
sensor_msgs::PointCloud2 pc2;
pc2.header.frame_id= "velodyne"; //ros::this_node::getName();
pc2.header.stamp=header->stamp;
pc2.header.seq=header->seq;
points->header = pcl_conversions::toPCL(pc2.header);
pub.publish(points);
return 1;
}
}
/**
* @brief getCalibration
* @param dir_root
* @param camera_name
* @param K double K[9] - Calibration Matrix
* @param D double D[5] - Distortion Coefficients
* @param R double R[9] - Rectification Matrix
* @param P double P[12] - Projection Matrix Rectified (u,v,w) = P * R * (x,y,z,q)
* @return 1: file found, 0: file not found
*
* from: http://kitti.is.tue.mpg.de/kitti/devkit_raw_data.zip
* calib_cam_to_cam.txt: Camera-to-camera calibration
*
* - S_xx: 1x2 size of image xx before rectification
* - K_xx: 3x3 calibration matrix of camera xx before rectification
* - D_xx: 1x5 distortion vector of camera xx before rectification
* - R_xx: 3x3 rotation matrix of camera xx (extrinsic)
* - T_xx: 3x1 translation vector of camera xx (extrinsic)
* - S_rect_xx: 1x2 size of image xx after rectification
* - R_rect_xx: 3x3 rectifying rotation to make image planes co-planar
* - P_rect_xx: 3x4 projection matrix after rectification
*/
int getCalibration(string dir_root, string camera_name, double* K,std::vector<double> & D,double *R,double* P){
string calib_cam_to_cam=dir_root+"calib_cam_to_cam.txt";
ifstream file_c2c(calib_cam_to_cam.c_str());
if (!file_c2c.is_open())
return false;
ROS_INFO_STREAM("Reading camera" << camera_name << " calibration from " << calib_cam_to_cam);
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep{" "};
string line="";
char index=0;
tokenizer::iterator token_iterator;
while (getline(file_c2c,line))
{
// Parse string phase 1, tokenize it using Boost.
tokenizer tok(line,sep);
// Move the iterator at the beginning of the tokenize vector and check for K/D/R/P matrices.
token_iterator=tok.begin();
if (strcmp((*token_iterator).c_str(),((string)(string("K_")+camera_name+string(":"))).c_str())==0) //Calibration Matrix
{
index=0; //should be 9 at the end
ROS_DEBUG_STREAM("K_" << camera_name);
for (token_iterator++; token_iterator != tok.end(); token_iterator++)
{
//std::cout << *token_iterator << '\n';
K[index++]=boost::lexical_cast<double>(*token_iterator);
}
}
// EXPERIMENTAL: use with unrectified images
// token_iterator=tok.begin();
// if (strcmp((*token_iterator).c_str(),((string)(string("D_")+camera_name+string(":"))).c_str())==0) //Distortion Coefficients
// {
// index=0; //should be 5 at the end
// ROS_DEBUG_STREAM("D_" << camera_name);
// for (token_iterator++; token_iterator != tok.end(); token_iterator++)
// {
//// std::cout << *token_iterator << '\n';
// D[index++]=boost::lexical_cast<double>(*token_iterator);
// }
// }
token_iterator=tok.begin();
if (strcmp((*token_iterator).c_str(),((string)(string("R_")+camera_name+string(":"))).c_str())==0) //Rectification Matrix
{
index=0; //should be 12 at the end
ROS_DEBUG_STREAM("R_" << camera_name);
for (token_iterator++; token_iterator != tok.end(); token_iterator++)
{
//std::cout << *token_iterator << '\n';
R[index++]=boost::lexical_cast<double>(*token_iterator);
}
}
token_iterator=tok.begin();
if (strcmp((*token_iterator).c_str(),((string)(string("P_rect_")+camera_name+string(":"))).c_str())==0) //Projection Matrix Rectified
{
index=0; //should be 12 at the end
ROS_DEBUG_STREAM("P_rect_" << camera_name);
for (token_iterator++; token_iterator != tok.end(); token_iterator++)
{
//std::cout << *token_iterator << '\n';
P[index++]=boost::lexical_cast<double>(*token_iterator);
}
}
}
ROS_INFO_STREAM("... ok");
return true;
}
int getGPS(string filename, sensor_msgs::NavSatFix *ros_msgGpsFix, std_msgs::Header *header)
{
ifstream file_oxts(filename.c_str());
if (!file_oxts.is_open()){
ROS_ERROR_STREAM("Fail to open " << filename);
return 0;
}
ROS_DEBUG_STREAM("Reading GPS data from oxts file: " << filename );
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep{" "};
string line="";
getline(file_oxts,line);
tokenizer tok(line,sep);
vector<string> s(tok.begin(), tok.end());
ros_msgGpsFix->header.frame_id = ros::this_node::getName();
ros_msgGpsFix->header.stamp = header->stamp;
ros_msgGpsFix->latitude = boost::lexical_cast<double>(s[0]);
ros_msgGpsFix->longitude = boost::lexical_cast<double>(s[1]);
ros_msgGpsFix->altitude = boost::lexical_cast<double>(s[2]);
ros_msgGpsFix->position_covariance_type = sensor_msgs::NavSatFix::COVARIANCE_TYPE_APPROXIMATED;
for (int i=0;i<9;i++)
ros_msgGpsFix->position_covariance[i] = 0.0f;
ros_msgGpsFix->position_covariance[0] = boost::lexical_cast<double>(s[23]);
ros_msgGpsFix->position_covariance[4] = boost::lexical_cast<double>(s[23]);
ros_msgGpsFix->position_covariance[8] = boost::lexical_cast<double>(s[23]);
ros_msgGpsFix->status.service = sensor_msgs::NavSatStatus::SERVICE_GPS;
ros_msgGpsFix->status.status = sensor_msgs::NavSatStatus::STATUS_GBAS_FIX;
return 1;
}
int getIMU(string filename, sensor_msgs::Imu *ros_msgImu, std_msgs::Header *header)
{
ifstream file_oxts(filename.c_str());
if (!file_oxts.is_open())
{
ROS_ERROR_STREAM("Fail to open " << filename);
return 0;
}
ROS_DEBUG_STREAM("Reading IMU data from oxts file: " << filename );
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep{" "};
string line="";
getline(file_oxts,line);
tokenizer tok(line,sep);
vector<string> s(tok.begin(), tok.end());
ros_msgImu->header.frame_id = ros::this_node::getName();
ros_msgImu->header.stamp = header->stamp;
// - ax: acceleration in x, i.e. in direction of vehicle front (m/s^2)
// - ay: acceleration in y, i.e. in direction of vehicle left (m/s^2)
// - az: acceleration in z, i.e. in direction of vehicle top (m/s^2)
ros_msgImu->linear_acceleration.x = boost::lexical_cast<double>(s[11]);
ros_msgImu->linear_acceleration.y = boost::lexical_cast<double>(s[12]);
ros_msgImu->linear_acceleration.z = boost::lexical_cast<double>(s[13]);
// - vf: forward velocity, i.e. parallel to earth-surface (m/s)
// - vl: leftward velocity, i.e. parallel to earth-surface (m/s)
// - vu: upward velocity, i.e. perpendicular to earth-surface (m/s)
ros_msgImu->angular_velocity.x = boost::lexical_cast<double>(s[8]);
ros_msgImu->angular_velocity.y = boost::lexical_cast<double>(s[9]);
ros_msgImu->angular_velocity.z = boost::lexical_cast<double>(s[10]);
// - roll: roll angle (rad), 0 = level, positive = left side up (-pi..pi)
// - pitch: pitch angle (rad), 0 = level, positive = front down (-pi/2..pi/2)
// - yaw: heading (rad), 0 = east, positive = counter clockwise (-pi..pi)
tf::Quaternion q=tf::createQuaternionFromRPY( boost::lexical_cast<double>(s[3]),
boost::lexical_cast<double>(s[4]),
boost::lexical_cast<double>(s[5])
);
ros_msgImu->orientation.x = q.getX();
ros_msgImu->orientation.y = q.getY();
ros_msgImu->orientation.z = q.getZ();
ros_msgImu->orientation.w = q.getW();
return 1;
}
/**
* @brief parseTime
* @param timestamp in Epoch
* @return std_msgs::Header with input timpestamp converted from file input
*
* Epoch time conversion
* http://www.epochconverter.com/programming/functions-c.php
*/
std_msgs::Header parseTime(string timestamp)
{
std_msgs::Header header;
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
// example: 2011-09-26 13:21:35.134391552
// 01234567891111111111222222222
// 0123456789012345678
struct tm t = {0}; // Initalize to all 0's
t.tm_year = boost::lexical_cast<int>(timestamp.substr(0,4)) - 1900;
t.tm_mon = boost::lexical_cast<int>(timestamp.substr(5,2)) - 1;
t.tm_mday = boost::lexical_cast<int>(timestamp.substr(8,2));
t.tm_hour = boost::lexical_cast<int>(timestamp.substr(11,2));
t.tm_min = boost::lexical_cast<int>(timestamp.substr(14,2));
t.tm_sec = boost::lexical_cast<int>(timestamp.substr(17,2));
t.tm_isdst = -1;
time_t timeSinceEpoch = mktime(&t);
header.stamp.sec = timeSinceEpoch;
header.stamp.nsec = boost::lexical_cast<int>(timestamp.substr(20,8));
return header;
}
/**
* @brief getLaneDetection
* @param infile
* @param msg_lines
* @return
*/
/*
int getLaneDetection(string infile, road_layout_estimation::msg_lines *msg_lines)
{
ROS_DEBUG_STREAM("Reading lane detections from " << infile);
ifstream detection_file(infile);
if (!detection_file.is_open())
return false;
msg_lines->number_of_lines = 0;
msg_lines->goodLines = 0;
msg_lines->width = 0;
msg_lines->oneway = 0;
msg_lines->naive_width = 0;
msg_lines->lines.clear();
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep{"\t"}; // TAB
string line="";
char index = 0;
double last_right_detection = std::numeric_limits<double>::min(); //uses *ONLY* the valid lines
double last_left_detection = std::numeric_limits<double>::max(); //uses *ONLY* the valid lines
double naive_last_right_detection = std::numeric_limits<double>::min(); //uses all values, even if the line is not valid
double naive_last_left_detection = std::numeric_limits<double>::max(); //uses all values, even if the line is not valid
while (getline(detection_file,line))
{
// Parse string phase 1, tokenize it using Boost.
tokenizer tok(line,sep);
if (index==0)
{
vector<string> s(tok.begin(), tok.end());
msg_lines->goodLines = boost::lexical_cast<int>(s[0]);
index++;
}
else
{
road_layout_estimation::msg_lineInfo line;
vector<string> s(tok.begin(), tok.end());
if (s.size()!=3)
{
ROS_WARN_STREAM("Unexpected file format, can't read");
return false;
}
line.isValid = boost::lexical_cast<bool> (s[0]);
line.counter = boost::lexical_cast<int> (s[1]);
line.offset = boost::lexical_cast<float> (s[2]);
msg_lines->lines.push_back(line);
if (line.isValid)
{
if (line.offset > last_right_detection)
last_right_detection = line.offset;
if (line.offset < last_left_detection)
last_left_detection = line.offset;
}
if (line.offset > naive_last_right_detection)
naive_last_right_detection = line.offset;
if (line.offset < naive_last_left_detection)
naive_last_left_detection = line.offset;
index++;
}
}
// Number of lines in the file, 1 line 'in the picture' is one row in the file, minus
// one, the first, that is the number of "good" (current tracked in good state) lines.
msg_lines->number_of_lines = index -1 ;
if (msg_lines->goodLines > 1)
msg_lines->width = abs(last_left_detection) + abs(last_right_detection);
else
msg_lines->width = abs(last_left_detection);
msg_lines->naive_width = abs(naive_last_left_detection) + abs(naive_last_right_detection);
msg_lines->way_id = 0; ///WARNING this value is not used yet.
if (msg_lines->width == std::numeric_limits<double>::max())
msg_lines->width = 0.0f;
if (msg_lines->naive_width == std::numeric_limits<double>::max())
msg_lines->naive_width = 0.0f;
ROS_DEBUG_STREAM("Number of LANEs: " << msg_lines->number_of_lines << "\tNumber of good LINEs "<<msg_lines->goodLines);
ROS_DEBUG_STREAM("... getLaneDetection ok");
return true;
}
*/
/**
* @brief main Kitti_player, a player for KITTI raw datasets
* @param argc
* @param argv
* @return 0 and ros::shutdown at the end of the dataset, -1 if errors
*
* Allowed options:
* -h [ --help ] help message
* -d [ --directory ] arg *required* - path to the kitti dataset Directory
* -f [ --frequency ] arg (=1) set replay Frequency
* -a [ --all ] [=arg(=1)] (=0) replay All data
* -v [ --velodyne ] [=arg(=1)] (=0) replay Velodyne data
* -g [ --gps ] [=arg(=1)] (=0) replay Gps data
* -i [ --imu ] [=arg(=1)] (=0) replay Imu data
* -G [ --grayscale ] [=arg(=1)] (=0) replay Stereo Grayscale images
* -C [ --color ] [=arg(=1)] (=0) replay Stereo Color images
* -V [ --viewer ] [=arg(=1)] (=0) enable image viewer
* -T [ --timestamps ] [=arg(=1)] (=0) use KITTI timestamps
* -s [ --stereoDisp ] [=arg(=1)] (=0) use pre-calculated disparities
* -D [ --viewDisp ] [=arg(=1)] (=0) view loaded disparity images
* -l [ --laneDetect ] [=arg(=1)] (=0) send extra lanes message
* -F [ --frame ] [=arg(=0)] (=0) start playing at frame ...
*
* Datasets can be downloaded from: http://www.cvlibs.net/datasets/kitti/raw_data.php
*/
int main(int argc, char **argv)
{
kitti_player_options options;
po::variables_map vm;
po::options_description desc("Kitti_player, a player for KITTI raw datasets\nDatasets can be downloaded from: http://www.cvlibs.net/datasets/kitti/raw_data.php\n\nAllowed options",200);
desc.add_options()
("help,h" , "help message")
("directory ,d", po::value<string> (&options.path)->required() , "*required* - path to the kitti dataset Directory")
("frequency ,f", po::value<float> (&options.frequency) ->default_value(1.0) , "set replay Frequency")
("all ,a", po::value<bool> (&options.all_data) ->default_value(0) ->implicit_value(1) , "replay All data")
("velodyne ,v", po::value<bool> (&options.velodyne) ->default_value(0) ->implicit_value(1) , "replay Velodyne data")
("gps ,g", po::value<bool> (&options.gps) ->default_value(0) ->implicit_value(1) , "replay Gps data")
("imu ,i", po::value<bool> (&options.imu) ->default_value(0) ->implicit_value(1) , "replay Imu data")
("grayscale ,G", po::value<bool> (&options.grayscale) ->default_value(0) ->implicit_value(1) , "replay Stereo Grayscale images")
("color ,C", po::value<bool> (&options.color) ->default_value(0) ->implicit_value(1) , "replay Stereo Color images")
("viewer ,V", po::value<bool> (&options.viewer) ->default_value(0) ->implicit_value(1) , "enable image viewer")
("timestamps,T", po::value<bool> (&options.timestamps) ->default_value(0) ->implicit_value(1) , "use KITTI timestamps")
("stereoDisp,s", po::value<bool> (&options.stereoDisp) ->default_value(0) ->implicit_value(1) , "use pre-calculated disparities")
("viewDisp ,D ", po::value<bool> (&options.viewDisparities)->default_value(0) ->implicit_value(1) , "view loaded disparity images")
("laneDetect,l", po::value<bool> (&options.laneDetections) ->default_value(0) ->implicit_value(1) , "send extra lanes message")
("frame ,F", po::value<unsigned int> (&options.startFrame) ->default_value(0) ->implicit_value(0) , "start playing at frame...")
;
try // parse options
{
po::parsed_options parsed = po::command_line_parser(argc-2, argv).options(desc).allow_unregistered().run();
po::store(parsed, vm);
po::notify(vm);
vector<string> to_pass_further = po::collect_unrecognized(parsed.options, po::include_positional);
// Can't handle __ros (ROS parameters ... )
// if (to_pass_further.size()>0)
// {
// ROS_WARN_STREAM("Unknown Options Detected, shutting down node\n");
// cerr << desc << endl;
// return 1;
// }
}
catch(...)
{
cerr << desc << endl;
cout << "kitti_player needs a directory tree like the following:" << endl;
cout << "└── 2011_09_26_drive_0001_sync" << endl;
cout << " ├── image_00 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── image_01 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── image_02 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── image_03 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── oxts " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── velodyne_points " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " └── calib_cam_to_cam.txt " << endl << endl;
ROS_WARN_STREAM("Parse error, shutting down node\n");
return -1;
}
ros::init(argc, argv, "kitti_player");
ros::NodeHandle node("kitti_player");
ros::Rate loop_rate(options.frequency);
/// This sets the logger level; use this to disable all ROS prints
if( ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug) )
ros::console::notifyLoggerLevelsChanged();
else
std::cout << "Error while setting the logger level!" << std::endl;
DIR *dir;
struct dirent *ent;
unsigned int total_entries = 0; //number of elements to be played
unsigned int entries_played = 0; //number of elements played until now
unsigned int len = 0; //counting elements support variable
string dir_root ;
string dir_image00 ;string full_filename_image00; string dir_timestamp_image00;
string dir_image01 ;string full_filename_image01; string dir_timestamp_image01;
string dir_image02 ;string full_filename_image02; string dir_timestamp_image02;
string dir_image03 ;string full_filename_image03; string dir_timestamp_image03;
string dir_image04 ;string full_filename_image04;
string dir_laneDetections ;string full_filename_laneDetections;
string dir_laneProjected ;string full_filename_laneProjected;
string dir_oxts ;string full_filename_oxts; string dir_timestamp_oxts;
string dir_velodyne_points ;string full_filename_velodyne; string dir_timestamp_velodyne; //average of start&end (time of scan)
string str_support;
cv::Mat cv_image00;
cv::Mat cv_image01;
cv::Mat cv_image02;
cv::Mat cv_image03;
cv::Mat cv_image04;
cv::Mat cv_laneProjected;
std_msgs::Header header_support;
image_transport::ImageTransport it(node);
image_transport::CameraPublisher pub00 = it.advertiseCamera("grayscale/left/image_rect", 1);
image_transport::CameraPublisher pub01 = it.advertiseCamera("grayscale/right/image_rect", 1);
image_transport::CameraPublisher pub02 = it.advertiseCamera("color/left/image_rect", 1);
image_transport::CameraPublisher pub03 = it.advertiseCamera("color/right/image_rect", 1);
sensor_msgs::Image ros_msg00;
sensor_msgs::Image ros_msg01;
sensor_msgs::Image ros_msg02;
sensor_msgs::Image ros_msg03;
// sensor_msgs::CameraInfo ros_cameraInfoMsg;
sensor_msgs::CameraInfo ros_cameraInfoMsg_camera00;
sensor_msgs::CameraInfo ros_cameraInfoMsg_camera01;
sensor_msgs::CameraInfo ros_cameraInfoMsg_camera02;
sensor_msgs::CameraInfo ros_cameraInfoMsg_camera03;
cv_bridge::CvImage cv_bridge_img;
ros::Publisher map_pub = node.advertise<pcl::PointCloud<pcl::PointXYZ> > ("hdl64e", 1, true);
ros::Publisher gps_pub = node.advertise<sensor_msgs::NavSatFix> ("oxts/gps", 1, true);
ros::Publisher gps_pub_initial = node.advertise<sensor_msgs::NavSatFix> ("oxts/gps_initial", 1, true);
ros::Publisher imu_pub = node.advertise<sensor_msgs::Imu> ("oxts/imu", 1, true);
ros::Publisher disp_pub = node.advertise<stereo_msgs::DisparityImage> ("preprocessed_disparity",1,true);
//ros::Publisher lanes_pub = node.advertise<road_layout_estimation::msg_lines>("lanes",1,true);
sensor_msgs::NavSatFix ros_msgGpsFix;
sensor_msgs::NavSatFix ros_msgGpsFixInitial; // This message contains the first reading of the file
bool firstGpsData = true; // Flag to store the ros_msgGpsFixInitial message
sensor_msgs::Imu ros_msgImu;
//road_layout_estimation::msg_lines msgLanes;
if (vm.count("help")) {
cout << desc << endl;
cout << "kitti_player needs a directory tree like the following:" << endl;
cout << "└── 2011_09_26_drive_0001_sync" << endl;
cout << " ├── image_00 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── image_01 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── image_02 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── image_03 " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── oxts " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " ├── velodyne_points " << endl;
cout << " │ └── data " << endl;
cout << " │ └ timestamps.txt " << endl;
cout << " └── calib_cam_to_cam.txt " << endl << endl;
return 1;
}
if (!(options.all_data || options.color || options.gps || options.grayscale || options.imu || options.velodyne))
{
ROS_WARN_STREAM("Job finished without playing the dataset. No 'publishing' parameters provided");
node.shutdown();
return 1;
}
dir_root = options.path;
dir_image00 = options.path;
dir_image01 = options.path;
dir_image02 = options.path;
dir_image03 = options.path;
dir_image04 = options.path;
dir_oxts = options.path;
dir_velodyne_points = options.path;
dir_image04 = options.path;
(*(options.path.end()-1) != '/' ? dir_root = options.path+"/" : dir_root = options.path);
(*(options.path.end()-1) != '/' ? dir_image00 = options.path+"/image_00/data/" : dir_image00 = options.path+"image_00/data/");
(*(options.path.end()-1) != '/' ? dir_image01 = options.path+"/image_01/data/" : dir_image01 = options.path+"image_01/data/");
(*(options.path.end()-1) != '/' ? dir_image02 = options.path+"/image_02/data/" : dir_image02 = options.path+"image_02/data/");
(*(options.path.end()-1) != '/' ? dir_image03 = options.path+"/image_03/data/" : dir_image03 = options.path+"image_03/data/");
(*(options.path.end()-1) != '/' ? dir_image04 = options.path+"/disparities/" : dir_image04 = options.path+"disparities/");
(*(options.path.end()-1) != '/' ? dir_oxts = options.path+"/oxts/data/" : dir_oxts = options.path+"oxts/data/");
(*(options.path.end()-1) != '/' ? dir_velodyne_points = options.path+"/velodyne_points/data/" : dir_velodyne_points = options.path+"velodyne_points/data/");
(*(options.path.end()-1) != '/' ? dir_timestamp_image00 = options.path+"/image_00/" : dir_timestamp_image00 = options.path+"image_00/");
(*(options.path.end()-1) != '/' ? dir_timestamp_image01 = options.path+"/image_01/" : dir_timestamp_image01 = options.path+"image_01/");
(*(options.path.end()-1) != '/' ? dir_timestamp_image02 = options.path+"/image_02/" : dir_timestamp_image02 = options.path+"image_02/");
(*(options.path.end()-1) != '/' ? dir_timestamp_image03 = options.path+"/image_03/" : dir_timestamp_image03 = options.path+"image_03/");
(*(options.path.end()-1) != '/' ? dir_timestamp_oxts = options.path+"/oxts/" : dir_timestamp_oxts = options.path+"oxts/");
(*(options.path.end()-1) != '/' ? dir_timestamp_velodyne = options.path+"/velodyne_points/" : dir_timestamp_velodyne = options.path+"velodyne_points/");
(*(options.path.end()-1) != '/' ? dir_timestamp_velodyne = options.path+"/velodyne_points/" : dir_timestamp_velodyne = options.path+"velodyne_points/");
/// EXTRA
/// 01. Lane detections
(*(options.path.end()-1) != '/' ? dir_laneDetections = options.path+"/lane/" : dir_laneDetections = options.path+"lane/");
(*(options.path.end()-1) != '/' ? dir_laneProjected = options.path+"/all/" : dir_laneProjected = options.path+"all/");
// Check all the directories
if (
(options.all_data && ( (opendir(dir_image00.c_str()) == NULL) ||
(opendir(dir_image01.c_str()) == NULL) ||
(opendir(dir_image02.c_str()) == NULL) ||
(opendir(dir_image03.c_str()) == NULL) ||
(opendir(dir_oxts.c_str()) == NULL) ||
(opendir(dir_velodyne_points.c_str()) == NULL)))
||
(options.color && ( (opendir(dir_image02.c_str()) == NULL) ||
(opendir(dir_image03.c_str()) == NULL)))
||
(options.grayscale && ( (opendir(dir_image00.c_str()) == NULL) ||
(opendir(dir_image01.c_str()) == NULL)))
||
(options.imu && ( (opendir(dir_oxts.c_str()) == NULL)))
||
(options.gps && ( (opendir(dir_oxts.c_str()) == NULL)))
//||
//(options.stereoDisp && ( (opendir(dir_image04.c_str()) == NULL)))
||
(options.velodyne && ( (opendir(dir_velodyne_points.c_str()) == NULL)))
//||
//(options.laneDetections && ( (opendir(dir_laneDetections.c_str()) == NULL)))
||
(options.timestamps && ( (opendir(dir_timestamp_image00.c_str()) == NULL) ||
(opendir(dir_timestamp_image01.c_str()) == NULL) ||
(opendir(dir_timestamp_image02.c_str()) == NULL) ||
(opendir(dir_timestamp_image03.c_str()) == NULL) ||
(opendir(dir_timestamp_oxts.c_str()) == NULL) ||
(opendir(dir_timestamp_velodyne.c_str()) == NULL)))
)
{
ROS_ERROR("Incorrect tree directory , use --help for details");
node.shutdown();
return -1;
}
else
{
ROS_INFO_STREAM ("Checking directories...");
ROS_INFO_STREAM (options.path << "\t[OK]");
}
//count elements in the folder
if (options.all_data)
{
dir = opendir(dir_image02.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
}
closedir (dir);
}
else
{
bool done=false;
if (!done && options.color)
{
total_entries=0;
dir = opendir(dir_image02.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
} closedir (dir);
done=true;
}
if (!done && options.grayscale)
{
total_entries=0;
dir = opendir(dir_image00.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
}
closedir (dir);
done=true;
}
if (!done && options.gps)
{
total_entries=0;
dir = opendir(dir_oxts.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
}
closedir (dir);
done=true;
}
if (!done && options.imu)
{
total_entries=0;
dir = opendir(dir_oxts.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
}
closedir (dir);
done=true;
}
if (!done && options.velodyne)
{
total_entries=0;
dir = opendir(dir_oxts.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
}
closedir (dir);
done=true;
}
if (!done && options.stereoDisp)
{
total_entries=0;
dir = opendir(dir_image04.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
}
closedir (dir);
done=true;
}
if (!done && options.laneDetections)
{
total_entries=0;
dir = opendir(dir_laneDetections.c_str());
while(ent = readdir(dir))
{
//skip . & ..
len = strlen (ent->d_name);
//skip . & ..
if (len>2)
total_entries++;
}
closedir (dir);
done=true;
}
}
// Check options.startFrame and total_entries
if (options.startFrame > total_entries)
{
ROS_ERROR("Error, start number > total entries in the dataset");
node.shutdown();
return -1;
}
else
{
entries_played = options.startFrame;
ROS_INFO_STREAM("The entry point (frame number) is: " << entries_played);
}
if(options.viewer)
{
ROS_INFO_STREAM("Opening CV viewer(s)");
if(options.color || options.all_data)
{
ROS_DEBUG_STREAM("color||all " << options.color << " " << options.all_data);
cv::namedWindow("CameraSimulator Color Viewer",CV_WINDOW_AUTOSIZE);
full_filename_image02 = dir_image02 + boost::str(boost::format("%010d") % 0 ) + ".png";
cv_image02 = cv::imread(full_filename_image02, CV_LOAD_IMAGE_UNCHANGED);
cv::waitKey(5);
}
if(options.grayscale || options.all_data)
{
ROS_DEBUG_STREAM("grayscale||all " << options.grayscale << " " << options.all_data);
cv::namedWindow("CameraSimulator Grayscale Viewer",CV_WINDOW_AUTOSIZE);
full_filename_image00 = dir_image00 + boost::str(boost::format("%010d") % 0 ) + ".png";
cv_image00 = cv::imread(full_filename_image00, CV_LOAD_IMAGE_UNCHANGED);
cv::waitKey(5);
}
if (options.viewDisparities || options.all_data)
{
ROS_DEBUG_STREAM("viewDisparities||all " << options.grayscale << " " << options.all_data);
cv::namedWindow("Reprojection of Detected Lines",CV_WINDOW_AUTOSIZE);
full_filename_laneProjected = dir_laneProjected + boost::str(boost::format("%010d") % 0 ) + ".png";
cv_laneProjected = cv::imread(full_filename_laneProjected, CV_LOAD_IMAGE_UNCHANGED);
cv::waitKey(5);
}
ROS_INFO_STREAM("Opening CV viewer(s)... OK");
}
// CAMERA INFO SECTION: read one for all
ros_cameraInfoMsg_camera00.header.stamp = ros::Time::now();
ros_cameraInfoMsg_camera00.header.frame_id = ros::this_node::getName();
ros_cameraInfoMsg_camera00.height = 0;
ros_cameraInfoMsg_camera00.width = 0;
//ros_cameraInfoMsg_camera00.D.resize(5);
//ros_cameraInfoMsg_camera00.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB;
ros_cameraInfoMsg_camera01.header.stamp = ros::Time::now();
ros_cameraInfoMsg_camera01.header.frame_id = ros::this_node::getName();
ros_cameraInfoMsg_camera01.height = 0;
ros_cameraInfoMsg_camera01.width = 0;
//ros_cameraInfoMsg_camera01.D.resize(5);
//ros_cameraInfoMsg_camera00.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB;
ros_cameraInfoMsg_camera02.header.stamp = ros::Time::now();
ros_cameraInfoMsg_camera02.header.frame_id = ros::this_node::getName();
ros_cameraInfoMsg_camera02.height = 0;
ros_cameraInfoMsg_camera02.width = 0;
//ros_cameraInfoMsg_camera02.D.resize(5);
//ros_cameraInfoMsg_camera02.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB;
ros_cameraInfoMsg_camera03.header.stamp = ros::Time::now();
ros_cameraInfoMsg_camera03.header.frame_id = ros::this_node::getName();
ros_cameraInfoMsg_camera03.height = 0;
ros_cameraInfoMsg_camera03.width = 0;
//ros_cameraInfoMsg_camera03.D.resize(5);
//ros_cameraInfoMsg_camera03.distortion_model=sensor_msgs::distortion_models::PLUMB_BOB;
if(options.color || options.all_data)
{
if(
!(getCalibration(dir_root,"02",ros_cameraInfoMsg_camera02.K.data(),ros_cameraInfoMsg_camera02.D,ros_cameraInfoMsg_camera02.R.data(),ros_cameraInfoMsg_camera02.P.data()) &&
getCalibration(dir_root,"03",ros_cameraInfoMsg_camera03.K.data(),ros_cameraInfoMsg_camera03.D,ros_cameraInfoMsg_camera03.R.data(),ros_cameraInfoMsg_camera03.P.data()))
)
{
ROS_ERROR_STREAM("Error reading CAMERA02/CAMERA03 calibration");
//node.shutdown();
//return -1;
}
//Assume same height/width for the camera pair
full_filename_image02 = dir_image02 + boost::str(boost::format("%010d") % 0 ) + ".png";
cv_image02 = cv::imread(full_filename_image02, CV_LOAD_IMAGE_UNCHANGED);
cv::waitKey(5);
ros_cameraInfoMsg_camera03.height = ros_cameraInfoMsg_camera02.height = cv_image02.rows;// -1;TODO: CHECK, qui potrebbe essere -1
ros_cameraInfoMsg_camera03.width = ros_cameraInfoMsg_camera02.width = cv_image02.cols;// -1;
}
if(options.grayscale || options.all_data)
{
if(
!(getCalibration(dir_root,"00",ros_cameraInfoMsg_camera00.K.data(),ros_cameraInfoMsg_camera00.D,ros_cameraInfoMsg_camera00.R.data(),ros_cameraInfoMsg_camera00.P.data()) &&
getCalibration(dir_root,"01",ros_cameraInfoMsg_camera01.K.data(),ros_cameraInfoMsg_camera01.D,ros_cameraInfoMsg_camera01.R.data(),ros_cameraInfoMsg_camera01.P.data()))
)
{
ROS_ERROR_STREAM("Error reading CAMERA00/CAMERA01 calibration");
//node.shutdown();
//return -1;
}
//Assume same height/width for the camera pair
full_filename_image00 = dir_image00 + boost::str(boost::format("%010d") % 0 ) + ".png";
cv_image00 = cv::imread(full_filename_image00, CV_LOAD_IMAGE_UNCHANGED);
cv::waitKey(5);
ros_cameraInfoMsg_camera01.height = ros_cameraInfoMsg_camera00.height = cv_image00.rows;// -1; TODO: CHECK -1?
ros_cameraInfoMsg_camera01.width = ros_cameraInfoMsg_camera00.width = cv_image00.cols;// -1;
}
boost::progress_display progress(total_entries) ;
double cv_min, cv_max=0.0f;
// This is the main KITTI_PLAYER Loop
do
{
// single timestamp for all published stuff
Time current_timestamp=ros::Time::now();
if(options.stereoDisp)
{
// Allocate new disparity image message
stereo_msgs::DisparityImagePtr disp_msg = boost::make_shared<stereo_msgs::DisparityImage>();
full_filename_image04 = dir_image04 + boost::str(boost::format("%010d") % entries_played ) + ".png";
cv_image04 = cv::imread(full_filename_image04, CV_LOAD_IMAGE_GRAYSCALE);
cv::minMaxLoc(cv_image04,&cv_min,&cv_max);
disp_msg->min_disparity = (int)cv_min;
disp_msg->max_disparity = (int)cv_max;
disp_msg->valid_window.x_offset = 0; // should be safe, checked!
disp_msg->valid_window.y_offset = 0; // should be safe, checked!
disp_msg->valid_window.width = 0; // should be safe, checked!
disp_msg->valid_window.height = 0; // should be safe, checked!
disp_msg->T = 0; // should be safe, checked!
disp_msg->f = 0; // should be safe, checked!
disp_msg->delta_d = 0; // should be safe, checked!
disp_msg->header.stamp = current_timestamp;
disp_msg->header.frame_id = ros::this_node::getName();
disp_msg->header.seq = progress.count();
sensor_msgs::Image& dimage = disp_msg->image;
dimage.width = cv_image04.size().width ;
dimage.height = cv_image04.size().height ;
dimage.encoding = sensor_msgs::image_encodings::TYPE_32FC1;
dimage.step = dimage.width * sizeof(float);
dimage.data.resize(dimage.step * dimage.height);
cv::Mat_<float> dmat(dimage.height, dimage.width, reinterpret_cast<float*>(&dimage.data[0]), dimage.step);
cv_image04.convertTo(dmat,dmat.type());
disp_pub.publish(disp_msg);
}
/*
if(options.laneDetections)
{
//msgLanes;
//msgSingleLaneInfo;
string file=dir_laneDetections+boost::str(boost::format("%010d") % entries_played )+".txt";
if(getLaneDetection(file,&msgLanes))
{
msgLanes.header.stamp = current_timestamp;
msgLanes.header.frame_id = ros::this_node::getName();
lanes_pub.publish(msgLanes);
}
if (options.viewDisparities)
{
full_filename_laneProjected = dir_laneProjected + boost::str(boost::format("%010d") % entries_played ) + ".png";
cv_laneProjected = cv::imread(full_filename_laneProjected, CV_LOAD_IMAGE_UNCHANGED);
cv::imshow("Reprojection of Detected Lines",cv_laneProjected);
cv::waitKey(5);
}
}
*/
if(options.color || options.all_data)
{
full_filename_image02 = dir_image02 + boost::str(boost::format("%010d") % entries_played ) + ".png";
full_filename_image03 = dir_image03 + boost::str(boost::format("%010d") % entries_played ) + ".png";
ROS_DEBUG_STREAM ( full_filename_image02 << endl << full_filename_image03 << endl << endl);
cv_image02 = cv::imread(full_filename_image02, CV_LOAD_IMAGE_UNCHANGED);
cv_image03 = cv::imread(full_filename_image03, CV_LOAD_IMAGE_UNCHANGED);
if ( (cv_image02.data == NULL) || (cv_image03.data == NULL) ){
ROS_ERROR_STREAM("Error reading color images (02 & 03)");
ROS_ERROR_STREAM(full_filename_image02 << endl << full_filename_image03);
node.shutdown();
return -1;
}
if(options.viewer)
{
//display the left image only
cv::imshow("CameraSimulator Color Viewer",cv_image02);
//give some time to draw images
cv::waitKey(5);
}
cv_bridge_img.encoding = sensor_msgs::image_encodings::BGR8;
cv_bridge_img.header.frame_id = "camera"; //ros::this_node::getName();
if (!options.timestamps)
{
cv_bridge_img.header.stamp = current_timestamp ;
ros_msg02.header.stamp = ros_cameraInfoMsg_camera02.header.stamp = cv_bridge_img.header.stamp;
}
else
{
str_support = dir_timestamp_image02 + "timestamps.txt";
ifstream timestamps(str_support.c_str());
if (!timestamps.is_open())
{
string timestamps_string;
timestamps >> timestamps_string;
ROS_ERROR_STREAM("Fail to open " << timestamps_string);
node.shutdown();
return -1;
}
timestamps.seekg(30*entries_played);
getline(timestamps,str_support);
cv_bridge_img.header.stamp = parseTime(str_support).stamp;
ros_msg02.header.stamp = ros_cameraInfoMsg_camera02.header.stamp = cv_bridge_img.header.stamp;
}
cv_bridge_img.image = cv_image02;
cv_bridge_img.toImageMsg(ros_msg02);
if (!options.timestamps)
{
cv_bridge_img.header.stamp = current_timestamp;
ros_msg03.header.stamp = ros_cameraInfoMsg_camera03.header.stamp = cv_bridge_img.header.stamp;
}
else
{
str_support = dir_timestamp_image03 + "timestamps.txt";
ifstream timestamps(str_support.c_str());
if (!timestamps.is_open())
{
string timestamps_string;
timestamps >> timestamps_string;
ROS_ERROR_STREAM("Fail to open " << timestamps_string);
node.shutdown();
return -1;
}
timestamps.seekg(30*entries_played);
getline(timestamps,str_support);
cv_bridge_img.header.stamp = parseTime(str_support).stamp;
ros_msg03.header.stamp = ros_cameraInfoMsg_camera03.header.stamp = cv_bridge_img.header.stamp;
}
cv_bridge_img.image = cv_image03;
cv_bridge_img.toImageMsg(ros_msg03);
pub02.publish(ros_msg02,ros_cameraInfoMsg_camera02);
pub03.publish(ros_msg03,ros_cameraInfoMsg_camera03);
}
if(options.grayscale || options.all_data)
{
full_filename_image00 = dir_image00 + boost::str(boost::format("%010d") % entries_played ) + ".png";
full_filename_image01 = dir_image01 + boost::str(boost::format("%010d") % entries_played ) + ".png";
ROS_DEBUG_STREAM ( full_filename_image00 << endl << full_filename_image01 << endl << endl);
cv_image00 = cv::imread(full_filename_image00, CV_LOAD_IMAGE_UNCHANGED);
cv_image01 = cv::imread(full_filename_image01, CV_LOAD_IMAGE_UNCHANGED);
if ( (cv_image00.data == NULL) || (cv_image01.data == NULL) ){
ROS_ERROR_STREAM("Error reading color images (00 & 01)");
ROS_ERROR_STREAM(full_filename_image00 << endl << full_filename_image01);
node.shutdown();
return -1;
}
if(options.viewer)
{
//display the left image only
cv::imshow("CameraSimulator Grayscale Viewer",cv_image00);
//give some time to draw images
cv::waitKey(5);
}
cv_bridge_img.encoding = sensor_msgs::image_encodings::MONO8;
cv_bridge_img.header.frame_id = "camera"; //ros::this_node::getName();
if (!options.timestamps)
{
cv_bridge_img.header.stamp = current_timestamp;
ros_msg00.header.stamp = ros_cameraInfoMsg_camera00.header.stamp = cv_bridge_img.header.stamp;
}
else
{
str_support = dir_timestamp_image02 + "timestamps.txt";
ifstream timestamps(str_support.c_str());
if (!timestamps.is_open())
{
string timestamps_string;
timestamps >> timestamps_string;
ROS_ERROR_STREAM("Fail to open " << timestamps_string);
node.shutdown();
return -1;
}
timestamps.seekg(30*entries_played);
getline(timestamps,str_support);
cv_bridge_img.header.stamp = parseTime(str_support).stamp;
ros_msg00.header.stamp = ros_cameraInfoMsg_camera00.header.stamp = cv_bridge_img.header.stamp;
}
cv_bridge_img.image = cv_image00;
cv_bridge_img.toImageMsg(ros_msg00);
if (!options.timestamps)
{
cv_bridge_img.header.stamp = current_timestamp;
ros_msg01.header.stamp = ros_cameraInfoMsg_camera01.header.stamp = cv_bridge_img.header.stamp;
}
else
{
str_support = dir_timestamp_image02 + "timestamps.txt";
ifstream timestamps(str_support.c_str());
if (!timestamps.is_open())
{
string timestamps_string;
timestamps >> timestamps_string;
ROS_ERROR_STREAM("Fail to open " << timestamps_string);
node.shutdown();
return -1;
}
timestamps.seekg(30*entries_played);
getline(timestamps,str_support);
cv_bridge_img.header.stamp = parseTime(str_support).stamp;
ros_msg01.header.stamp = ros_cameraInfoMsg_camera01.header.stamp = cv_bridge_img.header.stamp;
}
cv_bridge_img.image = cv_image01;
cv_bridge_img.toImageMsg(ros_msg01);
pub00.publish(ros_msg00,ros_cameraInfoMsg_camera00);
pub01.publish(ros_msg01,ros_cameraInfoMsg_camera01);
}
if(options.velodyne || options.all_data)
{
header_support.stamp = current_timestamp;
full_filename_velodyne = dir_velodyne_points + boost::str(boost::format("%010d") % entries_played ) + ".bin";
if (!options.timestamps)
publish_velodyne(map_pub, full_filename_velodyne,&header_support);
else
{
str_support = dir_timestamp_velodyne + "timestamps.txt";
ifstream timestamps(str_support.c_str());
if (!timestamps.is_open())
{
string timestamps_string;
timestamps >> timestamps_string;
ROS_ERROR_STREAM("Fail to open " << timestamps_string);
node.shutdown();
return -1;
}
timestamps.seekg(30*entries_played);
getline(timestamps,str_support);
header_support.stamp = parseTime(str_support).stamp;
header_support.seq = progress.count();
publish_velodyne(map_pub, full_filename_velodyne,&header_support);
}
}
if(options.gps || options.all_data)
{
header_support.stamp = current_timestamp; //ros::Time::now();
if (options.timestamps)
{
str_support = dir_timestamp_oxts + "timestamps.txt";
ifstream timestamps(str_support.c_str());
if (!timestamps.is_open())
{
string timestamps_string;
timestamps >> timestamps_string;
ROS_ERROR_STREAM("Fail to open " << timestamps_string);
node.shutdown();
return -1;
}
timestamps.seekg(30*entries_played);
getline(timestamps,str_support);
header_support.stamp = parseTime(str_support).stamp;
}
full_filename_oxts = dir_oxts + boost::str(boost::format("%010d") % entries_played ) + ".txt";
if (!getGPS(full_filename_oxts,&ros_msgGpsFix,&header_support))
{
ROS_ERROR_STREAM("Fail to open " << full_filename_oxts);
node.shutdown();
return -1;
}
if (firstGpsData)
{
ROS_DEBUG_STREAM("Setting initial GPS fix at " << endl << ros_msgGpsFix);
firstGpsData = false;
ros_msgGpsFixInitial = ros_msgGpsFix;
ros_msgGpsFixInitial.header.frame_id = "/local_map";
ros_msgGpsFixInitial.altitude = 0.0f;
}
gps_pub.publish(ros_msgGpsFix);
gps_pub_initial.publish(ros_msgGpsFixInitial);
}
if(options.imu || options.all_data)
{
header_support.stamp = current_timestamp; //ros::Time::now();
if (options.timestamps)
{
str_support = dir_timestamp_oxts + "timestamps.txt";
ifstream timestamps(str_support.c_str());
if (!timestamps.is_open())
{
string timestamps_string;
timestamps >> timestamps_string;
ROS_ERROR_STREAM("Fail to open " << timestamps_string);
node.shutdown();
return -1;
}
timestamps.seekg(30*entries_played);
getline(timestamps,str_support);
header_support.stamp = parseTime(str_support).stamp;
}
full_filename_oxts = dir_oxts + boost::str(boost::format("%010d") % entries_played ) + ".txt";
if (!getIMU(full_filename_oxts,&ros_msgImu,&header_support))
{
ROS_ERROR_STREAM("Fail to open " << full_filename_oxts);
node.shutdown();
return -1;
}
imu_pub.publish(ros_msgImu);
}
++progress;
entries_played++;
loop_rate.sleep();
}
while(entries_played<=total_entries-1 && ros::ok());
if(options.viewer)
{
ROS_INFO_STREAM(" Closing CV viewer(s)");
if(options.color || options.all_data)
cv::destroyWindow("CameraSimulator Color Viewer");
if(options.grayscale || options.all_data)
cv::destroyWindow("CameraSimulator Grayscale Viewer");
if (options.viewDisparities)
cv::destroyWindow("Reprojection of Detected Lines");
ROS_INFO_STREAM(" Closing CV viewer(s)... OK");
}
ROS_INFO_STREAM("Done!");
node.shutdown();
return 0;
}
| 43.259176 | 189 | 0.561531 | filiperinaldi |
f3956e30071100252e640894359d9a4ebf8c1d42 | 1,548 | cpp | C++ | Prog-CalibrateCamera/src/Logger.cpp | BProj-LMN/Studienarbeit | 94cb93654e58f155aa6b56b93230a49f63846e01 | [
"BSD-3-Clause"
] | null | null | null | Prog-CalibrateCamera/src/Logger.cpp | BProj-LMN/Studienarbeit | 94cb93654e58f155aa6b56b93230a49f63846e01 | [
"BSD-3-Clause"
] | null | null | null | Prog-CalibrateCamera/src/Logger.cpp | BProj-LMN/Studienarbeit | 94cb93654e58f155aa6b56b93230a49f63846e01 | [
"BSD-3-Clause"
] | null | null | null | /*
* Logger.cpp
*
* function: Logger Singleton for logging with different log levels to a file
*
* author: Jannik Beyerstedt
*/
#include "Logger.h"
#include <iomanip>
Logger::Logger() {
logfile.open("logfile.txt", std::ios::trunc);
logfile << std::setprecision(3) << std::fixed;
time_start = std::chrono::high_resolution_clock::now();
logLevel = ERROR;
}
Logger::~Logger() {
logfile.close();
}
void Logger::setLogLevel(log_t logLevel) {
this->logLevel = logLevel;
}
log_t Logger::getLogLevel() {
return logLevel;
}
std::ofstream& Logger::log(log_t logType) {
std::chrono::duration<double, std::milli> timediff_ms = std::chrono::high_resolution_clock::now() - time_start;
auto time = std::chrono::system_clock::now();
logfile << std::chrono::system_clock::to_time_t(time) << " (" << timediff_ms.count() << ") [" << logType << "] ";
return logfile;
}
std::ofstream& Logger::log() {
std::chrono::duration<double, std::milli> timediff_ms = std::chrono::high_resolution_clock::now() - time_start;
auto time = std::chrono::system_clock::now();
logfile << std::chrono::system_clock::to_time_t(time) << " (" << timediff_ms.count() << ") ";
return logfile;
}
LogScope::LogScope(const std::string& s)
: logger(Logger::getLogger()), s_(s) {
if (!(Logger::getLogger().getLogLevel() < DEBUG)) {
logger.log(DEBUG) << "entering function " << s_ << "\n";
}
}
LogScope::~LogScope() {
if (!(Logger::getLogger().getLogLevel() < DEBUG)) {
logger.log(DEBUG) << "exiting function " << s_ << "\n";
}
}
| 25.377049 | 115 | 0.646641 | BProj-LMN |
f395941baaf477d25d4a8d532a72c23989a73cf3 | 386 | cpp | C++ | competitive_programming/programming_contests/uri/the_race_of_slugs.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 205 | 2018-12-01T17:49:49.000Z | 2021-12-22T07:02:27.000Z | competitive_programming/programming_contests/uri/the_race_of_slugs.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 2 | 2020-01-01T16:34:29.000Z | 2020-04-26T19:11:13.000Z | competitive_programming/programming_contests/uri/the_race_of_slugs.cpp | LeandroTk/Algorithms | 569ed68eba3eeff902f8078992099c28ce4d7cd6 | [
"MIT"
] | 50 | 2018-11-28T20:51:36.000Z | 2021-11-29T04:08:25.000Z | // https://www.urionlinejudge.com.br/judge/en/problems/view/1789
#include <iostream>
using namespace std;
int main() {
int n, x, faster = 0;
while (scanf("%d", &n) != EOF) {
while (n--) {
cin >> x;
if (x > faster) faster = x;
}
if (faster < 10) cout << 1 << endl;
else if (faster < 20) cout << 2 << endl;
else cout << 3 << endl;
faster = 0;
}
return 0;
} | 14.846154 | 64 | 0.546632 | LeandroTk |
f397a52a0959e109d3355165c93f6957ff7a0d20 | 1,421 | cpp | C++ | Maligaro/cpp_lib/test/main.cpp | Leviyu/ForwardTomography | 5d10ccb9e8bf32352fe383633883499b163e0c1f | [
"MIT"
] | 1 | 2018-09-20T19:12:47.000Z | 2018-09-20T19:12:47.000Z | Maligaro/cpp_lib/test/main.cpp | Leviyu/ForwardTomography | 5d10ccb9e8bf32352fe383633883499b163e0c1f | [
"MIT"
] | null | null | null | Maligaro/cpp_lib/test/main.cpp | Leviyu/ForwardTomography | 5d10ccb9e8bf32352fe383633883499b163e0c1f | [
"MIT"
] | null | null | null | //###include "../01_cpp_lib/hongyulib.h"
#include <iostream> // std::cout
#include <algorithm> // std::unique, std::distance
#include <vector> // std::vector
bool myfunction (int i, int j) {
return (i==j);
}
using namespace std;
int main () {
int myints[] = {10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10
string mystrings[] = {"me", "the_me", "me", "me","me", "the_me"};
//##std::vector<int> myvector (myints,myints+9);
//##vector<string> mystringvector ( mystrings, mystrings+5);
vector<string> mystringvector(mystrings,mystrings+6);
// using default comparison:
//##std::vector<int>::iterator it;
vector<string>:: iterator it;
//it = std::unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 ? ? ? ?
// ^
//it = unique( mystringvector.begin(), mystringvector.end());
it = unique( mystringvector.begin(), mystringvector.end());
//yvector.resize( std::distance(myvector.begin(),it) ); // 10 20 30 20 10
mystringvector.resize(distance(mystringvector.begin() , it));
// using predicate comparison:
//##std::unique (myvector.begin(), myvector.end(), myfunction); // (no changes)
// print out content:
std::cout << "myvector contains:";
for (it=mystringvector.begin(); it!=mystringvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
| 34.658537 | 87 | 0.593948 | Leviyu |
f397f0ecd5d99a66bcfacb16c0cb0c30816c72a0 | 16,716 | cpp | C++ | inference-engine/thirdparty/mkl-dnn/src/cpu/gemm/f32/jit_avx2_kernel_sgemm_kern.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | 48 | 2020-07-29T18:09:23.000Z | 2021-10-09T01:53:33.000Z | inference-engine/thirdparty/mkl-dnn/src/cpu/gemm/f32/jit_avx2_kernel_sgemm_kern.cpp | zhoub/dldt | e42c01cf6e1d3aefa55e2c5df91f1054daddc575 | [
"Apache-2.0"
] | 9 | 2021-04-02T02:28:07.000Z | 2022-03-26T18:23:59.000Z | Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/cpu/gemm/f32/jit_avx2_kernel_sgemm_kern.cpp | lablup/training_results_v0.7 | f5bb59aa0f8b18b602763abe47d1d24d0d54b197 | [
"Apache-2.0"
] | 42 | 2020-08-01T06:41:24.000Z | 2022-01-20T10:33:08.000Z | /*******************************************************************************
* Copyright 2019 Intel Corporation
*
* 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 "jit_avx2_kernel_sgemm_kern.hpp"
#ifdef _WIN32
static const bool is_windows = true;
#else
static const bool is_windows = false;
#endif
namespace mkldnn {
namespace impl {
namespace cpu {
int jit_avx2_kernel_sgemm_kern::next_acc(int idx, int um, int un) {
while (!(((idx / unroll_n_) < std::max(1, um / nelt_per_vecreg_))
|| ((idx % unroll_n_) < un)))
idx++;
return idx;
}
void jit_avx2_kernel_sgemm_kern::prefetchB_beforeBload(
int um, int un, int k_idx, int n_idx) {
if (!mayiuse(avx512_core)) {
if ((n_idx == 0) && (k_idx == 0) && (un == unroll_n_) && (um != 16)) {
prefetcht0(ptr[BO_ + elt_size_ * (PREFETCHSIZEB_ + offb_)]);
offb_ += 16;
}
}
}
void jit_avx2_kernel_sgemm_kern::prefetchB_beforeFMA(
int um, int un, int k_idx, int n_idx, int m_idx) {
if (!mayiuse(avx512_core)) {
if ((um == 16) || (un < unroll_n_)) {
if ((k_idx + m_idx + n_idx) == 0) {
prefetcht0(ptr[BO_ + elt_size_ * (PREFETCHSIZEB_ + offb_)]);
offb_ += 16;
}
if ((um == 16) && (un == 4) && (k_idx == 2)
&& ((m_idx + n_idx) == 0)) {
prefetcht0(ptr[BO_ + elt_size_ * (PREFETCHSIZEB_ + offb_)]);
offb_ += 16;
}
}
}
}
void jit_avx2_kernel_sgemm_kern::prefetchA_afterFMA(
int um, int un, int k_idx, int n_idx, int m_idx) {
if (mayiuse(avx512_core)) {
if ((um < unroll_m_) && (m_idx == 0)) {
if (((k_idx % (nb_zmm_a_ / unroll_m_reg_) == 0) && (n_idx % 6 == 0))
|| ((k_idx % (nb_zmm_a_ / unroll_m_reg_) == 1)
&& (n_idx == 3))) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
}
} else {
if (un == unroll_n_) {
if (((um < nelt_per_vecreg_) && (n_idx == 0)
&& (k_idx == std::min(2, nelt_per_vecreg_ / um - 1)))
|| ((um == nelt_per_vecreg_) && (un == unroll_n_)
&& (n_idx == 1) && (k_idx == 0))) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
}
}
}
void jit_avx2_kernel_sgemm_kern::prefetchA_afterBload(
int um, int un, int k_idx, int n_idx) {
if (!mayiuse(avx512_core)) {
if ((um == unroll_m_) && (un == 2)) {
if (k_idx % 3 == 0) {
if (n_idx == 1) {
if (k_idx == 0)
off_ += 16;
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
if ((k_idx == 0) && (n_idx == 0)) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
} else {
if (n_idx == 1) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
}
}
}
}
void jit_avx2_kernel_sgemm_kern::prefetchB_afterFMA(
int k_idx, int n_idx, int m_idx) {
if (mayiuse(avx512_core)) {
if (((m_idx + (k_idx % (nb_zmm_a_ / unroll_m_reg_)) * unroll_m_reg_)
== 0)
&& (n_idx == 1)) {
prefetcht0(ptr[BO_
+ elt_size_
* (PREFETCHSIZEB_
+ nelt_per_vecreg_ * k_idx
/ (nb_zmm_a_ / unroll_m_reg_))]);
}
}
}
void jit_avx2_kernel_sgemm_kern::prefetchA_beforeFMA(
int um, int un, int k_idx, int n_idx, int m_idx) {
if (!mayiuse(avx512_core)) {
if ((um == unroll_m_) && (un == unroll_n_)) {
if (((k_idx == 0) && (n_idx % 2 == 1) && (m_idx == 0))
|| ((k_idx == 1) && (n_idx == 2) && (m_idx == 0))
|| ((k_idx == 2) && (n_idx == 0) && (m_idx == 2))
|| ((k_idx == 2) && (n_idx == 3) && (m_idx == 0))
|| ((k_idx == 3) && (n_idx == 1) && (m_idx == 0))) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
}
if ((um == unroll_m_) && (un == 1)) {
if (m_idx == 2) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
} else if ((m_idx == 0) && ((k_idx == 1) || (k_idx == 2))) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
}
if ((um == 16) && (un == unroll_n_) && (m_idx == 0) && (n_idx == 2)) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
if ((um == 8) && (un == unroll_n_) && (m_idx == 0) && (n_idx == 1)
&& (k_idx == 2)) {
prefetcht0(ptr[AO_ + elt_size_ * (PREFETCHSIZEA_ + off_)]);
off_ += 16;
}
}
}
void jit_avx2_kernel_sgemm_kern::prefetchC_afterBload(
int um, int un, int k_idx, int n_idx) {
if (mayiuse(avx512_core)) {
if (um == unroll_m_) {
if (n_idx == std::min(1, un - 1)) {
if (k_idx == unroll_k_ - 1)
lea(CO2_, ptr[CO2_ + LDC_]);
else
prefetchw(ptr[CO2_ + elt_size_ * k_idx * nelt_per_vecreg_]);
}
}
}
}
void jit_avx2_kernel_sgemm_kern::prefetchC_beforeKloop(int um) {
if (mayiuse(avx512_core)) {
if (um < unroll_m_) {
prefetchw(ptr[CO2_ + elt_size_ * 0]);
prefetchw(ptr[CO2_ + elt_size_ * 8]);
if (um <= 16)
prefetchw(ptr[CO2_ + elt_size_ * 16]);
lea(CO2_, ptr[CO2_ + LDC_]);
}
} else {
prefetcht2(ptr[AA_ - 16 * elt_size_]);
prefetcht0(ptr[CO1_ + 7 * elt_size_]);
prefetcht0(ptr[CO1_ + LDC_ + 7 * elt_size_]);
prefetcht0(ptr[CO2_ + 7 * elt_size_]);
prefetcht0(ptr[CO2_ + LDC_ + 7 * elt_size_]);
prefetcht0(ptr[CO1_ + 23 * elt_size_]);
prefetcht0(ptr[CO1_ + LDC_ + 23 * elt_size_]);
prefetcht0(ptr[CO2_ + 23 * elt_size_]);
prefetcht0(ptr[CO2_ + LDC_ + 23 * elt_size_]);
add(LL_, second_fetch_);
prefetcht2(ptr[AA_]);
}
}
void jit_avx2_kernel_sgemm_kern::generate() {
int i, unroll_x, unroll_y, uy_bin, ux_bin;
int C_off = is_windows ? 56 : 8;
int LDC_off = is_windows ? 64 : 16;
int sepload = 0;
Xbyak::Label unroll_x_label[MAX_UNROLL_M],
unroll_y_label[(MAX_UNROLL_N_BIN + 1) * MAX_UNROLL_M];
Xbyak::Label end_n_loop_label[MAX_UNROLL_M], end_m_loop_label;
preamble();
if (is_windows) {
mov(M_, ptr[rcx]);
mov(N_, ptr[rdx]);
mov(K_, ptr[r8]);
mov(A_, ptr[rsp + get_size_of_abi_save_regs() + 40]);
mov(B_, ptr[rsp + get_size_of_abi_save_regs() + 48]);
} else {
mov(M_, ptr[M_]);
mov(N_, ptr[N_]);
mov(K_, ptr[K_]);
}
mov(C_, ptr[rsp + get_size_of_abi_save_regs() + C_off]);
mov(LDC_, ptr[rsp + get_size_of_abi_save_regs() + LDC_off]);
if (mayiuse(avx512_core)) {
for (i = zmm_acc_idx_; i < unroll_m_reg_ * unroll_n_ + zmm_acc_idx_;
i++)
vpxorq(Xbyak::Zmm(i), Xbyak::Zmm(i), Xbyak::Zmm(i));
}
sub(A_, -addr_off_ * elt_size_);
sub(B_, -addr_off_ * elt_size_);
sal(LDC_, elt_size_bin_);
for (unroll_x = unroll_m_, i = 0, ux_bin = unroll_m_bin_; unroll_x >= 1;
unroll_x -= std::min(nelt_per_vecreg_, std::max(1, unroll_x / 2)),
i++, ux_bin--) {
if (unroll_x == unroll_m_) {
mov(J_, M_);
cmp(J_, unroll_m_);
jl(unroll_x_label[i + 1], T_NEAR);
L_aligned(unroll_x_label[i]);
} else {
L_aligned(unroll_x_label[i]);
test(J_, unroll_x);
if (unroll_x > 1)
jle(unroll_x_label[i + 1], T_NEAR);
else
jle(end_m_loop_label, T_NEAR);
}
mov(AA_, KK_);
if ((1 << ux_bin) > unroll_x)
imul(AA_, AA_, unroll_x * elt_size_);
else
sal(AA_, elt_size_bin_ + ux_bin);
add(AA_, A_);
mov(CO1_, C_);
if ((unroll_x == unroll_m_) || (!mayiuse(avx512_core)))
lea(CO2_, ptr[C_ + LDC_ * 2]);
add(C_, unroll_x * elt_size_);
mov(BO_, B_);
for (unroll_y = unroll_n_, uy_bin = unroll_n_bin_; unroll_y >= 1;
unroll_y /= 2, uy_bin--) {
if (unroll_y == unroll_n_) {
mov(I_, N_);
sar(I_, uy_bin);
jle(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin - 1],
T_NEAR);
L_aligned(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin]);
} else {
L_aligned(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin]);
test(N_, unroll_y);
if (uy_bin == 0)
jle(end_n_loop_label[i], T_NEAR);
else
jle(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin - 1],
T_NEAR);
}
if (!mayiuse(avx512_core))
prefetcht2(ptr[AA_ - addr_off_ * elt_size_]);
switch (unroll_x) {
case 8:
if (mayiuse(avx512_core)) {
loop<Xbyak::Zmm, Xbyak::Zmm, Xbyak::Address, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vbroadcastf64x4,
&Xbyak::CodeGenerator::vbroadcastss);
update<Xbyak::Ymm, Xbyak::Operand>(unroll_x, unroll_y, 0,
beta_zero_, &Xbyak::CodeGenerator::vaddps,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vmovups);
} else {
loop<Xbyak::Ymm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vbroadcastss);
update<Xbyak::Ymm, Xbyak::Operand>(unroll_x, unroll_y, 1,
beta_zero_, &Xbyak::CodeGenerator::vaddps,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vmovups);
}
break;
case 4:
if (mayiuse(avx512_core)) {
loop<Xbyak::Zmm, Xbyak::Ymm, Xbyak::Address, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vbroadcastf32x4,
&Xbyak::CodeGenerator::vbroadcastss);
sepload = 0;
} else {
loop<Xbyak::Xmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vbroadcastss);
sepload = 1;
}
update<Xbyak::Xmm, Xbyak::Operand>(unroll_x, unroll_y, sepload,
beta_zero_, &Xbyak::CodeGenerator::vaddps,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vmovups);
break;
case 2:
if (mayiuse(avx512_core)) {
loop<Xbyak::Zmm, Xbyak::Ymm, Xbyak::Operand, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vbroadcastsd,
&Xbyak::CodeGenerator::vbroadcastss);
} else {
loop<Xbyak::Xmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vmovddup,
&Xbyak::CodeGenerator::vbroadcastss);
}
update<Xbyak::Xmm, Xbyak::Address>(unroll_x, unroll_y, 1,
beta_zero_, &Xbyak::CodeGenerator::vaddps,
&Xbyak::CodeGenerator::vmovlps,
&Xbyak::CodeGenerator::vmovsd);
break;
case 1:
if (mayiuse(avx512_core)) {
loop<Xbyak::Zmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vbroadcastss,
&Xbyak::CodeGenerator::vbroadcastss);
sepload = 0;
} else {
loop<Xbyak::Xmm, Xbyak::Xmm, Xbyak::Address, Xbyak::Xmm,
Xbyak::Address>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vmovss,
&Xbyak::CodeGenerator::vmovss);
sepload = 1;
}
update<Xbyak::Xmm, Xbyak::Address>(unroll_x, unroll_y, sepload,
beta_zero_, &Xbyak::CodeGenerator::vaddss,
&Xbyak::CodeGenerator::vmovss,
&Xbyak::CodeGenerator::vmovss);
break;
default:
if (mayiuse(avx512_core)) {
loop<Xbyak::Zmm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vbroadcastss);
update<Xbyak::Zmm, Xbyak::Operand>(unroll_x, unroll_y, 0,
beta_zero_, &Xbyak::CodeGenerator::vaddps,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vmovups);
} else {
loop<Xbyak::Ymm, Xbyak::Xmm, Xbyak::Operand, Xbyak::Xmm,
Xbyak::Operand>(unroll_x, unroll_y,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vbroadcastss);
update<Xbyak::Ymm, Xbyak::Operand>(unroll_x, unroll_y, 1,
beta_zero_, &Xbyak::CodeGenerator::vaddps,
&Xbyak::CodeGenerator::vmovups,
&Xbyak::CodeGenerator::vmovups);
}
break;
}
if (mayiuse(avx512_core)) {
sub(AA_, -16 * elt_size_);
} else {
if ((unroll_y != unroll_n_) || (unroll_x <= 4)) {
if (unroll_x == unroll_m_)
sub(AA_, -16 * elt_size_);
else
sub(AA_, -32 * elt_size_);
} else
sub(AA_, -48 * elt_size_);
}
if (unroll_y == unroll_n_) {
dec(I_);
jg(unroll_y_label[i * (unroll_n_bin_ + 1) + uy_bin], T_NEAR);
}
}
L_aligned(end_n_loop_label[i]);
mov(A_, AO_);
if (unroll_x == unroll_m_) {
sub(J_, unroll_x);
cmp(J_, unroll_x);
jge(unroll_x_label[i], T_NEAR);
}
}
L_aligned(end_m_loop_label);
postamble();
}
jit_avx2_kernel_sgemm_kern::jit_avx2_kernel_sgemm_kern(bool beta_zero)
: jit_generator(nullptr, 65536) {
beta_zero_ = beta_zero;
generate();
}
}
}
}
| 37.479821 | 80 | 0.465183 | zhoub |
f3987c636add0d194e61c5fcff23adbfcc003687 | 7,577 | hpp | C++ | boost/boost/spirit/home/lex/lexer/support_functions.hpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 71 | 2015-01-17T00:29:44.000Z | 2021-02-09T02:59:16.000Z | boost/boost/spirit/home/lex/lexer/support_functions.hpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 6 | 2016-01-11T05:20:05.000Z | 2021-02-06T11:37:24.000Z | boost/boost/spirit/home/lex/lexer/support_functions.hpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 44 | 2015-03-18T09:20:37.000Z | 2021-12-21T08:09:17.000Z | // Copyright (c) 2001-2011 Hartmut Kaiser
//
// 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)
#if !defined(SPIRIT_LEX_SUPPORT_FUNCTIONS_JUN_08_2009_0211PM)
#define SPIRIT_LEX_SUPPORT_FUNCTIONS_JUN_08_2009_0211PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/home/support/detail/scoped_enum_emulation.hpp>
#include <boost/spirit/home/lex/lexer/pass_flags.hpp>
#include <boost/spirit/home/lex/lexer/support_functions_expression.hpp>
///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace lex
{
///////////////////////////////////////////////////////////////////////////
// The function object less_type is used by the implementation of the
// support function lex::less(). Its functionality is equivalent to flex'
// function yyless(): it returns an iterator positioned to the nth input
// character beyond the current start iterator (i.e. by assigning the
// return value to the placeholder '_end' it is possible to return all but
// the first n characters of the current token back to the input stream.
//
// This Phoenix actor is invoked whenever the function lex::less(n) is
// used inside a lexer semantic action:
//
// lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
// this->self = identifier [ _end = lex::less(4) ];
//
// The example shows how to limit the length of the matched identifier to
// four characters.
//
// Note: the function lex::less() has no effect if used on it's own, you
// need to use the returned result in order to make use of its
// functionality.
template <typename Actor>
struct less_type
{
typedef mpl::true_ no_nullary;
template <typename Env>
struct result
{
typedef typename
remove_const<
typename mpl::at_c<typename Env::args_type, 4>::type
>::type
context_type;
typedef typename context_type::base_iterator_type type;
};
template <typename Env>
typename result<Env>::type
eval(Env const& env) const
{
typename result<Env>::type it;
return fusion::at_c<4>(env.args()).less(it, actor_());
}
less_type(Actor const& actor)
: actor_(actor) {}
Actor actor_;
};
// The function lex::less() is used to create a Phoenix actor allowing to
// implement functionality similar to flex' function yyless().
template <typename T>
inline typename expression::less<
typename phoenix::as_actor<T>::type
>::type const
less(T const& v)
{
return expression::less<T>::make(phoenix::as_actor<T>::convert(v));
}
///////////////////////////////////////////////////////////////////////////
// The function object more_type is used by the implementation of the
// support function lex::more(). Its functionality is equivalent to flex'
// function yymore(): it tells the lexer that the next time it matches a
// rule, the corresponding token should be appended onto the current token
// value rather than replacing it.
//
// This Phoenix actor is invoked whenever the function lex::more(n) is
// used inside a lexer semantic action:
//
// lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
// this->self = identifier [ lex::more() ];
//
// The example shows how prefix the next matched token with the matched
// identifier.
struct more_type
{
typedef mpl::true_ no_nullary;
template <typename Env>
struct result
{
typedef void type;
};
template <typename Env>
void eval(Env const& env) const
{
fusion::at_c<4>(env.args()).more();
}
};
// The function lex::more() is used to create a Phoenix actor allowing to
// implement functionality similar to flex' function yymore().
//inline expression::more<mpl::void_>::type const
inline phoenix::actor<more_type> more()
{
return phoenix::actor<more_type>();
}
///////////////////////////////////////////////////////////////////////////
// The function object lookahead_type is used by the implementation of the
// support function lex::lookahead(). Its functionality is needed to
// emulate the flex' lookahead operator a/b. Use lex::lookahead() inside
// of lexer semantic actions to test whether the argument to this function
// matches the current look ahead input. lex::lookahead() can be used with
// either a token id or a token_def instance as its argument. It returns
// a bool indicating whether the look ahead has been matched.
template <typename IdActor, typename StateActor>
struct lookahead_type
{
typedef mpl::true_ no_nullary;
template <typename Env>
struct result
{
typedef bool type;
};
template <typename Env>
bool eval(Env const& env) const
{
return fusion::at_c<4>(env.args()).
lookahead(id_actor_(), state_actor_());
}
lookahead_type(IdActor const& id_actor, StateActor const& state_actor)
: id_actor_(id_actor), state_actor_(state_actor) {}
IdActor id_actor_;
StateActor state_actor_;
};
// The function lex::lookahead() is used to create a Phoenix actor
// allowing to implement functionality similar to flex' lookahead operator
// a/b.
template <typename T>
inline typename expression::lookahead<
typename phoenix::as_actor<T>::type
, typename phoenix::as_actor<std::size_t>::type
>::type const
lookahead(T const& id)
{
typedef typename phoenix::as_actor<T>::type id_actor_type;
typedef typename phoenix::as_actor<std::size_t>::type state_actor_type;
return expression::lookahead<id_actor_type, state_actor_type>::make(
phoenix::as_actor<T>::convert(id),
phoenix::as_actor<std::size_t>::convert(std::size_t(~0)));
}
template <typename Attribute, typename Char, typename Idtype>
inline typename expression::lookahead<
typename phoenix::as_actor<Idtype>::type
, typename phoenix::as_actor<std::size_t>::type
>::type const
lookahead(token_def<Attribute, Char, Idtype> const& tok)
{
typedef typename phoenix::as_actor<Idtype>::type id_actor_type;
typedef typename phoenix::as_actor<std::size_t>::type state_actor_type;
std::size_t state = tok.state();
// The following assertion fires if you pass a token_def instance to
// lex::lookahead without first associating this instance with the
// lexer.
BOOST_ASSERT(std::size_t(~0) != state &&
"token_def instance not associated with lexer yet");
return expression::lookahead<id_actor_type, state_actor_type>::make(
phoenix::as_actor<Idtype>::convert(tok.id()),
phoenix::as_actor<std::size_t>::convert(state));
}
///////////////////////////////////////////////////////////////////////////
inline BOOST_SCOPED_ENUM(pass_flags) ignore()
{
return pass_flags::pass_ignore;
}
}}}
#endif
| 36.781553 | 81 | 0.608156 | randolphwong |
f39d65531e34de6e388da58124bcb1d379d34cd6 | 71,494 | cpp | C++ | src/chrono_vehicle/terrain/SCMDeformableTerrain.cpp | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | 1 | 2021-01-03T00:54:53.000Z | 2021-01-03T00:54:53.000Z | src/chrono_vehicle/terrain/SCMDeformableTerrain.cpp | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | null | null | null | src/chrono_vehicle/terrain/SCMDeformableTerrain.cpp | Benatti1991/chrono | d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora, Radu Serban, Jay Taves
// =============================================================================
//
// Deformable terrain based on SCM (Soil Contact Model) from DLR
// (Krenn & Hirzinger)
//
// =============================================================================
#include <cstdio>
#include <cmath>
#include <queue>
#include <unordered_set>
#include <limits>
#include <omp.h>
#include "chrono/physics/ChMaterialSurfaceNSC.h"
#include "chrono/physics/ChMaterialSurfaceSMC.h"
#include "chrono/assets/ChTexture.h"
#include "chrono/assets/ChBoxShape.h"
#include "chrono/utils/ChConvexHull.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/terrain/SCMDeformableTerrain.h"
#include "chrono_thirdparty/stb/stb.h"
namespace chrono {
namespace vehicle {
// -----------------------------------------------------------------------------
// Implementation of the SCMDeformableTerrain wrapper class
// -----------------------------------------------------------------------------
SCMDeformableTerrain::SCMDeformableTerrain(ChSystem* system, bool visualization_mesh) {
m_ground = chrono_types::make_shared<SCMDeformableSoil>(system, visualization_mesh);
system->Add(m_ground);
}
// Get the initial terrain height below the specified location.
double SCMDeformableTerrain::GetInitHeight(const ChVector<>& loc) const {
return m_ground->GetInitHeight(loc);
}
// Get the initial terrain normal at the point below the specified location.
ChVector<> SCMDeformableTerrain::GetInitNormal(const ChVector<>& loc) const {
return m_ground->GetInitNormal(loc);
}
// Get the terrain height below the specified location.
double SCMDeformableTerrain::GetHeight(const ChVector<>& loc) const {
return m_ground->GetHeight(loc);
}
// Get the terrain normal at the point below the specified location.
ChVector<> SCMDeformableTerrain::GetNormal(const ChVector<>& loc) const {
return m_ground->GetNormal(loc);
}
// Return the terrain coefficient of friction at the specified location.
float SCMDeformableTerrain::GetCoefficientFriction(const ChVector<>& loc) const {
return m_friction_fun ? (*m_friction_fun)(loc) : 0.8f;
}
// Set the color of the visualization assets.
void SCMDeformableTerrain::SetColor(const ChColor& color) {
if (m_ground->m_color)
m_ground->m_color->SetColor(color);
}
// Set the texture and texture scaling.
void SCMDeformableTerrain::SetTexture(const std::string tex_file, float tex_scale_x, float tex_scale_y) {
std::shared_ptr<ChTexture> texture(new ChTexture);
texture->SetTextureFilename(tex_file);
texture->SetTextureScale(tex_scale_x, tex_scale_y);
m_ground->AddAsset(texture);
}
// Set the SCM reference plane.
void SCMDeformableTerrain::SetPlane(const ChCoordsys<>& plane) {
m_ground->m_plane = plane;
m_ground->m_Z = plane.rot.GetZaxis();
}
// Get the SCM reference plane.
const ChCoordsys<>& SCMDeformableTerrain::GetPlane() const {
return m_ground->m_plane;
}
// Set the visualization mesh as wireframe or as solid.
void SCMDeformableTerrain::SetMeshWireframe(bool val) {
if (m_ground->m_trimesh_shape)
m_ground->m_trimesh_shape->SetWireframe(val);
}
// Get the trimesh that defines the ground shape.
std::shared_ptr<ChTriangleMeshShape> SCMDeformableTerrain::GetMesh() const {
return m_ground->m_trimesh_shape;
}
// Save the visualization mesh as a Wavefront OBJ file.
void SCMDeformableTerrain::WriteMesh(const std::string& filename) const {
if (!m_ground->m_trimesh_shape) {
std::cout << "SCMDeformableTerrain::WriteMesh -- visualization mesh not created.";
return;
}
auto trimesh = m_ground->m_trimesh_shape->GetMesh();
std::vector<geometry::ChTriangleMeshConnected> meshes = {*trimesh};
trimesh->WriteWavefront(filename, meshes);
}
// Set properties of the SCM soil model.
void SCMDeformableTerrain::SetSoilParameters(
double Bekker_Kphi, // Kphi, frictional modulus in Bekker model
double Bekker_Kc, // Kc, cohesive modulus in Bekker model
double Bekker_n, // n, exponent of sinkage in Bekker model (usually 0.6...1.8)
double Mohr_cohesion, // Cohesion for shear failure [Pa]
double Mohr_friction, // Friction angle for shear failure [degree]
double Janosi_shear, // Shear parameter in Janosi-Hanamoto formula [m]
double elastic_K, // elastic stiffness K per unit area, [Pa/m] (must be larger than Kphi)
double damping_R // vertical damping R per unit area [Pa.s/m] (proportional to vertical speed)
) {
m_ground->m_Bekker_Kphi = Bekker_Kphi;
m_ground->m_Bekker_Kc = Bekker_Kc;
m_ground->m_Bekker_n = Bekker_n;
m_ground->m_Mohr_cohesion = Mohr_cohesion;
m_ground->m_Mohr_mu = std::tan(Mohr_friction * CH_C_DEG_TO_RAD);
m_ground->m_Janosi_shear = Janosi_shear;
m_ground->m_elastic_K = ChMax(elastic_K, Bekker_Kphi);
m_ground->m_damping_R = damping_R;
}
// Enable/disable bulldozing effect.
void SCMDeformableTerrain::EnableBulldozing(bool val) {
m_ground->m_bulldozing = val;
}
// Set parameters controlling the creation of side ruts (bulldozing effects).
void SCMDeformableTerrain::SetBulldozingParameters(
double erosion_angle, // angle of erosion of the displaced material [degrees]
double flow_factor, // growth of lateral volume relative to pressed volume
int erosion_iterations, // number of erosion refinements per timestep
int erosion_propagations // number of concentric vertex selections subject to erosion
) {
m_ground->m_flow_factor = flow_factor;
m_ground->m_erosion_slope = std::tan(erosion_angle * CH_C_DEG_TO_RAD);
m_ground->m_erosion_iterations = erosion_iterations;
m_ground->m_erosion_propagations = erosion_propagations;
}
void SCMDeformableTerrain::SetTestHeight(double offset) {
m_ground->m_test_offset_up = offset;
}
double SCMDeformableTerrain::GetTestHeight() const {
return m_ground->m_test_offset_up;
}
// Set the color plot type.
void SCMDeformableTerrain::SetPlotType(DataPlotType plot_type, double min_val, double max_val) {
m_ground->m_plot_type = plot_type;
m_ground->m_plot_v_min = min_val;
m_ground->m_plot_v_max = max_val;
}
// Enable moving patch.
void SCMDeformableTerrain::AddMovingPatch(std::shared_ptr<ChBody> body,
const ChVector<>& OOBB_center,
const ChVector<>& OOBB_dims) {
SCMDeformableSoil::MovingPatchInfo pinfo;
pinfo.m_body = body;
pinfo.m_center = OOBB_center;
pinfo.m_hdims = OOBB_dims / 2;
m_ground->m_patches.push_back(pinfo);
// Moving patch monitoring is now enabled
m_ground->m_moving_patch = true;
}
// Set user-supplied callback for evaluating location-dependent soil parameters.
void SCMDeformableTerrain::RegisterSoilParametersCallback(std::shared_ptr<SoilParametersCallback> cb) {
m_ground->m_soil_fun = cb;
}
// Initialize the terrain as a flat grid.
void SCMDeformableTerrain::Initialize(double sizeX, double sizeY, double delta) {
m_ground->Initialize(sizeX, sizeY, delta);
}
// Initialize the terrain from a specified height map.
void SCMDeformableTerrain::Initialize(const std::string& heightmap_file,
double sizeX,
double sizeY,
double hMin,
double hMax,
double delta) {
m_ground->Initialize(heightmap_file, sizeX, sizeY, hMin, hMax, delta);
}
// Get the heights of modified grid nodes.
std::vector<SCMDeformableTerrain::NodeLevel> SCMDeformableTerrain::GetModifiedNodes(bool all_nodes) const {
return m_ground->GetModifiedNodes(all_nodes);
}
// Modify the level of grid nodes from the given list.
void SCMDeformableTerrain::SetModifiedNodes(const std::vector<NodeLevel>& nodes) {
m_ground->SetModifiedNodes(nodes);
}
// Return the current cumulative contact force on the specified body (due to interaction with the SCM terrain).
TerrainForce SCMDeformableTerrain::GetContactForce(std::shared_ptr<ChBody> body) const {
auto itr = m_ground->m_contact_forces.find(body.get());
if (itr != m_ground->m_contact_forces.end())
return itr->second;
TerrainForce frc;
frc.point = body->GetPos();
frc.force = ChVector<>(0, 0, 0);
frc.moment = ChVector<>(0, 0, 0);
return frc;
}
// Return the number of rays cast at last step.
int SCMDeformableTerrain::GetNumRayCasts() const {
return m_ground->m_num_ray_casts;
}
// Return the number of ray hits at last step.
int SCMDeformableTerrain::GetNumRayHits() const {
return m_ground->m_num_ray_hits;
}
// Return the number of contact patches at last step.
int SCMDeformableTerrain::GetNumContactPatches() const {
return m_ground->m_num_contact_patches;
}
// Return the number of nodes in the erosion domain at last step (bulldosing effects).
int SCMDeformableTerrain::GetNumErosionNodes() const {
return m_ground->m_num_erosion_nodes;
}
// Timer information
double SCMDeformableTerrain::GetTimerMovingPatches() const {
return 1e3 * m_ground->m_timer_moving_patches();
}
double SCMDeformableTerrain::GetTimerRayTesting() const {
return 1e3 * m_ground->m_timer_ray_testing();
}
double SCMDeformableTerrain::GetTimerRayCasting() const {
return 1e3 * m_ground->m_timer_ray_casting();
}
double SCMDeformableTerrain::GetTimerContactPatches() const {
return 1e3 * m_ground->m_timer_contact_patches();
}
double SCMDeformableTerrain::GetTimerContactForces() const {
return 1e3 * m_ground->m_timer_contact_forces();
}
double SCMDeformableTerrain::GetTimerBulldozing() const {
return 1e3 * m_ground->m_timer_bulldozing();
}
double SCMDeformableTerrain::GetTimerVisUpdate() const {
return 1e3 * m_ground->m_timer_visualization();
}
// Print timing and counter information for last step.
void SCMDeformableTerrain::PrintStepStatistics(std::ostream& os) const {
os << " Timers (ms):" << std::endl;
os << " Moving patches: " << 1e3 * m_ground->m_timer_moving_patches() << std::endl;
os << " Ray testing: " << 1e3 * m_ground->m_timer_ray_testing() << std::endl;
os << " Ray casting: " << 1e3 * m_ground->m_timer_ray_casting() << std::endl;
os << " Contact patches: " << 1e3 * m_ground->m_timer_contact_patches() << std::endl;
os << " Contact forces: " << 1e3 * m_ground->m_timer_contact_forces() << std::endl;
os << " Bulldozing: " << 1e3 * m_ground->m_timer_bulldozing() << std::endl;
os << " Raise boundary: " << 1e3 * m_ground->m_timer_bulldozing_boundary() << std::endl;
os << " Compute domain: " << 1e3 * m_ground->m_timer_bulldozing_domain() << std::endl;
os << " Apply erosion: " << 1e3 * m_ground->m_timer_bulldozing_erosion() << std::endl;
os << " Visualization: " << 1e3 * m_ground->m_timer_visualization() << std::endl;
os << " Counters:" << std::endl;
os << " Number ray casts: " << m_ground->m_num_ray_casts << std::endl;
os << " Number ray hits: " << m_ground->m_num_ray_hits << std::endl;
os << " Number contact patches: " << m_ground->m_num_contact_patches << std::endl;
os << " Number erosion nodes: " << m_ground->m_num_erosion_nodes << std::endl;
}
// -----------------------------------------------------------------------------
// Contactable user-data (contactable-soil parameters)
// -----------------------------------------------------------------------------
SCMContactableData::SCMContactableData(double area_ratio,
double Mohr_cohesion,
double Mohr_friction,
double Janosi_shear)
: area_ratio(area_ratio),
Mohr_cohesion(Mohr_cohesion),
Mohr_mu(std::tan(Mohr_friction * CH_C_DEG_TO_RAD)),
Janosi_shear(Janosi_shear) {}
// -----------------------------------------------------------------------------
// Implementation of SCMDeformableSoil
// -----------------------------------------------------------------------------
// Constructor.
SCMDeformableSoil::SCMDeformableSoil(ChSystem* system, bool visualization_mesh) : m_soil_fun(nullptr) {
this->SetSystem(system);
if (visualization_mesh) {
// Create the visualization mesh and asset
m_trimesh_shape = std::shared_ptr<ChTriangleMeshShape>(new ChTriangleMeshShape);
m_trimesh_shape->SetWireframe(true);
m_trimesh_shape->SetFixedConnectivity();
this->AddAsset(m_trimesh_shape);
// Create the default mesh asset
m_color = std::shared_ptr<ChColorAsset>(new ChColorAsset);
m_color->SetColor(ChColor(0.3f, 0.3f, 0.3f));
this->AddAsset(m_color);
}
// Default SCM plane and plane normal
m_plane = ChCoordsys<>(VNULL, QUNIT);
m_Z = m_plane.rot.GetZaxis();
// Bulldozing effects
m_bulldozing = false;
m_flow_factor = 1.2;
m_erosion_slope = std::tan(40.0 * CH_C_DEG_TO_RAD);
m_erosion_iterations = 3;
m_erosion_propagations = 10;
// Default soil parameters
m_Bekker_Kphi = 2e6;
m_Bekker_Kc = 0;
m_Bekker_n = 1.1;
m_Mohr_cohesion = 50;
m_Mohr_mu = std::tan(20.0 * CH_C_DEG_TO_RAD);
m_Janosi_shear = 0.01;
m_elastic_K = 50000000;
m_damping_R = 0;
m_plot_type = SCMDeformableTerrain::PLOT_NONE;
m_plot_v_min = 0;
m_plot_v_max = 0.2;
m_test_offset_up = 0.1;
m_test_offset_down = 0.5;
m_moving_patch = false;
}
// Initialize the terrain as a flat grid
void SCMDeformableSoil::Initialize(double sizeX, double sizeY, double delta) {
m_type = PatchType::FLAT;
m_nx = static_cast<int>(std::ceil((sizeX / 2) / delta)); // half number of divisions in X direction
m_ny = static_cast<int>(std::ceil((sizeY / 2) / delta)); // number of divisions in Y direction
m_delta = sizeX / (2 * m_nx); // grid spacing
m_area = std::pow(m_delta, 2); // area of a cell
// Return now if no visualization
if (!m_trimesh_shape)
return;
int nvx = 2 * m_nx + 1; // number of grid vertices in X direction
int nvy = 2 * m_ny + 1; // number of grid vertices in Y direction
int n_verts = nvx * nvy; // total number of vertices for initial visualization trimesh
int n_faces = 2 * (2 * m_nx) * (2 * m_ny); // total number of faces for initial visualization trimesh
double x_scale = 0.5 / m_nx; // scale for texture coordinates (U direction)
double y_scale = 0.5 / m_ny; // scale for texture coordinates (V direction)
// Readability aliases
auto trimesh = m_trimesh_shape->GetMesh();
trimesh->Clear();
std::vector<ChVector<>>& vertices = trimesh->getCoordsVertices();
std::vector<ChVector<>>& normals = trimesh->getCoordsNormals();
std::vector<ChVector<int>>& idx_vertices = trimesh->getIndicesVertexes();
std::vector<ChVector<int>>& idx_normals = trimesh->getIndicesNormals();
std::vector<ChVector<>>& uv_coords = trimesh->getCoordsUV();
std::vector<ChVector<float>>& colors = trimesh->getCoordsColors();
// Resize mesh arrays
vertices.resize(n_verts);
normals.resize(n_verts);
uv_coords.resize(n_verts);
colors.resize(n_verts);
idx_vertices.resize(n_faces);
idx_normals.resize(n_faces);
// Load mesh vertices.
// We order the vertices starting at the bottom-left corner, row after row.
// The bottom-left corner corresponds to the point (-sizeX/2, -sizeY/2).
// UV coordinates are mapped in [0,1] x [0,1].
int iv = 0;
for (int iy = 0; iy < nvy; iy++) {
double y = iy * m_delta - 0.5 * sizeY;
for (int ix = 0; ix < nvx; ix++) {
double x = ix * m_delta - 0.5 * sizeX;
// Set vertex location
vertices[iv] = m_plane * ChVector<>(x, y, 0);
// Initialize vertex normal to Y up
normals[iv] = m_plane.TransformDirectionLocalToParent(ChVector<>(0, 0, 1));
// Assign color white to all vertices
colors[iv] = ChVector<float>(1, 1, 1);
// Set UV coordinates in [0,1] x [0,1]
uv_coords[iv] = ChVector<>(ix * x_scale, iy * y_scale, 0.0);
++iv;
}
}
// Specify triangular faces (two at a time).
// Specify the face vertices counter-clockwise.
// Set the normal indices same as the vertex indices.
int it = 0;
for (int iy = 0; iy < nvy - 1; iy++) {
for (int ix = 0; ix < nvx - 1; ix++) {
int v0 = ix + nvx * iy;
idx_vertices[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1);
idx_normals[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1);
++it;
idx_vertices[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx);
idx_normals[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx);
++it;
}
}
}
// Initialize the terrain from a specified height map.
void SCMDeformableSoil::Initialize(const std::string& heightmap_file,
double sizeX,
double sizeY,
double hMin,
double hMax,
double delta) {
m_type = PatchType::HEIGHT_MAP;
// Read the image file (request only 1 channel) and extract number of pixels.
STB hmap;
if (!hmap.ReadFromFile(heightmap_file, 1)) {
std::cout << "STB error in reading height map file " << heightmap_file << std::endl;
throw ChException("Cannot read height map image file");
}
int nx_img = hmap.GetWidth();
int ny_img = hmap.GetHeight();
double dx_img = 1.0 / (nx_img - 1.0);
double dy_img = 1.0 / (ny_img - 1.0);
m_nx = static_cast<int>(std::ceil((sizeX / 2) / delta)); // half number of divisions in X direction
m_ny = static_cast<int>(std::ceil((sizeY / 2) / delta)); // number of divisions in Y direction
m_delta = sizeX / (2.0 * m_nx); // grid spacing
m_area = std::pow(m_delta, 2); // area of a cell
double dx_grid = 0.5 / m_nx;
double dy_grid = 0.5 / m_ny;
int nvx = 2 * m_nx + 1; // number of grid vertices in X direction
int nvy = 2 * m_ny + 1; // number of grid vertices in Y direction
int n_verts = nvx * nvy; // total number of vertices for initial visualization trimesh
int n_faces = 2 * (2 * m_nx) * (2 * m_ny); // total number of faces for initial visualization trimesh
double x_scale = 0.5 / m_nx; // scale for texture coordinates (U direction)
double y_scale = 0.5 / m_ny; // scale for texture coordinates (V direction)
// Resample image and calculate interpolated gray levels and then map it to the height range, with black
// corresponding to hMin and white corresponding to hMax. Entry (0,0) corresponds to bottom-left grid vertex.
// Note that pixels in the image start at top-left corner.
double h_scale = (hMax - hMin) / hmap.GetRange();
m_heights = ChMatrixDynamic<>(nvx, nvy);
for (int ix = 0; ix < nvx; ix++) {
double x = ix * dx_grid; // x location in image (in [0,1], 0 at left)
int jx1 = (int)std::floor(x / dx_img); // Left pixel
int jx2 = (int)std::ceil(x / dx_img); // Right pixel
double ax = (x - jx1 * dx_img) / dx_img; // Scaled offset from left pixel
assert(ax < 1.0);
assert(jx1 < nx_img);
assert(jx2 < nx_img);
assert(jx1 <= jx2);
for (int iy = 0; iy < nvy; iy++) {
double y = (2 * m_ny - iy) * dy_grid; // y location in image (in [0,1], 0 at top)
int jy1 = (int)std::floor(y / dy_img); // Up pixel
int jy2 = (int)std::ceil(y / dy_img); // Down pixel
double ay = (y - jy1 * dy_img) / dy_img; // Scaled offset from down pixel
assert(ay < 1.0);
assert(jy1 < ny_img);
assert(jy2 < ny_img);
assert(jy1 <= jy2);
// Gray levels at left-up, left-down, right-up, and right-down pixels
double g11 = hmap.Gray(jx1, jy1);
double g12 = hmap.Gray(jx1, jy2);
double g21 = hmap.Gray(jx2, jy1);
double g22 = hmap.Gray(jx2, jy2);
// Bilinear interpolation (gray level)
m_heights(ix, iy) = (1 - ax) * (1 - ay) * g11 + (1 - ax) * ay * g12 + ax * (1 - ay) * g21 + ax * ay * g22;
// Map into height range
m_heights(ix, iy) = hMin + m_heights(ix, iy) * h_scale;
}
}
// Return now if no visualization
if (!m_trimesh_shape)
return;
// Readability aliases
auto trimesh = m_trimesh_shape->GetMesh();
trimesh->Clear();
std::vector<ChVector<>>& vertices = trimesh->getCoordsVertices();
std::vector<ChVector<>>& normals = trimesh->getCoordsNormals();
std::vector<ChVector<int>>& idx_vertices = trimesh->getIndicesVertexes();
std::vector<ChVector<int>>& idx_normals = trimesh->getIndicesNormals();
std::vector<ChVector<>>& uv_coords = trimesh->getCoordsUV();
std::vector<ChVector<float>>& colors = trimesh->getCoordsColors();
// Resize mesh arrays.
vertices.resize(n_verts);
normals.resize(n_verts);
uv_coords.resize(n_verts);
colors.resize(n_verts);
idx_vertices.resize(n_faces);
idx_normals.resize(n_faces);
// Load mesh vertices.
// We order the vertices starting at the bottom-left corner, row after row.
// The bottom-left corner corresponds to the point (-sizeX/2, -sizeY/2).
// UV coordinates are mapped in [0,1] x [0,1]. Use smoothed vertex normals.
int iv = 0;
for (int iy = 0; iy < nvy; iy++) {
double y = iy * m_delta - 0.5 * sizeY;
for (int ix = 0; ix < nvx; ix++) {
double x = ix * m_delta - 0.5 * sizeX;
// Set vertex location
vertices[iv] = m_plane * ChVector<>(x, y, m_heights(ix, iy));
// Initialize vertex normal to Y up
normals[iv] = m_plane.TransformDirectionLocalToParent(ChVector<>(0, 0, 1));
// Assign color white to all vertices
colors[iv] = ChVector<float>(1, 1, 1);
// Set UV coordinates in [0,1] x [0,1]
uv_coords[iv] = ChVector<>(ix * x_scale, iy * y_scale, 0.0);
++iv;
}
}
// Specify triangular faces (two at a time).
// Specify the face vertices counter-clockwise.
// Set the normal indices same as the vertex indices.
int it = 0;
for (int iy = 0; iy < nvy - 1; iy++) {
for (int ix = 0; ix < nvx - 1; ix++) {
int v0 = ix + nvx * iy;
idx_vertices[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1);
idx_normals[it] = ChVector<int>(v0, v0 + 1, v0 + nvx + 1);
++it;
idx_vertices[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx);
idx_normals[it] = ChVector<int>(v0, v0 + nvx + 1, v0 + nvx);
++it;
}
}
// Initialize the array of accumulators (number of adjacent faces to a vertex)
std::vector<int> accumulators(n_verts, 0);
// Calculate normals and then average the normals from all adjacent faces.
for (it = 0; it < n_faces; it++) {
// Calculate the triangle normal as a normalized cross product.
ChVector<> nrm = Vcross(vertices[idx_vertices[it][1]] - vertices[idx_vertices[it][0]],
vertices[idx_vertices[it][2]] - vertices[idx_vertices[it][0]]);
nrm.Normalize();
// Increment the normals of all incident vertices by the face normal
normals[idx_normals[it][0]] += nrm;
normals[idx_normals[it][1]] += nrm;
normals[idx_normals[it][2]] += nrm;
// Increment the count of all incident vertices by 1
accumulators[idx_normals[it][0]] += 1;
accumulators[idx_normals[it][1]] += 1;
accumulators[idx_normals[it][2]] += 1;
}
// Set the normals to the average values.
for (int in = 0; in < n_verts; in++) {
normals[in] /= (double)accumulators[in];
}
}
void SCMDeformableSoil::SetupInitial() {
// If no user-specified moving patches, create one that will encompass all collision shapes in the system
if (!m_moving_patch) {
SCMDeformableSoil::MovingPatchInfo pinfo;
pinfo.m_body = nullptr;
m_patches.push_back(pinfo);
}
}
bool SCMDeformableSoil::CheckMeshBounds(const ChVector2<int>& loc) const {
return loc.x() >= -m_nx && loc.x() <= m_nx && loc.y() >= -m_ny && loc.y() <= m_ny;
}
// Get index of trimesh vertex corresponding to the specified grid vertex.
int SCMDeformableSoil::GetMeshVertexIndex(const ChVector2<int>& loc) {
assert(loc.x() >= -m_nx);
assert(loc.x() <= +m_nx);
assert(loc.y() >= -m_ny);
assert(loc.y() <= +m_ny);
return (loc.x() + m_nx) + (2 * m_nx + 1) * (loc.y() + m_ny);
}
// Get indices of trimesh faces incident to the specified grid vertex.
std::vector<int> SCMDeformableSoil::GetMeshFaceIndices(const ChVector2<int>& loc) {
int i = loc.x();
int j = loc.y();
// Ignore boundary vertices
if (i == -m_nx || i == m_nx || j == -m_ny || j == m_ny)
return std::vector<int>();
// Load indices of 6 adjacent faces
i += m_nx;
j += m_ny;
int nx = 2 * m_nx;
std::vector<int> faces(6);
faces[0] = 2 * ((i - 1) + nx * (j - 1));
faces[1] = 2 * ((i - 1) + nx * (j - 1)) + 1;
faces[2] = 2 * ((i - 1) + nx * (j - 0));
faces[3] = 2 * ((i - 0) + nx * (j - 0));
faces[4] = 2 * ((i - 0) + nx * (j - 0)) + 1;
faces[5] = 2 * ((i - 0) + nx * (j - 1)) + 1;
return faces;
}
// Get the initial undeformed terrain height (relative to the SCM plane) at the specified grid vertex.
double SCMDeformableSoil::GetInitHeight(const ChVector2<int>& loc) const {
switch (m_type) {
case PatchType::FLAT:
return 0;
case PatchType::HEIGHT_MAP: {
auto x = ChClamp(loc.x(), -m_nx, +m_nx);
auto y = ChClamp(loc.y(), -m_ny, +m_ny);
return m_heights(x + m_nx, y + m_ny);
}
default:
return 0;
}
}
// Get the initial undeformed terrain normal (relative to the SCM plane) at the specified grid node.
ChVector<> SCMDeformableSoil::GetInitNormal(const ChVector2<int>& loc) const {
switch (m_type) {
case PatchType::HEIGHT_MAP: {
// Average normals of 4 triangular faces incident to given grid node
auto hE = GetInitHeight(loc + ChVector2<int>(1, 0)); // east
auto hW = GetInitHeight(loc - ChVector2<int>(1, 0)); // west
auto hN = GetInitHeight(loc + ChVector2<int>(0, 1)); // north
auto hS = GetInitHeight(loc - ChVector2<int>(0, 1)); // south
return ChVector<>(hW - hE, hS - hN, 2 * m_delta).GetNormalized();
}
case PatchType::FLAT:
default:
return ChVector<>(0, 0, 1);
}
}
// Get the terrain height (relative to the SCM plane) at the specified grid vertex.
double SCMDeformableSoil::GetHeight(const ChVector2<int>& loc) const {
// First query the hash-map
auto p = m_grid_map.find(loc);
if (p != m_grid_map.end())
return p->second.level;
// Else return undeformed height
return GetInitHeight(loc);
}
// Get the terrain normal (relative to the SCM plane) at the specified grid vertex.
ChVector<> SCMDeformableSoil::GetNormal(const ChVector2<>& loc) const {
switch (m_type) {
case PatchType::HEIGHT_MAP: {
// Average normals of 4 triangular faces incident to given grid node
auto hE = GetHeight(loc + ChVector2<int>(1, 0)); // east
auto hW = GetHeight(loc - ChVector2<int>(1, 0)); // west
auto hN = GetHeight(loc + ChVector2<int>(0, 1)); // north
auto hS = GetHeight(loc - ChVector2<int>(0, 1)); // south
return ChVector<>(hW - hE, hS - hN, 2 * m_delta).GetNormalized();
}
case PatchType::FLAT:
default:
return ChVector<>(0, 0, 1);
}
}
// Get the initial terrain height below the specified location.
double SCMDeformableSoil::GetInitHeight(const ChVector<>& loc) const {
// Express location in the SCM frame
ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc);
// Get height (relative to SCM plane) at closest grid vertex (approximation)
int i = static_cast<int>(std::round(loc_loc.x() / m_delta));
int j = static_cast<int>(std::round(loc_loc.y() / m_delta));
loc_loc.z() = GetInitHeight(ChVector2<int>(i, j));
// Express in global frame
ChVector<> loc_abs = m_plane.TransformPointLocalToParent(loc_loc);
return ChWorldFrame::Height(loc_abs);
}
// Get the initial terrain normal at the point below the specified location.
ChVector<> SCMDeformableSoil::GetInitNormal(const ChVector<>& loc) const {
// Express location in the SCM frame
ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc);
// Get height (relative to SCM plane) at closest grid vertex (approximation)
int i = static_cast<int>(std::round(loc_loc.x() / m_delta));
int j = static_cast<int>(std::round(loc_loc.y() / m_delta));
auto nrm_loc = GetInitNormal(ChVector2<int>(i, j));
// Express in global frame
auto nrm_abs = m_plane.TransformDirectionLocalToParent(nrm_loc);
return ChWorldFrame::FromISO(nrm_abs);
}
// Get the terrain height below the specified location.
double SCMDeformableSoil::GetHeight(const ChVector<>& loc) const {
// Express location in the SCM frame
ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc);
// Get height (relative to SCM plane) at closest grid vertex (approximation)
int i = static_cast<int>(std::round(loc_loc.x() / m_delta));
int j = static_cast<int>(std::round(loc_loc.y() / m_delta));
loc_loc.z() = GetHeight(ChVector2<int>(i, j));
// Express in global frame
ChVector<> loc_abs = m_plane.TransformPointLocalToParent(loc_loc);
return ChWorldFrame::Height(loc_abs);
}
// Get the terrain normal at the point below the specified location.
ChVector<> SCMDeformableSoil::GetNormal(const ChVector<>& loc) const {
// Express location in the SCM frame
ChVector<> loc_loc = m_plane.TransformPointParentToLocal(loc);
// Get height (relative to SCM plane) at closest grid vertex (approximation)
int i = static_cast<int>(std::round(loc_loc.x() / m_delta));
int j = static_cast<int>(std::round(loc_loc.y() / m_delta));
auto nrm_loc = GetNormal(ChVector2<int>(i, j));
// Express in global frame
auto nrm_abs = m_plane.TransformDirectionLocalToParent(nrm_loc);
return ChWorldFrame::FromISO(nrm_abs);
}
// Synchronize information for a moving patch
void SCMDeformableSoil::UpdateMovingPatch(MovingPatchInfo& p, const ChVector<>& Z) {
ChVector2<> p_min(+std::numeric_limits<double>::max());
ChVector2<> p_max(-std::numeric_limits<double>::max());
// Loop over all corners of the OOBB
for (int j = 0; j < 8; j++) {
int ix = j % 2;
int iy = (j / 2) % 2;
int iz = (j / 4);
// OOBB corner in body frame
ChVector<> c_body = p.m_center + p.m_hdims * ChVector<>(2.0 * ix - 1, 2.0 * iy - 1, 2.0 * iz - 1);
// OOBB corner in absolute frame
ChVector<> c_abs = p.m_body->GetFrame_REF_to_abs().TransformPointLocalToParent(c_body);
// OOBB corner expressed in SCM frame
ChVector<> c_scm = m_plane.TransformPointParentToLocal(c_abs);
// Update AABB of patch projection onto SCM plane
p_min.x() = std::min(p_min.x(), c_scm.x());
p_min.y() = std::min(p_min.y(), c_scm.y());
p_max.x() = std::max(p_max.x(), c_scm.x());
p_max.y() = std::max(p_max.y(), c_scm.y());
}
// Find index ranges for grid vertices contained in the patch projection AABB
int x_min = static_cast<int>(std::ceil(p_min.x() / m_delta));
int y_min = static_cast<int>(std::ceil(p_min.y() / m_delta));
int x_max = static_cast<int>(std::floor(p_max.x() / m_delta));
int y_max = static_cast<int>(std::floor(p_max.y() / m_delta));
int n_x = x_max - x_min + 1;
int n_y = y_max - y_min + 1;
p.m_range.resize(n_x * n_y);
for (int i = 0; i < n_x; i++) {
for (int j = 0; j < n_y; j++) {
p.m_range[j * n_x + i] = ChVector2<int>(i + x_min, j + y_min);
}
}
// Calculate inverse of SCM normal expressed in body frame (for optimization of ray-OBB test)
ChVector<> dir = p.m_body->TransformDirectionParentToLocal(Z);
p.m_ooN.x() = (dir.x() == 0) ? 1e10 : 1.0 / dir.x();
p.m_ooN.y() = (dir.y() == 0) ? 1e10 : 1.0 / dir.y();
p.m_ooN.z() = (dir.z() == 0) ? 1e10 : 1.0 / dir.z();
}
// Synchronize information for fixed patch
void SCMDeformableSoil::UpdateFixedPatch(MovingPatchInfo& p) {
ChVector2<> p_min(+std::numeric_limits<double>::max());
ChVector2<> p_max(-std::numeric_limits<double>::max());
// Get current bounding box (AABB) of all collision shapes
ChVector<> aabb_min;
ChVector<> aabb_max;
GetSystem()->GetCollisionSystem()->GetBoundingBox(aabb_min, aabb_max);
// Loop over all corners of the AABB
for (int j = 0; j < 8; j++) {
int ix = j % 2;
int iy = (j / 2) % 2;
int iz = (j / 4);
// AABB corner in absolute frame
ChVector<> c_abs = aabb_max * ChVector<>(ix, iy, iz) + aabb_min * ChVector<>(1.0 - ix, 1.0 - iy, 1.0 - iz);
// AABB corner in SCM frame
ChVector<> c_scm = m_plane.TransformPointParentToLocal(c_abs);
// Update AABB of patch projection onto SCM plane
p_min.x() = std::min(p_min.x(), c_scm.x());
p_min.y() = std::min(p_min.y(), c_scm.y());
p_max.x() = std::max(p_max.x(), c_scm.x());
p_max.y() = std::max(p_max.y(), c_scm.y());
}
// Find index ranges for grid vertices contained in the patch projection AABB
int x_min = static_cast<int>(std::ceil(p_min.x() / m_delta));
int y_min = static_cast<int>(std::ceil(p_min.y() / m_delta));
int x_max = static_cast<int>(std::floor(p_max.x() / m_delta));
int y_max = static_cast<int>(std::floor(p_max.y() / m_delta));
int n_x = x_max - x_min + 1;
int n_y = y_max - y_min + 1;
p.m_range.resize(n_x * n_y);
for (int i = 0; i < n_x; i++) {
for (int j = 0; j < n_y; j++) {
p.m_range[j * n_x + i] = ChVector2<int>(i + x_min, j + y_min);
}
}
}
// Ray-OBB intersection test
bool SCMDeformableSoil::RayOBBtest(const MovingPatchInfo& p, const ChVector<>& from, const ChVector<>& Z) {
// Express ray origin in OBB frame
ChVector<> orig = p.m_body->TransformPointParentToLocal(from) - p.m_center;
// Perform ray-AABB test (slab tests)
double t1 = (-p.m_hdims.x() - orig.x()) * p.m_ooN.x();
double t2 = (+p.m_hdims.x() - orig.x()) * p.m_ooN.x();
double t3 = (-p.m_hdims.y() - orig.y()) * p.m_ooN.y();
double t4 = (+p.m_hdims.y() - orig.y()) * p.m_ooN.y();
double t5 = (-p.m_hdims.z() - orig.z()) * p.m_ooN.z();
double t6 = (+p.m_hdims.z() - orig.z()) * p.m_ooN.z();
double tmin = std::max(std::max(std::min(t1, t2), std::min(t3, t4)), std::min(t5, t6));
double tmax = std::min(std::min(std::max(t1, t2), std::max(t3, t4)), std::max(t5, t6));
if (tmax < 0)
return false;
if (tmin > tmax)
return false;
return true;
}
// Offsets for the 8 neighbors of a grid vertex
static const std::vector<ChVector2<int>> neighbors8{
ChVector2<int>(-1, -1), // SW
ChVector2<int>(0, -1), // S
ChVector2<int>(1, -1), // SE
ChVector2<int>(-1, 0), // W
ChVector2<int>(1, 0), // E
ChVector2<int>(-1, 1), // NW
ChVector2<int>(0, 1), // N
ChVector2<int>(1, 1) // NE
};
static const std::vector<ChVector2<int>> neighbors4{
ChVector2<int>(0, -1), // S
ChVector2<int>(-1, 0), // W
ChVector2<int>(1, 0), // E
ChVector2<int>(0, 1) // N
};
// Default implementation uses Map-Reduce for collecting ray intersection hits.
// The alternative is to simultaenously load the global map of hits while ray casting (using a critical section).
////#define RAY_CASTING_WITH_CRITICAL_SECTION
// Reset the list of forces, and fills it with forces from a soil contact model.
void SCMDeformableSoil::ComputeInternalForces() {
// Initialize list of modified visualization mesh vertices (use any externally modified vertices)
std::vector<int> modified_vertices = m_external_modified_vertices;
m_external_modified_vertices.clear();
// Reset quantities at grid nodes modified over previous step
// (required for bulldozing effects and for proper visualization coloring)
for (const auto& ij : m_modified_nodes) {
auto& nr = m_grid_map.at(ij);
nr.sigma = 0;
nr.sinkage_elastic = 0;
nr.step_plastic_flow = 0;
nr.erosion = false;
nr.hit_level = 1e9;
// Update visualization (only color changes relevant here)
if (m_trimesh_shape && CheckMeshBounds(ij)) {
int iv = GetMeshVertexIndex(ij); // mesh vertex index
UpdateMeshVertexCoordinates(ij, iv, nr); // update vertex coordinates and color
modified_vertices.push_back(iv);
}
}
m_modified_nodes.clear();
// Reset timers
m_timer_moving_patches.reset();
m_timer_ray_testing.reset();
m_timer_ray_casting.reset();
m_timer_contact_patches.reset();
m_timer_contact_forces.reset();
m_timer_bulldozing.reset();
m_timer_bulldozing_boundary.reset();
m_timer_bulldozing_domain.reset();
m_timer_bulldozing_erosion.reset();
m_timer_visualization.reset();
// Reset the load list and map of contact forces
this->GetLoadList().clear();
m_contact_forces.clear();
// ---------------------
// Update moving patches
// ---------------------
m_timer_moving_patches.start();
// Update patch information (find range of grid indices)
if (m_moving_patch) {
for (auto& p : m_patches)
UpdateMovingPatch(p, m_Z);
} else {
assert(m_patches.size() == 1);
UpdateFixedPatch(m_patches[0]);
}
m_timer_moving_patches.stop();
// -------------------------
// Perform ray casting tests
// -------------------------
// Information of vertices with ray-cast hits
struct HitRecord {
ChContactable* contactable; // pointer to hit object
ChVector<> abs_point; // hit point, expressed in global frame
int patch_id; // index of associated patch id
};
// Hash-map for vertices with ray-cast hits
std::unordered_map<ChVector2<int>, HitRecord, CoordHash> hits;
m_num_ray_casts = 0;
m_num_ray_hits = 0;
m_timer_ray_casting.start();
#ifdef RAY_CASTING_WITH_CRITICAL_SECTION
int nthreads = GetSystem()->GetNumThreadsChrono();
// Loop through all moving patches (user-defined or default one)
for (auto& p : m_patches) {
// Loop through all vertices in the patch range
int num_ray_casts = 0;
#pragma omp parallel for num_threads(nthreads) reduction(+ : num_ray_casts)
for (int k = 0; k < p.m_range.size(); k++) {
ChVector2<int> ij = p.m_range[k];
// Move from (i, j) to (x, y, z) representation in the world frame
double x = ij.x() * m_delta;
double y = ij.y() * m_delta;
double z;
#pragma omp critical(SCM_ray_casting)
z = GetHeight(ij);
ChVector<> vertex_abs = m_plane.TransformPointLocalToParent(ChVector<>(x, y, z));
// Create ray at current grid location
collision::ChCollisionSystem::ChRayhitResult mrayhit_result;
ChVector<> to = vertex_abs + m_Z * m_test_offset_up;
ChVector<> from = to - m_Z * m_test_offset_down;
// Ray-OBB test (quick rejection)
if (m_moving_patch && !RayOBBtest(p, from, m_Z))
continue;
// Cast ray into collision system
GetSystem()->GetCollisionSystem()->RayHit(from, to, mrayhit_result);
num_ray_casts++;
if (mrayhit_result.hit) {
#pragma omp critical(SCM_ray_casting)
{
// If this is the first hit from this node, initialize the node record
if (m_grid_map.find(ij) == m_grid_map.end()) {
m_grid_map.insert(std::make_pair(ij, NodeRecord(z, z, GetInitNormal(ij))));
}
// Add to our map of hits to process
HitRecord record = {mrayhit_result.hitModel->GetContactable(), mrayhit_result.abs_hitPoint, -1};
hits.insert(std::make_pair(ij, record));
m_num_ray_hits++;
}
}
}
m_num_ray_casts += num_ray_casts;
}
#else
// Map-reduce approach (to eliminate critical section)
const int nthreads = GetSystem()->GetNumThreadsChrono();
std::vector<std::unordered_map<ChVector2<int>, HitRecord, CoordHash>> t_hits(nthreads);
// Loop through all moving patches (user-defined or default one)
for (auto& p : m_patches) {
m_timer_ray_testing.start();
// Loop through all vertices in the patch range
int num_ray_casts = 0;
#pragma omp parallel for num_threads(nthreads) reduction(+:num_ray_casts)
for (int k = 0; k < p.m_range.size(); k++) {
int t_num = omp_get_thread_num();
ChVector2<int> ij = p.m_range[k];
// Move from (i, j) to (x, y, z) representation in the world frame
double x = ij.x() * m_delta;
double y = ij.y() * m_delta;
double z = GetHeight(ij);
ChVector<> vertex_abs = m_plane.TransformPointLocalToParent(ChVector<>(x, y, z));
// Create ray at current grid location
collision::ChCollisionSystem::ChRayhitResult mrayhit_result;
ChVector<> to = vertex_abs + m_Z * m_test_offset_up;
ChVector<> from = to - m_Z * m_test_offset_down;
// Ray-OBB test (quick rejection)
if (m_moving_patch && !RayOBBtest(p, from, m_Z))
continue;
// Cast ray into collision system
GetSystem()->GetCollisionSystem()->RayHit(from, to, mrayhit_result);
num_ray_casts++;
if (mrayhit_result.hit) {
// Add to our map of hits to process
HitRecord record = {mrayhit_result.hitModel->GetContactable(), mrayhit_result.abs_hitPoint, -1};
t_hits[t_num].insert(std::make_pair(ij, record));
}
}
m_timer_ray_testing.stop();
m_num_ray_casts += num_ray_casts;
// Sequential insertion in global hits
for (int t_num = 0; t_num < nthreads; t_num++) {
for (auto& h : t_hits[t_num]) {
// If this is the first hit from this node, initialize the node record
if (m_grid_map.find(h.first) == m_grid_map.end()) {
double z = GetInitHeight(h.first);
m_grid_map.insert(std::make_pair(h.first, NodeRecord(z, z, GetInitNormal(h.first))));
}
////hits.insert(h);
}
hits.insert(t_hits[t_num].begin(), t_hits[t_num].end());
t_hits[t_num].clear();
}
m_num_ray_hits = (int)hits.size();
}
#endif
m_timer_ray_casting.stop();
// --------------------
// Find contact patches
// --------------------
m_timer_contact_patches.start();
// Collect hit vertices assigned to each contact patch.
struct ContactPatchRecord {
std::vector<ChVector2<>> points; // points in contact patch (in reference plane)
std::vector<ChVector2<int>> nodes; // grid nodes in the contact patch
double area; // contact patch area
double perimeter; // contact patch perimeter
double oob; // approximate value of 1/b
};
std::vector<ContactPatchRecord> contact_patches;
// Loop through all hit nodes and determine to which contact patch they belong.
// Use a queue-based flood-filling algorithm based on the neighbors of each hit node.
m_num_contact_patches = 0;
for (auto& h : hits) {
if (h.second.patch_id != -1)
continue;
ChVector2<int> ij = h.first;
// Make a new contact patch and add this hit node to it
h.second.patch_id = m_num_contact_patches++;
ContactPatchRecord patch;
patch.nodes.push_back(ij);
patch.points.push_back(ChVector2<>(m_delta * ij.x(), m_delta * ij.y()));
// Add current node to the work queue
std::queue<ChVector2<int>> todo;
todo.push(ij);
while (!todo.empty()) {
auto crt = hits.find(todo.front()); // Current hit node is first element in queue
todo.pop(); // Remove first element from queue
ChVector2<int> crt_ij = crt->first;
int crt_patch = crt->second.patch_id;
// Loop through the neighbors of the current hit node
for (int k = 0; k < 4; k++) {
ChVector2<int> nbr_ij = crt_ij + neighbors4[k];
// If neighbor is not a hit node, move on
auto nbr = hits.find(nbr_ij);
if (nbr == hits.end())
continue;
// If neighbor already assigned to a contact patch, move on
if (nbr->second.patch_id != -1)
continue;
// Assign neighbor to the same contact patch
nbr->second.patch_id = crt_patch;
// Add neighbor point to patch lists
patch.nodes.push_back(nbr_ij);
patch.points.push_back(ChVector2<>(m_delta * nbr_ij.x(), m_delta * nbr_ij.y()));
// Add neighbor to end of work queue
todo.push(nbr_ij);
}
}
contact_patches.push_back(patch);
}
// Calculate area and perimeter of each contact patch.
// Calculate approximation to Beker term 1/b.
for (auto& p : contact_patches) {
utils::ChConvexHull2D ch(p.points);
p.area = ch.GetArea();
p.perimeter = ch.GetPerimeter();
if (p.area < 1e-6) {
p.oob = 0;
} else {
p.oob = p.perimeter / (2 * p.area);
}
}
m_timer_contact_patches.stop();
// ----------------------
// Compute contact forces
// ----------------------
m_timer_contact_forces.start();
// Initialize local values for the soil parameters
double Bekker_Kphi = m_Bekker_Kphi;
double Bekker_Kc = m_Bekker_Kc;
double Bekker_n = m_Bekker_n;
double Mohr_cohesion = m_Mohr_cohesion;
double Mohr_mu = m_Mohr_mu;
double Janosi_shear = m_Janosi_shear;
double elastic_K = m_elastic_K;
double damping_R = m_damping_R;
// Process only hit nodes
for (auto& h : hits) {
ChVector2<> ij = h.first;
auto& nr = m_grid_map.at(ij); // node record
const double& ca = nr.normal.z(); // cosine of angle between local normal and SCM plane vertical
ChContactable* contactable = h.second.contactable;
const ChVector<>& hit_point_abs = h.second.abs_point;
int patch_id = h.second.patch_id;
auto hit_point_loc = m_plane.TransformPointParentToLocal(hit_point_abs);
if (m_soil_fun) {
double Mohr_friction;
m_soil_fun->Set(hit_point_loc, Bekker_Kphi, Bekker_Kc, Bekker_n, Mohr_cohesion, Mohr_friction, Janosi_shear,
elastic_K, damping_R);
Mohr_mu = std::tan(Mohr_friction * CH_C_DEG_TO_RAD);
}
nr.hit_level = hit_point_loc.z(); // along SCM z axis
double p_hit_offset = ca * (nr.level_initial - nr.hit_level); // along local normal direction
// Elastic try (along local normal direction)
nr.sigma = elastic_K * (p_hit_offset - nr.sinkage_plastic);
// Handle unilaterality
if (nr.sigma < 0) {
nr.sigma = 0;
continue;
}
// Mark current node as modified
m_modified_nodes.push_back(ij);
// Calculate velocity at touched grid node
ChVector<> point_local(ij.x() * m_delta, ij.y() * m_delta, nr.level);
ChVector<> point_abs = m_plane.TransformPointLocalToParent(point_local);
ChVector<> speed_abs = contactable->GetContactPointSpeed(point_abs);
// Calculate normal and tangent directions (expressed in absolute frame)
ChVector<> N = m_plane.TransformDirectionLocalToParent(nr.normal);
double Vn = Vdot(speed_abs, N);
ChVector<> T = -(speed_abs - Vn * N);
T.Normalize();
// Update total sinkage and current level for this hit node
nr.sinkage = p_hit_offset;
nr.level = nr.hit_level;
// Accumulate shear for Janosi-Hanamoto (along local tangent direction)
nr.kshear += Vdot(speed_abs, -T) * GetSystem()->GetStep();
// Plastic correction (along local normal direction)
if (nr.sigma > nr.sigma_yield) {
// Bekker formula
nr.sigma = (contact_patches[patch_id].oob * Bekker_Kc + Bekker_Kphi) * pow(nr.sinkage, Bekker_n);
nr.sigma_yield = nr.sigma;
double old_sinkage_plastic = nr.sinkage_plastic;
nr.sinkage_plastic = nr.sinkage - nr.sigma / elastic_K;
nr.step_plastic_flow = (nr.sinkage_plastic - old_sinkage_plastic) / GetSystem()->GetStep();
}
// Elastic sinkage (along local normal direction)
nr.sinkage_elastic = nr.sinkage - nr.sinkage_plastic;
// Add compressive speed-proportional damping (not clamped by pressure yield)
////if (Vn < 0) {
nr.sigma += -Vn * damping_R;
////}
// Mohr-Coulomb
double tau_max = Mohr_cohesion + nr.sigma * Mohr_mu;
// Janosi-Hanamoto (along local tangent direction)
nr.tau = tau_max * (1.0 - exp(-(nr.kshear / Janosi_shear)));
// Calculate normal and tangential forces (in local node directions).
// If specified, combine properties for soil-contactable interaction and soil-soil interaction.
ChVector<> Fn = N * m_area * nr.sigma;
ChVector<> Ft;
//// TODO: take into account "tread height" (add to SCMContactableData)?
if (auto cprops = contactable->GetUserData<vehicle::SCMContactableData>()) {
// Use weighted sum of soil-contactable and soil-soil parameters
double c_tau_max = cprops->Mohr_cohesion + nr.sigma * cprops->Mohr_mu;
double c_tau = c_tau_max * (1.0 - exp(-(nr.kshear / cprops->Janosi_shear)));
double ratio = cprops->area_ratio;
Ft = T * m_area * ((1 - ratio) * nr.tau + ratio * c_tau);
} else {
// Use only soil-soil parameters
Ft = T * m_area * nr.tau;
}
if (ChBody* rigidbody = dynamic_cast<ChBody*>(contactable)) {
// [](){} Trick: no deletion for this shared ptr, since 'rigidbody' was not a new ChBody()
// object, but an already used pointer because mrayhit_result.hitModel->GetPhysicsItem()
// cannot return it as shared_ptr, as needed by the ChLoadBodyForce:
std::shared_ptr<ChBody> srigidbody(rigidbody, [](ChBody*) {});
std::shared_ptr<ChLoadBodyForce> mload(new ChLoadBodyForce(srigidbody, Fn + Ft, false, point_abs, false));
this->Add(mload);
// Accumulate contact force for this rigid body.
// The resultant force is assumed to be applied at the body COM.
// All components of the generalized terrain force are expressed in the global frame.
auto itr = m_contact_forces.find(contactable);
if (itr == m_contact_forces.end()) {
// Create new entry and initialize generalized force.
ChVector<> force = Fn + Ft;
TerrainForce frc;
frc.point = srigidbody->GetPos();
frc.force = force;
frc.moment = Vcross(Vsub(point_abs, srigidbody->GetPos()), force);
m_contact_forces.insert(std::make_pair(contactable, frc));
} else {
// Update generalized force.
ChVector<> force = Fn + Ft;
itr->second.force += force;
itr->second.moment += Vcross(Vsub(point_abs, srigidbody->GetPos()), force);
}
} else if (ChLoadableUV* surf = dynamic_cast<ChLoadableUV*>(contactable)) {
// [](){} Trick: no deletion for this shared ptr
std::shared_ptr<ChLoadableUV> ssurf(surf, [](ChLoadableUV*) {});
std::shared_ptr<ChLoad<ChLoaderForceOnSurface>> mload(new ChLoad<ChLoaderForceOnSurface>(ssurf));
mload->loader.SetForce(Fn + Ft);
mload->loader.SetApplication(0.5, 0.5); //***TODO*** set UV, now just in middle
this->Add(mload);
// Accumulate contact forces for this surface.
//// TODO
}
// Update grid node height (in local SCM frame, along SCM z axis)
nr.level = nr.level_initial - nr.sinkage / ca;
} // end loop on ray hits
m_timer_contact_forces.stop();
// --------------------------------------------------
// Flow material to the side of rut, using heuristics
// --------------------------------------------------
m_timer_bulldozing.start();
m_num_erosion_nodes = 0;
if (m_bulldozing) {
typedef std::unordered_set<ChVector2<int>, CoordHash> NodeSet;
// Maximum level change between neighboring nodes (smoothing phase)
double dy_lim = m_delta * m_erosion_slope;
// (1) Raise boundaries of each contact patch
m_timer_bulldozing_boundary.start();
NodeSet boundary; // union of contact patch boundaries
for (auto p : contact_patches) {
NodeSet p_boundary; // boundary of effective contact patch
// Calculate the displaced material from all touched nodes and identify boundary
double tot_step_flow = 0;
for (const auto& ij : p.nodes) { // for each node in contact patch
const auto& nr = m_grid_map.at(ij); // get node record
if (nr.sigma <= 0) // if node not touched
continue; // skip (not in effective patch)
tot_step_flow += nr.step_plastic_flow; // accumulate displaced material
for (int k = 0; k < 4; k++) { // check each node neighbor
ChVector2<int> nbr_ij = ij + neighbors4[k]; // neighbor node coordinates
////if (!CheckMeshBounds(nbr_ij)) // if neighbor out of bounds
//// continue; // skip neighbor
if (m_grid_map.find(nbr_ij) == m_grid_map.end()) // if neighbor not yet recorded
p_boundary.insert(nbr_ij); // set neighbor as boundary
else if (m_grid_map.at(nbr_ij).sigma <= 0) // if neighbor not touched
p_boundary.insert(nbr_ij); // set neighbor as boundary
}
}
tot_step_flow *= GetSystem()->GetStep();
// Target raise amount for each boundary node (unless clamped)
double diff = m_flow_factor * tot_step_flow / p_boundary.size();
// Raise boundary (create a sharp spike which will be later smoothed out with erosion)
for (const auto& ij : p_boundary) { // for each node in bndry
m_modified_nodes.push_back(ij); // mark as modified
if (m_grid_map.find(ij) == m_grid_map.end()) { // if not yet recorded
double z = GetInitHeight(ij); // undeformed height
const ChVector<>& n = GetInitNormal(ij); // terrain normal
m_grid_map.insert(std::make_pair(ij, NodeRecord(z, z, n))); // add new node record
m_modified_nodes.push_back(ij); // mark as modified
} //
auto& nr = m_grid_map.at(ij); // node record
nr.erosion = true; // add to erosion domain
AddMaterialToNode(diff, nr); // add raise amount
}
// Accumulate boundary
boundary.insert(p_boundary.begin(), p_boundary.end());
} // end for contact_patches
m_timer_bulldozing_boundary.stop();
// (2) Calculate erosion domain (dilate boundary)
m_timer_bulldozing_domain.start();
NodeSet erosion_domain = boundary;
NodeSet erosion_front = boundary; // initialize erosion front to boundary nodes
for (int i = 0; i < m_erosion_propagations; i++) {
NodeSet front; // new erosion front
for (const auto& ij : erosion_front) { // for each node in current erosion front
for (int k = 0; k < 4; k++) { // check each of its neighbors
ChVector2<int> nbr_ij = ij + neighbors4[k]; // neighbor node coordinates
////if (!CheckMeshBounds(nbr_ij)) // if out of bounds
//// continue; // ignore neighbor
if (m_grid_map.find(nbr_ij) == m_grid_map.end()) { // if neighbor not yet recorded
double z = GetInitHeight(nbr_ij); // undeformed height at neighbor location
const ChVector<>& n = GetInitNormal(nbr_ij); // terrain normal at neighbor location
NodeRecord nr(z, z, n); // create new record
nr.erosion = true; // include in erosion domain
m_grid_map.insert(std::make_pair(nbr_ij, nr)); // add new node record
front.insert(nbr_ij); // add neighbor to new front
m_modified_nodes.push_back(nbr_ij); // mark as modified
} else { // if neighbor previously recorded
NodeRecord& nr = m_grid_map.at(nbr_ij); // get existing record
if (!nr.erosion && nr.sigma <= 0) { // if neighbor not touched
nr.erosion = true; // include in erosion domain
front.insert(nbr_ij); // add neighbor to new front
m_modified_nodes.push_back(nbr_ij); // mark as modified
}
}
}
}
erosion_domain.insert(front.begin(), front.end()); // add current front to erosion domain
erosion_front = front; // advance erosion front
}
m_num_erosion_nodes = static_cast<int>(erosion_domain.size());
m_timer_bulldozing_domain.stop();
// (3) Erosion algorithm on domain
m_timer_bulldozing_erosion.start();
for (int iter = 0; iter < m_erosion_iterations; iter++) {
for (const auto& ij : erosion_domain) {
auto& nr = m_grid_map.at(ij);
for (int k = 0; k < 4; k++) {
ChVector2<int> nbr_ij = ij + neighbors4[k];
auto rec = m_grid_map.find(nbr_ij);
if (rec == m_grid_map.end())
continue;
auto& nbr_nr = rec->second;
// (3.1) Flow remaining material to neighbor
double diff = 0.5 * (nr.massremainder - nbr_nr.massremainder) / 4; //// TODO: rethink this!
if (diff > 0) {
RemoveMaterialFromNode(diff, nr);
AddMaterialToNode(diff, nbr_nr);
}
// (3.2) Smoothing
if (nbr_nr.sigma == 0) {
double dy = (nr.level + nr.massremainder) - (nbr_nr.level + nbr_nr.massremainder);
diff = 0.5 * (std::abs(dy) - dy_lim) / 4; //// TODO: rethink this!
if (diff > 0) {
if (dy > 0) {
RemoveMaterialFromNode(diff, nr);
AddMaterialToNode(diff, nbr_nr);
} else {
RemoveMaterialFromNode(diff, nbr_nr);
AddMaterialToNode(diff, nr);
}
}
}
}
}
}
m_timer_bulldozing_erosion.stop();
} // end do_bulldozing
m_timer_bulldozing.stop();
// --------------------
// Update visualization
// --------------------
m_timer_visualization.start();
if (m_trimesh_shape) {
// Loop over list of modified nodes and adjust corresponding mesh vertices.
// If not rendering a wireframe mesh, also update normals.
for (const auto& ij : m_modified_nodes) {
if (!CheckMeshBounds(ij)) // if node outside mesh
continue; // do nothing
const auto& nr = m_grid_map.at(ij); // grid node record
int iv = GetMeshVertexIndex(ij); // mesh vertex index
UpdateMeshVertexCoordinates(ij, iv, nr); // update vertex coordinates and color
modified_vertices.push_back(iv); // cache in list of modified mesh vertices
if (!m_trimesh_shape->IsWireframe()) // if not wireframe
UpdateMeshVertexNormal(ij, iv); // update vertex normal
}
m_trimesh_shape->SetModifiedVertices(modified_vertices);
}
m_timer_visualization.stop();
}
void SCMDeformableSoil::AddMaterialToNode(double amount, NodeRecord& nr) {
if (amount > nr.hit_level - nr.level) { // if not possible to assign all mass
nr.massremainder += amount - (nr.hit_level - nr.level); // material to be further propagated
amount = nr.hit_level - nr.level; // clamp raise amount
} //
nr.level += amount; // modify node level
nr.level_initial += amount; // reset node initial level
}
void SCMDeformableSoil::RemoveMaterialFromNode(double amount, NodeRecord& nr) {
if (nr.massremainder > amount) { // if too much remainder material
nr.massremainder -= amount; // decrease remainder material
/*amount = 0;*/ // ???
} else if (nr.massremainder < amount && nr.massremainder > 0) { // if not enough remainder material
amount -= nr.massremainder; // clamp removed amount
nr.massremainder = 0; // remainder material exhausted
} //
nr.level -= amount; // modify node level
nr.level_initial -= amount; // reset node initial level
}
// Update vertex position and color in visualization mesh
void SCMDeformableSoil::UpdateMeshVertexCoordinates(const ChVector2<int> ij, int iv, const NodeRecord& nr) {
auto& trimesh = *m_trimesh_shape->GetMesh();
std::vector<ChVector<>>& vertices = trimesh.getCoordsVertices();
std::vector<ChVector<float>>& colors = trimesh.getCoordsColors();
// Update visualization mesh vertex position
vertices[iv] = m_plane.TransformPointLocalToParent(ChVector<>(ij.x() * m_delta, ij.y() * m_delta, nr.level));
// Update visualization mesh vertex color
if (m_plot_type != SCMDeformableTerrain::PLOT_NONE) {
ChColor mcolor;
switch (m_plot_type) {
case SCMDeformableTerrain::PLOT_LEVEL:
mcolor = ChColor::ComputeFalseColor(nr.level, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_LEVEL_INITIAL:
mcolor = ChColor::ComputeFalseColor(nr.level_initial, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_SINKAGE:
mcolor = ChColor::ComputeFalseColor(nr.sinkage, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_SINKAGE_ELASTIC:
mcolor = ChColor::ComputeFalseColor(nr.sinkage_elastic, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_SINKAGE_PLASTIC:
mcolor = ChColor::ComputeFalseColor(nr.sinkage_plastic, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_STEP_PLASTIC_FLOW:
mcolor = ChColor::ComputeFalseColor(nr.step_plastic_flow, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_K_JANOSI:
mcolor = ChColor::ComputeFalseColor(nr.kshear, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_PRESSURE:
mcolor = ChColor::ComputeFalseColor(nr.sigma, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_PRESSURE_YELD:
mcolor = ChColor::ComputeFalseColor(nr.sigma_yield, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_SHEAR:
mcolor = ChColor::ComputeFalseColor(nr.tau, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_MASSREMAINDER:
mcolor = ChColor::ComputeFalseColor(nr.massremainder, m_plot_v_min, m_plot_v_max);
break;
case SCMDeformableTerrain::PLOT_ISLAND_ID:
if (nr.erosion)
mcolor = ChColor(0, 0, 0);
if (nr.sigma > 0)
mcolor = ChColor(1, 0, 0);
break;
case SCMDeformableTerrain::PLOT_IS_TOUCHED:
if (nr.sigma > 0)
mcolor = ChColor(1, 0, 0);
else
mcolor = ChColor(0, 0, 1);
break;
case SCMDeformableTerrain::PLOT_NONE:
break;
}
colors[iv] = {mcolor.R, mcolor.G, mcolor.B};
}
}
// Update vertex normal in visualization mesh.
void SCMDeformableSoil::UpdateMeshVertexNormal(const ChVector2<int> ij, int iv) {
auto& trimesh = *m_trimesh_shape->GetMesh();
std::vector<ChVector<>>& vertices = trimesh.getCoordsVertices();
std::vector<ChVector<>>& normals = trimesh.getCoordsNormals();
std::vector<ChVector<int>>& idx_normals = trimesh.getIndicesNormals();
// Average normals from adjacent faces
normals[iv] = ChVector<>(0, 0, 0);
auto faces = GetMeshFaceIndices(ij);
for (auto f : faces) {
ChVector<> nrm = Vcross(vertices[idx_normals[f][1]] - vertices[idx_normals[f][0]],
vertices[idx_normals[f][2]] - vertices[idx_normals[f][0]]);
nrm.Normalize();
normals[iv] += nrm;
}
normals[iv] /= (double)faces.size();
}
// Get the heights of modified grid nodes.
std::vector<SCMDeformableTerrain::NodeLevel> SCMDeformableSoil::GetModifiedNodes(bool all_nodes) const {
std::vector<SCMDeformableTerrain::NodeLevel> nodes;
if (all_nodes) {
for (const auto& nr : m_grid_map) {
nodes.push_back(std::make_pair(nr.first, nr.second.level));
}
} else {
for (const auto& ij : m_modified_nodes) {
auto rec = m_grid_map.find(ij);
assert(rec != m_grid_map.end());
nodes.push_back(std::make_pair(ij, rec->second.level));
}
}
return nodes;
}
// Modify the level of grid nodes from the given list.
// NOTE: We set only the level of the specified nodes and none of the other soil properties.
// As such, some plot types may be incorrect at these nodes.
void SCMDeformableSoil::SetModifiedNodes(const std::vector<SCMDeformableTerrain::NodeLevel>& nodes) {
for (const auto& n : nodes) {
// Modify existing entry in grid map or insert new one
m_grid_map[n.first] = SCMDeformableSoil::NodeRecord(n.second, n.second, GetInitNormal(n.first));
}
// Update visualization
if (m_trimesh_shape) {
for (const auto& n : nodes) {
auto ij = n.first; // grid location
if (!CheckMeshBounds(ij)) // if outside mesh
continue; // do nothing
const auto& nr = m_grid_map.at(ij); // grid node record
int iv = GetMeshVertexIndex(ij); // mesh vertex index
UpdateMeshVertexCoordinates(ij, iv, nr); // update vertex coordinates and color
if (!m_trimesh_shape->IsWireframe()) // if not in wireframe mode
UpdateMeshVertexNormal(ij, iv); // update vertex normal
m_external_modified_vertices.push_back(iv); // cache in list
}
}
}
} // end namespace vehicle
} // end namespace chrono
| 43.042745 | 120 | 0.58514 | Benatti1991 |
f39eb71102fb1006d6183b7187098ee51401ba17 | 3,220 | cpp | C++ | test/record/object.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | test/record/object.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | test/record/object.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// 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/noncopyable.hpp>
#include <fcppt/record/element.hpp>
#include <fcppt/record/get.hpp>
#include <fcppt/record/make_label.hpp>
#include <fcppt/record/set.hpp>
#include <fcppt/record/variadic.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <utility>
#include <fcppt/config/external_end.hpp>
TEST_CASE(
"record::object",
"[record]"
)
{
class copy_only
{
public:
explicit
copy_only(
int const _value
)
:
value_(
_value
)
{
}
copy_only(
copy_only const &
) = default;
int
value() const
{
return
value_;
}
private:
int value_;
};
class move_only
{
FCPPT_NONCOPYABLE(
move_only
);
public:
explicit
move_only(
int const _value
)
:
value_{
_value
},
valid_{
true
}
{
}
move_only(
move_only &&_other
)
:
value_{
_other.value_
},
valid_{
_other.valid_
}
{
_other.valid_ =
false;
}
move_only &
operator=(
move_only &&_other
)
{
value_ =
_other.value_;
valid_ =
_other.valid_;
_other.valid_ =
false;
return
*this;
}
~move_only()
{
}
int
value() const
{
CHECK(
valid_
);
return
value_;
}
private:
int value_;
bool valid_;
};
FCPPT_RECORD_MAKE_LABEL(
int_label
);
FCPPT_RECORD_MAKE_LABEL(
bool_label
);
FCPPT_RECORD_MAKE_LABEL(
copy_only_label
);
FCPPT_RECORD_MAKE_LABEL(
move_only_label
);
typedef
fcppt::record::variadic<
fcppt::record::element<
int_label,
int
>,
fcppt::record::element<
bool_label,
bool
>,
fcppt::record::element<
copy_only_label,
copy_only
>,
fcppt::record::element<
move_only_label,
move_only
>
>
my_record;
int const arg1{
4
};
my_record test{
int_label{} =
arg1,
bool_label{} =
true,
copy_only_label{} =
copy_only(
42
),
move_only_label{} =
move_only{
10
}
};
CHECK(
fcppt::record::get<
int_label
>(
test
)
==
4
);
CHECK(
fcppt::record::get<
bool_label
>(
test
)
);
CHECK(
fcppt::record::get<
copy_only_label
>(
test
).value()
==
42
);
CHECK(
fcppt::record::get<
move_only_label
>(
test
).value()
==
10
);
my_record test2(
std::move(
test
)
);
CHECK(
fcppt::record::get<
int_label
>(
test2
)
==
4
);
CHECK(
fcppt::record::get<
bool_label
>(
test2
)
);
CHECK(
fcppt::record::get<
move_only_label
>(
test2
).value()
==
10
);
fcppt::record::set<
bool_label
>(
test2,
false
);
CHECK_FALSE(
fcppt::record::get<
bool_label
>(
test2
)
);
fcppt::record::set<
move_only_label
>(
test2,
move_only{
100
}
);
CHECK(
fcppt::record::get<
move_only_label
>(
test2
).value()
==
100
);
fcppt::record::get<
int_label
>(
test2
) =
42;
CHECK(
fcppt::record::get<
int_label
>(
test2
)
==
42
);
}
| 10.592105 | 61 | 0.581056 | pmiddend |
f39f9901fd56c6a8d1b8a44591374f786561c487 | 5,593 | cc | C++ | src/cc/kfsio/ChunkAccessToken.cc | beol/qfs | 41201cfc1ff6c081324543712d0c02074fa66326 | [
"Apache-2.0"
] | null | null | null | src/cc/kfsio/ChunkAccessToken.cc | beol/qfs | 41201cfc1ff6c081324543712d0c02074fa66326 | [
"Apache-2.0"
] | null | null | null | src/cc/kfsio/ChunkAccessToken.cc | beol/qfs | 41201cfc1ff6c081324543712d0c02074fa66326 | [
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------- -*- Mode: C++ -*-
// $Id$
//
// Created 2013/10/9
// Author: Mike Ovsiannikov
//
// Copyright 2013,2016 Quantcast Corporation. All rights reserved.
//
// This file is part of Kosmos File System (KFS).
//
// 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 "ChunkAccessToken.h"
#include "common/MsgLogger.h"
namespace KFS
{
using std::ostream;
class ChunkAccessToken::Subject : public DelegationToken::Subject
{
public:
Subject(
kfsChunkId_t inChunkId,
int64_t inId)
{
char* thePtr = mBuf;
const char* const theEndPtr = thePtr + kSubjectLength;
*thePtr++ = 'C';
*thePtr++ = 'A';
kfsChunkId_t theId = inChunkId;
while (thePtr < theEndPtr - sizeof(inId)) {
*thePtr++ = (char)(theId & 0xFF);
theId >>= 8;
}
int64_t theWId = inId;
while (thePtr < theEndPtr) {
*thePtr++ = (char)(theWId & 0xFF);
theWId >>= 8;
}
}
virtual int Get(
const DelegationToken& inToken,
const char*& outPtr)
{
outPtr = mBuf;
return (((inToken.GetFlags() &
(kUsesWriteIdFlag | kUsesLeaseIdFlag)) != 0) ?
kSubjectLength : kSubjectLength - (int)sizeof(int64_t));
}
operator DelegationToken::Subject* ()
{ return this; }
private:
enum {
kSubjectLength = 2 + (int)sizeof(kfsChunkId_t) + (int)sizeof(int64_t)
};
char mBuf[kSubjectLength];
};
ChunkAccessToken::ChunkAccessToken(
kfsChunkId_t inChunkId,
kfsUid_t inUid,
TokenSeq inSeq,
kfsKeyId_t inKeyId,
int64_t inIssueTime,
uint16_t inFlags,
uint32_t inValidForSec,
const char* inKeyPtr,
int inKeyLen,
int64_t inId)
: mChunkId(inChunkId),
mDelegationToken(
inUid,
inSeq,
inKeyId,
inIssueTime,
inFlags,
inValidForSec,
inKeyPtr,
inKeyLen,
Subject(inChunkId, inId)
)
{
}
bool
ChunkAccessToken::Process(
kfsChunkId_t inChunkId,
const char* inBufPtr,
int inBufLen,
int64_t inTimeNowSec,
const CryptoKeys& inKeys,
string* outErrMsgPtr,
int64_t inId)
{
Subject theSubject(inChunkId, inId);
return (0 <= mDelegationToken.Process(
inBufPtr,
inBufLen,
inTimeNowSec,
inKeys,
0, // inSessionKeyPtr
-1, // inMaxSessionKeyLength
outErrMsgPtr,
&theSubject
));
}
bool
ChunkAccessToken::Process(
kfsChunkId_t inChunkId,
kfsUid_t inUid,
const char* inBufPtr,
int inBufLen,
int64_t inTimeNowSec,
const CryptoKeys& inKeys,
string* outErrMsgPtr,
int64_t inId)
{
if (! Process(
inChunkId,
inUid,
inBufPtr,
inBufLen,
inTimeNowSec,
inKeys,
outErrMsgPtr,
inId)) {
return false;
}
if (inUid != mDelegationToken.GetUid()) {
if (outErrMsgPtr) {
*outErrMsgPtr = "user id mismatch";
} else {
KFS_LOG_STREAM_ERROR <<
"user id mismatch: uid: " << inUid <<
" token uid: " << mDelegationToken.GetUid() <<
KFS_LOG_EOM;
}
return false;
}
return true;
}
ostream&
ChunkAccessToken::ShowSelf(
ostream& inStream) const
{
return (inStream <<
"chunkId: " << mChunkId <<
" " << mDelegationToken.Show()
);
}
/* static */ bool
ChunkAccessToken::WriteToken(
IOBufferWriter& inWriter,
kfsChunkId_t inChunkId,
kfsUid_t inUid,
TokenSeq inSeq,
kfsKeyId_t inKeyId,
int64_t inIssuedTime,
uint16_t inFlags,
uint32_t inValidForSec,
const char* inKeyPtr,
int inKeyLen,
int64_t inId)
{
Subject theSubject(inChunkId, inId);
return DelegationToken::WriteToken(
inWriter,
inUid,
inSeq,
inKeyId,
inIssuedTime,
inFlags,
inValidForSec,
inKeyPtr,
inKeyLen,
&theSubject
);
}
/* static */ bool
ChunkAccessToken::WriteToken(
ostream& inStream,
kfsChunkId_t inChunkId,
kfsUid_t inUid,
TokenSeq inSeq,
kfsKeyId_t inKeyId,
int64_t inIssuedTime,
uint16_t inFlags,
uint32_t inValidForSec,
const char* inKeyPtr,
int inKeyLen,
int64_t inId)
{
Subject theSubject(inChunkId, inId);
return DelegationToken::WriteToken(
inStream,
inUid,
inSeq,
inKeyId,
inIssuedTime,
inFlags,
inValidForSec,
inKeyPtr,
inKeyLen,
&theSubject
);
}
}
| 24.530702 | 78 | 0.547649 | beol |
f3a3293e03aa843ebe20c80d9b6fd22f697ea6e7 | 4,737 | cpp | C++ | libs/Compensation/Perspiration.cpp | Sensirion/wearable-dev-kit-firmware | 2e503c7360b30d8ecb9597bb310f93e7a655e534 | [
"BSD-3-Clause"
] | 1 | 2019-11-06T15:50:11.000Z | 2019-11-06T15:50:11.000Z | libs/Compensation/Perspiration.cpp | Sensirion/wearable-dev-kit-firmware | 2e503c7360b30d8ecb9597bb310f93e7a655e534 | [
"BSD-3-Clause"
] | null | null | null | libs/Compensation/Perspiration.cpp | Sensirion/wearable-dev-kit-firmware | 2e503c7360b30d8ecb9597bb310f93e7a655e534 | [
"BSD-3-Clause"
] | 2 | 2019-11-06T15:49:31.000Z | 2021-01-28T18:05:33.000Z | /*------------------------------------------------------------------------------
* Copyright 2016 Sensirion AG, Switzerland. All rights reserved.
*
* Software source code and Compensation Algorithms are Sensirion Confidential
* Information and trade secrets. Licensee shall protect confidentiality of
* Software source code and Compensation Algorithms.
*
* Licensee shall not distribute Software and/or Compensation Algorithms other
* than in binary form incorporated in Products. DISTRIBUTION OF SOURCE CODE
* AND/OR COMPENSATION ALGORITHMS IS NOT ALLOWED.
*
* Software and Compensation Algorithms are licensed for use with Sensirion
* sensors only.
*
* Licensee shall not change the source code unless otherwise stated by
* Sensirion.
*
* Software and Compensation Algorithms are provided "AS IS" and any and all
* express or implied warranties are disclaimed.
*
* THIS SOFTWARE IS PROVIDED BY SENSIRION "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 SENSIRION 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 "Perspiration.h"
#include <cmath>
#include "LowPassFilter.h"
#define REMOVE_OFFSET_AND_CAP_DATA 1
void initPerspirationEngine()
{
}
static float absoluteHumidity(float temperature, float relativeHumidity)
{
static const float A = 6.112f; // hPa
static const float Tn = 243.12f; // °C
static const float m = 17.62f;
return 216.7f * (relativeHumidity * 0.01f * A * std::exp(m * temperature / (Tn + temperature)) / (273.15f + temperature));
}
void perspirationEngine(unsigned long timeStampMs,
float temperatureAmbientSensor, float relativeHumidityAmbientSensor,
float temperatureSkinSensor, float relativeHumiditySkinSensor,
float *perspiration)
{
/* compute the time delta from the timestamp, the time delta will slightly vary but this is desireable for the filter computation */
static unsigned long timeStampMsLastCall = 0;
static float delta_t = int(timeStampMs - timeStampMsLastCall) / 1000.0f;
timeStampMsLastCall = timeStampMs;
/* relative humidity offset of ambient sensor */
static const float RH_OFFSET = 0;
/* temperature offset of ambient sensor */
static const float T_OFFSET = 0;
/* distance between sensors in m */
static const float D_SHT = 0.008f;
/* diffusion coefficient @ 25°C in m^2/s */
static const float DIFF_COEF_25_DEGREES = 2.6e-5f;
/* emperical constant, slope of temperature vs calibration factor */
static const float T_CORRECTION_FACTOR = 0.04f;
/* diffusion coefficient temperature dependent */
float DIFF_COEF = DIFF_COEF_25_DEGREES * T_CORRECTION_FACTOR * temperatureSkinSensor;
float CONVERSION_FACTOR = 1.0f / D_SHT * DIFF_COEF * 3600.0f;
/* calibration factor of device */
static const float CALIBRATION_FACTOR = 1.5f;
/* define time constant for low pass filter and apply filtering on both temperature values */
static const float TAU = 30;
temperatureAmbientSensor = firstOrder_lowPassFilter(temperatureAmbientSensor, TAU, delta_t);
temperatureSkinSensor = firstOrder_lowPassFilter(temperatureSkinSensor, TAU, delta_t);
#if REMOVE_OFFSET_AND_CAP_DATA
/* use adjusted temperature and relative humidity to calculate absolute humidity */
temperatureAmbientSensor += T_OFFSET;
relativeHumidityAmbientSensor += RH_OFFSET;
#endif /* REMOVE_OFFSET_AND_CAP_DATA */
float absoluteHumidityAmbientSensor = absoluteHumidity(temperatureAmbientSensor, relativeHumidityAmbientSensor);
float absoluteHumiditySkinSensor = absoluteHumidity(temperatureSkinSensor, relativeHumiditySkinSensor);
#if REMOVE_OFFSET_AND_CAP_DATA
if (absoluteHumiditySkinSensor > absoluteHumidityAmbientSensor) {
#endif /* REMOVE_OFFSET_AND_CAP_DATA */
*perspiration = CALIBRATION_FACTOR * CONVERSION_FACTOR * (absoluteHumiditySkinSensor - absoluteHumidityAmbientSensor);
#if REMOVE_OFFSET_AND_CAP_DATA
} else {
*perspiration = 0.0f;
}
#endif /* REMOVE_OFFSET_AND_CAP_DATA */
}
| 47.848485 | 136 | 0.725142 | Sensirion |
f3a37d53defb5dbef57d32c49afcf11d90b318cf | 1,136 | cpp | C++ | src/XML Tree/XML_Node.cpp | VladimirAnaniev/XML-Parser | 118f71831dc5ba96d1f6e57d42560e866d0fe22b | [
"MIT"
] | 1 | 2020-09-20T16:11:58.000Z | 2020-09-20T16:11:58.000Z | src/XML Tree/XML_Node.cpp | VladimirAnaniev/XML-Parser | 118f71831dc5ba96d1f6e57d42560e866d0fe22b | [
"MIT"
] | 2 | 2017-06-03T16:29:01.000Z | 2017-08-30T11:40:29.000Z | src/XML Tree/XML_Node.cpp | VladimirAnaniev/XML-Parser | 118f71831dc5ba96d1f6e57d42560e866d0fe22b | [
"MIT"
] | null | null | null | #include "XML_Node.h"
#include "../Parser/Parser.h"
String XML_Node::getTag() const {
return this->data.tag;
}
void XML_Node::addArgument(Argument arg) {
this->data.arguments.push(arg);
}
List<Argument> &XML_Node::getArguments() {
return this->data.arguments;
}
Argument XML_Node::removeArgument(int index) {
return this->data.arguments.deleteAt(index);
}
void XML_Node::setTag(String tag) {
this->data.tag.set(tag);
}
void XML_Node::setId(String id) {
this->data.id.set(id);
}
String XML_Node::getId() const {
return this->data.id;
}
void XML_Node::setContent(String content) {
this->data.content = content;
}
String XML_Node::getContent() const {
return this->data.content;
}
XML_Node *XML_Node::findById(String id) {
if (this->getId() == id) return this;
List<TreeNode *> children = this->getChildren();
for (int i = 0; i < children.getSize(); i++) {
XML_Node *result = ((XML_Node *) children[i])->findById(id);
if (result != nullptr) return result;
}
return nullptr;
}
String XML_Node::toString() {
return Parser::nodeTreeToString(this);
}
| 19.586207 | 68 | 0.65669 | VladimirAnaniev |
f3a3eb8ecb31b16a049e1f6008ff3649d06dfcf7 | 605 | cpp | C++ | src/Win32Intro/TestWindow.cpp | yottaawesome/win32-intro | fa1caa6ea5cdd829d9cda9667a52ec2c624746c0 | [
"MIT"
] | null | null | null | src/Win32Intro/TestWindow.cpp | yottaawesome/win32-intro | fa1caa6ea5cdd829d9cda9667a52ec2c624746c0 | [
"MIT"
] | null | null | null | src/Win32Intro/TestWindow.cpp | yottaawesome/win32-intro | fa1caa6ea5cdd829d9cda9667a52ec2c624746c0 | [
"MIT"
] | 1 | 2021-06-23T18:37:18.000Z | 2021-06-23T18:37:18.000Z | module;
#include <Windows.h>
module main_window;
LRESULT MainWindow::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(m_hwnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
EndPaint(m_hwnd, &ps);
}
return 0;
default:
return DefWindowProc(m_hwnd, uMsg, wParam, lParam);
}
return TRUE;
} | 21.607143 | 75 | 0.522314 | yottaawesome |
f3a41cdae45cbc6517b3da51420429faa4244481 | 6,266 | cpp | C++ | Tests/UnitTests/ReaderTests/ImageReaderTests.cpp | alexboukhvalova/CNTK | 8835d4f61b393f068a4f019424bbc80c0b4e761a | [
"RSA-MD"
] | 6 | 2019-08-18T05:29:09.000Z | 2021-01-19T09:58:45.000Z | Tests/UnitTests/ReaderTests/ImageReaderTests.cpp | Omar-Belghaouti/CNTK | 422f710242c602b2660a634f2234abf5aaf5b337 | [
"RSA-MD"
] | null | null | null | Tests/UnitTests/ReaderTests/ImageReaderTests.cpp | Omar-Belghaouti/CNTK | 422f710242c602b2660a634f2234abf5aaf5b337 | [
"RSA-MD"
] | 1 | 2019-03-20T21:44:46.000Z | 2019-03-20T21:44:46.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
#include "stdafx.h"
#include "Common/ReaderTestHelper.h"
using namespace Microsoft::MSR::CNTK;
namespace Microsoft { namespace MSR { namespace CNTK { namespace Test {
struct ImageReaderFixture : ReaderFixture
{
ImageReaderFixture()
: ReaderFixture("/Data")
{
}
};
BOOST_FIXTURE_TEST_SUITE(ReaderTestSuite, ImageReaderFixture)
BOOST_AUTO_TEST_CASE(ImageReaderSimple)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderSimple_Config.cntk",
testDataPath() + "/Control/ImageReaderSimple_Control.txt",
testDataPath() + "/Control/ImageReaderSimple_Output.txt",
"Simple_Test",
"reader",
4,
4,
1,
1,
0,
0,
1);
}
BOOST_AUTO_TEST_CASE(ImageAndTextReaderSimple)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageAndTextReaderSimple_Config.cntk",
testDataPath() + "/Control/ImageAndTextReaderSimple_Control.txt",
testDataPath() + "/Control/ImageAndTextReaderSimple_Output.txt",
"Simple_Test",
"reader",
4,
4,
1,
1,
0,
0,
1);
}
BOOST_AUTO_TEST_CASE(ImageReaderBadMap)
{
BOOST_REQUIRE_EXCEPTION(
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderBadMap_Config.cntk",
testDataPath() + "/Control/ImageReaderSimple_Control.txt",
testDataPath() + "/Control/ImageReaderSimple_Output.txt",
"Simple_Test",
"reader",
4,
4,
1,
1,
0,
0,
1),
std::runtime_error,
[](std::runtime_error const& ex) { return string("Invalid map file format, must contain 2 or 3 tab-delimited columns, line 2 in file ./ImageReaderBadMap_map.txt.") == ex.what(); });
}
BOOST_AUTO_TEST_CASE(ImageReaderBadLabel)
{
BOOST_REQUIRE_EXCEPTION(
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderBadLabel_Config.cntk",
testDataPath() + "/Control/ImageReaderSimple_Control.txt",
testDataPath() + "/Control/ImageReaderSimple_Output.txt",
"Simple_Test",
"reader",
4,
4,
1,
1,
0,
0,
1),
std::runtime_error,
[](std::runtime_error const& ex) { return string("Cannot parse label value on line 1, second column, in file ./ImageReaderBadLabel_map.txt.") == ex.what(); });
}
BOOST_AUTO_TEST_CASE(ImageReaderLabelOutOfRange)
{
BOOST_REQUIRE_EXCEPTION(
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderLabelOutOfRange_Config.cntk",
testDataPath() + "/Control/ImageReaderSimple_Control.txt",
testDataPath() + "/Control/ImageReaderSimple_Output.txt",
"Simple_Test",
"reader",
4,
4,
1,
1,
0,
0,
1),
std::runtime_error,
[](std::runtime_error const& ex) { return string("Image 'images\\red.jpg' has invalid class id '10'. Expected label dimension is '4'. Line 3 in file ./ImageReaderLabelOutOfRange_map.txt.") == ex.what(); });
}
BOOST_AUTO_TEST_CASE(ImageReaderZip)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderZip_Config.cntk",
testDataPath() + "/Control/ImageReaderZip_Control.txt",
testDataPath() + "/Control/ImageReaderZip_Output.txt",
"Zip_Test",
"reader",
4,
4,
1,
1,
0,
0,
1);
}
BOOST_AUTO_TEST_CASE(ImageReaderZipMissingFile)
{
BOOST_REQUIRE_EXCEPTION(
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderZipMissing_Config.cntk",
testDataPath() + "/Control/ImageReaderZip_Control.txt",
testDataPath() + "/Control/ImageReaderZip_Output.txt",
"ZipMissing_Test",
"reader",
4,
4,
1,
1,
0,
0,
1),
std::runtime_error,
[](std::runtime_error const& ex) { return string("Failed to get file info of missing.jpg, zip library error: Unknown error -1") == ex.what(); });
}
BOOST_AUTO_TEST_CASE(ImageReaderMultiView)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderMultiView_Config.cntk",
testDataPath() + "/Control/ImageReaderMultiView_Control.txt",
testDataPath() + "/Control/ImageReaderMultiView_Output.txt",
"MultiView_Test",
"reader",
10,
10,
1,
1,
0,
0,
1);
}
BOOST_AUTO_TEST_CASE(ImageReaderIntensityTransform)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderIntensityTransform_Config.cntk",
testDataPath() + "/Control/ImageReaderIntensityTransform_Control.txt",
testDataPath() + "/Control/ImageReaderIntensityTransform_Output.txt",
"IntensityTransform_Test",
"reader",
1,
1,
2,
1,
0,
0,
1);
}
BOOST_AUTO_TEST_CASE(ImageReaderColorTransform)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderColorTransform_Config.cntk",
testDataPath() + "/Control/ImageReaderColorTransform_Control.txt",
testDataPath() + "/Control/ImageReaderColorTransform_Output.txt",
"ColorTransform_Test",
"reader",
1,
1,
2,
1,
0,
0,
1);
}
BOOST_AUTO_TEST_CASE(ImageReaderGrayscale)
{
HelperRunReaderTest<float>(
testDataPath() + "/Config/ImageReaderGrayscale_Config.cntk",
testDataPath() + "/Control/ImageReaderGrayscale_Control.txt",
testDataPath() + "/Control/ImageReaderGrayscale_Output.txt",
"Grayscale_Test",
"reader",
1,
1,
1,
1,
0,
0,
1);
}
BOOST_AUTO_TEST_SUITE_END()
} } } }
| 27.848889 | 218 | 0.588733 | alexboukhvalova |
f3a535973989e234f0a9c325dd93b3f0475bc68e | 1,953 | cc | C++ | base/allocator/allocator_shim_default_dispatch_to_glibc.cc | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | base/allocator/allocator_shim_default_dispatch_to_glibc.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | base/allocator/allocator_shim_default_dispatch_to_glibc.cc | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.000Z | // Copyright 2016 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 "base/allocator/allocator_shim.h"
#include <malloc.h>
// This translation unit defines a default dispatch for the allocator shim which
// routes allocations to libc functions.
// The code here is strongly inspired from tcmalloc's libc_override_glibc.h.
extern "C" {
void* __libc_malloc(size_t size);
void* __libc_calloc(size_t n, size_t size);
void* __libc_realloc(void* address, size_t size);
void* __libc_memalign(size_t alignment, size_t size);
void __libc_free(void* ptr);
} // extern "C"
namespace {
using base::allocator::AllocatorDispatch;
void* GlibcMalloc(const AllocatorDispatch*, size_t size) {
return __libc_malloc(size);
}
void* GlibcCalloc(const AllocatorDispatch*, size_t n, size_t size) {
return __libc_calloc(n, size);
}
void* GlibcRealloc(const AllocatorDispatch*, void* address, size_t size) {
return __libc_realloc(address, size);
}
void* GlibcMemalign(const AllocatorDispatch*, size_t alignment, size_t size) {
return __libc_memalign(alignment, size);
}
void GlibcFree(const AllocatorDispatch*, void* address) {
__libc_free(address);
}
size_t GlibcGetSizeEstimate(const AllocatorDispatch*, void* address) {
// TODO(siggi, primiano): malloc_usable_size may need redirection in the
// presence of interposing shims that divert allocations.
return malloc_usable_size(address);
}
} // namespace
const AllocatorDispatch AllocatorDispatch::default_dispatch = {
&GlibcMalloc, /* alloc_function */
&GlibcCalloc, /* alloc_zero_initialized_function */
&GlibcMemalign, /* alloc_aligned_function */
&GlibcRealloc, /* realloc_function */
&GlibcFree, /* free_function */
&GlibcGetSizeEstimate, /* get_size_estimate_function */
nullptr, /* next */
};
| 31.5 | 80 | 0.730159 | google-ar |
f3a577fcb91417cf1d9a6e4807469ace4b0d48d0 | 5,612 | hpp | C++ | ntt/schoenhage-strassen-radix2.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 69 | 2020-11-06T05:21:42.000Z | 2022-03-29T03:38:35.000Z | ntt/schoenhage-strassen-radix2.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 21 | 2020-07-25T04:47:12.000Z | 2022-02-01T14:39:29.000Z | ntt/schoenhage-strassen-radix2.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 9 | 2020-11-06T11:55:10.000Z | 2022-03-20T04:45:31.000Z | #pragma once
template <typename T>
struct Schoenhage_Strassen_radix2 {
T* buf = nullptr;
void rot(T* dst, T* src, int s, int d) {
assert(0 <= d and d < 2 * s);
bool f = s <= d;
if (s <= d) d -= s;
int i = 0;
if (f) {
for (; i < s - d; i++) dst[i + d] = -src[i];
for (; i < s; i++) dst[i + d - s] = src[i];
} else {
for (; i < s - d; i++) dst[i + d] = src[i];
for (; i < s; i++) dst[i + d - s] = -src[i];
}
}
void in_add(T* dst, T* src, int s) {
for (int i = 0; i < s; i++) dst[i] += src[i];
}
void in_sub(T* dst, T* src, int s) {
for (int i = 0; i < s; i++) dst[i] -= src[i];
}
void cp(T* dst, T* src, int s) { memcpy(dst, src, s * sizeof(T)); }
void reset(T* dst, int s) { fill(dst, dst + s, T()); }
// R[x] / (1 + x^(2^m)) 上の長さ2^LのFFT
void fft(T* a, int l, int m) {
if (l == 0) return;
int L = 1 << l, M = 1 << m;
assert(M * 2 >= L);
assert(buf != nullptr);
vector<int> dw(l - 1);
for (int i = 0; i < l - 1; i++) {
dw[i] = (1 << (l - 2 - i)) + (1 << (l - 1 - i)) - (1 << (l - 1));
if (dw[i] < 0) dw[i] += L;
if (L == M) dw[i] *= 2;
if (2 * L == M) dw[i] *= 4;
}
for (int d = L; d >>= 1;) {
int w = 0;
for (int s = 0, k = 0;;) {
for (int i = s, j = s + d; i < s + d; ++i, ++j) {
T *ai = a + i * M, *aj = a + j * M;
rot(buf, aj, M, w);
cp(aj, ai, M);
in_add(ai, buf, M);
in_sub(aj, buf, M);
}
if ((s += 2 * d) >= L) break;
w += dw[__builtin_ctz(++k)];
if (w >= 2 * M) w -= 2 * M;
}
}
}
// R[x] / (1 + x^(2^m)) 上の長さ2^LのIFFT
void ifft(T* a, int l, int m) {
if (l == 0) return;
int L = 1 << l, M = 1 << m;
assert(M * 2 >= L);
assert(buf != nullptr);
vector<int> dw(l - 1);
for (int i = 0; i < l - 1; i++) {
dw[i] = (1 << (l - 2 - i)) + (1 << (l - 1 - i)) - (1 << (l - 1));
if (dw[i] < 0) dw[i] += L;
if (L == M) dw[i] *= 2;
if (2 * L == M) dw[i] *= 4;
}
for (int d = 1; d < L; d *= 2) {
int w = 0;
for (int s = 0, k = 0;;) {
for (int i = s, j = s + d; i < s + d; ++i, ++j) {
T *ai = a + i * M, *aj = a + j * M;
cp(buf, ai, M);
in_add(ai, aj, M);
in_sub(buf, aj, M);
rot(aj, buf, M, w);
}
if ((s += 2 * d) >= L) break;
w -= dw[__builtin_ctz(++k)];
if (w < 0) w += 2 * M;
}
}
}
// a <- ab / (x^(2^n)+1)
int naive_mul(T* a, T* b, int n) {
int N = 1 << n;
reset(buf, N);
for (int i = 0; i < N; i++) {
int j = 0;
for (; j < N - i; j++) buf[i + j] += a[i] * b[j];
for (; j < N; j++) buf[i + j - N] -= a[i] * b[j];
}
cp(a, buf, N);
return 0;
}
// a <- ab / (x^(2^n)+1)
int inplace_mul(T* a, T* b, int n) {
if (n <= 5) {
naive_mul(a, b, n);
return 0;
}
int l = (n + 1) / 2;
int m = n / 2;
int L = 1 << l, M = 1 << m, N = 1 << n;
int cnt = 0;
// R[x] (x^(2^(m+1))-1) R[y] (y^(2^l)-1)
vector<T> A(N * 2), B(N * 2);
reset(buf + M, M);
for (int i = 0, s = 0, ds = 2 * M / L; i < L; i++) {
// y -> x^{2m/r} y
cp(buf, a + i * M, M);
rot(A.data() + i * M * 2, buf, 2 * M, s);
cp(buf, b + i * M, M);
rot(B.data() + i * M * 2, buf, 2 * M, s);
s += ds;
if (s >= 4 * M) s -= 4 * M;
}
fft(A.data(), l, m + 1);
fft(B.data(), l, m + 1);
for (int i = 0; i < L; i++) {
cnt = inplace_mul(A.data() + i * M * 2, B.data() + i * M * 2, m + 1);
}
ifft(A.data(), l, m + 1);
for (int i = 0, s = 0, ds = 2 * M / L; i < L; i++) {
// y -> x^{-2m/r} y
cp(buf, A.data() + i * M * 2, 2 * M);
rot(A.data() + i * M * 2, buf, 2 * M, s);
s -= ds;
if (s < 0) s += 4 * M;
}
for (int i = 0; i < L; i++) {
for (int j = 0; j < M; j++) {
a[i * M + j] = A[i * M * 2 + j];
if (i == 0) {
a[i * M + j] -= A[(L - 1) * M * 2 + M + j];
} else {
a[i * M + j] += A[(i - 1) * M * 2 + M + j];
}
}
}
return cnt + l;
}
// a <- ab / (x^(2^n)-1)
int inplace_mul2(T* a, T* b, int n) {
if (n <= 5) {
naive_mul(a, b, n);
return 0;
}
int l = (n + 1) / 2;
int m = n / 2;
int L = 1 << l, M = 1 << m, N = 1 << n;
int cnt = 0;
// R[x] (x^(2^(m+1))-1) R[y] (y^(2^l)-1)
vector<T> A(N * 2), B(N * 2);
for (int i = 0; i < L; i++) {
cp(A.data() + i * M * 2, a + i * M, M);
cp(B.data() + i * M * 2, b + i * M, M);
}
fft(A.data(), l, m + 1);
fft(B.data(), l, m + 1);
for (int i = 0; i < L; i++) {
cnt = inplace_mul(A.data() + i * M * 2, B.data() + i * M * 2, m + 1);
}
ifft(A.data(), l, m + 1);
for (int i = 0; i < L; i++) {
for (int j = 0; j < M; j++) {
a[i * M + j] = A[i * M * 2 + j];
a[i * M + j] += A[(i ? i - 1 : L - 1) * M * 2 + M + j];
}
}
return cnt + l;
}
pair<vector<T>, int> multiply(const vector<T>& a, const vector<T>& b) {
int L = a.size() + b.size() - 1;
int M = 1, m = 0;
while (M < L) M *= 2, m++;
buf = new T[M];
vector<T> s(M), t(M);
for (int i = 0; i < (int)a.size(); i++) s[i] = a[i];
for (int i = 0; i < (int)b.size(); i++) t[i] = b[i];
int cnt = inplace_mul2(s.data(), t.data(), m);
vector<T> u(L);
for (int i = 0; i < L; i++) u[i] = s[i];
delete[] buf;
return make_pair(u, cnt);
}
};
/**
* @brief Schönhage-Strassen Algorithm(radix-2)
*/
| 26.347418 | 75 | 0.349252 | NachiaVivias |
f3a59904019cb9973a786d4b279191483a15a5a1 | 312 | cpp | C++ | 2-YellowBelt/week5/Assignment1/DIYInheritance.cpp | mamoudmatook/CPlusPlusInRussian | ef1f92e4880f24fe16fbcbef8dba3a2658d2208e | [
"MIT"
] | null | null | null | 2-YellowBelt/week5/Assignment1/DIYInheritance.cpp | mamoudmatook/CPlusPlusInRussian | ef1f92e4880f24fe16fbcbef8dba3a2658d2208e | [
"MIT"
] | null | null | null | 2-YellowBelt/week5/Assignment1/DIYInheritance.cpp | mamoudmatook/CPlusPlusInRussian | ef1f92e4880f24fe16fbcbef8dba3a2658d2208e | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class Animal
{
public:
Animal(const string &st) : Name(st)
{}
// ваш код
const string Name;
};
class Dog: public Animal
{
public:
Dog(const string &st): Animal(st) {}
void Bark()
{
cout << Name << " barks: woof!" << endl;
}
}; | 13 | 48 | 0.557692 | mamoudmatook |
f3a6aeb8c01617a070d894a3896803dd3bb90023 | 60 | cpp | C++ | src/disolarm64.cpp | flamencist/Detours | c0c0ef9bff2355f97e0c34ba7360116c741ad22a | [
"MIT"
] | 2,204 | 2019-05-07T02:53:35.000Z | 2022-03-31T21:46:25.000Z | src/disolarm64.cpp | flamencist/Detours | c0c0ef9bff2355f97e0c34ba7360116c741ad22a | [
"MIT"
] | 1,065 | 2021-06-24T16:08:11.000Z | 2022-03-31T23:12:32.000Z | src/disolarm64.cpp | flamencist/Detours | c0c0ef9bff2355f97e0c34ba7360116c741ad22a | [
"MIT"
] | 557 | 2019-05-09T09:15:31.000Z | 2022-03-31T09:33:29.000Z | #define DETOURS_ARM64_OFFLINE_LIBRARY
#include "disasm.cpp"
| 20 | 37 | 0.85 | flamencist |
f3a78d9156fe9bff12def082052809dcd66dcc99 | 1,298 | cpp | C++ | aoj/22/aoj2253.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | 1 | 2018-11-12T15:18:55.000Z | 2018-11-12T15:18:55.000Z | aoj/22/aoj2253.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | aoj/22/aoj2253.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define MP make_pair
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl
#define fst first
#define snd second
const int dx[6] = {0, 1, 1, 0, -1, -1};
const int dy[6] = {1, 1, 0, -1, -1, 0};
int board[128][128];
int geta = 64;
int main() {
ios_base::sync_with_stdio(false);
while (1) {
int t, n;
cin >> t >> n;
if (t == 0 && n == 0) break;
memset(board, 0, sizeof(board));
REP(i, n) {
int x, y;
cin >> x >> y;
board[y+geta][x+geta] = -1;
}
int sx, sy;
cin >> sx >> sy;
queue<T> que;
que.push(T(sx, sy, t));
while (!que.empty()) {
int x, y, rest;
tie(x, y, rest) = que.front();
que.pop();
if (rest < 0 || board[y+geta][x+geta] != 0) continue;
board[y+geta][x+geta] = 1;
REP(i, 6) {
int nx = x + dx[i], ny = y + dy[i];
que.push(T(nx, ny, rest - 1));
}
}
int ans = 0;
REP(i, 128) REP(j, 128) ans += board[i][j] > 0;
cout << ans << endl;
}
return 0;
}
| 20.603175 | 59 | 0.498459 | knuu |
f3a8bb2621f54b42e2e744a1314cb98f8e1c4a20 | 1,304 | hh | C++ | include/MEPED_DetectorMessenger.hh | kbyando/meped-etelescope | cb1805cb8d1662a561fb1b7a405aecbfffac8f2c | [
"Apache-2.0"
] | null | null | null | include/MEPED_DetectorMessenger.hh | kbyando/meped-etelescope | cb1805cb8d1662a561fb1b7a405aecbfffac8f2c | [
"Apache-2.0"
] | null | null | null | include/MEPED_DetectorMessenger.hh | kbyando/meped-etelescope | cb1805cb8d1662a561fb1b7a405aecbfffac8f2c | [
"Apache-2.0"
] | null | null | null | // NOAA POES Monte Carlo Simulation v1.3, 17/09/2008e
// MEPED (Medium Energy Proton and Electron Detector)
// Karl Yando, Professor Robyn Millan
// Dartmouth College, 2008
//
// "MEPED_DetectorMessenger.hh" - (generic)
#ifndef MEPED_DetectorMessenger_h
#define MEPED_DetectorMessenger_h 1
#include "globals.hh"
#include "G4UImessenger.hh"
class MEPED_DetectorConstruction;
class G4UIdirectory;
class G4UIcmdWithAString;
class G4UIcmdWithAnInteger;
class G4UIcmdWithADoubleAndUnit;
class G4UIcmdWithoutParameter;
class MEPED_DetectorMessenger: public G4UImessenger
{
public:
MEPED_DetectorMessenger(MEPED_DetectorConstruction* );
~MEPED_DetectorMessenger();
void SetNewValue(G4UIcommand*, G4String);
private:
MEPED_DetectorConstruction* MEPED_Detector;
G4UIdirectory* MEPEDDir;
G4UIdirectory* detDir;
G4UIcmdWithAString* DeteMaterCmd;
G4UIcmdWithAString* ShieldMaterCmd;
G4UIcmdWithAString* HouseMaterCmd;
G4UIcmdWithAString* ContactMaterCmd;
G4UIcmdWithAString* BelvilleMaterCmd;
G4UIcmdWithAString* InsulatorMaterCmd;
G4UIcmdWithAString* FoilMaterCmd;
G4UIcmdWithADoubleAndUnit* DetectorThickCmd;
G4UIcmdWithoutParameter* UpdateCmd;
};
#endif
| 27.744681 | 58 | 0.742331 | kbyando |
f3a99d7e42e117c5859ebaaabe12d20ddb502f45 | 4,281 | hpp | C++ | engine/gems/image/conversions.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | engine/gems/image/conversions.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | engine/gems/image/conversions.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-07-02T11:51:17.000Z | 2020-07-02T11:51:17.000Z | /*
Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include "engine/core/image/image.hpp"
#include "engine/core/tensor/tensor.hpp"
#include "third_party/nlohmann/json.hpp"
namespace isaac {
// Convert the image encoded in yuyv to rgb.
// The yuyv format is described here:
// https://www.linuxtv.org/downloads/v4l-dvb-apis-old/V4L2-PIX-FMT-YUYV.html
void ConvertYuyvToRgb(const Image2ub& yuyv, Image3ub& rgb);
// Convert a pixels colorspace from rgb to hsv.
// The rgb values are expected to be in [0, 1].
// The result will have H in [0, 360], S in [0, 255], V in [0, 255].
// https://en.wikipedia.org/wiki/HSL_and_HSV
Pixel3f RgbToHsv(const Pixel3f& rgb);
// Convert a float32 RGBA image to a uint8 RGB image
// Input RGBA pixel values are expected to be in [0, 1].
// Result RGB pixel values will be in [0, 255].
void ConvertRgbaToRgb(ImageConstView4f source, ImageView3ub target);
// Convert a uint8 RGBA image to a uint8 RGB image dropping the alpha channel
void ConvertRgbaToRgb(ImageConstView4ub source, ImageView3ub target);
// Convert a uint8 BGRA image to a uint8 RGB image dropping the alpha channel
void ConvertBgraToRgb(ImageConstView4ub source, ImageView3ub target);
// Convert a uint8 RGB image to a uint8 RGBA image and sets the alpha channel to `alpha`.
void ConvertRgbToRgba(ImageConstView3ub source, ImageView4ub target,
uint8_t alpha = 255);
// Converts a uint16_t image to a 1f image using a scale factor
void ConvertUi16ToF32(ImageConstView1ui16 source, ImageView1f target, float scale);
// Converts a 1f image to a uint16_t image using a scale factor
void ConvertF32ToUi16(ImageConstView1f source, ImageView1ui16 target, float scale);
// The indexing order for row, column, channel can be specified by the ImageToTensorIndexOrder
// enum.
enum class ImageToTensorIndexOrder {
k012 = 1, // Specifies ordering as row, column, channel
k201 = 2 // Specifies ordering as channel, row, column
};
// Use strings when serializing ImageToTensorIndexOrder enum
NLOHMANN_JSON_SERIALIZE_ENUM(ImageToTensorIndexOrder, {
{ImageToTensorIndexOrder::k012, "012"},
{ImageToTensorIndexOrder::k201, "201"},
});
// The normalization method for row, column, channel can be specified by the
// ImageToTensorNormalization enum.
enum class ImageToTensorNormalization {
kNone = 1,
kUnit = 2, // Normalize each pixel intensity into a range [0, 1] or vice versa
kPositiveNegative = 3, // Normalize each pixel intensity into a range [-1, 1] or vice versa
kHalfAndHalf = 4 // Normalize each pixel intensity into a range [-0.5, 0.5] or vice versa
};
// Use strings when serializing ImageToTensorNormalization enum
NLOHMANN_JSON_SERIALIZE_ENUM(ImageToTensorNormalization, {
{ImageToTensorNormalization::kNone, "None"},
{ImageToTensorNormalization::kUnit, "Unit"},
{ImageToTensorNormalization::kPositiveNegative, "PositiveNegative"},
{ImageToTensorNormalization::kHalfAndHalf, "HalfAndHalf"},
});
// Copy an image into a tensor and normalize each pixel intensity into a given range.
void ImageToNormalizedTensor(
ImageConstView3ub rgb_image,
Tensor3f& tensor,
ImageToTensorIndexOrder index_order = ImageToTensorIndexOrder::k012,
ImageToTensorNormalization normalization = ImageToTensorNormalization::kPositiveNegative);
// Converts a 3-channel 8-bit image to a 32-bit floating point tensor.
void ImageToNormalizedTensor(
CudaImageConstView3ub rgb_image,
CudaTensorView3f result,
ImageToTensorIndexOrder index_order = ImageToTensorIndexOrder::k012,
ImageToTensorNormalization normalization = ImageToTensorNormalization::kPositiveNegative);
// Copy a tensor into an image and normalize each pixel intensity into into a given range.
void NormalizedTensorToImage(
TensorConstView3f tensor,
ImageToTensorNormalization normalization, Image3ub& rgb_image);
} // namespace isaac
| 42.81 | 98 | 0.772483 | stereoboy |
f3aa41b696f21cba2f2d1a5dfa4b8dd8664c7306 | 36,350 | cpp | C++ | src/SurfaceSource/SurfaceSource.cpp | sellitforcache/ss2dist | 943284bca9ca5ce8ffeb43ef3b6ef2e39d207702 | [
"BSD-3-Clause"
] | null | null | null | src/SurfaceSource/SurfaceSource.cpp | sellitforcache/ss2dist | 943284bca9ca5ce8ffeb43ef3b6ef2e39d207702 | [
"BSD-3-Clause"
] | null | null | null | src/SurfaceSource/SurfaceSource.cpp | sellitforcache/ss2dist | 943284bca9ca5ce8ffeb43ef3b6ef2e39d207702 | [
"BSD-3-Clause"
] | 1 | 2018-09-25T13:50:15.000Z | 2018-09-25T13:50:15.000Z | #include <fstream>
#include <vector>
#include <string>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <valarray>
#include <climits>
#include <sstream>
#include <sys/stat.h>
#include <bitset>
#include "SurfaceSource.hpp"
/*
Adapated from https://wiki.calculquebec.ca/w/C%2B%2B_:_fichier_Fortran_binaire/en
*/
void SurfaceSource::Init(){
// init paramters
strncpy(id, " \0" , 9 );
strncpy(kods, " \0" , 9 );
strncpy(vers, " \0" , 6 );
strncpy(lods, " \0" , 9 );
strncpy(idtms, " \0" , 20 );
strncpy(probs, " \0" , 20 );
strncpy(aids, " \0" , 81 );
knods = 0;
np1 = 0;
nrss = 0;
nrcd = 0;
njsw = 0;
niss = 0;
niwr = 0;
mipts = 0;
kjaq = 0;
surface_count = 0;
// init particle lookup table
strncpy(particles[ 1-1].name , "neutron\0" , 8);
strncpy(particles[ 5-1].name , "anti-neutron\0" ,13);
strncpy(particles[ 2-1].name , "photon\0" , 7);
strncpy(particles[ 3-1].name , "electron\0" , 9);
strncpy(particles[ 8-1].name , "positron\0" , 9);
strncpy(particles[ 4-1].name , "muon-\0" , 6);
strncpy(particles[ 16-1].name , "muon+\0" , 6);
strncpy(particles[ 6-1].name , "electron neutrino\0" ,18);
strncpy(particles[ 17-1].name , "anti-electron neutrino\0" ,23);
strncpy(particles[ 7-1].name , "muon neutrino\0" ,14);
strncpy(particles[ 18-1].name , "anti muon neutrino\0" ,19);
strncpy(particles[ 9-1].name , "proton\0" , 7);
strncpy(particles[ 19-1].name , "anti-proton\0" ,12);
strncpy(particles[ 10-1].name , "lambda baryon\0" ,14);
strncpy(particles[ 25-1].name , "anti lambda baryon\0" ,19);
strncpy(particles[ 11-1].name , "positive sigma baryon\0" ,22);
strncpy(particles[ 26-1].name , "anti positive sigma baryon\0" ,17);
strncpy(particles[ 12-1].name , "negative sigma baryon\0" ,22);
strncpy(particles[ 27-1].name , "anti negative sigma baryon\0" ,27);
strncpy(particles[ 13-1].name , "cascade\0" , 8);
strncpy(particles[ 28-1].name , "anti cascade\0" ,13);
strncpy(particles[ 14-1].name , "negative cascade\0" ,17);
strncpy(particles[ 29-1].name , "positive cascade\0" ,17);
strncpy(particles[ 15-1].name , "omega baryon\0" ,13);
strncpy(particles[ 30-1].name , "anti omega baryon\0" ,18);
strncpy(particles[ 20-1].name , "positive pion\0" ,14);
strncpy(particles[ 35-1].name , "negative pion\0" ,14);
strncpy(particles[ 21-1].name , "neutral pion\0" ,13);
strncpy(particles[ 22-1].name , "positive kaon\0" ,14);
strncpy(particles[ 36-1].name , "negative kaon\0" ,14);
strncpy(particles[ 23-1].name , "kaon, short\0" ,12);
strncpy(particles[ 24-1].name , "kaon, long\0" ,11);
strncpy(particles[ 31-1].name , "deuteron\0" , 9);
strncpy(particles[ 32-1].name , "triton\0" , 7);
strncpy(particles[ 33-1].name , "helion\0" , 7);
strncpy(particles[ 34-1].name , "alpha\0" , 6);
strncpy(particles[ 37-1].name , "heavy ions\0" ,11);
//
strncpy(particles[ 1-1].symbol , "n\0", 2);
strncpy(particles[ 5-1].symbol , "q\0", 2);
strncpy(particles[ 2-1].symbol , "p\0", 2);
strncpy(particles[ 3-1].symbol , "e\0", 2);
strncpy(particles[ 8-1].symbol , "f\0", 2);
strncpy(particles[ 4-1].symbol , "|\0", 2);
strncpy(particles[ 16-1].symbol , "!\0", 2);
strncpy(particles[ 6-1].symbol , "u\0", 2);
strncpy(particles[ 17-1].symbol , "<\0", 2);
strncpy(particles[ 7-1].symbol , "v\0", 2);
strncpy(particles[ 18-1].symbol , ">\0", 2);
strncpy(particles[ 9-1].symbol , "h\0", 2);
strncpy(particles[ 19-1].symbol , "g\0", 2);
strncpy(particles[ 10-1].symbol , "l\0", 2);
strncpy(particles[ 25-1].symbol , "b\0", 2);
strncpy(particles[ 11-1].symbol , "+\0", 2);
strncpy(particles[ 26-1].symbol , "_\0", 2);
strncpy(particles[ 12-1].symbol , "-\0", 2);
strncpy(particles[ 27-1].symbol , "~\0", 2);
strncpy(particles[ 13-1].symbol , "x\0", 2);
strncpy(particles[ 28-1].symbol , "c\0", 2);
strncpy(particles[ 14-1].symbol , "y\0", 2);
strncpy(particles[ 29-1].symbol , "w\0", 2);
strncpy(particles[ 15-1].symbol , "o\0", 2);
strncpy(particles[ 30-1].symbol , "@\0", 2);
strncpy(particles[ 20-1].symbol , "/\0", 2);
strncpy(particles[ 35-1].symbol , "*\0", 2);
strncpy(particles[ 21-1].symbol , "z\0", 2);
strncpy(particles[ 22-1].symbol , "k\0", 2);
strncpy(particles[ 36-1].symbol , "?\0", 2);
strncpy(particles[ 23-1].symbol , "%\0", 2);
strncpy(particles[ 24-1].symbol , "^\0", 2);
strncpy(particles[ 31-1].symbol , "d\0", 2);
strncpy(particles[ 32-1].symbol , "t\0", 2);
strncpy(particles[ 33-1].symbol , "s\0", 2);
strncpy(particles[ 34-1].symbol , "a\0", 2);
strncpy(particles[ 37-1].symbol , "#\0", 2);
// init surface lookup table
strncpy(surface_card[ 0].symbol , "XXX\0" , 4);
strncpy(surface_card[ 1].symbol , "p \0" , 4);
strncpy(surface_card[ 2].symbol , "px \0" , 4);
strncpy(surface_card[ 3].symbol , "py \0" , 4);
strncpy(surface_card[ 4].symbol , "pz \0" , 4);
strncpy(surface_card[ 5].symbol , "so \0" , 4);
strncpy(surface_card[ 6].symbol , "s \0" , 4);
strncpy(surface_card[ 7].symbol , "sx \0" , 4);
strncpy(surface_card[ 8].symbol , "sy \0" , 4);
strncpy(surface_card[ 9].symbol , "sz \0" , 4);
strncpy(surface_card[10].symbol , "c/x\0" , 4);
strncpy(surface_card[11].symbol , "c/y\0" , 4);
strncpy(surface_card[12].symbol , "c/z\0" , 4);
strncpy(surface_card[13].symbol , "cx \0" , 4);
strncpy(surface_card[14].symbol , "cy \0" , 4);
strncpy(surface_card[15].symbol , "cz \0" , 4);
strncpy(surface_card[16].symbol , "k/x\0" , 4);
strncpy(surface_card[17].symbol , "k/y\0" , 4);
strncpy(surface_card[18].symbol , "k/z\0" , 4);
strncpy(surface_card[19].symbol , "kx \0" , 4);
strncpy(surface_card[20].symbol , "ky \0" , 4);
strncpy(surface_card[21].symbol , "kz \0" , 4);
strncpy(surface_card[22].symbol , "sq \0" , 4);
strncpy(surface_card[23].symbol , "gq \0" , 4);
strncpy(surface_card[24].symbol , "tx \0" , 4);
strncpy(surface_card[25].symbol , "ty \0" , 4);
strncpy(surface_card[26].symbol , "tz \0" , 4);
strncpy(surface_card[27].symbol , "x \0" , 4);
strncpy(surface_card[28].symbol , "y \0" , 4);
strncpy(surface_card[29].symbol , "z \0" , 4);
strncpy(surface_card[30].symbol , "box\0" , 4);
strncpy(surface_card[31].symbol , "rpp\0" , 4);
strncpy(surface_card[32].symbol , "sph\0" , 4);
strncpy(surface_card[33].symbol , "rcc\0" , 4);
strncpy(surface_card[34].symbol , "rec\0" , 4);
strncpy(surface_card[35].symbol , "ell\0" , 4);
strncpy(surface_card[36].symbol , "trc\0" , 4);
strncpy(surface_card[37].symbol , "wed\0" , 4);
strncpy(surface_card[38].symbol , "arb\0" , 4);
strncpy(surface_card[39].symbol , "rhp\0" , 4);
strncpy(surface_card[40].symbol , "hex\0" , 4);
//
surface_card[ 0].n_coefficients = 0;
surface_card[ 1].n_coefficients = 4;
surface_card[ 2].n_coefficients = 1;
surface_card[ 3].n_coefficients = 1;
surface_card[ 4].n_coefficients = 1;
surface_card[ 5].n_coefficients = 1;
surface_card[ 6].n_coefficients = 4;
surface_card[ 7].n_coefficients = 2;
surface_card[ 8].n_coefficients = 2;
surface_card[ 9].n_coefficients = 2;
surface_card[10].n_coefficients = 3;
surface_card[11].n_coefficients = 3;
surface_card[12].n_coefficients = 3;
surface_card[13].n_coefficients = 1;
surface_card[14].n_coefficients = 1;
surface_card[15].n_coefficients = 1;
surface_card[16].n_coefficients = 5;
surface_card[17].n_coefficients = 5;
surface_card[18].n_coefficients = 5;
surface_card[19].n_coefficients = 3;
surface_card[20].n_coefficients = 3;
surface_card[21].n_coefficients = 3;
surface_card[22].n_coefficients = 10;
surface_card[23].n_coefficients = 10;
surface_card[24].n_coefficients = 6;
surface_card[25].n_coefficients = 6;
surface_card[26].n_coefficients = 6;
surface_card[27].n_coefficients = 0;
surface_card[28].n_coefficients = 0;
surface_card[29].n_coefficients = 0;
surface_card[30].n_coefficients = 12;
surface_card[31].n_coefficients = 6;
surface_card[32].n_coefficients = 4;
surface_card[33].n_coefficients = 7;
surface_card[34].n_coefficients = 12;
surface_card[35].n_coefficients = 7;
surface_card[36].n_coefficients = 8;
surface_card[37].n_coefficients = 12;
surface_card[38].n_coefficients = 30;
surface_card[39].n_coefficients = 15;
surface_card[40].n_coefficients = 15;
//
strncpy(surface_card[ 0].description , "INDEXING ERROR \0", 41);
strncpy(surface_card[ 1].description , "General plane \0", 41);
strncpy(surface_card[ 2].description , "Plane normal to X-axis \0", 41);
strncpy(surface_card[ 3].description , "Plane normal to Y-axis \0", 41);
strncpy(surface_card[ 4].description , "Plane normal to Z-axis \0", 41);
strncpy(surface_card[ 5].description , "Sphere centered at the origin \0", 41);
strncpy(surface_card[ 6].description , "General sphere \0", 41);
strncpy(surface_card[ 7].description , "Sphere centered on X-axis \0", 41);
strncpy(surface_card[ 8].description , "Sphere centered on Y-axis \0", 41);
strncpy(surface_card[ 9].description , "Sphere centered on Z-axis \0", 41);
strncpy(surface_card[10].description , "Cylinder parallel to X-axis \0", 41);
strncpy(surface_card[11].description , "Cylinder parallel to Y-axis \0", 41);
strncpy(surface_card[12].description , "Cylinder parallel to Z-axis \0", 41);
strncpy(surface_card[13].description , "Cylinder on X-axis \0", 41);
strncpy(surface_card[14].description , "Cylinder on Y-axis \0", 41);
strncpy(surface_card[15].description , "Cylinder on Z-axis \0", 41);
strncpy(surface_card[16].description , "Cone parallel to X-axis \0", 41);
strncpy(surface_card[17].description , "Cone parallel to Y-axis \0", 41);
strncpy(surface_card[18].description , "Cone parallel to Z-axis \0", 41);
strncpy(surface_card[19].description , "Cone on X-axis \0", 41);
strncpy(surface_card[20].description , "Cone on Y-axis \0", 41);
strncpy(surface_card[21].description , "Cone on Z-axis \0", 41);
strncpy(surface_card[22].description , "Quadric parallel to X-,Y-, or Z-axis \0", 41);
strncpy(surface_card[23].description , "Quadric not parallel to X-,Y-, or Z-axis\0", 41);
strncpy(surface_card[24].description , "Torus parallel to X-axis \0", 41);
strncpy(surface_card[25].description , "Torus parallel to Y-axis \0", 41);
strncpy(surface_card[26].description , "Torus parallel to Z-axis \0", 41);
strncpy(surface_card[27].description , "Surface defined by points sym. about X \0", 41);
strncpy(surface_card[28].description , "Surface defined by points sym. about Y \0", 41);
strncpy(surface_card[29].description , "Surface defined by points sym. about Z \0", 41);
strncpy(surface_card[30].description , "Arbitrarily oriented orthogonal box \0", 41);
strncpy(surface_card[31].description , "Rectangular Parallelepiped \0", 41);
strncpy(surface_card[32].description , "Sphere \0", 41);
strncpy(surface_card[33].description , "Right Circular Cylinder \0", 41);
strncpy(surface_card[34].description , "Right Elliptical Cylinder \0", 41);
strncpy(surface_card[35].description , "Ellipsoid \0", 41);
strncpy(surface_card[36].description , "Truncated Right-angle Cone \0", 41);
strncpy(surface_card[37].description , "Wedge \0", 41);
strncpy(surface_card[38].description , "Arbitrary polydron \0", 41);
strncpy(surface_card[39].description , "Right Hexagonal Prism \0", 41);
strncpy(surface_card[40].description , "Right Hexagonal Prism - Same as RHP \0", 41);
}
//
// CON/DE-STRUCTORS
//
SurfaceSource::~SurfaceSource(){
input_file.close();
output_file.close();
}
SurfaceSource::SurfaceSource(const std::string& fileName){
Init();
OpenWssaFile_Read(fileName.c_str());
}
SurfaceSource::SurfaceSource(const std::string& fileName1, const std::string& fileName2){
Init();
OpenWssaFile_Read( fileName1.c_str());
OpenWssaFile_Write(fileName2.c_str());
}
SurfaceSource::SurfaceSource(const char* fileName){
Init();
OpenWssaFile_Read(fileName);
}
SurfaceSource::SurfaceSource(const char* fileName1, const char* fileName2){
Init();
OpenWssaFile_Read(fileName1);
OpenWssaFile_Write(fileName2);
}
SurfaceSource::SurfaceSource(const std::string& fileName, const int flag){
Init();
switch(flag){
case RSSA_READ: OpenWssaFile_Read( fileName.c_str()); break;
case RSSA_WRITE: OpenWssaFile_Write(fileName.c_str()); break;
}
}
SurfaceSource::SurfaceSource(const char* fileName, const int flag){
Init();
switch(flag){
case RSSA_READ: OpenWssaFile_Read( fileName); break;
case RSSA_WRITE: OpenWssaFile_Write(fileName); break;
}
}
//
// FILE IO
//
bool SurfaceSource::OpenWssaFile_Read(const char* fileName){
// for file check
struct stat buffer;
// set object name
input_file_name.assign(fileName);
// open file
if( (stat (fileName, &buffer) == 0)){
input_file.open(fileName, std::ios::in | std::ios::binary);
return true;
}
else{
printf("problem opening %s for reading.\n",fileName);
return false;
}
}
bool SurfaceSource::OpenWssaFile_Write(const char* fileName){
// for file check
struct stat buffer;
// set object name
output_file_name.assign(fileName);
// open file, make sure it doens't already exist
if( (stat (fileName, &buffer) != 0)){
output_file.open(fileName, std::ios::out | std::ios::binary);
return true;
}
else{
printf("problem opening %s for writing.\n",fileName);
return false;
}
}
//
// RECORD READS
//
bool SurfaceSource::ReadRecord(void** destination, size_t* size, size_t NumberOfEntries)
{
int record_length0 = 0;
int record_length1 = 0;
int null = 0;
int length_read = 0;
int dist_to_end = 0;
if (input_file.good())
{
// read starting delimiter
input_file.read((char*) &record_length0, RECORD_DELIMITER_LENGTH);
//printf("READ RECORD LENGTH %d\n",record_length0);
// read what's asked for
for(int i=0;i<NumberOfEntries;i++){
length_read = length_read + size[i];
if(length_read>record_length0){
printf("DATA REQUESTED (%d) OVERRAN RECORD LENGTH (%d)!\n",length_read,record_length0);
return false;
}
else{
input_file.read((char*) destination[i], size[i]);
}
}
// go to the end of the record
dist_to_end = record_length0-length_read;
if( dist_to_end > 0 ){
printf("--> skipping ahead %d bytes to end of record after %d entries\n",dist_to_end, NumberOfEntries);
input_file.seekg(dist_to_end, std::ios::cur);
}
// read ending delimiter, assert
input_file.read((char*) &record_length1, RECORD_DELIMITER_LENGTH);
if(record_length0!=record_length1){
printf("BEGINNING (%d) AND ENDING (%d) RECORD LENGTH DELIMITERS DO NOT MATCH\n",record_length0,record_length1);
return false;
}
else{
return true;
}
}
else
{
return false;
}
}
bool SurfaceSource::ReadSurfaceRecord0(int* numbers, int* types, int* lengths, surface* parameters)
{
// internal variables
int record_length0 = 0;
int record_length1 = 0;
// read record
if (input_file.good())
{
input_file.read((char*) &record_length0, sizeof(record_length0));
input_file.read((char*) numbers, sizeof(int));
input_file.read((char*) types, sizeof(int));
input_file.read((char*) lengths, sizeof(int));
input_file.read((char*) parameters,lengths[0]*sizeof(parameters->value[0]));
input_file.read((char*) &record_length1, sizeof(record_length1));
if(record_length0!=record_length1){
printf("SurfaceRecord0 BEGINNING (%d) AND ENDING (%d) RECORD LENGTH DELIMITERS DO NOT MATCH\n",record_length0,record_length1);
return false;
}
else{
return true;
}
}
else
{
return false;
}
}
bool SurfaceSource::ReadSurfaceRecord1(int* numbers, int* types, int* lengths, surface* parameters, int* facets)
{
// internal variables
int record_length = 0;
if (input_file.good())
{
input_file.read((char*) &record_length, sizeof(record_length));
input_file.read((char*) numbers, sizeof(int));
input_file.read((char*) facets, sizeof(int));
input_file.read((char*) types, sizeof(int));
input_file.read((char*) lengths, sizeof(int));
input_file.read((char*) parameters,lengths[0]*sizeof(parameters->value[0]));
input_file.seekg(RECORD_DELIMITER_LENGTH, std::ios::cur);
return true;
}
else
{
return false;
}
}
bool SurfaceSource::ReadSummaryRecord(int** summaries)
{
int record_length0 = 0;
int record_length1 = 0;
int null = 0;
double dnull = 0.0;
int length_read = 0;
int dist_to_end = 0;
int this_record_legnth = 0;
if (input_file.good())
{
// read starting delimiter
input_file.read((char*) &record_length0, RECORD_DELIMITER_LENGTH);
//printf("RECORD LENGTH %d\n",record_length0);
// read dumb leading (double) zero
input_file.read((char*) &dnull, sizeof(double));
length_read = sizeof(double);
// read what's asked for
for(int i=0;i<surface_count;i++){
for(int j=0;j<surface_summary_length;j++){
length_read = length_read + sizeof(int);
if(length_read>record_length0){
printf("SUMMARY DATA REQUESTED (%d) OVERRAN RECORD LENGTH (%d)!\n",length_read,record_length0);
return false;
}
else{
input_file.read((char*) &summaries[i][j], sizeof(int));
}
}
}
// go to the end of the record
dist_to_end = record_length0-length_read;
if( dist_to_end > 0 ){
printf("--> skipping ahead %d bytes to end of record\n",dist_to_end);
input_file.seekg(dist_to_end, std::ios::cur);
}
// read ending delimiter, assert
input_file.read((char*) &record_length1, RECORD_DELIMITER_LENGTH);
if(record_length0!=record_length1){
printf("BEGINNING (%d) AND ENDING (%d) SUMMARY RECORD LENGTH DELIMITERS DO NOT MATCH\n",record_length0,record_length1);
return false;
}
else{
return true;
}
}
else
{
return false;
}
}
//
// RECORD WRITES
//
bool SurfaceSource::WriteRecord(void** source, size_t* size, size_t NumberOfEntries)
{
int record_length0 = 0;
for (int i=0;i<NumberOfEntries;i++){
record_length0 += size[i];
}
//printf("WRITE RECORD LENGTH %d\n",record_length0);
if (output_file.good())
{
// read starting delimiter
output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH);
// write what's given
for(int i=0;i<NumberOfEntries;i++){
output_file.write((char*) source[i], size[i]);
}
// write ending delimiter
output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH);
return true;
}
else
{
printf("OUTPUT FILE NOT GOOD.\n");
return false;
}
}
bool SurfaceSource::WriteSurfaceRecord0(int* numbers, int* types, int* lengths, surface* parameters)
{
// internal variables
int record_length = 3*sizeof(int) + lengths[0]*sizeof(parameters->value[0]);
// write record
if (output_file.good())
{
output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH);
output_file.write((char*) numbers, sizeof(int));
output_file.write((char*) types, sizeof(int));
output_file.write((char*) lengths, sizeof(int));
output_file.write((char*) parameters,lengths[0]*sizeof(parameters->value[0]));
output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH);
return true;
}
else
{
return false;
}
}
bool SurfaceSource::WriteSurfaceRecord1(int* numbers, int* types, int* lengths, surface* parameters, int* facets)
{
// internal variables
int record_length = 4*sizeof(int) + lengths[0]*sizeof(parameters->value[0]);
if (output_file.good())
{
output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH);
output_file.write((char*) numbers, sizeof(int));
output_file.write((char*) facets, sizeof(int));
output_file.write((char*) types, sizeof(int));
output_file.write((char*) lengths, sizeof(int));
output_file.write((char*) parameters,lengths[0]*sizeof(parameters->value[0]));
output_file.write((char*) &record_length, RECORD_DELIMITER_LENGTH);
return true;
}
else
{
return false;
}
}
bool SurfaceSource::WriteSummaryRecord(int** summaries)
{
int record_length0 = surface_summary_length*surface_count*sizeof(int)+sizeof(double);
int null = 0;
double dnull = 0.0;
int length_write = 0;
if (output_file.good())
{
// write starting delimiter
output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH);
// write stupid leading (double) zero
output_file.write((char*) &dnull, sizeof(double));
// write what's asked for
for(int i=0;i<surface_count;i++){
for(int j=0;j<surface_summary_length;j++){
length_write = length_write + sizeof(int);
output_file.write((char*) &summaries[i][j], sizeof(int));
}
}
// write ending delimiter, assert
output_file.write((char*) &record_length0, RECORD_DELIMITER_LENGTH);
return true;
}
else
{
return false;
}
}
//
// HIGHER LEVEL ROUTINES
//
void SurfaceSource::ReadHeader(){
// HEADER FORMATTING
//
// record 1: id;
// record 2: kods,vers,lods,idtms,probs,aids,knods;
// record 3: np1,nrss,nrcd,njsw,niss;
// record 4: niwr,mipts,kjaq;
//
// id = The ID string, should be SF_00001 for MCNP6-made surface source, char8
// kods = code name, char8
// vers = code version, char5
// lods = LODDAT of code that wrote surface source file, char8
// idtms = IDTM of the surface source write run, char19
// probs = probid, problem id, char19
// aids = title string of the creation run, char80
// knods = ending dump number, int
// np1 = total number of histories in SS write run, int
// nrss = the total number of tracks recorded, int
// nrcd = Number of values in a surface-source record, int
// njsw = Number of surfaces in JASW, int
// niss = Number of histories in input surface source, int
// niwr = Number of cells in RSSA file, int
// mipts = Source particle type, int
// kjaq = Flag for macrobody facets on source tape, int
//
//
// the next njsw+niwr records describe the surfaces/cells in the SS
//
//
// the last record is the SS summary vector
// first record
void** pointers = new void* [20];
size_t* sizes = new size_t [20];
size_t size = 1;
pointers[0] = (void**) &id;
sizes[0] = sizeof(id)-1;
if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING FIRST RECORD\n");std::exit(1);}
// second record, first make array of pointers, then sizes
size = 7;
pointers[0] = (void*) &kods;
pointers[1] = (void*) &vers;
pointers[2] = (void*) &lods;
pointers[3] = (void*) &idtms;
pointers[4] = (void*) &probs;
pointers[5] = (void*) &aids;
pointers[6] = (void*) &knods;
sizes[0] = sizeof(kods)-1;
sizes[1] = sizeof(vers)-1;
sizes[2] = sizeof(lods)-1;
sizes[3] = sizeof(idtms)-1;
sizes[4] = sizeof(probs)-1;
sizes[5] = sizeof(aids)-1;
sizes[6] = sizeof(knods);
if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING SECOND RECORD\n");std::exit(1);}
// third record, first make array of pointers, then sizes
size = 5;
pointers[0] = (void*) &np1;
pointers[1] = (void*) &nrss;
pointers[2] = (void*) &nrcd;
pointers[3] = (void*) &njsw;
pointers[4] = (void*) &niss;
sizes[0] = sizeof(np1);
sizes[1] = sizeof(nrss);
sizes[2] = sizeof(nrcd);
sizes[3] = sizeof(njsw);
sizes[4] = sizeof(niss);
if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING THIRD RECORD\n");std::exit(1);}
// fourth record, first make array of pointers, then sizes
size = 3+17; // 17 zeros written after for whatever reason!
pointers[0] = (void*) &niwr;
pointers[1] = (void*) &mipts;
pointers[2] = (void*) &kjaq;
int null = 0;
for (int g=3;g<3+17;g++){pointers[g]=&null;}
sizes[0] = sizeof(niwr);
sizes[1] = sizeof(mipts);
sizes[2] = sizeof(kjaq);
for (int g=3;g<3+17;g++){sizes[g]=sizeof(null);}
if(!ReadRecord(pointers, sizes, size)){printf("ERROR READING FOURTH RECORD\n");std::exit(1);}
// init arays for surface information
surface_count = njsw+niwr;
surface_parameters = new surface [surface_count];
surface_parameters_lengths = new int [surface_count];
surface_numbers = new int [surface_count];
surface_types = new int [surface_count];
surface_facets = new int [surface_count];
surface_summaries = new int* [surface_count];
for(int i = 0 ; i < surface_count ; i++){
for(int j = 0 ; j < 10 ; j++){
surface_parameters [i].value[j] = 0;
}
surface_summaries[i] = new int [surface_summary_length];
for(int k=0;k<surface_summary_length;k++){
surface_summaries[i][k]=0;
}
surface_numbers [i] = -1;
surface_facets [i] = -1;
}
// go on, copying surface/cell information from the next records until particle data starts
for(int i = 0 ; i < surface_count ; i++){
if( kjaq==0 | i>njsw-1 ) {
ReadSurfaceRecord0(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i]);
}
if( kjaq==1 & i<=njsw-1 ) {
ReadSurfaceRecord1(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i],&surface_facets[i]);
}
}
// last record is the summary tables
ReadSummaryRecord(surface_summaries);
}
void SurfaceSource::WriteHeader(){
// HEADER FORMATTING
//
// record 1: id;
// record 2: kods,vers,lods,idtms,probs,aids,knods;
// record 3: np1,nrss,nrcd,njsw,niss;
// record 4: niwr,mipts,kjaq;
//
// id = The ID string, should be SF_00001 for MCNP6-made surface source, char8
// kods = code name, char8
// vers = code version, char5
// lods = LODDAT of code that wrote surface source file, char8
// idtms = IDTM of the surface source write run, char19
// probs = probid, problem id, char19
// aids = title string of the creation run, char80
// knods = ending dump number, int
// np1 = total number of histories in SS write run, int
// nrss = the total number of tracks recorded, int
// nrcd = Number of values in a surface-source record, int
// njsw = Number of surfaces in JASW, int
// niss = Number of histories in input surface source, int
// niwr = Number of cells in RSSA file, int
// mipts = Source particle type, int
// kjaq = Flag for macrobody facets on source tape, int
//
//
// the next njsw+niwr records describe the surfaces/cells in the SS
//
//
// the last record is the SS summary vector
// first record
int largest_size = 3+17;
void** pointers = new void* [largest_size];
size_t* sizes = new size_t [largest_size];
size_t size = 1;
pointers[0] = (void**) &id;
sizes[0] = sizeof(id)-1;
if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING FIRST RECORD\n");std::exit(1);}
// second record, first make array of pointers, then sizes
size = 7;
pointers[0] = (void*) &kods;
pointers[1] = (void*) &vers;
pointers[2] = (void*) &lods;
pointers[3] = (void*) &idtms;
pointers[4] = (void*) &probs;
pointers[5] = (void*) &aids;
pointers[6] = (void*) &knods;
sizes[0] = sizeof(kods)-1;
sizes[1] = sizeof(vers)-1;
sizes[2] = sizeof(lods)-1;
sizes[3] = sizeof(idtms)-1;
sizes[4] = sizeof(probs)-1;
sizes[5] = sizeof(aids)-1;
sizes[6] = sizeof(knods);
if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING SECOND RECORD\n");std::exit(1);}
// third record, first make array of pointers, then sizes
size = 5;
pointers[0] = (void*) &np1;
pointers[1] = (void*) &nrss;
pointers[2] = (void*) &nrcd;
pointers[3] = (void*) &njsw;
pointers[4] = (void*) &niss;
sizes[0] = sizeof(np1);
sizes[1] = sizeof(nrss);
sizes[2] = sizeof(nrcd);
sizes[3] = sizeof(njsw);
sizes[4] = sizeof(niss);
if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING THIRD RECORD\n");std::exit(1);}
// fourth record, first make array of pointers, then sizes
size = 3+17;
pointers[0] = (void*) &niwr;
pointers[1] = (void*) &mipts;
pointers[2] = (void*) &kjaq;
int null = 0;
for (int g=3;g<size;g++){pointers[g]=&null;}
sizes[0] = sizeof(niwr);
sizes[1] = sizeof(mipts);
sizes[2] = sizeof(kjaq);
for (int g=3;g<size;g++){sizes[g]=sizeof(null);}
if(!WriteRecord(pointers, sizes, size)){printf("ERROR WRITING FOURTH RECORD\n");std::exit(1);}
// init arays for surface information
//surface_count = njsw+niwr;
//surface_parameters = new surface [surface_count];
//surface_parameters_lengths = new int [surface_count];
//surface_numbers = new int [surface_count];
//surface_types = new int [surface_count];
//surface_facets = new int [surface_count];
//surface_summaries = new int* [surface_count];
//for(int i = 0 ; i < surface_count ; i++){
// for(int j = 0 ; j < 10 ; j++){
// surface_parameters [i].value[j] = 0;
// }
// surface_summaries[i] = new int [surface_summary_length];
// for(int k=0;k<surface_summary_length;k++){
// surface_summaries[i][k]=0;
// }
// surface_numbers [i] = -1;
// surface_facets [i] = -1;
//}
// go on, copying surface/cell information from the next records until particle data starts
for(int i = 0 ; i < surface_count ; i++){
if( kjaq==0 | i>njsw-1 ) {
WriteSurfaceRecord0(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i]);
}
if( kjaq==1 & i<=njsw-1 ) {
WriteSurfaceRecord1(&surface_numbers[i],&surface_types[i],&surface_parameters_lengths[i],&surface_parameters[i],&surface_facets[i]);
}
}
// last record is the summary tables
WriteSummaryRecord(surface_summaries);
output_file.flush();
}
void SurfaceSource::PrintSizes(){
printf("== DATA SIZE INFORMATION == \n");
printf("normal integers : %1ld bytes\n", sizeof(knods));
printf("floating points : %1ld bytes\n", sizeof(surface_parameters->value[0]));
printf("characters : %1ld bytes\n", sizeof(id[0]));
printf("\n");
}
void SurfaceSource::PrintHeader(){
printf("=========================================== HEADER INFORMATION =========================================== \n");
printf("RSSA ID string : %8s \n", id);
printf("code name : %8s \n", kods);
printf("code version : %5s \n", vers);
printf("LODDAT of code that wrote surface source file : %8s \n", lods);
printf("IDTM of the surface source write run : %19s\n", idtms);
printf("probid, problem id : %19s\n", probs);
printf("title string of the creation run : %80s\n", aids);
printf("ending dump number : %d\n", knods);
printf("total number of histories in SS write run : %lld\n", np1);
printf("the total number of tracks recorded : %lld\n", nrss);
printf("Number of values in a surface-source record : %d\n", nrcd);
printf("Number of surfaces in JASW : %d\n", njsw);
printf("Number of histories in input surface source : %lld\n", niss);
printf("Number of cells in RSSA file : %d\n", niwr);
printf("Source particle type : %d\n", mipts);
printf("Flag for macrobody facets on source tape : %d\n", kjaq);
if( kjaq == 0 ) {
printf("\n============================================================ SURFACE INFORMATION ============================================================ \n");
printf("creation-run surfaces | surface | type | coefficients\n");
}
else if( kjaq == 1 ) {
printf("\n============================================================ SURFACE INFORMATION ============================================================ \n");
printf("creation-run surfaces | surface | facet | type | coefficients\n");
}
for(int i = 0 ; i < surface_count ; i++){
if( kjaq == 0 ) {
printf(" %5d %5d %s ",i,surface_numbers[i],surface_card[surface_types[i]].symbol);
for(int j = 0 ; j < surface_parameters_lengths[i] ; j++){
printf(" % 10.8E",surface_parameters[i].value[j]);
}
printf("\n");
}
else if( kjaq == 1 ) {
printf(" %5d %5d %1d %s ",i,surface_numbers[i],surface_facets[i],surface_card[surface_types[i]].symbol);
for(int j = 0 ; j < surface_parameters_lengths[i] ; j++){
printf(" % 10.8E",surface_parameters[i].value[j]);
}
printf("\n");
}
}
printf("\n");
printf("\n============================================================= SURFACE SUMMARIES ============================================================= \n");
int a,b,c,d;
for(int i=0;i<surface_count;i++){
printf("--=== Surface %5d ===--\n",surface_numbers[i]);
printf("%20s %21s\n","TOTAL TRACKS","INDEPENDENT HISTORIES");
printf(" %12d %12d\n",surface_summaries[i][0],surface_summaries[i][1]);
for(int j=0;j<mipts;j++){
a = surface_summaries[i][(2+j*4)+0];
b = surface_summaries[i][(2+j*4)+1];
c = surface_summaries[i][(2+j*4)+2];
d = surface_summaries[i][(2+j*4)+3];
if (a+b+c+d > 0){
printf("---- %s ----\n",particles[j].name);
printf("%20s %20s %20s %20s\n","TOTAL TRACKS","INDEPENDENT TRACKS","UNCOLLIDED","INDEP. UNCOLLIDED");
printf(" %12d %12d %12d %12d\n",a,b,c,d);
}
}
printf("\n");
}
}
void SurfaceSource::GetTrack(track* this_track){
// local vars
size_t sizes = 11*sizeof(double);
// try reading it all in at once... copy from array to make sure struct padding doesn't do anything...
double* this_track_data = new double [12];
if(!ReadRecord((void**) &this_track_data, &sizes, 1)){printf("ERROR READING TRACKS RECORD\n");std::exit(1);}
this_track->nps = this_track_data[ 0];
this_track->bitarray = this_track_data[ 1];
this_track->wgt = this_track_data[ 2];
this_track->erg = this_track_data[ 3];
this_track->tme = this_track_data[ 4];
this_track->x = this_track_data[ 5];
this_track->y = this_track_data[ 6];
this_track->z = this_track_data[ 7];
this_track->xhat = this_track_data[ 8];
this_track->yhat = this_track_data[ 9];
this_track->cs = this_track_data[10];
this_track->zhat = this_track_data[11];
delete this_track_data;
// calculate missing zhat from the data
if ((this_track->xhat*this_track->xhat+this_track->yhat*this_track->yhat)<1.0){
this_track->zhat = copysign(std::sqrt(1.0 - this_track->xhat*this_track->xhat -
this_track->yhat*this_track->yhat), this_track->bitarray);
}
else{
this_track->zhat = 0.0;
}
}
void SurfaceSource::PutTrack(double nps, double bitarray, double wgt, double erg, double tme, double x, double y, double z, double xhat, double yhat, double cs, double zhat){
// local vars
size_t sizes = 11*sizeof(double); // only write the first 11, track in record doesn't have zhat
double* this_track_data = new double [12];
this_track_data[ 0] = nps ;
this_track_data[ 1] = bitarray;
this_track_data[ 2] = wgt ;
this_track_data[ 3] = erg ;
this_track_data[ 4] = tme ;
this_track_data[ 5] = x ;
this_track_data[ 6] = y ;
this_track_data[ 7] = z ;
this_track_data[ 8] = xhat ;
this_track_data[ 9] = yhat ;
this_track_data[10] = cs ;
this_track_data[11] = zhat ;
// writing it all in at once...
if(!WriteRecord((void**) &this_track_data, &sizes, 1)){printf("ERROR WRITING TRACK RECORD\n");std::exit(1);}
delete this_track_data;
}
void SurfaceSource::PutTrack(track* this_track){
// pass to other method since it copies to a continguous array, so contiguity is guranteed, some compilers might pad the struct...
PutTrack( this_track->nps,
this_track->bitarray,
this_track->wgt,
this_track->erg,
this_track->tme,
this_track->x,
this_track->y,
this_track->z,
this_track->xhat,
this_track->yhat,
this_track->cs,
this_track->zhat
);
}
| 36.133201 | 174 | 0.635626 | sellitforcache |
f3ac9ec03734001a5239da0d0e564b5d54538367 | 2,111 | hpp | C++ | simulations/landau/pdi_out.yml.hpp | gyselax/gyselalibxx | 5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34 | [
"MIT"
] | 3 | 2022-02-28T08:47:07.000Z | 2022-03-01T10:29:08.000Z | simulations/landau/pdi_out.yml.hpp | gyselax/gyselalibxx | 5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34 | [
"MIT"
] | null | null | null | simulations/landau/pdi_out.yml.hpp | gyselax/gyselalibxx | 5f9b4b1e20050f87e2a9f05d510bedf0f9a15b34 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: MIT
constexpr char const* const PDI_CFG = R"PDI_CFG(
metadata:
Nx : int
Nvx : int
iter : int
time_saved : double
nbstep_diag: int
iter_saved : int
MeshX_extents: { type: array, subtype: int64, size: 1 }
MeshX:
type: array
subtype: double
size: [ '$MeshX_extents[0]' ]
MeshVx_extents: { type: array, subtype: int64, size: 1 }
MeshVx:
type: array
subtype: double
size: [ '$MeshVx_extents[0]' ]
Nkinspecies: int
fdistribu_charges_extents : { type: array, subtype: int64, size: 1 }
fdistribu_charges:
type: array
subtype: int
size: [ '$fdistribu_charges_extents[0]' ]
fdistribu_masses_extents : { type: array, subtype: int64, size: 1 }
fdistribu_masses:
type: array
subtype: double
size: [ '$fdistribu_masses_extents[0]' ]
fdistribu_eq_extents : { type: array, subtype: int64, size: 2 }
fdistribu_eq:
type: array
subtype: double
size: [ '$fdistribu_eq_extents[0]', '$fdistribu_eq_extents[1]' ]
data:
fdistribu_extents: { type: array, subtype: int64, size: 3 }
fdistribu:
type: array
subtype: double
size: [ '$fdistribu_extents[0]', '$fdistribu_extents[1]', '$fdistribu_extents[2]' ]
electrostatic_potential_extents: { type: array, subtype: int64, size: 1 }
electrostatic_potential:
type: array
subtype: double
size: [ '$electrostatic_potential_extents[0]' ]
plugins:
set_value:
on_init:
- share:
- iter_saved: 0
on_data:
iter:
- set:
- iter_saved: '${iter}/${nbstep_diag}'
on_finalize:
- release: [iter_saved]
decl_hdf5:
- file: 'VOICEXX_initstate.h5'
on_event: [initial_state]
collision_policy: replace_and_warn
write: [Nx, Nvx, MeshX, MeshVx, nbstep_diag, Nkinspecies, fdistribu_charges,fdistribu_masses, fdistribu_eq]
- file: 'VOICEXX_${iter_saved:05}.h5'
on_event: [iteration, last_iteration]
when: '${iter} % ${nbstep_diag} = 0'
collision_policy: replace_and_warn
write: [time_saved, fdistribu, electrostatic_potential]
#trace: ~
)PDI_CFG";
| 28.917808 | 113 | 0.661772 | gyselax |
f3af0329054a8dc0eb1d0bfc6e412946eb4c21ba | 10,247 | cpp | C++ | torrentR/src/PhaseFit.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 125 | 2015-01-22T05:43:23.000Z | 2022-03-22T17:15:59.000Z | torrentR/src/PhaseFit.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 59 | 2015-02-10T09:13:06.000Z | 2021-11-11T02:32:38.000Z | torrentR/src/PhaseFit.cpp | konradotto/TS | bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e | [
"Apache-2.0"
] | 98 | 2015-01-17T01:25:10.000Z | 2022-03-18T17:29:42.000Z | /* Copyright (C) 2010 Ion Torrent Systems, Inc. All Rights Reserved */
#include <iostream>
#include <iomanip>
#include "PhaseFit.h"
#include "Stats.h"
PhaseFit::PhaseFit() {
read.resize(0);
signal.resize(0);
residual_raw_vec.resize(0);
residual_weighted_vec.resize(0);
err.resize(0);
flowString = "";
flowCycle.resize(0);
concentration.resize(0);
cf.resize(0);
ie.resize(0);
dr.resize(0);
nFlow = 0;
droopType = ONLY_WHEN_INCORPORATING;
maxAdv = 0;
droopAdvancerFirst.resize(0);
extendAdvancerFirst.resize(0);
droopAdvancer.resize(0);
extendAdvancer.resize(0);
flowWeight.resize(0);
ignoreHPs = false;
extraTaps = 0;
residualType = SQUARED;
residualSummary = MEAN;
}
void PhaseFit::InitializeFlowSpecs(
string _flowString,
vector<weight_vec_t> _concentration,
weight_vec_t _cf,
weight_vec_t _ie,
weight_vec_t _dr,
unsigned int _nFlow,
DroopType _droopType,
unsigned int _maxAdv
) {
read.resize(0);
signal.resize(0);
flowString = _flowString;
flowCycle.resize(flowString.length());
for(unsigned int iFlow=0; iFlow<flowString.length(); iFlow++)
flowCycle[iFlow] = charToNuc(flowString[iFlow]);
concentration = _concentration;
cf = _cf;
ie = _ie;
dr = _dr;
nFlow = _nFlow;
droopType = _droopType;
maxAdv = _maxAdv;
}
void PhaseFit::AddRead(weight_vec_t &seqFlow, weight_vec_t &sig, weight_t maxErr) {
// Convert vector of continuous values to ints
hpLen_vec_t hpFlow;
vector<unsigned int> untrustedFlow;
weight_vec_t::iterator iSeqFlow=seqFlow.begin();
for(unsigned int iFlow=0; iSeqFlow != seqFlow.end(); iFlow++, iSeqFlow++) {
// Round the signal
hpLen_t rounded = (hpLen_t) floor(*iSeqFlow + 0.5);
hpFlow.push_back(rounded);
// Check if it was larger than we'd like
weight_t err = abs(*iSeqFlow - (weight_t) rounded);
if(err > maxErr)
untrustedFlow.push_back(iFlow);
}
// Set weights
weight_vec_t newHpWeight(seqFlow.size(),1);
if(untrustedFlow.size() > 0) {
unsigned int first_to_ignore = std::max(((int)untrustedFlow[0])-4,1);
for(weight_vec_t::iterator iHpWeight=newHpWeight.begin()+first_to_ignore; iHpWeight != newHpWeight.end(); iHpWeight++)
*iHpWeight = 0;
}
//cout << "Weights: ";
//for(unsigned int i=0; i<newHpWeight.size(); i++)
// cout << ", " << setiosflags(ios::fixed) << setprecision(2) << newHpWeight[i];
//cout << "\n";
// Set up the read
PhaseSim newRead;
newRead.setDroopType(droopType);
newRead.setFlowCycle(flowString);
newRead.setSeq(hpFlow);
newRead.setAdvancerContexts(maxAdv);
newRead.setExtraTaps(extraTaps);
// Store the results
read.push_back(newRead);
hpWeight.push_back(newHpWeight);
signal.push_back(sig);
}
void PhaseFit::AddRead(string seq, weight_vec_t &sig) {
PhaseSim newRead;
newRead.setDroopType(droopType);
newRead.setFlowCycle(flowString);
newRead.setSeq(seq);
newRead.setAdvancerContexts(maxAdv);
newRead.setExtraTaps(extraTaps);
read.push_back(newRead);
signal.push_back(sig);
}
int PhaseFit::LevMarFit(int max_iter, int nParam, float *params) {
unsigned int nRead = signal.size();
int nData = nRead * nFlow;
// Call LevMarFitter::Initialize() - the 3rd arg is null as we don't need access to
// the LevMarFitter's internal x array in the calls to Evaluate
Initialize(nParam,nData,NULL);
// Update LevMarFitter::residualWeight array if we are using flow-specific weighting or
// if we are ignoring homopolymers of size > 1
if( (!ignoreHPs) || (flowWeight.size() > 0) || (hpWeight.size() > 0) )
updateResidualWeight(ignoreHPs, flowWeight, hpWeight);
// Gather the observed data into an array of floats
float *y = new float[nData];
unsigned int iY=0;
for(unsigned int iRead=0; iRead<nRead; iRead++)
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++)
y[iY++] = (float) signal[iRead][iFlow];
err.resize(nData);
int nIter = LevMarFitter::Fit(max_iter, y, params);
// Store the (possibly weighted) residuals
float *fval = new float[len];
Evaluate(fval,params);
residual_raw_vec.resize(nRead);
residual_weighted_vec.resize(nRead);
for(unsigned int iRead=0,iY=0; iRead<nRead; iRead++) {
residual_raw_vec[iRead].resize(nFlow);
residual_weighted_vec[iRead].resize(nFlow);
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iY++) {
weight_t res = y[iY] - fval[iY];
residual_raw_vec[iRead][iFlow] = res;
residual_weighted_vec[iRead][iFlow] = residualWeight[iY] * res;
}
}
delete [] fval;
delete [] y;
return(nIter);
}
void PhaseFit::updateResidualWeight(bool ignoreHPs, weight_vec_t &flowWeight, vector<weight_vec_t> &hpWeight) {
// residualWeight is initialized in the call to LevMarFitter::Initialize(nparams,len,x)
// so this function should be called just after that call and
if(len > 0) {
// Initialize all weights to 1
for(int iRes=0; iRes<len; iRes++)
residualWeight[iRes] = 1;
// Apply per-flow multipliers
unsigned int nRead = read.size();
if(flowWeight.size() > 0) {
unsigned int iRes = 0;
for(unsigned int iRead=0; iRead < nRead; iRead++) {
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iRes++) {
if(iFlow >= flowWeight.size())
throw("flowWeight vector is shorter than the number of flows in one or more of the reads.");
residualWeight[iRes] *= flowWeight[iFlow];
}
}
}
// Apply per-flow multipliers
if(hpWeight.size() > 0) {
if(hpWeight.size()!=nRead)
throw("hpWeight vector should be either empty or of the same length as the number of reads");
unsigned int iRes = 0;
for(unsigned int iRead=0; iRead < nRead; iRead++) {
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iRes++) {
residualWeight[iRes] *= hpWeight[iRead][iFlow];
}
}
}
// Optionally ignore residuals for homopolymer runs of length larger than 1
if(ignoreHPs) {
unsigned int iRes = 0;
for(unsigned int iRead=0; iRead < nRead; iRead++) {
const hpLen_vec_t seqFlow = read[iRead].getSeqFlow();
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++, iRes++) {
if(seqFlow[iFlow] > 1)
residualWeight[iRes] = 0;
}
}
}
}
//cout << "weight for first read:\n";
//for(unsigned int iFlow=0, iRes=0; iFlow<nFlow; iFlow++, iRes++)
// cout << ", " << setiosflags(ios::fixed) << setprecision(2) << residualWeight[iRes];
//cout << "\n";
}
void PhaseFit::PrintResidual(float *params) {
unsigned int nRead = signal.size();
unsigned int nData = nRead * nFlow;
float *tmp = new float[nData];
Evaluate(tmp,params);
float *y = new float[nData];
for(unsigned int iRead=0, iY=0; iRead<nRead; iRead++)
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++)
y[iY++] = (float) signal[iRead][iFlow];
float res = CalcResidual(y, tmp, len);
cout << "Residual = " << setiosflags(ios::fixed) << setprecision(3) << res << "\n";
for(unsigned int iRead=0, iY=0; iRead<std::min(nRead,(unsigned int)2); iRead++) {
cout << "raw res [" << iRead << "]: ";
unsigned int iYsave = iY;
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iY++)
cout << " " << setiosflags(ios::fixed) << setprecision(3) << y[iY] - tmp[iY];
cout << "\n";
iY = iYsave;
cout << "wt res [" << iRead << "]: ";
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iY++)
cout << " " << setiosflags(ios::fixed) << setprecision(3) << residualWeight[iY] * (y[iY] - tmp[iY]);
cout << "\n";
}
delete [] y;
delete [] tmp;
}
float PhaseFit::CalcResidual(float *refVals, float *testVals, int numVals, double *err_vec) {
// Compute raw residuals and if necessary, return them
for (int i=0;i < numVals;i++)
err[i] = residualWeight[i] * (refVals[i]-testVals[i]);
if (err_vec)
for (int i=0;i < numVals;i++)
err_vec[i] = err[i];
// Transform residuals
switch(residualType) {
case(SQUARED):
for (int i=0;i < numVals;i++)
err[i] = pow(err[i], 2.0);
break;
case(ABSOLUTE):
for (int i=0;i < numVals;i++)
err[i] = abs(err[i]);
break;
case(GEMAN_MCCLURE):
for (int i=0;i < numVals;i++)
err[i] = ionStats::geman_mcclure(err[i]);
break;
default:
throw("Invalid residual type");
}
// Summarize the residuals
float r=0;
float numerator=0;
float denominator=0;
unsigned int nRead = signal.size();
weight_vec_t readErr;
switch(residualSummary) {
case(MEAN):
for (int i=0;i < numVals;i++)
if(residualWeight[i] > 0) {
numerator += err[i];
denominator += residualWeight[i];
}
r = numerator/denominator;
break;
case(MEDIAN):
readErr.reserve(numVals);
for (int i=0;i < numVals;i++)
if(residualWeight[i] > 0)
readErr.push_back(err[i]);
r = ionStats::median(readErr);
break;
case(MEAN_OF_MEDIAN):
readErr.reserve(nFlow);
for(unsigned int iRead=0, iErr=0; iRead<nRead; iRead++) {
readErr.resize(0);
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iErr++) {
if(residualWeight[iErr] > 0)
readErr.push_back(err[iErr]);
}
if(readErr.size() > 0) {
numerator += readErr.size() * ionStats::median(readErr);
denominator += readErr.size();
}
}
r = numerator/denominator;
break;
case(MEDIAN_OF_MEAN):
readErr.reserve(nRead);
readErr.resize(0);
for(unsigned int iRead=0, iErr=0; iRead<nRead; iRead++) {
numerator = 0;
denominator = 0;
for(unsigned int iFlow=0; iFlow<nFlow; iFlow++,iErr++) {
if(residualWeight[iErr] > 0) {
numerator += err[iErr];
denominator += residualWeight[iErr];
}
}
if(denominator > 0)
readErr.push_back(numerator/denominator);
}
r = ionStats::median(readErr);
break;
default:
throw("Invalid residual summary method");
}
return r;
}
| 29.787791 | 122 | 0.6235 | konradotto |
f3af83afc90d2e5d70380cedd8f4f19e2436f029 | 312 | cpp | C++ | MSVC/14.24.28314/crt/src/vcruntime/exe_main.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 2 | 2021-01-27T10:19:30.000Z | 2021-02-09T06:24:30.000Z | MSVC/14.24.28314/crt/src/vcruntime/exe_main.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | null | null | null | MSVC/14.24.28314/crt/src/vcruntime/exe_main.cpp | 825126369/UCRT | 8853304fdc2a5c216658d08b6dbbe716aa2a7b1f | [
"MIT"
] | 1 | 2021-01-27T10:19:36.000Z | 2021-01-27T10:19:36.000Z | //
// exe_wwinmain.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The mainCRTStartup() entry point, linked into client executables that
// uses main().
//
#define _SCRT_STARTUP_MAIN
#include "exe_common.inl"
extern "C" int mainCRTStartup()
{
return __scrt_common_main();
}
| 17.333333 | 72 | 0.705128 | 825126369 |
f3b027a869b88350a76d63899a2c1399332b7327 | 10,952 | cpp | C++ | libgtkgraph/annotation.cpp | arthursoprano/welldrift | 57fe6c2f5a5caea18c5e29fb1b17f6f29a59a98e | [
"MIT"
] | 1 | 2019-03-14T21:46:21.000Z | 2019-03-14T21:46:21.000Z | libgtkgraph/annotation.cpp | arthursoprano/welldrift | 57fe6c2f5a5caea18c5e29fb1b17f6f29a59a98e | [
"MIT"
] | null | null | null | libgtkgraph/annotation.cpp | arthursoprano/welldrift | 57fe6c2f5a5caea18c5e29fb1b17f6f29a59a98e | [
"MIT"
] | 2 | 2019-05-14T02:31:52.000Z | 2020-08-04T18:29:06.000Z | #include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include "libgtkgraph/gtkgraph.h"
#include "libgtkgraph/gtkgraph_internal.h"
/* Declaration of all local functions */
static GtkGraphAnnotation *gtk_graph_annotation_allocate(void);
/* Externally referenceable functions */
static GtkGraphAnnotation *gtk_graph_annotation_allocate(void)
{
GtkGraphAnnotation *tmp;
tmp = (GtkGraphAnnotation *) g_malloc(sizeof(GtkGraphAnnotation));
if (tmp == (GtkGraphAnnotation *) NULL)
{
(void) fprintf(stderr,"malloc failed at: %s\n","gtk_graph_trace_allocate");
return ((GtkGraphAnnotation *) NULL);
}
tmp->type = VERTICAL;
tmp->value = 0;
tmp->text = NULL;
tmp->next = NULL;
return(tmp);
}
/**
* gtk_graph_annotation_new:
* @graph: The #GtkGraph that you wish to add the annotation to
*
* Adds an annotation to a pre-existing #GtkGraph @graph.
*
* Returns: an unique integer identifying the new annotation. This must be
* stored if you wish to alter the properties of the annotation
*/
gint gtk_graph_annotation_new(GtkGraph *graph)
{
int i;
GtkGraphAnnotation *new_annotation, *tmp;
g_return_val_if_fail (graph != NULL, FALSE);
g_return_val_if_fail (GTK_IS_GRAPH (graph), FALSE);
new_annotation = gtk_graph_annotation_allocate();
if (graph->annotations == NULL)
graph->annotations = new_annotation;
else
{
for (i = 0, tmp = graph->annotations; tmp->next != NULL ; tmp = tmp->next , i++) // Should advance us to last item in list
;
tmp->next = new_annotation;
}
graph->num_annotations += 1;
return graph->num_annotations - 1;
}
/**
* gtk_graph_annotation_set_data:
* @graph: the #GtkGraph that contains the annotation you wish to modify
* @annotation_id: the unique integer ID returned by gtk_graph_annotation_new()
* @type:
* @value: value at which to display the annotation
* @text: any text that you want displayed next to the
*
* The function description goes here. You can use @par1 to refer to parameters
* so that they are highlighted in the output. You can also use %constant
* for constants, function_name2() for functions and #GtkWidget for links to
* other declarations (which may be documented elsewhere).
*/
void gtk_graph_annotation_set_data(GtkGraph *graph, gint annotation_id, GtkGraphAnnotationType type, gfloat value, gchar *text)
{
GtkGraphAnnotation *t;
gint i;
g_return_if_fail (graph != NULL);
g_return_if_fail (GTK_IS_GRAPH (graph));
if (graph->annotations == NULL)
return;
g_return_if_fail (annotation_id < graph->num_annotations);
t = graph->annotations;
for (i = 0 ; i < annotation_id ; i++)
t = t->next;
t->type = type;
t->value = value;
t->text = g_strdup(text);
}
void gtk_graph_plot_annotations(GtkGraph *graph)
{
gint n;
gint plotting_value, text_width, text_height;
GtkGraphAnnotation *tmp;
PangoFontDescription *fontdesc = NULL;
PangoLayout *layout = NULL;
gint centre_x = user_width / 2.0 + user_origin_x, xpos;
gint centre_y = user_height / 2.0 + user_origin_y, ypos;
gfloat theta, new_angle, r;
gchar *text_buffer = NULL;
//gint horizontal_position = user_origin_x;
gint vertical_position = user_origin_y;
g_return_if_fail (graph != NULL);
g_return_if_fail (GTK_IS_GRAPH (graph));
g_return_if_fail (gtk_widget_get_realized(GTK_WIDGET(graph)));
if (graph->annotations == NULL)
return;
fontdesc = pango_font_description_from_string("Sans 9");
layout = gtk_widget_create_pango_layout(GTK_WIDGET(graph), NULL);
pango_layout_set_font_description(layout, fontdesc);
tmp = graph->annotations;
for (n = 0 ; n < graph->num_annotations ; n++)
{
switch(tmp->type)
{
case HORIZONTAL:
if (graph->graph_type != XY) /* Skip on if the graph is not the correct type */
continue;
/* Ensure that we are within the plotable range and then draw the line*/
plotting_value = (gint) rint((graph->dependant->axis_max - tmp->value ) * graph->dependant->scale_factor) + user_origin_y;
if (tmp->value < graph->dependant->axis_min)
plotting_value = (gint) rint((graph->dependant->axis_max - graph->dependant->axis_min) * graph->dependant->scale_factor) + user_origin_y;
if (tmp->value > graph->dependant->axis_max)
plotting_value = user_origin_y;
gdk_draw_line(buffer, BlueandWcontext, user_origin_x, plotting_value, (graph->independant->n_maj_tick * graph->independant->pxls_per_maj_tick ) + user_origin_x, plotting_value);
/* Set text and then plot above line if value is below half way and vice versa */
if (text_buffer)
g_free(text_buffer);
if (tmp->text)
text_buffer = g_strdup_printf( "%s\nY: %.2f", tmp->text, tmp->value);
else
text_buffer = g_strdup_printf("Y: %.2f", tmp->value);
pango_layout_set_text(layout, text_buffer, -1);
pango_layout_get_pixel_size(layout, &text_width, &text_height);
if (tmp->value <= (graph->dependant->axis_max - graph->dependant->axis_min) / 2.0)
gdk_draw_layout(buffer, BandWcontext, (graph->independant->n_maj_tick * graph->independant->pxls_per_maj_tick )/2 + user_origin_x, plotting_value - text_height - 2, layout);
else
gdk_draw_layout(buffer, BandWcontext, (graph->independant->n_maj_tick * graph->independant->pxls_per_maj_tick )/2 + user_origin_x, plotting_value + 2, layout);
break;
case VERTICAL:
if (graph->graph_type != XY) /* Skip on if the graph is not the correct type */
continue;
/* Ensure that we are within the plotable range and then draw the line*/
plotting_value = (gint) rint((tmp->value - graph->independant->axis_min ) * graph->independant->scale_factor) + user_origin_x;
if (tmp->value < graph->independant->axis_min)
plotting_value = user_origin_x;
if (tmp->value > graph->independant->axis_max)
plotting_value = user_origin_x + graph->independant->pxls_per_maj_tick * graph->independant->n_maj_tick;
gdk_draw_line(buffer, BlueandWcontext, plotting_value, user_origin_y, plotting_value, user_origin_y + graph->dependant->pxls_per_maj_tick * graph->dependant->n_maj_tick);
/* Set text and then plot to the left if line on the right of the middle and vice versa */
if (text_buffer)
g_free(text_buffer);
if (tmp->text)
text_buffer = g_strdup_printf("%s\nX: %.2f", tmp->text, tmp->value);
else
text_buffer = g_strdup_printf("X: %.2f", tmp->value);
pango_layout_set_text(layout, text_buffer, -1);
pango_layout_get_pixel_size(layout, &text_width, &text_height);
if (tmp->value <= (graph->independant->axis_max - graph->independant->axis_min) / 2.0)
gdk_draw_layout(buffer, BandWcontext, plotting_value +2, vertical_position, layout);
else
gdk_draw_layout(buffer, BandWcontext, plotting_value - text_width - 2, vertical_position, layout);
vertical_position += text_height;
break;
case RADIAL:
if (graph->graph_type != POLAR)
continue;
new_angle = wrap_angle(tmp->value, graph->polar_format);
if (graph->polar_format.type >> 2) // i.e. one of the radian options
theta = new_angle + graph->polar_format.polar_start;
else // otherwise we must be in degrees
theta = (new_angle + graph->polar_format.polar_start) * M_PI / 180.0;
xpos = centre_x + (gint) (user_width / 2.0 * sin(theta));
ypos = centre_y - (gint) (user_height / 2.0 * cos(theta));
gdk_draw_line(buffer, BlueandWcontext, centre_x, centre_y, xpos, ypos);
if (text_buffer)
g_free(text_buffer);
if (tmp->text)
text_buffer = g_strdup_printf("%s\nTheta: %.2f", tmp->text, tmp->value);
else
text_buffer = g_strdup_printf("Theta: %.1f", tmp->value);
pango_layout_set_text(layout, text_buffer, -1);
pango_layout_get_pixel_size(layout, &text_width, &text_height);
if (xpos > centre_x)
{
if (ypos >= centre_y)
gdk_draw_layout(buffer, BandWcontext, xpos, ypos, layout);
else
gdk_draw_layout(buffer, BandWcontext, xpos, ypos-text_height - 2, layout);
}
else
{
if (ypos >= centre_y)
gdk_draw_layout(buffer, BandWcontext, xpos - text_width - 2, ypos, layout);
else
gdk_draw_layout(buffer, BandWcontext, xpos - text_width - 2, ypos - text_height - 2, layout);
}
break;
case AZIMUTHAL:
if (graph->graph_type != POLAR)
continue;
plotting_value = (gint) rint(((tmp->value - graph->dependant->axis_min ) * graph->dependant->scale_factor));
if (tmp->value < graph->dependant->axis_min)
plotting_value = 0;
if (tmp->value > graph->dependant->axis_max)
plotting_value = (gint) rint((graph->dependant->axis_max - graph->dependant->axis_min) * graph->dependant->scale_factor);
gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - plotting_value, centre_y - plotting_value, 2.0 * plotting_value, 2.0 * plotting_value, 0, 23040);
if (text_buffer)
g_free(text_buffer);
if (tmp->text)
text_buffer = g_strdup_printf( "%s\nRadius: %.1f", tmp->text, tmp->value);
else
text_buffer = g_strdup_printf( "Radius: %.1f", tmp->value);
pango_layout_set_text(layout, text_buffer, -1);
pango_layout_get_pixel_size(layout, &text_width, &text_height);
gdk_draw_layout(buffer, BandWcontext, centre_x - plotting_value / 1.414 - text_width - 2, centre_y - plotting_value / 1.414 - text_height, layout);
break;
case VSWR:
if (graph->graph_type != SMITH)
continue;
plotting_value = fabs((tmp->value - 1.0)/(tmp->value + 1.0))*graph->dependant->scale_factor;
gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - plotting_value, centre_y - plotting_value, 2.0 * plotting_value, 2.0 * plotting_value, 0, 23040);
if (text_buffer)
g_free(text_buffer);
if (tmp->text)
text_buffer = g_strdup_printf( "%s\nVSWR: %.1f", tmp->text, tmp->value);
else
text_buffer = g_strdup_printf( "VSWR: %.1f", tmp->value);
pango_layout_set_text(layout, text_buffer, -1);
pango_layout_get_pixel_size(layout, &text_width, &text_height);
break;
case Q:
if (graph->graph_type != SMITH)
continue;
plotting_value = (1.0 / tmp->value) * graph->dependant->scale_factor;
r = sqrt(1.0 / (tmp->value * tmp->value) + 1.0) * graph->dependant->scale_factor;
theta = atan(1.0 / tmp->value) * 180.0 / M_PI * 64;
gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - r, centre_y + plotting_value - r, 2.0 * r, 2.0 * r, theta, 11520 - 2.0 * theta);
gdk_draw_arc(buffer, BlueandWcontext, FALSE, centre_x - r, centre_y - plotting_value - r, 2.0 * r, 2.0 * r, 11520 + theta, 11520 - 2.0 * theta);
if (text_buffer)
g_free(text_buffer);
if (tmp->text)
text_buffer = g_strdup_printf( "%s\nQ: %.1f", tmp->text, tmp->value);
else
text_buffer = g_strdup_printf( "Q: %.1f", tmp->value);
pango_layout_set_text(layout, text_buffer, -1);
pango_layout_get_pixel_size(layout, &text_width, &text_height);
gdk_draw_layout(buffer, BandWcontext, centre_x - text_width / 2, centre_y - plotting_value + r, layout);
break;
}
/* and then move onto the next trace */
tmp = tmp->next;
}
pango_font_description_free(fontdesc);
g_object_unref(layout);
}
| 39.681159 | 180 | 0.710738 | arthursoprano |
f3b08568106455f684f40669c567e4062eea231e | 427 | cpp | C++ | programming/numerical_algorithms/horner_value.cpp | Kartm/hs-cs-final-exam | 6af11324740d53a68b921582ab6ec1adee7634e6 | [
"MIT"
] | 1 | 2019-01-27T13:34:42.000Z | 2019-01-27T13:34:42.000Z | programming/numerical_algorithms/horner_value.cpp | Kartm/hs-cs-final-exam | 6af11324740d53a68b921582ab6ec1adee7634e6 | [
"MIT"
] | null | null | null | programming/numerical_algorithms/horner_value.cpp | Kartm/hs-cs-final-exam | 6af11324740d53a68b921582ab6ec1adee7634e6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int calculate(vector<int> coefficients, int x) {
int result = coefficients[0];
for(int i = 1; i < coefficients.size(); i++) {
result = result * x + coefficients[i];
}
return result;
}
int main() {
//* x*x*x + 2*x - 10;
vector<int> coefficients {1, 0, 2, -10};
cout << calculate(coefficients, 10);
return 0;
} | 21.35 | 50 | 0.594848 | Kartm |
f3b1ddfb733df2d1cb3c849ea5ef2d8a171ffd61 | 1,885 | hpp | C++ | openstudiocore/src/isomodel/Lighting.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | 1 | 2016-12-29T08:45:03.000Z | 2016-12-29T08:45:03.000Z | openstudiocore/src/isomodel/Lighting.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | openstudiocore/src/isomodel/Lighting.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef ISOMODEL_LIGHTING_HPP
#define ISOMODEL_LIGHTING_HPP
namespace openstudio {
namespace isomodel {
class Lighting
{
public:
double powerDensityOccupied() const {return _powerDensityOccupied;}
double powerDensityUnoccupied() const {return _powerDensityUnoccupied;}
double dimmingFraction() const {return _dimmingFraction;}
double exteriorEnergy() const {return _exteriorEnergy;}
void setPowerDensityOccupied(double value) {_powerDensityOccupied = value;}
void setPowerDensityUnoccupied(double value) {_powerDensityUnoccupied = value;}
void setDimmingFraction(double value) {_dimmingFraction = value;}
void setExteriorEnergy(double value) {_exteriorEnergy = value;}
private:
double _powerDensityOccupied;
double _powerDensityUnoccupied;
double _dimmingFraction;
double _exteriorEnergy;
};
} // isomodel
} // openstudio
#endif // ISOMODEL_LIGHTING_HPP
| 39.270833 | 83 | 0.708753 | jasondegraw |
f3b203cab02e2ef25204d35e14bd9ac6f4cf315b | 261 | hpp | C++ | SystemResource/Source/Container/QuadTree/QuadTreePosition.hpp | BitPaw/BitFireEngine | 2c02a4eae19276bf60ac925e4393966cec605112 | [
"MIT"
] | 5 | 2021-10-19T18:30:43.000Z | 2022-03-19T22:02:02.000Z | SystemResource/Source/Container/QuadTree/QuadTreePosition.hpp | BitPaw/BitFireEngine | 2c02a4eae19276bf60ac925e4393966cec605112 | [
"MIT"
] | 12 | 2022-03-09T13:40:21.000Z | 2022-03-31T12:47:48.000Z | SystemResource/Source/Container/QuadTree/QuadTreePosition.hpp | BitPaw/BitFireEngine | 2c02a4eae19276bf60ac925e4393966cec605112 | [
"MIT"
] | null | null | null | #pragma once
namespace BF
{
template<typename NumberType>
struct QuadTreePosition
{
public:
NumberType X;
NumberType Y;
QuadTreePosition()
{
X = 0;
Y = 0;
}
QuadTreePosition(NumberType x, NumberType y)
{
X = x;
Y = y;
}
};
} | 10.875 | 46 | 0.609195 | BitPaw |
f3b28456787c91d898fe1fe0ff964eb330dd546b | 240 | cpp | C++ | 7-Reverse-Integer.cpp | andy-sheng/leetcode | 1fa070036f31d0bd18a9a11a5c771641f3cd9a03 | [
"MIT"
] | null | null | null | 7-Reverse-Integer.cpp | andy-sheng/leetcode | 1fa070036f31d0bd18a9a11a5c771641f3cd9a03 | [
"MIT"
] | null | null | null | 7-Reverse-Integer.cpp | andy-sheng/leetcode | 1fa070036f31d0bd18a9a11a5c771641f3cd9a03 | [
"MIT"
] | null | null | null | class Solution {
public:
int reverse(int x) {
long int tmp = 0;
while (x != 0) {
tmp = tmp * 10 + x % 10;
x = x / 10;
}
return (tmp > INT_MAX || tmp < INT_MIN) ? 0 : tmp;
}
}; | 21.818182 | 58 | 0.4 | andy-sheng |
f3b86313a2b242622e540a7112921b8a072d7eac | 6,712 | cpp | C++ | kernel/thor/arch/arm/ints.cpp | kITerE/managarm | e6d1229a0bed68cb672a9cad300345a9006d78c1 | [
"MIT"
] | 935 | 2018-05-23T14:56:18.000Z | 2022-03-29T07:27:20.000Z | kernel/thor/arch/arm/ints.cpp | kITerE/managarm | e6d1229a0bed68cb672a9cad300345a9006d78c1 | [
"MIT"
] | 314 | 2018-05-04T15:58:06.000Z | 2022-03-30T16:24:17.000Z | kernel/thor/arch/arm/ints.cpp | kITerE/managarm | e6d1229a0bed68cb672a9cad300345a9006d78c1 | [
"MIT"
] | 65 | 2019-04-21T14:26:51.000Z | 2022-03-12T03:16:41.000Z | #include <thor-internal/arch/cpu.hpp>
#include <thor-internal/arch/ints.hpp>
#include <thor-internal/arch/gic.hpp>
#include <thor-internal/debug.hpp>
#include <thor-internal/thread.hpp>
#include <assert.h>
namespace thor {
extern "C" void *thorExcVectors;
void initializeIrqVectors() {
asm volatile ("msr vbar_el1, %0" :: "r"(&thorExcVectors));
}
extern "C" void enableIntsAndHaltForever();
void suspendSelf() {
assert(!intsAreEnabled());
getCpuData()->currentDomain = static_cast<uint64_t>(Domain::idle);
enableIntsAndHaltForever();
}
extern frg::manual_box<GicDistributor> dist;
void sendPingIpi(int id) {
dist->sendIpi(getCpuData(id)->gicCpuInterface->interfaceNumber(), 0);
}
void sendShootdownIpi() {
dist->sendIpiToOthers(1);
}
extern "C" void onPlatformInvalidException(FaultImageAccessor image) {
thor::panicLogger() << "thor: an invalid exception has occured" << frg::endlog;
}
namespace {
Word mmuAbortError(uint64_t esr) {
Word errorCode = 0;
auto ec = esr >> 26;
auto iss = esr & ((1 << 25) - 1);
// Originated from EL0
if (ec == 0x20 || ec == 0x24)
errorCode |= kPfUser;
// Is an instruction abort
if (ec == 0x20 || ec == 0x21) {
errorCode |= kPfInstruction;
} else {
if (iss & (1 << 6))
errorCode |= kPfWrite;
}
auto sc = iss & 0x3F;
if (sc < 16) {
auto type = (sc >> 2) & 0b11;
if (type == 0) // Address size fault
errorCode |= kPfBadTable;
if (type != 1) // Not a translation fault
errorCode |= kPfAccess;
}
return errorCode;
}
bool updatePageAccess(FaultImageAccessor image, Word error) {
if ((error & kPfWrite) && (error & kPfAccess) && !inHigherHalf(*image.faultAddr())) {
// Check if it's just a writable page that's not dirty yet
smarter::borrowed_ptr<Thread> this_thread = getCurrentThread();
return this_thread->getAddressSpace()->updatePageAccess(*image.faultAddr() & ~(kPageSize - 1));
}
return false;
}
} // namespace anonymous
void handlePageFault(FaultImageAccessor image, uintptr_t address, Word errorCode);
void handleOtherFault(FaultImageAccessor image, Interrupt fault);
void handleSyscall(SyscallImageAccessor image);
constexpr bool logUpdatePageAccess = false;
extern "C" void onPlatformSyncFault(FaultImageAccessor image) {
auto ec = *image.code() >> 26;
enableInts();
switch (ec) {
case 0x00: // Invalid
case 0x18: // Trapped MSR, MRS, or System instruction
handleOtherFault(image, kIntrIllegalInstruction);
break;
case 0x20: // Instruction abort, lower EL
case 0x21: // Instruction abort, same EL
case 0x24: // Data abort, lower EL
case 0x25: { // Data abort, same EL
auto error = mmuAbortError(*image.code());
if (updatePageAccess(image, error)) {
if constexpr (logUpdatePageAccess) {
infoLogger() << "thor: updated page "
<< (void *)(*image.faultAddr() & ~(kPageSize - 1))
<< " status on access from " << (void *)*image.ip() << frg::endlog;
}
break;
}
handlePageFault(image, *image.faultAddr(), error);
break;
}
case 0x15: // Trapped SVC in AArch64
handleSyscall(image);
break;
case 0x30: // Breakpoint, lower EL
case 0x31: // Breakpoint, same EL
handleOtherFault(image, kIntrBreakpoint);
break;
case 0x0E: // Illegal Execution fault
case 0x22: // IP alignment fault
case 0x26: // SP alignment fault
handleOtherFault(image, kIntrGeneralFault);
break;
case 0x3C: // BRK instruction
handleOtherFault(image, kIntrBreakpoint);
break;
default:
panicLogger() << "Unexpected fault " << ec
<< " from ip: " << (void *)*image.ip() << "\n"
<< "sp: " << (void *)*image.sp() << " "
<< "syndrome: 0x" << frg::hex_fmt(*image.code()) << " "
<< "saved state: 0x" << frg::hex_fmt(*image.rflags()) << frg::endlog;
}
disableInts();
}
extern "C" void onPlatformAsyncFault(FaultImageAccessor image) {
urgentLogger() << "thor: On CPU " << getCpuData()->cpuIndex << frg::endlog;
urgentLogger() << "thor: An asynchronous fault has occured!" << frg::endlog;
auto code = *image.code();
auto ec = code >> 26;
bool recoverable = false;
if (ec == 0x2F) {
bool ids = code & (1 << 24);
bool iesb = code & (1 << 13);
uint8_t aet = (code >> 10) & 7;
bool ea = code & (1 << 9);
uint8_t dfsc = code & 0x3F;
constexpr const char *aet_str[] = {
"Uncontainable",
"Unrecoverable state",
"Restartable state",
"Recoverable state",
"Reserved",
"Reserved",
"Corrected",
"Reserved"
};
if (ids) {
urgentLogger() << "thor: SError with implementation defined information: ESR = 0x"
<< frg::hex_fmt{code} << frg::endlog;
} else {
auto log = urgentLogger();
log << "thor: ";
if (dfsc == 0x11)
log << aet_str[aet] << " ";
log << "SError ";
log << " (EA = " << (ea ? "true" : "false")
<< ", IESB = " << (iesb ? "true" : "false") << ")";
if (dfsc != 0x11)
log << " with DFSC = " << dfsc;
log << frg::endlog;
if (aet == 2 || aet == 12)
recoverable = true;
}
} else {
urgentLogger() << "thor: unexpectec EC " << ec << " (ESR = 0x"
<< frg::hex_fmt{code} << ")" << frg::endlog;
}
urgentLogger() << "thor: IP = 0x" << frg::hex_fmt{*image.ip()}
<< ", SP = 0x" << frg::hex_fmt{*image.sp()} << frg::endlog;
if (!recoverable)
panicLogger() << "thor: Panic due to unrecoverable error" << frg::endlog;
}
void handleIrq(IrqImageAccessor image, int number);
void handlePreemption(IrqImageAccessor image);
static constexpr bool logSGIs = false;
static constexpr bool logSpurious = false;
extern "C" void onPlatformIrq(IrqImageAccessor image) {
auto &cpuInterface = getCpuData()->gicCpuInterface;
auto [cpu, irq] = cpuInterface->get();
asm volatile ("isb" ::: "memory");
if (irq < 16) {
if constexpr (logSGIs)
infoLogger() << "thor: onPlatformIrq: on CPU " << getCpuData()->cpuIndex << ", got a SGI (no. " << irq << ") that originated from CPU " << cpu << frg::endlog;
cpuInterface->eoi(cpu, irq);
if (irq == 0) {
handlePreemption(image);
} else {
assert(irq == 1);
assert(!irqMutex().nesting());
disableUserAccess();
for(int i = 0; i < maxAsid; i++)
getCpuData()->asidBindings[i].shootdown();
getCpuData()->globalBinding.shootdown();
}
} else if (irq >= 1020) {
if constexpr (logSpurious)
infoLogger() << "thor: on CPU " << getCpuData()->cpuIndex << ", spurious IRQ " << irq << " occured" << frg::endlog;
// no need to EOI spurious irqs
} else {
handleIrq(image, irq);
}
}
extern "C" void onPlatformWork() {
assert(!irqMutex().nesting());
// TODO: User-access should already be disabled here.
disableUserAccess();
enableInts();
getCurrentThread()->mainWorkQueue()->run();
disableInts();
}
} // namespace thor
| 26.425197 | 161 | 0.637217 | kITerE |
f3b93238faf0dd7870d5a703b97ec754824b1ca7 | 8,515 | cc | C++ | content/browser/compositor/reflector_impl.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-01-25T09:58:49.000Z | 2020-01-25T09:58:49.000Z | content/browser/compositor/reflector_impl.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/compositor/reflector_impl.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/compositor/reflector_impl.h"
#include "base/bind.h"
#include "base/location.h"
#include "content/browser/compositor/browser_compositor_output_surface.h"
#include "content/browser/compositor/owned_mailbox.h"
#include "content/common/gpu/client/gl_helper.h"
#include "ui/compositor/layer.h"
namespace content {
ReflectorImpl::ReflectorImpl(
ui::Compositor* mirrored_compositor,
ui::Layer* mirroring_layer,
IDMap<BrowserCompositorOutputSurface>* output_surface_map,
base::MessageLoopProxy* compositor_thread_loop,
int surface_id)
: impl_unsafe_(output_surface_map),
main_unsafe_(mirrored_compositor, mirroring_layer),
impl_message_loop_(compositor_thread_loop),
main_message_loop_(base::MessageLoopProxy::current()),
surface_id_(surface_id) {
GLHelper* helper = ImageTransportFactory::GetInstance()->GetGLHelper();
MainThreadData& main = GetMain();
main.mailbox = new OwnedMailbox(helper);
impl_message_loop_->PostTask(
FROM_HERE,
base::Bind(
&ReflectorImpl::InitOnImplThread, this, main.mailbox->holder()));
}
ReflectorImpl::MainThreadData::MainThreadData(
ui::Compositor* mirrored_compositor,
ui::Layer* mirroring_layer)
: needs_set_mailbox(true),
mirrored_compositor(mirrored_compositor),
mirroring_layer(mirroring_layer) {}
ReflectorImpl::MainThreadData::~MainThreadData() {}
ReflectorImpl::ImplThreadData::ImplThreadData(
IDMap<BrowserCompositorOutputSurface>* output_surface_map)
: output_surface_map(output_surface_map),
output_surface(NULL),
texture_id(0) {}
ReflectorImpl::ImplThreadData::~ImplThreadData() {}
ReflectorImpl::ImplThreadData& ReflectorImpl::GetImpl() {
DCHECK(impl_message_loop_->BelongsToCurrentThread());
return impl_unsafe_;
}
ReflectorImpl::MainThreadData& ReflectorImpl::GetMain() {
DCHECK(main_message_loop_->BelongsToCurrentThread());
return main_unsafe_;
}
void ReflectorImpl::InitOnImplThread(const gpu::MailboxHolder& mailbox_holder) {
ImplThreadData& impl = GetImpl();
// Ignore if the reflector was shutdown before
// initialized, or it's already initialized.
if (!impl.output_surface_map || impl.gl_helper.get())
return;
impl.mailbox_holder = mailbox_holder;
BrowserCompositorOutputSurface* source_surface =
impl.output_surface_map->Lookup(surface_id_);
// Skip if the source surface isn't ready yet. This will be
// initialized when the source surface becomes ready.
if (!source_surface)
return;
AttachToOutputSurfaceOnImplThread(impl.mailbox_holder, source_surface);
}
void ReflectorImpl::OnSourceSurfaceReady(
BrowserCompositorOutputSurface* source_surface) {
ImplThreadData& impl = GetImpl();
AttachToOutputSurfaceOnImplThread(impl.mailbox_holder, source_surface);
}
void ReflectorImpl::Shutdown() {
MainThreadData& main = GetMain();
main.mailbox = NULL;
main.mirroring_layer->SetShowPaintedContent();
main.mirroring_layer = NULL;
impl_message_loop_->PostTask(
FROM_HERE, base::Bind(&ReflectorImpl::ShutdownOnImplThread, this));
}
void ReflectorImpl::DetachFromOutputSurface() {
ImplThreadData& impl = GetImpl();
DCHECK(impl.output_surface);
impl.output_surface->SetReflector(NULL);
DCHECK(impl.texture_id);
impl.gl_helper->DeleteTexture(impl.texture_id);
impl.texture_id = 0;
impl.gl_helper.reset();
impl.output_surface = NULL;
}
void ReflectorImpl::ShutdownOnImplThread() {
ImplThreadData& impl = GetImpl();
if (impl.output_surface)
DetachFromOutputSurface();
impl.output_surface_map = NULL;
// The instance must be deleted on main thread.
main_message_loop_->PostTask(FROM_HERE,
base::Bind(&ReflectorImpl::DeleteOnMainThread,
scoped_refptr<ReflectorImpl>(this)));
}
void ReflectorImpl::ReattachToOutputSurfaceFromMainThread(
BrowserCompositorOutputSurface* output_surface) {
MainThreadData& main = GetMain();
GLHelper* helper = ImageTransportFactory::GetInstance()->GetGLHelper();
main.mailbox = new OwnedMailbox(helper);
main.needs_set_mailbox = true;
main.mirroring_layer->SetShowPaintedContent();
impl_message_loop_->PostTask(
FROM_HERE,
base::Bind(&ReflectorImpl::AttachToOutputSurfaceOnImplThread,
this,
main.mailbox->holder(),
output_surface));
}
void ReflectorImpl::OnMirroringCompositorResized() {
MainThreadData& main = GetMain();
main.mirroring_layer->SchedulePaint(main.mirroring_layer->bounds());
}
void ReflectorImpl::OnSwapBuffers() {
ImplThreadData& impl = GetImpl();
gfx::Size size = impl.output_surface->SurfaceSize();
if (impl.texture_id) {
impl.gl_helper->CopyTextureFullImage(impl.texture_id, size);
impl.gl_helper->Flush();
}
main_message_loop_->PostTask(
FROM_HERE,
base::Bind(
&ReflectorImpl::FullRedrawOnMainThread, this->AsWeakPtr(), size));
}
void ReflectorImpl::OnPostSubBuffer(gfx::Rect rect) {
ImplThreadData& impl = GetImpl();
if (impl.texture_id) {
impl.gl_helper->CopyTextureSubImage(impl.texture_id, rect);
impl.gl_helper->Flush();
}
main_message_loop_->PostTask(
FROM_HERE,
base::Bind(&ReflectorImpl::UpdateSubBufferOnMainThread,
this->AsWeakPtr(),
impl.output_surface->SurfaceSize(),
rect));
}
ReflectorImpl::~ReflectorImpl() {
// Make sure the reflector is deleted on main thread.
DCHECK_EQ(main_message_loop_.get(), base::MessageLoopProxy::current().get());
}
static void ReleaseMailbox(scoped_refptr<OwnedMailbox> mailbox,
unsigned int sync_point,
bool is_lost) {
mailbox->UpdateSyncPoint(sync_point);
}
void ReflectorImpl::AttachToOutputSurfaceOnImplThread(
const gpu::MailboxHolder& mailbox_holder,
BrowserCompositorOutputSurface* output_surface) {
ImplThreadData& impl = GetImpl();
if (output_surface == impl.output_surface)
return;
if (impl.output_surface)
DetachFromOutputSurface();
impl.output_surface = output_surface;
output_surface->context_provider()->BindToCurrentThread();
impl.gl_helper.reset(
new GLHelper(output_surface->context_provider()->ContextGL(),
output_surface->context_provider()->ContextSupport()));
impl.texture_id = impl.gl_helper->ConsumeMailboxToTexture(
mailbox_holder.mailbox, mailbox_holder.sync_point);
impl.gl_helper->ResizeTexture(impl.texture_id, output_surface->SurfaceSize());
impl.gl_helper->Flush();
output_surface->SetReflector(this);
// The texture doesn't have the data, so invokes full redraw now.
main_message_loop_->PostTask(
FROM_HERE,
base::Bind(&ReflectorImpl::FullRedrawContentOnMainThread,
scoped_refptr<ReflectorImpl>(this)));
}
void ReflectorImpl::UpdateTextureSizeOnMainThread(gfx::Size size) {
MainThreadData& main = GetMain();
if (!main.mirroring_layer || !main.mailbox.get() ||
main.mailbox->mailbox().IsZero())
return;
if (main.needs_set_mailbox) {
main.mirroring_layer->SetTextureMailbox(
cc::TextureMailbox(main.mailbox->holder()),
cc::SingleReleaseCallback::Create(
base::Bind(ReleaseMailbox, main.mailbox)),
size);
main.needs_set_mailbox = false;
} else {
main.mirroring_layer->SetTextureSize(size);
}
main.mirroring_layer->SetBounds(gfx::Rect(size));
}
void ReflectorImpl::FullRedrawOnMainThread(gfx::Size size) {
MainThreadData& main = GetMain();
if (!main.mirroring_layer)
return;
UpdateTextureSizeOnMainThread(size);
main.mirroring_layer->SchedulePaint(main.mirroring_layer->bounds());
}
void ReflectorImpl::UpdateSubBufferOnMainThread(gfx::Size size,
gfx::Rect rect) {
MainThreadData& main = GetMain();
if (!main.mirroring_layer)
return;
UpdateTextureSizeOnMainThread(size);
// Flip the coordinates to compositor's one.
int y = size.height() - rect.y() - rect.height();
gfx::Rect new_rect(rect.x(), y, rect.width(), rect.height());
main.mirroring_layer->SchedulePaint(new_rect);
}
void ReflectorImpl::FullRedrawContentOnMainThread() {
MainThreadData& main = GetMain();
main.mirrored_compositor->ScheduleFullRedraw();
}
} // namespace content
| 34.613821 | 80 | 0.723899 | Fusion-Rom |
f3bba51408e86ab52e64850002a9730e4b3a3adc | 2,984 | hpp | C++ | copper/hpp/triangle.hpp | CobaltXII/sterling | abef14ec8019aca55e359f78da5711c70be77d35 | [
"MIT"
] | 1 | 2019-03-15T11:55:15.000Z | 2019-03-15T11:55:15.000Z | copper/hpp/triangle.hpp | CobaltXII/copper | abef14ec8019aca55e359f78da5711c70be77d35 | [
"MIT"
] | null | null | null | copper/hpp/triangle.hpp | CobaltXII/copper | abef14ec8019aca55e359f78da5711c70be77d35 | [
"MIT"
] | null | null | null | #pragma once
struct triangle: shape
{
float x0;
float y0;
float z0;
float x1;
float y1;
float z1;
float x2;
float y2;
float z2;
float norm_x;
float norm_y;
float norm_z;
triangle
(
material_type material,
float x0,
float y0,
float z0,
float x1,
float y1,
float z1,
float x2,
float y2,
float z2,
float r,
float g,
float b
)
{
this->primitive = shape_type::st_triangle;
this->x0 = x0;
this->y0 = y0;
this->z0 = z0;
this->x1 = x1;
this->y1 = y1;
this->z1 = z1;
this->x2 = x2;
this->y2 = y2;
this->z2 = z2;
this->r = r;
this->g = g;
this->b = b;
this->material = material;
// Surface normal.
float v1v0_x = x1 - x0;
float v1v0_y = y1 - y0;
float v1v0_z = z1 - z0;
float v2v0_x = x2 - x0;
float v2v0_y = y2 - y0;
float v2v0_z = z2 - z0;
float cross_x = v1v0_y * v2v0_z - v2v0_y * v1v0_z;
float cross_y = v1v0_x * v2v0_z - v2v0_x * v1v0_z;
float cross_z = v1v0_x * v2v0_y - v2v0_x * v1v0_y;
float cross_len = sqrtf
(
cross_x * cross_x +
cross_y * cross_y +
cross_z * cross_z
);
norm_x = cross_x / cross_len;
norm_y = cross_y / cross_len;
norm_z = cross_z / cross_len;
}
};
inline triangle TO_TRIANGLE(shape* __victim)
{
return *((triangle*)__victim);
}
inline float triangle_intersect
(
triangle triangle1,
float ray_ox, float ray_oy, float ray_oz,
float ray_dx, float ray_dy, float ray_dz,
float* norm_x,
float* norm_y,
float* norm_z,
float* texture_u,
float* texture_v
)
{
#define v0_x (triangle1.x0)
#define v0_y (triangle1.y0)
#define v0_z (triangle1.z0)
#define v1_x (triangle1.x1)
#define v1_y (triangle1.y1)
#define v1_z (triangle1.z1)
#define v2_x (triangle1.x2)
#define v2_y (triangle1.y2)
#define v2_z (triangle1.z2)
float v0v1_x = v1_x - v0_x;
float v0v1_y = v1_y - v0_y;
float v0v1_z = v1_z - v0_z;
float v0v2_x = v2_x - v0_x;
float v0v2_y = v2_y - v0_y;
float v0v2_z = v2_z - v0_z;
float pvec_x = ray_dy * v0v2_z - ray_dz * v0v2_y;
float pvec_y = ray_dz * v0v2_x - ray_dx * v0v2_z;
float pvec_z = ray_dx * v0v2_y - ray_dy * v0v2_x;
float inv_det = 1.0f /
(
v0v1_x * pvec_x +
v0v1_y * pvec_y +
v0v1_z * pvec_z
);
float tvec_x = ray_ox - v0_x;
float tvec_y = ray_oy - v0_y;
float tvec_z = ray_oz - v0_z;
float u = inv_det *
(
tvec_x * pvec_x +
tvec_y * pvec_y +
tvec_z * pvec_z
);
if (u < 0.0f || u > 1.0f)
{
return -1.0f;
}
float qvec_x = tvec_y * v0v1_z - tvec_z * v0v1_y;
float qvec_y = tvec_z * v0v1_x - tvec_x * v0v1_z;
float qvec_z = tvec_x * v0v1_y - tvec_y * v0v1_x;
float v = inv_det *
(
ray_dx * qvec_x +
ray_dy * qvec_y +
ray_dz * qvec_z
);
if (v < 0.0f || u + v > 1.0f)
{
return -1.0f;
}
float t = inv_det *
(
v0v2_x * qvec_x +
v0v2_y * qvec_y +
v0v2_z * qvec_z
);
set_ptr(norm_x, triangle1.norm_x);
set_ptr(norm_y, triangle1.norm_y);
set_ptr(norm_z, triangle1.norm_z);
set_ptr(texture_u, u);
set_ptr(texture_v, v);
return t;
} | 15.957219 | 52 | 0.632708 | CobaltXII |
f3bf94ef4e82be09f5968720040b6142bcd48cd7 | 11,104 | cpp | C++ | src/tools/codeeditor/docsearchcontroller.cpp | SpartanJ/eepp | 21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac | [
"MIT"
] | 37 | 2020-01-20T06:21:24.000Z | 2022-03-21T17:44:50.000Z | src/tools/codeeditor/docsearchcontroller.cpp | SpartanJ/eepp | 21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac | [
"MIT"
] | null | null | null | src/tools/codeeditor/docsearchcontroller.cpp | SpartanJ/eepp | 21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac | [
"MIT"
] | 9 | 2019-03-22T00:33:07.000Z | 2022-03-01T01:35:59.000Z | #include "docsearchcontroller.hpp"
#include "codeeditor.hpp"
DocSearchController::DocSearchController( UICodeEditorSplitter* editorSplitter, App* app ) :
mEditorSplitter( editorSplitter ), mApp( app ) {}
void DocSearchController::initSearchBar( UISearchBar* searchBar ) {
mSearchBarLayout = searchBar;
mSearchBarLayout->setVisible( false )->setEnabled( false );
auto addClickListener = [&]( UIWidget* widget, std::string cmd ) {
widget->addEventListener( Event::MouseClick, [this, cmd]( const Event* event ) {
const MouseEvent* mouseEvent = static_cast<const MouseEvent*>( event );
if ( mouseEvent->getFlags() & EE_BUTTON_LMASK )
mSearchBarLayout->execute( cmd );
} );
};
auto addReturnListener = [&]( UIWidget* widget, std::string cmd ) {
widget->addEventListener( Event::OnPressEnter, [this, cmd]( const Event* ) {
mSearchBarLayout->execute( cmd );
} );
};
UITextInput* findInput = mSearchBarLayout->find<UITextInput>( "search_find" );
UITextInput* replaceInput = mSearchBarLayout->find<UITextInput>( "search_replace" );
UICheckBox* caseSensitiveChk = mSearchBarLayout->find<UICheckBox>( "case_sensitive" );
UICheckBox* wholeWordChk = mSearchBarLayout->find<UICheckBox>( "whole_word" );
UICheckBox* luaPatternChk = mSearchBarLayout->find<UICheckBox>( "lua_pattern" );
caseSensitiveChk->addEventListener(
Event::OnValueChange, [&, caseSensitiveChk]( const Event* ) {
mSearchState.caseSensitive = caseSensitiveChk->isChecked();
} );
wholeWordChk->addEventListener( Event::OnValueChange, [&, wholeWordChk]( const Event* ) {
mSearchState.wholeWord = wholeWordChk->isChecked();
} );
luaPatternChk->addEventListener( Event::OnValueChange, [&, luaPatternChk]( const Event* ) {
mSearchState.type = luaPatternChk->isChecked() ? TextDocument::FindReplaceType::LuaPattern
: TextDocument::FindReplaceType::Normal;
} );
findInput->addEventListener( Event::OnTextChanged, [&, findInput]( const Event* ) {
if ( mSearchState.editor && mEditorSplitter->editorExists( mSearchState.editor ) ) {
mSearchState.text = findInput->getText();
mSearchState.editor->setHighlightWord( mSearchState.text );
if ( !mSearchState.text.empty() ) {
mSearchState.editor->getDocument().setSelection( { 0, 0 } );
if ( !findNextText( mSearchState ) ) {
findInput->addClass( "error" );
} else {
findInput->removeClass( "error" );
}
} else {
findInput->removeClass( "error" );
mSearchState.editor->getDocument().setSelection(
mSearchState.editor->getDocument().getSelection().start() );
}
}
} );
mSearchBarLayout->addCommand( "close-searchbar", [&] {
hideSearchBar();
if ( mEditorSplitter->getCurEditor() )
mEditorSplitter->getCurEditor()->setFocus();
if ( mSearchState.editor ) {
if ( mEditorSplitter->editorExists( mSearchState.editor ) ) {
mSearchState.editor->setHighlightWord( "" );
mSearchState.editor->setHighlightTextRange( TextRange() );
}
}
} );
mSearchBarLayout->addCommand( "repeat-find", [this] { findNextText( mSearchState ); } );
mSearchBarLayout->addCommand( "replace-all", [this, replaceInput] {
size_t count = replaceAll( mSearchState, replaceInput->getText() );
mApp->getNotificationCenter()->addNotification(
String::format( "Replaced %zu occurrences.", count ) );
replaceInput->setFocus();
} );
mSearchBarLayout->addCommand( "find-and-replace", [this, replaceInput] {
findAndReplace( mSearchState, replaceInput->getText() );
} );
mSearchBarLayout->addCommand( "find-prev", [this] { findPrevText( mSearchState ); } );
mSearchBarLayout->addCommand( "replace-selection", [this, replaceInput] {
replaceSelection( mSearchState, replaceInput->getText() );
} );
mSearchBarLayout->addCommand( "change-case", [&, caseSensitiveChk] {
caseSensitiveChk->setChecked( !caseSensitiveChk->isChecked() );
} );
mSearchBarLayout->addCommand( "change-whole-word", [&, wholeWordChk] {
wholeWordChk->setChecked( !wholeWordChk->isChecked() );
} );
mSearchBarLayout->addCommand( "toggle-lua-pattern", [&, luaPatternChk] {
luaPatternChk->setChecked( !luaPatternChk->isChecked() );
} );
mSearchBarLayout->getKeyBindings().addKeybindsString( { { "f3", "repeat-find" },
{ "ctrl+g", "repeat-find" },
{ "escape", "close-searchbar" },
{ "ctrl+r", "replace-all" },
{ "ctrl+s", "change-case" },
{ "ctrl+w", "change-whole-word" },
{ "ctrl+l", "toggle-lua-pattern" } } );
addReturnListener( findInput, "repeat-find" );
addReturnListener( replaceInput, "find-and-replace" );
addClickListener( mSearchBarLayout->find<UIPushButton>( "find_prev" ), "find-prev" );
addClickListener( mSearchBarLayout->find<UIPushButton>( "find_next" ), "repeat-find" );
addClickListener( mSearchBarLayout->find<UIPushButton>( "replace" ), "replace-selection" );
addClickListener( mSearchBarLayout->find<UIPushButton>( "replace_find" ), "find-and-replace" );
addClickListener( mSearchBarLayout->find<UIPushButton>( "replace_all" ), "replace-all" );
addClickListener( mSearchBarLayout->find<UIWidget>( "searchbar_close" ), "close-searchbar" );
replaceInput->addEventListener( Event::OnTabNavigate,
[findInput]( const Event* ) { findInput->setFocus(); } );
}
void DocSearchController::showFindView() {
mApp->hideLocateBar();
mApp->hideGlobalSearchBar();
UICodeEditor* editor = mEditorSplitter->getCurEditor();
if ( !editor )
return;
mSearchState.editor = editor;
mSearchState.range = TextRange();
mSearchState.caseSensitive =
mSearchBarLayout->find<UICheckBox>( "case_sensitive" )->isChecked();
mSearchState.wholeWord = mSearchBarLayout->find<UICheckBox>( "whole_word" )->isChecked();
mSearchBarLayout->setEnabled( true )->setVisible( true );
UITextInput* findInput = mSearchBarLayout->find<UITextInput>( "search_find" );
findInput->getDocument().selectAll();
findInput->setFocus();
const TextDocument& doc = editor->getDocument();
if ( doc.getSelection().hasSelection() && doc.getSelection().inSameLine() ) {
String text = doc.getSelectedText();
if ( !text.empty() ) {
findInput->setText( text );
findInput->getDocument().selectAll();
} else if ( !findInput->getText().empty() ) {
findInput->getDocument().selectAll();
}
} else if ( doc.getSelection().hasSelection() ) {
mSearchState.range = doc.getSelection( true );
if ( !findInput->getText().empty() )
findInput->getDocument().selectAll();
}
mSearchState.text = findInput->getText();
editor->setHighlightTextRange( mSearchState.range );
editor->setHighlightWord( mSearchState.text );
editor->getDocument().setActiveClient( editor );
}
bool DocSearchController::findPrevText( SearchState& search ) {
if ( search.text.empty() )
search.text = mLastSearch;
if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) || search.text.empty() )
return false;
search.editor->getDocument().setActiveClient( search.editor );
mLastSearch = search.text;
TextDocument& doc = search.editor->getDocument();
TextRange range = doc.getDocRange();
TextPosition from = doc.getSelection( true ).start();
if ( search.range.isValid() ) {
range = doc.sanitizeRange( search.range ).normalized();
from = from < range.start() ? range.start() : from;
}
TextPosition found =
doc.findLast( search.text, from, search.caseSensitive, search.wholeWord, search.range );
if ( found.isValid() ) {
doc.setSelection( { doc.positionOffset( found, search.text.size() ), found } );
return true;
} else {
found = doc.findLast( search.text, range.end() );
if ( found.isValid() ) {
doc.setSelection( { doc.positionOffset( found, search.text.size() ), found } );
return true;
}
}
return false;
}
bool DocSearchController::findNextText( SearchState& search ) {
if ( search.text.empty() )
search.text = mLastSearch;
if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) || search.text.empty() )
return false;
search.editor->getDocument().setActiveClient( search.editor );
mLastSearch = search.text;
TextDocument& doc = search.editor->getDocument();
TextRange range = doc.getDocRange();
TextPosition from = doc.getSelection( true ).end();
if ( search.range.isValid() ) {
range = doc.sanitizeRange( search.range ).normalized();
from = from < range.start() ? range.start() : from;
}
TextRange found =
doc.find( search.text, from, search.caseSensitive, search.wholeWord, search.type, range );
if ( found.isValid() ) {
doc.setSelection( found.reversed() );
return true;
} else {
found = doc.find( search.text, range.start(), search.caseSensitive, search.wholeWord,
search.type, range );
if ( found.isValid() ) {
doc.setSelection( found.reversed() );
return true;
}
}
return false;
}
bool DocSearchController::replaceSelection( SearchState& search, const String& replacement ) {
if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) ||
!search.editor->getDocument().hasSelection() )
return false;
search.editor->getDocument().setActiveClient( search.editor );
search.editor->getDocument().replaceSelection( replacement );
return true;
}
int DocSearchController::replaceAll( SearchState& search, const String& replace ) {
if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) )
return 0;
if ( search.text.empty() )
search.text = mLastSearch;
if ( search.text.empty() )
return 0;
search.editor->getDocument().setActiveClient( search.editor );
mLastSearch = search.text;
TextDocument& doc = search.editor->getDocument();
TextPosition startedPosition = doc.getSelection().start();
int count = doc.replaceAll( search.text, replace, search.caseSensitive, search.wholeWord,
search.type, search.range );
doc.setSelection( startedPosition );
return count;
}
bool DocSearchController::findAndReplace( SearchState& search, const String& replace ) {
if ( !search.editor || !mEditorSplitter->editorExists( search.editor ) )
return false;
if ( search.text.empty() )
search.text = mLastSearch;
if ( search.text.empty() )
return false;
search.editor->getDocument().setActiveClient( search.editor );
mLastSearch = search.text;
TextDocument& doc = search.editor->getDocument();
if ( doc.hasSelection() && doc.getSelectedText() == search.text ) {
return replaceSelection( search, replace );
} else {
return findNextText( search );
}
}
void DocSearchController::hideSearchBar() {
mSearchBarLayout->setEnabled( false )->setVisible( false );
}
void DocSearchController::onCodeEditorFocusChange( UICodeEditor* editor ) {
if ( mSearchState.editor && mSearchState.editor != editor ) {
String word = mSearchState.editor->getHighlightWord();
mSearchState.editor->setHighlightWord( "" );
mSearchState.editor->setHighlightTextRange( TextRange() );
mSearchState.text = "";
mSearchState.range = TextRange();
if ( editor ) {
mSearchState.editor = editor;
mSearchState.editor->setHighlightWord( word );
mSearchState.range = TextRange();
}
}
}
SearchState& DocSearchController::getSearchState() {
return mSearchState;
}
| 39.375887 | 96 | 0.706412 | SpartanJ |
f3c3ee553473a1a56d52f298a0d5cdae363bcf10 | 434 | cpp | C++ | level_zero/core/source/gen12lp/adlp/cmdqueue_adlp.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 778 | 2017-09-29T20:02:43.000Z | 2022-03-31T15:35:28.000Z | level_zero/core/source/gen12lp/adlp/cmdqueue_adlp.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 478 | 2018-01-26T16:06:45.000Z | 2022-03-30T10:19:10.000Z | level_zero/core/source/gen12lp/adlp/cmdqueue_adlp.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 215 | 2018-01-30T08:39:32.000Z | 2022-03-29T11:08:51.000Z | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/core/source/cmdqueue/cmdqueue_hw.inl"
#include "level_zero/core/source/cmdqueue/cmdqueue_hw_base.inl"
#include "cmdqueue_extended.inl"
namespace L0 {
template struct CommandQueueHw<IGFX_GEN12LP_CORE>;
static CommandQueuePopulateFactory<IGFX_ALDERLAKE_P, CommandQueueHw<IGFX_GEN12LP_CORE>>
populateADLP;
} // namespace L0 | 24.111111 | 87 | 0.790323 | troels |
f3ca6f4d336f0b837cea93e26f59bcefe1e2cf61 | 625 | cpp | C++ | SimpleEngine/Simulation/WorldLogic.cpp | RichardBangs/SimpleEngine | a4acdf11d05e018db5a55994291475df55856c0c | [
"MIT"
] | null | null | null | SimpleEngine/Simulation/WorldLogic.cpp | RichardBangs/SimpleEngine | a4acdf11d05e018db5a55994291475df55856c0c | [
"MIT"
] | null | null | null | SimpleEngine/Simulation/WorldLogic.cpp | RichardBangs/SimpleEngine | a4acdf11d05e018db5a55994291475df55856c0c | [
"MIT"
] | null | null | null | #include "WorldLogic.h"
#include "WorldState.h"
#include "GameState.h"
#include "Events\ObjectDestroyedEvent.h"
namespace Simulation
{
WorldLogic::WorldLogic()
{
}
WorldLogic::~WorldLogic()
{
}
void WorldLogic::Tick(WorldState* thisWorld, GameState* stateLastFrame, std::vector<EventBase*> eventsThisFrame)
{
for (auto it = eventsThisFrame.begin(); it < eventsThisFrame.end(); ++it)
{
EventBase* myEvent = *it;
switch (myEvent->GetType())
{
case eEventType::ObjectDestroyed:
{
thisWorld->_objects.erase(static_cast<ObjectDestroyedEvent*>(myEvent)->_id);
}
break;
}
}
}
} | 17.857143 | 113 | 0.68 | RichardBangs |
f3d050ec97a6e657e2d1e97828d0134d2540e995 | 2,353 | hpp | C++ | grad_computer.hpp | auckland-cosmo/pspectre | c9114411bc9db0c353324c0f7c5ce2977daab452 | [
"BSD-2-Clause"
] | 1 | 2019-03-07T13:17:43.000Z | 2019-03-07T13:17:43.000Z | grad_computer.hpp | auckland-cosmo/pspectre | c9114411bc9db0c353324c0f7c5ce2977daab452 | [
"BSD-2-Clause"
] | 1 | 2019-08-21T01:08:43.000Z | 2019-08-21T01:08:43.000Z | grad_computer.hpp | auckland-cosmo/pspectre | c9114411bc9db0c353324c0f7c5ce2977daab452 | [
"BSD-2-Clause"
] | 4 | 2019-03-07T13:17:46.000Z | 2020-06-05T07:00:50.000Z | /*
* SpectRE - A Spectral Code for Reheating
* Copyright (C) 2009-2010 Hal Finkel, Nathaniel Roth and Richard Easther
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``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 AUTHORS 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
* @brief Computation of the gradient in Fourier space.
*/
#ifndef GRAD_COMPUTER_HPP
#define GRAD_COMPUTER_HPP
#include "field_size.hpp"
#include "model_params.hpp"
#include "field.hpp"
template <typename R>
class grad_computer {
public:
grad_computer(field_size &fs_, model_params<R> &mp_, field<R> &phi_, field<R> &chi_)
: fs(fs_), upfs(fs_.n), mp(mp_), phi(phi_), chi(chi_),
phigradx("phigradx"), chigradx("chigradx"),
phigrady("phigrady"), chigrady("chigrady"),
phigradz("phigradz"), chigradz("chigradz")
{
phigradx.construct(upfs);
chigradx.construct(upfs);
phigrady.construct(upfs);
chigrady.construct(upfs);
phigradz.construct(upfs);
chigradz.construct(upfs);
}
public:
void compute(field_state final_state = position);
protected:
field_size &fs, upfs;
model_params<R> ∓
field<R> &phi, χ
public:
field<R> phigradx, chigradx;
field<R> phigrady, chigrady;
field<R> phigradz, chigradz;
};
#endif // GRAD_COMPUTER_HPP
| 32.232877 | 85 | 0.740756 | auckland-cosmo |
f3d234bbf34a00d7ee88677f1fee56a2095e917b | 695 | hpp | C++ | src/backend/opencl/solve.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-06-14T23:49:18.000Z | 2018-06-14T23:49:18.000Z | src/backend/opencl/solve.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2015-07-02T15:53:02.000Z | 2015-07-02T15:53:02.000Z | src/backend/opencl/solve.hpp | JuliaComputing/arrayfire | 93427f09ff928f97df29c0e358c3fcf6b478bec6 | [
"BSD-3-Clause"
] | 1 | 2018-02-26T17:11:03.000Z | 2018-02-26T17:11:03.000Z | /*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/array.h>
#include <Array.hpp>
namespace opencl
{
template<typename T>
Array<T> solve(const Array<T> &a, const Array<T> &b, const af_mat_prop options = AF_MAT_NONE);
template<typename T>
Array<T> solveLU(const Array<T> &a, const Array<int> &pivot,
const Array<T> &b, const af_mat_prop options = AF_MAT_NONE);
}
| 31.590909 | 98 | 0.569784 | JuliaComputing |
f3d6029e8c4952c7d86d54ae1084376d2eb22cc7 | 654 | cc | C++ | zircon/system/ulib/zx/guest.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 49 | 2018-12-20T00:35:06.000Z | 2021-12-30T22:40:05.000Z | zircon/system/ulib/zx/guest.cc | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 5 | 2020-09-06T09:02:06.000Z | 2022-03-02T04:44:22.000Z | zircon/system/ulib/zx/guest.cc | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | 21 | 2019-01-03T11:06:10.000Z | 2021-08-06T00:55:50.000Z | // Copyright 2018 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 <lib/zx/guest.h>
#include <zircon/syscalls.h>
#include <lib/zx/vmar.h>
namespace zx {
zx_status_t guest::create(const resource& resource, uint32_t options,
guest* guest, vmar* vmar) {
// Assume |resource|, |guest| and |vmar| must refer to different containers,
// due to strict aliasing.
return zx_guest_create(
resource.get(), options, guest->reset_and_get_address(),
vmar->reset_and_get_address());
}
} // namespace zx
| 28.434783 | 80 | 0.678899 | zhangpf |
f3d9e15089af8235aca90e3dcc8bc194a1584881 | 9,769 | hpp | C++ | Code/Engine/Renderer/DebugObjectProperties.hpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | 1 | 2021-01-25T23:53:44.000Z | 2021-01-25T23:53:44.000Z | Code/Engine/Renderer/DebugObjectProperties.hpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | null | null | null | Code/Engine/Renderer/DebugObjectProperties.hpp | pronaypeddiraju/Engine | 0ca9720a00f51340c6eb6bba07d70972489663e8 | [
"Unlicense"
] | 1 | 2021-01-25T23:53:46.000Z | 2021-01-25T23:53:46.000Z | //------------------------------------------------------------------------------------------------------------------------------
#pragma once
//Engine Systems
#include "Engine/Commons/EngineCommon.hpp"
#include "Engine/Math/AABB2.hpp"
#include "Engine/Math/AABB3.hpp"
#include "Engine/Math/Capsule3D.hpp"
#include "Engine/Math/Disc2D.hpp"
#include "Engine/Renderer/CPUMesh.hpp"
#include "Engine/Renderer/GPUMesh.hpp"
#include "Engine/Renderer/Rgba.hpp"
//------------------------------------------------------------------------------------------------------------------------------
class TextureView;
//------------------------------------------------------------------------------------------------------------------------------
enum eDebugRenderObject
{
DEBUG_RENDER_POINT,
DEBUG_RENDER_POINT3D,
DEBUG_RENDER_LINE,
DEBUG_RENDER_LINE3D,
DEBUG_RENDER_QUAD,
DEBUG_RENDER_WIRE_QUAD,
DEBUG_RENDER_QUAD3D,
DEBUG_RENDER_DISC,
DEBUG_RENDER_RING,
DEBUG_RENDER_SPHERE,
DEBUG_RENDER_WIRE_SPHERE, //This has to be an icoSphere
DEBUG_RENDER_BOX,
DEBUG_RENDER_WIRE_BOX,
DEBUG_RENDER_ARROW,
DEBUG_RENDER_ARROW3D,
DEBUG_RENDER_CAPSULE,
DEBUG_RENDER_WIRE_CAPSULE,
DEBUG_RENDER_BASIS,
DEBUG_RENDER_TEXT,
DEBUG_RENDER_TEXT3D,
DEBUG_RENDER_LOG
};
//------------------------------------------------------------------------------------------------------------------------------
class ObjectProperties
{
public:
virtual ~ObjectProperties();
eDebugRenderObject m_renderObjectType;
float m_durationSeconds = 0.0f; // show for a single frame
float m_startDuration = 0.f;
Rgba m_currentColor = Rgba::WHITE;
CPUMesh* m_mesh;
};
//------------------------------------------------------------------------------------------------------------------------------
// 2D Render Objects
//------------------------------------------------------------------------------------------------------------------------------
// Point
//------------------------------------------------------------------------------------------------------------------------------
class Point2DProperties : public ObjectProperties
{
public:
explicit Point2DProperties(eDebugRenderObject renderObject, const Vec2& screenPosition,
float durationSeconds = 0.f, float size = DEFAULT_POINT_SIZE);
virtual ~Point2DProperties();
public:
Vec2 m_screenPosition = Vec2::ZERO;
float m_size = DEFAULT_POINT_SIZE;
};
// Line
//------------------------------------------------------------------------------------------------------------------------------
class Line2DProperties : public ObjectProperties
{
public:
explicit Line2DProperties(eDebugRenderObject renderObject, const Vec2& startPos, const Vec2& endPos,
float durationSeconds = 0.f, float lineWidth = DEFAULT_LINE_WIDTH);
virtual ~Line2DProperties();
public:
Vec2 m_startPos = Vec2::ZERO;
Vec2 m_endPos = Vec2::ZERO;
float m_lineWidth = DEFAULT_LINE_WIDTH;
};
// Arrow
//------------------------------------------------------------------------------------------------------------------------------
class Arrow2DProperties : public ObjectProperties
{
public:
explicit Arrow2DProperties(eDebugRenderObject renderObject, const Vec2& start, const Vec2& end,
float durationSeconds = 0.f, float lineWidth = DEFAULT_LINE_WIDTH);
virtual ~Arrow2DProperties();
public:
Vec2 m_startPos = Vec2::ZERO;
Vec2 m_endPos = Vec2::ZERO;
float m_lineWidth = DEFAULT_LINE_WIDTH;
Vec2 m_lineEnd = Vec2::ZERO;
Vec2 m_arrowTip = Vec2::ZERO;
Vec2 m_lineNorm = Vec2::ZERO;
};
// Quad
//------------------------------------------------------------------------------------------------------------------------------
class Quad2DProperties : public ObjectProperties
{
public:
explicit Quad2DProperties( eDebugRenderObject renderObject, const AABB2& quad,
float durationSeconds = 0.f, float thickness = DEFAULT_WIRE_WIDTH_2D, TextureView* texture = nullptr );
virtual ~Quad2DProperties();
public:
TextureView* m_texture = nullptr;
float m_thickness = DEFAULT_WIRE_WIDTH_2D; //Only used when rendering as a wire box
AABB2 m_quad;
};
// Disc
//------------------------------------------------------------------------------------------------------------------------------
class Disc2DProperties : public ObjectProperties
{
public:
explicit Disc2DProperties( eDebugRenderObject renderObject, const Disc2D& disc, float thickness,
float durationSeconds = 0.f);
virtual ~Disc2DProperties();
public:
Disc2D m_disc;
float m_thickness; //Only used when rendering it as a ring
};
//------------------------------------------------------------------------------------------------------------------------------
// 3D Render Objects
//------------------------------------------------------------------------------------------------------------------------------
// Point
//------------------------------------------------------------------------------------------------------------------------------
class Point3DProperties : public ObjectProperties
{
public:
explicit Point3DProperties( eDebugRenderObject renderObject, const Vec3& position, float size = DEFAULT_POINT_SIZE_3D,
float durationSeconds = 0.f, TextureView* texture = nullptr);
virtual ~Point3DProperties();
public:
Vec3 m_position = Vec3::ZERO;
TextureView* m_texture = nullptr;
float m_size = DEFAULT_POINT_SIZE_3D;
AABB2 m_point;
};
// Line
//------------------------------------------------------------------------------------------------------------------------------
class Line3DProperties : public ObjectProperties
{
public:
explicit Line3DProperties( eDebugRenderObject renderObject, const Vec3& startPos, const Vec3& endPos,
float durationSeconds = 0.f, float lineWidth = DEFAULT_LINE_WIDTH);
virtual ~Line3DProperties();
public:
Vec3 m_startPos = Vec3::ZERO;
Vec3 m_endPos = Vec3::ZERO;
Vec3 m_center = Vec3::ZERO;
float m_lineWidth = DEFAULT_LINE_WIDTH;
AABB2 m_line;
};
// Quad
//------------------------------------------------------------------------------------------------------------------------------
class Quad3DProperties : public ObjectProperties
{
public:
explicit Quad3DProperties( eDebugRenderObject renderObject, const AABB2& quad, const Vec3& position,
float durationSeconds = 0.f, TextureView* texture = nullptr, bool billBoarded = true );
virtual ~Quad3DProperties();
public:
Vec3 m_position = Vec3::ZERO;
TextureView* m_texture = nullptr;
bool m_billBoarded = true;
AABB2 m_quad;
};
// Sphere
//------------------------------------------------------------------------------------------------------------------------------
class SphereProperties : public ObjectProperties
{
public:
explicit SphereProperties( eDebugRenderObject renderObject, const Vec3& center, float radius,
float durationSeconds = 0.f, TextureView* texture = nullptr);
virtual ~SphereProperties();
public:
Vec3 m_center = Vec3::ZERO;
float m_radius = 0.f;
TextureView* m_texture = nullptr;
};
// Capsule
//------------------------------------------------------------------------------------------------------------------------------
class CapsuleProperties : public ObjectProperties
{
public:
explicit CapsuleProperties( eDebugRenderObject renderObject, const Capsule3D& capsule, const Vec3& position,
float durationSeconds = 0.f, TextureView* texture = nullptr);
virtual ~CapsuleProperties();
public:
Vec3 m_position = Vec3::ZERO;
TextureView* m_texture = nullptr;
Capsule3D m_capsule;
};
// Box
//------------------------------------------------------------------------------------------------------------------------------
class BoxProperties : public ObjectProperties
{
public:
explicit BoxProperties( eDebugRenderObject renderObject, const AABB3& box, const Vec3& position,
float durationSeconds = 0.f, TextureView* texture = nullptr);
virtual ~BoxProperties();
public:
Vec3 m_position = Vec3::ZERO;
TextureView* m_texture = nullptr;
AABB3 m_box;
};
//------------------------------------------------------------------------------------------------------------------------------
// Text Render Objects
//------------------------------------------------------------------------------------------------------------------------------
class TextProperties : public ObjectProperties
{
public:
explicit TextProperties( eDebugRenderObject renderObject, const Vec3& position, const Vec2& pivot, const std::string& text,
float fontHeight, float durationSeconds = 0.f, bool isBillboarded = true);
explicit TextProperties( eDebugRenderObject renderObject, const Vec2& startPosition, const Vec2& endPosition, const std::string& text,
float fontHeight, float durationSeconds = 0.f);
virtual ~TextProperties();
public:
//For 3D
Vec3 m_position = Vec3::ZERO;
Vec2 m_pivot = Vec2::ZERO;
bool m_isBillboarded = true;
//For 2D
Vec2 m_startPosition = Vec2::ZERO;
Vec2 m_endPosition = Vec2::ZERO;
float m_fontHeight = DEFAULT_TEXT_HEIGHT_3D;
std::string m_string;
};
//------------------------------------------------------------------------------------------------------------------------------
// Text Log Entry
//------------------------------------------------------------------------------------------------------------------------------
class LogProperties : public ObjectProperties
{
public:
explicit LogProperties(eDebugRenderObject renderObject, const Rgba& printColor, const std::string& printString, float durationSeconds = 0.f);
virtual ~LogProperties();
public:
Rgba m_printColor = Rgba::WHITE;
std::string m_string;
}; | 33.686207 | 142 | 0.518784 | pronaypeddiraju |
f3dab8d3f7a83ef1bf5765005926c1f999cc2168 | 4,657 | cc | C++ | src/server.cc | nim65s/gepetto-viewer-corba | b0b59b43cc0466c310744d11d220e68bfa4f14fc | [
"BSD-3-Clause"
] | 5 | 2019-01-22T03:42:52.000Z | 2021-06-04T18:28:54.000Z | src/server.cc | nim65s/gepetto-viewer-corba | b0b59b43cc0466c310744d11d220e68bfa4f14fc | [
"BSD-3-Clause"
] | 57 | 2018-10-18T10:17:10.000Z | 2022-01-29T09:31:36.000Z | src/server.cc | humanoid-path-planner/gepetto-viewer-corba | b0b59b43cc0466c310744d11d220e68bfa4f14fc | [
"BSD-3-Clause"
] | 16 | 2015-01-08T17:16:47.000Z | 2018-07-06T12:13:03.000Z | // Copyright (C) 2014, 2010 by Mathieu Geisert, LAAS-CNRS.
//
// This file is part of the SceneViewer-corba.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// See the COPYING file for more information.
#include <errno.h>
#include <pthread.h>
#include <iostream>
#include <stdexcept>
#include "server.hh"
#include "server-private.hh"
namespace gepetto {
namespace viewer {
namespace corba {
using CORBA::Exception;
using CORBA::Object_var;
using CORBA::SystemException;
using CORBA::ORB_init;
using CORBA::PolicyList;
using omniORB::fatalException;
Server::Server(WindowsManagerPtr_t wm, int argc, const char *argv[],
bool inMultiThread, bool useNameService)
: windowsManager_ (wm)
{
private_ = new impl::Server;
initORBandServers (argc, argv, inMultiThread, useNameService);
}
void Server::qparent (QObject* parent)
{
private_->qparent (parent);
}
Server::~Server()
{
private_->deactivateAndDestroyServers();
delete private_;
private_ = NULL;
}
/// CORBA SERVER INITIALIZATION
void Server::initORBandServers(int argc, const char* argv[],
bool inMultiThread, bool useNameService)
{
Object_var obj;
PortableServer::ThreadPolicy_var threadPolicy;
PortableServer::POA_var rootPoa;
/// ORB init
private_->orb_ = ORB_init (argc, const_cast<char **> (argv));
if (is_nil(private_->orb_)) {
std::string msg ("failed to initialize ORB");
throw std::runtime_error (msg.c_str ());
}
/// ORB init
if (useNameService) {
obj = private_->orb_->resolve_initial_references("RootPOA");
/// Create thread policy
//
// Make the CORBA object single-threaded to avoid GUI krash
//
// Create a sigle threaded policy object
rootPoa = PortableServer::POA::_narrow(obj);
if (inMultiThread) {
threadPolicy = rootPoa->create_thread_policy
(PortableServer::ORB_CTRL_MODEL);
}
else {
threadPolicy = rootPoa->create_thread_policy
(PortableServer::MAIN_THREAD_MODEL);
}
/// Duplicate thread policy
PolicyList policyList;
policyList.length(1);
policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy);
try {
private_->poa_ = rootPoa->create_POA
("child", PortableServer::POAManager::_nil(), policyList);
} catch (PortableServer::POA::AdapterAlreadyExists& /*e*/) {
private_->poa_ = rootPoa->find_POA ("child", false);
}
// Destroy policy object
threadPolicy->destroy();
} else {
// TODO: There is no way to use omniINSPOA with a different policy.
// A rather easy workaround can be found here:
// http://www.omniorb-support.com/pipermail/omniorb-list/2006-January/027358.html
obj = private_->orb_->resolve_initial_references("omniINSPOA");
private_->poa_ = PortableServer::POA::_narrow(obj);
}
private_->useNameService_ = useNameService;
private_->createServant(this);
if (useNameService)
private_->initRootPOA();
else
private_->initOmniINSPOA();
}
void Server::startCorbaServer()
{
if (private_->useNameService_) {
// Obtain a reference to objects, and register them in
// the naming service.
Object_var graphicalInterfaceObj = private_->graphicalInterfaceServant_->_this();
private_->createContext ();
// Bind graphicalInterfaceObj with name graphicalinterface to the Context:
CosNaming::Name objectName;
objectName.length(1);
objectName[0].id = (const char*) "corbaserver"; // string copied
objectName[0].kind = (const char*) "gui"; // string copied
private_->bindObjectToName(graphicalInterfaceObj, objectName);
private_->graphicalInterfaceServant_->_remove_ref();
}
PortableServer::POAManager_var pman = private_->poa_->the_POAManager();
pman->activate();
}
int Server::processRequest (bool loop)
{
if (loop)
{
private_->orb_->run();
}
else
{
if (private_->orb_->work_pending())
private_->orb_->perform_work();
}
return 0;
}
void Server::shutdown (bool wait)
{
private_->orb_->shutdown(wait);
}
} // end of namespace corba.
} // end of namespace viewer.
} // end of namespace gepetto.
| 29.66242 | 89 | 0.63732 | nim65s |
f3dc80f6d6932e33a11831e6471e86a45d66d3c8 | 3,786 | cc | C++ | hoomd/md/ConstraintSphereGPU.cc | XT-Lee/hoomd-blue | 0188f56f32c4a3efe0e74a3dc27397d6ec3469b0 | [
"BSD-3-Clause"
] | null | null | null | hoomd/md/ConstraintSphereGPU.cc | XT-Lee/hoomd-blue | 0188f56f32c4a3efe0e74a3dc27397d6ec3469b0 | [
"BSD-3-Clause"
] | null | null | null | hoomd/md/ConstraintSphereGPU.cc | XT-Lee/hoomd-blue | 0188f56f32c4a3efe0e74a3dc27397d6ec3469b0 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Maintainer: joaander
#include "ConstraintSphereGPU.h"
#include "ConstraintSphereGPU.cuh"
namespace py = pybind11;
using namespace std;
/*! \file ConstraintSphereGPU.cc
\brief Contains code for the ConstraintSphereGPU class
*/
/*! \param sysdef SystemDefinition containing the ParticleData to compute forces on
\param group Group of particles on which to apply this constraint
\param P position of the sphere
\param r radius of the sphere
*/
ConstraintSphereGPU::ConstraintSphereGPU(std::shared_ptr<SystemDefinition> sysdef,
std::shared_ptr<ParticleGroup> group,
Scalar3 P,
Scalar r)
: ConstraintSphere(sysdef, group, P, r), m_block_size(256)
{
if (!m_exec_conf->isCUDAEnabled())
{
m_exec_conf->msg->error()
<< "Creating a ConstraintSphereGPU with no GPU in the execution configuration" << endl;
throw std::runtime_error("Error initializing ConstraintSphereGPU");
}
}
/*! Computes the specified constraint forces
\param timestep Current timestep
*/
void ConstraintSphereGPU::computeForces(uint64_t timestep)
{
unsigned int group_size = m_group->getNumMembers();
if (group_size == 0)
return;
if (m_prof)
m_prof->push(m_exec_conf, "ConstraintSphere");
assert(m_pdata);
// access the particle data arrays
const GlobalArray<Scalar4>& net_force = m_pdata->getNetForce();
ArrayHandle<Scalar4> d_net_force(net_force, access_location::device, access_mode::read);
const GlobalArray<unsigned int>& group_members = m_group->getIndexArray();
ArrayHandle<unsigned int> d_group_members(group_members,
access_location::device,
access_mode::read);
ArrayHandle<Scalar4> d_pos(m_pdata->getPositions(), access_location::device, access_mode::read);
ArrayHandle<Scalar4> d_vel(m_pdata->getVelocities(),
access_location::device,
access_mode::read);
ArrayHandle<Scalar4> d_force(m_force, access_location::device, access_mode::overwrite);
ArrayHandle<Scalar> d_virial(m_virial, access_location::device, access_mode::overwrite);
// run the kernel in parallel on all GPUs
gpu_compute_constraint_sphere_forces(d_force.data,
d_virial.data,
m_virial.getPitch(),
d_group_members.data,
m_group->getNumMembers(),
m_pdata->getN(),
d_pos.data,
d_vel.data,
d_net_force.data,
m_P,
m_r,
m_deltaT,
m_block_size);
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
if (m_prof)
m_prof->pop(m_exec_conf);
}
void export_ConstraintSphereGPU(py::module& m)
{
py::class_<ConstraintSphereGPU, ConstraintSphere, std::shared_ptr<ConstraintSphereGPU>>(
m,
"ConstraintSphereGPU")
.def(py::init<std::shared_ptr<SystemDefinition>,
std::shared_ptr<ParticleGroup>,
Scalar3,
Scalar>());
}
| 38.242424 | 100 | 0.568146 | XT-Lee |
f3dc8bbe8a15638956e6cfeb0799afbcdad66bcb | 1,199 | cpp | C++ | test/common/test_timestamp.cpp | mweisgut/duckdb | 4cff1d7957ce895dd9984a87aa20aef67f5986e6 | [
"MIT"
] | 1 | 2019-08-01T08:21:33.000Z | 2019-08-01T08:21:33.000Z | test/common/test_timestamp.cpp | mweisgut/duckdb | 4cff1d7957ce895dd9984a87aa20aef67f5986e6 | [
"MIT"
] | null | null | null | test/common/test_timestamp.cpp | mweisgut/duckdb | 4cff1d7957ce895dd9984a87aa20aef67f5986e6 | [
"MIT"
] | null | null | null | #include "catch.hpp"
#include "common/types/timestamp.hpp"
#include <vector>
using namespace duckdb;
using namespace std;
static void VerifyTimestamp(date_t date, dtime_t time, int64_t epoch) {
// create the timestamp from the string
timestamp_t stamp = Timestamp::FromString(Date::ToString(date) + " " + Time::ToString(time));
// verify that we can get the date and time back
REQUIRE(Timestamp::GetDate(stamp) == date);
REQUIRE(Timestamp::GetTime(stamp) == time);
// verify that the individual extract functions work
int32_t hour, min, sec, msec;
Time::Convert(time, hour, min, sec, msec);
REQUIRE(Timestamp::GetHours(stamp) == hour);
REQUIRE(Timestamp::GetMinutes(stamp) == min);
REQUIRE(Timestamp::GetSeconds(stamp) == sec);
// verify that the epoch is correct
REQUIRE(epoch == (Date::Epoch(date) + time / 1000));
REQUIRE(Timestamp::GetEpoch(stamp) == epoch);
}
TEST_CASE("Verify that timestamp functions work", "[timestamp]") {
VerifyTimestamp(Date::FromDate(2019, 8, 26), Time::FromTime(8, 52, 6), 1566809526);
VerifyTimestamp(Date::FromDate(1970, 1, 1), Time::FromTime(0, 0, 0), 0);
VerifyTimestamp(Date::FromDate(2000, 10, 10), Time::FromTime(10, 10, 10), 971172610);
}
| 37.46875 | 94 | 0.717264 | mweisgut |
f3dcbbf606ae0721591c03266e840dbe96590b76 | 1,024 | cc | C++ | src/board/position.cc | wotulong/FoolGo | 0d18e78b0812f89eb55a19f67ee280d7dd74bb8e | [
"MIT"
] | null | null | null | src/board/position.cc | wotulong/FoolGo | 0d18e78b0812f89eb55a19f67ee280d7dd74bb8e | [
"MIT"
] | null | null | null | src/board/position.cc | wotulong/FoolGo | 0d18e78b0812f89eb55a19f67ee280d7dd74bb8e | [
"MIT"
] | 1 | 2020-03-23T12:51:41.000Z | 2020-03-23T12:51:41.000Z | #include "position.h"
#include <boost/format.hpp>
namespace foolgo {
namespace board {
using boost::format;
using std::string;
const BoardLen Position::STRAIGHT_ORNTTIONS[4][2] = { { 0, -1 }, { 1, 0 }, { 0,
1 }, { -1, 0 } };
const BoardLen Position::OBLIQUE_ORNTTIONS[4][2] = { { 1, -1 }, { 1, 1 }, { -1,
1 }, { -1, -1 } };
string PositionToString(const Position &position) {
return (boost::format("{%1%, %2%}") % static_cast<int>(position.x)
% static_cast<int>(position.y)).str();
}
std::ostream &operator<<(std::ostream &os, const Position &position) {
return os << PositionToString(position);
}
Position AdjacentPosition(const Position & position, int i) {
return Position(position.x + Position::STRAIGHT_ORNTTIONS[i][0],
position.y + Position::STRAIGHT_ORNTTIONS[i][1]);
}
Position ObliquePosition(const Position &position, int i) {
return Position(position.x + Position::OBLIQUE_ORNTTIONS[i][0],
position.y + Position::OBLIQUE_ORNTTIONS[i][1]);
}
}
}
| 26.947368 | 79 | 0.642578 | wotulong |
f3dd15e76204984345697029ec31b4d838c80eeb | 13,823 | cpp | C++ | 3rdparty/spirv-tools/test/val/val_function_test.cpp | bencoyote/bgfx | feb453025d7d5ba423b1bbd11a33816a86644023 | [
"BSD-2-Clause"
] | 1 | 2019-07-30T09:37:27.000Z | 2019-07-30T09:37:27.000Z | 3rdparty/spirv-tools/test/val/val_function_test.cpp | Vaiklol/bgfx | 1196825aebc4b4cdf9acc6c632d002d3c91ba095 | [
"BSD-2-Clause"
] | null | null | null | 3rdparty/spirv-tools/test/val/val_function_test.cpp | Vaiklol/bgfx | 1196825aebc4b4cdf9acc6c632d002d3c91ba095 | [
"BSD-2-Clause"
] | 2 | 2020-03-07T17:59:02.000Z | 2021-04-16T17:22:59.000Z | // Copyright (c) 2019 Google LLC.
//
// 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 <sstream>
#include <string>
#include <tuple>
#include "gmock/gmock.h"
#include "test/test_fixture.h"
#include "test/unit_spirv.h"
#include "test/val/val_fixtures.h"
namespace spvtools {
namespace val {
namespace {
using ::testing::Combine;
using ::testing::HasSubstr;
using ::testing::Values;
using ValidateFunctionCall = spvtest::ValidateBase<std::string>;
std::string GenerateShader(const std::string& storage_class,
const std::string& capabilities,
const std::string& extensions) {
std::string spirv = R"(
OpCapability Shader
OpCapability Linkage
OpCapability AtomicStorage
)" + capabilities + R"(
OpExtension "SPV_KHR_storage_buffer_storage_class"
)" +
extensions + R"(
OpMemoryModel Logical GLSL450
OpName %var "var"
%void = OpTypeVoid
%int = OpTypeInt 32 0
%ptr = OpTypePointer )" + storage_class + R"( %int
%caller_ty = OpTypeFunction %void
%callee_ty = OpTypeFunction %void %ptr
)";
if (storage_class != "Function") {
spirv += "%var = OpVariable %ptr " + storage_class;
}
spirv += R"(
%caller = OpFunction %void None %caller_ty
%1 = OpLabel
)";
if (storage_class == "Function") {
spirv += "%var = OpVariable %ptr Function";
}
spirv += R"(
%call = OpFunctionCall %void %callee %var
OpReturn
OpFunctionEnd
%callee = OpFunction %void None %callee_ty
%param = OpFunctionParameter %ptr
%2 = OpLabel
OpReturn
OpFunctionEnd
)";
return spirv;
}
std::string GenerateShaderParameter(const std::string& storage_class,
const std::string& capabilities,
const std::string& extensions) {
std::string spirv = R"(
OpCapability Shader
OpCapability Linkage
OpCapability AtomicStorage
)" + capabilities + R"(
OpExtension "SPV_KHR_storage_buffer_storage_class"
)" +
extensions + R"(
OpMemoryModel Logical GLSL450
OpName %p "p"
%void = OpTypeVoid
%int = OpTypeInt 32 0
%ptr = OpTypePointer )" + storage_class + R"( %int
%func_ty = OpTypeFunction %void %ptr
%caller = OpFunction %void None %func_ty
%p = OpFunctionParameter %ptr
%1 = OpLabel
%call = OpFunctionCall %void %callee %p
OpReturn
OpFunctionEnd
%callee = OpFunction %void None %func_ty
%param = OpFunctionParameter %ptr
%2 = OpLabel
OpReturn
OpFunctionEnd
)";
return spirv;
}
std::string GenerateShaderAccessChain(const std::string& storage_class,
const std::string& capabilities,
const std::string& extensions) {
std::string spirv = R"(
OpCapability Shader
OpCapability Linkage
OpCapability AtomicStorage
)" + capabilities + R"(
OpExtension "SPV_KHR_storage_buffer_storage_class"
)" +
extensions + R"(
OpMemoryModel Logical GLSL450
OpName %var "var"
OpName %gep "gep"
%void = OpTypeVoid
%int = OpTypeInt 32 0
%int2 = OpTypeVector %int 2
%int_0 = OpConstant %int 0
%ptr = OpTypePointer )" + storage_class + R"( %int2
%ptr2 = OpTypePointer )" +
storage_class + R"( %int
%caller_ty = OpTypeFunction %void
%callee_ty = OpTypeFunction %void %ptr2
)";
if (storage_class != "Function") {
spirv += "%var = OpVariable %ptr " + storage_class;
}
spirv += R"(
%caller = OpFunction %void None %caller_ty
%1 = OpLabel
)";
if (storage_class == "Function") {
spirv += "%var = OpVariable %ptr Function";
}
spirv += R"(
%gep = OpAccessChain %ptr2 %var %int_0
%call = OpFunctionCall %void %callee %gep
OpReturn
OpFunctionEnd
%callee = OpFunction %void None %callee_ty
%param = OpFunctionParameter %ptr2
%2 = OpLabel
OpReturn
OpFunctionEnd
)";
return spirv;
}
TEST_P(ValidateFunctionCall, VariableNoVariablePointers) {
const std::string storage_class = GetParam();
std::string spirv = GenerateShader(storage_class, "", "");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private", "Workgroup", "AtomicCounter"};
bool valid =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
CompileSuccessfully(spirv);
if (valid) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
if (storage_class == "StorageBuffer") {
EXPECT_THAT(getDiagnosticString(),
HasSubstr("StorageBuffer pointer operand 1[%var] requires a "
"variable pointers capability"));
} else {
EXPECT_THAT(
getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 1[%var]"));
}
}
}
TEST_P(ValidateFunctionCall, VariableVariablePointersStorageClass) {
const std::string storage_class = GetParam();
std::string spirv = GenerateShader(
storage_class, "OpCapability VariablePointersStorageBuffer",
"OpExtension \"SPV_KHR_variable_pointers\"");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private",
"Workgroup", "StorageBuffer", "AtomicCounter"};
bool valid =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
CompileSuccessfully(spirv);
if (valid) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
EXPECT_THAT(getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 1[%var]"));
}
}
TEST_P(ValidateFunctionCall, VariableVariablePointers) {
const std::string storage_class = GetParam();
std::string spirv =
GenerateShader(storage_class, "OpCapability VariablePointers",
"OpExtension \"SPV_KHR_variable_pointers\"");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private",
"Workgroup", "StorageBuffer", "AtomicCounter"};
bool valid =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
CompileSuccessfully(spirv);
if (valid) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
EXPECT_THAT(getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 1[%var]"));
}
}
TEST_P(ValidateFunctionCall, ParameterNoVariablePointers) {
const std::string storage_class = GetParam();
std::string spirv = GenerateShaderParameter(storage_class, "", "");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private", "Workgroup", "AtomicCounter"};
bool valid =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
CompileSuccessfully(spirv);
if (valid) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
if (storage_class == "StorageBuffer") {
EXPECT_THAT(getDiagnosticString(),
HasSubstr("StorageBuffer pointer operand 1[%p] requires a "
"variable pointers capability"));
} else {
EXPECT_THAT(getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 1[%p]"));
}
}
}
TEST_P(ValidateFunctionCall, ParameterVariablePointersStorageBuffer) {
const std::string storage_class = GetParam();
std::string spirv = GenerateShaderParameter(
storage_class, "OpCapability VariablePointersStorageBuffer",
"OpExtension \"SPV_KHR_variable_pointers\"");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private",
"Workgroup", "StorageBuffer", "AtomicCounter"};
bool valid =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
CompileSuccessfully(spirv);
if (valid) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
EXPECT_THAT(getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 1[%p]"));
}
}
TEST_P(ValidateFunctionCall, ParameterVariablePointers) {
const std::string storage_class = GetParam();
std::string spirv =
GenerateShaderParameter(storage_class, "OpCapability VariablePointers",
"OpExtension \"SPV_KHR_variable_pointers\"");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private",
"Workgroup", "StorageBuffer", "AtomicCounter"};
bool valid =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
CompileSuccessfully(spirv);
if (valid) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
EXPECT_THAT(getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 1[%p]"));
}
}
TEST_P(ValidateFunctionCall, NonMemoryObjectDeclarationNoVariablePointers) {
const std::string storage_class = GetParam();
std::string spirv = GenerateShaderAccessChain(storage_class, "", "");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private", "Workgroup", "AtomicCounter"};
bool valid_sc =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
CompileSuccessfully(spirv);
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
if (valid_sc) {
EXPECT_THAT(
getDiagnosticString(),
HasSubstr(
"Pointer operand 2[%gep] must be a memory object declaration"));
} else {
if (storage_class == "StorageBuffer") {
EXPECT_THAT(getDiagnosticString(),
HasSubstr("StorageBuffer pointer operand 2[%gep] requires a "
"variable pointers capability"));
} else {
EXPECT_THAT(
getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 2[%gep]"));
}
}
}
TEST_P(ValidateFunctionCall,
NonMemoryObjectDeclarationVariablePointersStorageBuffer) {
const std::string storage_class = GetParam();
std::string spirv = GenerateShaderAccessChain(
storage_class, "OpCapability VariablePointersStorageBuffer",
"OpExtension \"SPV_KHR_variable_pointers\"");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private",
"Workgroup", "StorageBuffer", "AtomicCounter"};
bool valid_sc =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
bool validate = storage_class == "StorageBuffer";
CompileSuccessfully(spirv);
if (validate) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
if (valid_sc) {
EXPECT_THAT(
getDiagnosticString(),
HasSubstr(
"Pointer operand 2[%gep] must be a memory object declaration"));
} else {
EXPECT_THAT(
getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 2[%gep]"));
}
}
}
TEST_P(ValidateFunctionCall, NonMemoryObjectDeclarationVariablePointers) {
const std::string storage_class = GetParam();
std::string spirv =
GenerateShaderAccessChain(storage_class, "OpCapability VariablePointers",
"OpExtension \"SPV_KHR_variable_pointers\"");
const std::vector<std::string> valid_storage_classes = {
"UniformConstant", "Function", "Private",
"Workgroup", "StorageBuffer", "AtomicCounter"};
bool valid_sc =
std::find(valid_storage_classes.begin(), valid_storage_classes.end(),
storage_class) != valid_storage_classes.end();
bool validate =
storage_class == "StorageBuffer" || storage_class == "Workgroup";
CompileSuccessfully(spirv);
if (validate) {
EXPECT_EQ(SPV_SUCCESS, ValidateInstructions());
} else {
EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions());
if (valid_sc) {
EXPECT_THAT(
getDiagnosticString(),
HasSubstr(
"Pointer operand 2[%gep] must be a memory object declaration"));
} else {
EXPECT_THAT(
getDiagnosticString(),
HasSubstr("Invalid storage class for pointer operand 2[%gep]"));
}
}
}
INSTANTIATE_TEST_SUITE_P(StorageClass, ValidateFunctionCall,
Values("UniformConstant", "Input", "Uniform", "Output",
"Workgroup", "Private", "Function",
"PushConstant", "Image", "StorageBuffer",
"AtomicCounter"));
} // namespace
} // namespace val
} // namespace spvtools
| 32.524706 | 80 | 0.669826 | bencoyote |
f3df7bf456716f6b3bd615f217e86def5818eea8 | 1,455 | hpp | C++ | include/crisp/interpreter/InterpretUserDefinedAST.hpp | pzque/crisp | 4c53db12a0cca5a0c4165b6333e2cdc574daaa4e | [
"Apache-2.0"
] | 3 | 2021-12-31T09:03:46.000Z | 2022-03-29T02:40:30.000Z | include/crisp/interpreter/InterpretUserDefinedAST.hpp | pzque/crisp | 4c53db12a0cca5a0c4165b6333e2cdc574daaa4e | [
"Apache-2.0"
] | null | null | null | include/crisp/interpreter/InterpretUserDefinedAST.hpp | pzque/crisp | 4c53db12a0cca5a0c4165b6333e2cdc574daaa4e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 by Crisp Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CRISP_INTERPRETUSERDEFINEDAST_HPP
#define CRISP_INTERPRETUSERDEFINEDAST_HPP
#include "Common.hpp"
#include "CrispFunction.hpp"
namespace crisp {
template <typename Environ, typename F, typename... Args>
struct CallCrispFunction {
using type = Interpret<Call<typename F::__name__, Args...>,
Environ>;
};
template <template <typename...> class F, typename Environ, typename... Args>
struct Interpret<F<Args...>, Environ> {
using FApply = F<Args...>;
using FApplyInterp = typename ConditionalApply<
When<Bool<is_base_of<CrispFunction, FApply>::value>,
DeferApply<CallCrispFunction, Environ, FApply, Args...>>,
Else<DeferConstruct<Id, FApply>>>::type;
using env = Environ;
using type = typename FApplyInterp::type;
};
} // namespace crisp
#endif // CRISP_INTERPRETUSERDEFINEDAST_HPP
| 31.630435 | 77 | 0.720275 | pzque |
f3dfd78c5a2b822873fff33ac7e1c2b1e17312be | 11,055 | hh | C++ | include/maxscale/protocol2.hh | Daniel-Xu/MaxScale | 35d12c0c9b75c4571dbbeb983c740de098661de6 | [
"BSD-3-Clause"
] | null | null | null | include/maxscale/protocol2.hh | Daniel-Xu/MaxScale | 35d12c0c9b75c4571dbbeb983c740de098661de6 | [
"BSD-3-Clause"
] | null | null | null | include/maxscale/protocol2.hh | Daniel-Xu/MaxScale | 35d12c0c9b75c4571dbbeb983c740de098661de6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-04-28
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#pragma once
#include <maxscale/ccdefs.hh>
#include <maxscale/protocol.hh>
#include <maxscale/authenticator.hh>
class BackendDCB;
class ClientDCB;
class DCB;
class SERVICE;
namespace maxscale
{
class BackendConnection;
class ClientConnection;
class ConfigParameters;
class UserAccountManager;
class ProtocolModule
{
public:
using AuthenticatorList = std::vector<mxs::SAuthenticatorModule>;
virtual ~ProtocolModule() = default;
enum Capabilities
{
CAP_AUTHDATA = (1u << 0), // Protocol implements a user account manager
CAP_BACKEND = (1u << 1), // Protocol supports backend communication
CAP_AUTH_MODULES = (1u << 2), // Protocol uses authenticator modules and does not integrate one
};
/**
* Allocate new client protocol session
*
* @param session The session to which the connection belongs to
* @param component The component to use for routeQuery
*
* @return New protocol session or null on error
*/
virtual std::unique_ptr<mxs::ClientConnection>
create_client_protocol(MXS_SESSION* session, mxs::Component* component) = 0;
/**
* Allocate new backend protocol session
*
* @param session The session to which the connection belongs to
* @param server Server where the connection is made
*
* @return New protocol session or null on error
*/
virtual std::unique_ptr<BackendConnection>
create_backend_protocol(MXS_SESSION* session, SERVER* server, mxs::Component* component)
{
mxb_assert(!true);
return nullptr;
}
/**
* Get the default authenticator for the protocol.
*
* @return The default authenticator for the protocol or empty if the protocol
* does not provide one
*/
virtual std::string auth_default() const = 0;
/**
* Get rejection message. The protocol should return an error indicating that access to MaxScale
* has been temporarily suspended.
*
* @param host The host that is blocked
* @return A buffer containing the error message
*/
virtual GWBUF* reject(const std::string& host)
{
return nullptr;
}
/**
* Get protocol module name.
*
* @return Module name
*/
virtual std::string name() const = 0;
/**
* Print a list of authenticator users to json. This should only be implemented by protocols without
* CAP_AUTHDATA.
*
* @return JSON user list
*/
virtual json_t* print_auth_users_json()
{
return nullptr;
}
/**
* Create a user account manager. Will be only called for protocols with CAP_AUTHDATA.
*
* @return New user account manager. Will be shared between all listeners of the service.
*/
virtual std::unique_ptr<UserAccountManager> create_user_data_manager()
{
mxb_assert(!true);
return nullptr;
}
virtual uint64_t capabilities() const
{
return 0;
}
/**
* The protocol module should read the listener parameters for the list of authenticators and their
* options and generate authenticator modules. This is only called if CAP_AUTH_MODULES is enabled.
*
* @param params Listener and authenticator settings
* @return An array of authenticators. Empty on error.
*/
virtual AuthenticatorList create_authenticators(const ConfigParameters& params)
{
mxb_assert(!true);
return {};
}
};
/**
* Client protocol connection interface. All protocols must implement this.
*/
class ClientConnection : public ProtocolConnection
{
public:
virtual ~ClientConnection() = default;
/**
* Initialize a connection.
*
* @return True, if the connection could be initialized, false otherwise.
*/
virtual bool init_connection() = 0;
/**
* Finalize a connection. Called right before the DCB itself is closed.
*/
virtual void finish_connection() = 0;
/**
* Handle connection limits. Currently the return value is ignored.
*
* @param limit Maximum number of connections
* @return 1 on success, 0 on error
*/
virtual int32_t connlimit(int limit)
{
return 0;
}
/**
* Return current database. Only required by query classifier.
*
* @return Current database
*/
virtual std::string current_db() const
{
return "";
}
virtual ClientDCB* dcb() = 0;
virtual const ClientDCB* dcb() const = 0;
virtual void wakeup()
{
// Should not be called for non-supported protocols.
mxb_assert(!true);
}
/**
* Called when the session starts to stop
*
* This can be used to do any preparatory work that needs to be done before the actual shutdown is
* started. At this stage the session is still valid and routing works normally.
*
* The default implementation does nothing.
*/
virtual void kill()
{
}
};
/**
* Partial client protocol implementation. More fields and functions may be added later.
*/
class ClientConnectionBase : public ClientConnection
{
public:
json_t* diagnostics() const override;
void set_dcb(DCB* dcb) override;
ClientDCB* dcb() override;
const ClientDCB* dcb() const override;
protected:
ClientDCB* m_dcb {nullptr}; /**< Dcb used by this protocol connection */
};
/**
* Backend protocol connection interface. Only protocols with backend support need to implement this.
*/
class BackendConnection : public mxs::ProtocolConnection
{
public:
virtual ~BackendConnection() = default;
/**
* Initialize a connection.
*
* @return True, if the connection could be initialized, false otherwise.
*/
virtual bool init_connection() = 0;
/**
* Finalize a connection. Called right before the DCB itself is closed.
*/
virtual void finish_connection() = 0;
/**
* Reuse a connection. The connection was in the persistent pool
* and will now be taken into use again.
*
* @param dcb The connection to be reused.
* @param upstream The upstream component.
*
* @return True, if the connection can be reused, false otherwise.
* If @c false is returned, the @c dcb should be closed.
*/
virtual bool reuse_connection(BackendDCB* dcb, mxs::Component* upstream) = 0;
/**
* Check if the connection has been fully established, used by connection pooling
*
* @return True if the connection is fully established and can be pooled
*/
virtual bool established() = 0;
/**
* Ping a backend connection
*
* The backend connection should perform an action that keeps the connection alive if it is currently
* idle. The idleness of a connection is determined at the protocol level and any actions taken at the
* protocol level should not propagate upwards.
*
* What this means in practice is that if a query is used to ping a backend, the result should be
* discarded and the pinging should not interrupt ongoing queries.
*/
virtual void ping() = 0;
/**
* Check if the connection can be closed in a controlled manner
*
* @return True if the connection can be closed without interruping anything
*/
virtual bool can_close() const = 0;
/**
* How many seconds has the connection been idle
*
* @return Number of seconds the connection has been idle
*/
virtual int64_t seconds_idle() const = 0;
virtual const BackendDCB* dcb() const = 0;
virtual BackendDCB* dcb() = 0;
};
class UserAccountCache;
/**
* An interface which a user account manager must implement. The instance is shared between all threads.
*/
class UserAccountManager
{
public:
virtual ~UserAccountManager() = default;
/**
* Start the user account manager. Should be called after creation.
*/
virtual void start() = 0;
/**
* Stop the user account manager. Should be called before destruction.
*/
virtual void stop() = 0;
/**
* Notify the manager that its data should be updated. The updating may happen
* in a separate thread.
*/
virtual void update_user_accounts() = 0;
/**
* Set the username and password the manager should use when accessing backends.
*
* @param user Username
* @param pw Password, possibly encrypted
*/
virtual void set_credentials(const std::string& user, const std::string& pw) = 0;
virtual void set_backends(const std::vector<SERVER*>& backends) = 0;
virtual void set_union_over_backends(bool union_over_backends) = 0;
virtual void set_strip_db_esc(bool strip_db_esc) = 0;
/**
* Which protocol this manager can be used with. Currently, it's assumed that the user data managers
* do not have listener-specific settings. If multiple listeners with the same protocol name feed
* the same service, only one manager is required.
*/
virtual std::string protocol_name() const = 0;
/**
* Create a thread-local account cache linked to this account manager.
*
* @return A new user account cache
*/
virtual std::unique_ptr<UserAccountCache> create_user_account_cache() = 0;
/**
* Set owning service.
*
* @param service
*/
virtual void set_service(SERVICE* service) = 0;
/**
* Print contents to a json array.
*
* @return Users as json
*/
virtual json_t* users_to_json() const = 0;
};
class UserAccountCache
{
public:
virtual ~UserAccountCache() = default;
virtual void update_from_master() = 0;
};
template<class ProtocolImplementation>
class ProtocolApiGenerator
{
public:
ProtocolApiGenerator() = delete;
ProtocolApiGenerator(const ProtocolApiGenerator&) = delete;
ProtocolApiGenerator& operator=(const ProtocolApiGenerator&) = delete;
static mxs::ProtocolModule* create_protocol_module()
{
// If protocols require non-authentication-related settings, add passing them here.
// The unsolved issue is how to separate listener, protocol and authenticator-settings from
// each other. Currently this is mostly a non-issue as the only authenticator with a setting
// is gssapi.
return ProtocolImplementation::create();
}
static MXS_PROTOCOL_API s_api;
};
template<class ProtocolImplementation>
MXS_PROTOCOL_API ProtocolApiGenerator<ProtocolImplementation>::s_api =
{
&ProtocolApiGenerator<ProtocolImplementation>::create_protocol_module,
};
}
| 28.565891 | 106 | 0.66332 | Daniel-Xu |
f3e15d6b4923bd907532dd59b3ffb3cca232094f | 4,325 | cxx | C++ | Modules/IO/Base/src/itkRegularExpressionSeriesFileNames.cxx | CapeDrew/DCMTK-ITK | 440bf8ed100445396912cfd0aa72f36d4cdefe0c | [
"Apache-2.0"
] | 2 | 2015-06-19T07:18:36.000Z | 2019-04-18T07:28:23.000Z | Modules/IO/Base/src/itkRegularExpressionSeriesFileNames.cxx | CapeDrew/DCMTK-ITK | 440bf8ed100445396912cfd0aa72f36d4cdefe0c | [
"Apache-2.0"
] | null | null | null | Modules/IO/Base/src/itkRegularExpressionSeriesFileNames.cxx | CapeDrew/DCMTK-ITK | 440bf8ed100445396912cfd0aa72f36d4cdefe0c | [
"Apache-2.0"
] | 2 | 2017-05-02T07:18:49.000Z | 2020-04-30T01:37:35.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.
*
*=========================================================================*/
#ifndef _itkRegularExpressionSeriesFileNames_cxx
#define _itkRegularExpressionSeriesFileNames_cxx
#include <vector>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include "itksys/SystemTools.hxx"
#include "itksys/Directory.hxx"
#include "itksys/RegularExpression.hxx"
#include "itkRegularExpressionSeriesFileNames.h"
struct lt_pair_numeric_string_string {
bool operator()(const std::pair< std::string, std::string > s1,
const std::pair< std::string, std::string > s2) const
{
return atof( s1.second.c_str() ) < atof( s2.second.c_str() );
}
};
struct lt_pair_alphabetic_string_string {
bool operator()(const std::pair< std::string, std::string > s1,
const std::pair< std::string, std::string > s2) const
{
return s1.second < s2.second;
}
};
namespace itk
{
const std::vector< std::string > &
RegularExpressionSeriesFileNames
::GetFileNames()
{
// Validate the ivars
if ( m_Directory == "" )
{
itkExceptionMacro (<< "No directory defined!");
}
itksys::RegularExpression reg;
if ( !reg.compile( m_RegularExpression.c_str() ) )
{
itkExceptionMacro(<< "Error compiling regular expression " << m_RegularExpression);
}
// Process all files in the directory
itksys::Directory fileDir;
if ( !fileDir.Load ( m_Directory.c_str() ) )
{
itkExceptionMacro (<< "Directory " << m_Directory.c_str() << " cannot be read!");
}
std::vector< std::pair< std::string, std::string > > sortedBySubMatch;
// Scan directory for files. Each file is checked to see if it
// matches the m_RegularExpression.
for ( unsigned long i = 0; i < fileDir.GetNumberOfFiles(); i++ )
{
// Only read files
if ( itksys::SystemTools::FileIsDirectory( ( m_Directory + "/" + fileDir.GetFile(i) ).c_str() ) )
{
continue;
}
if ( reg.find( fileDir.GetFile(i) ) )
{
// Store the full filename and the selected sub expression match
std::pair< std::string, std::string > fileNameMatch;
fileNameMatch.first = m_Directory + "/" + fileDir.GetFile(i);
fileNameMatch.second = reg.match(m_SubMatch);
sortedBySubMatch.push_back(fileNameMatch);
}
}
// Sort the files. The files are sorted by the sub match defined by
// m_SubMatch. Sorting can be alpahbetic or numeric.
if ( m_NumericSort )
{
std::sort( sortedBySubMatch.begin(),
sortedBySubMatch.end(),
lt_pair_numeric_string_string() );
}
else
{
std::sort( sortedBySubMatch.begin(),
sortedBySubMatch.end(),
lt_pair_alphabetic_string_string() );
}
// Now, store the sorted names in a vector
m_FileNames.clear();
std::vector< std::pair< std::string, std::string > >::iterator siter;
for ( siter = sortedBySubMatch.begin();
siter != sortedBySubMatch.end();
siter++ )
{
m_FileNames.push_back( ( *siter ).first );
}
return m_FileNames;
}
void
RegularExpressionSeriesFileNames
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Directory: " << m_Directory << std::endl;
os << indent << "SubMatch: " << m_SubMatch << std::endl;
os << indent << "NumericSort: " << m_NumericSort << std::endl;
os << indent << "RegularExpression: " << m_RegularExpression << std::endl;
for ( unsigned int i = 0; i < m_FileNames.size(); i++ )
{
os << indent << "Filenames[" << i << "]: " << m_FileNames[i] << std::endl;
}
}
} //namespace ITK
#endif
| 30.457746 | 101 | 0.631445 | CapeDrew |
f3e1a955c90fa3020065005b71c325296758dea0 | 1,822 | hpp | C++ | libs/fnd/cmath/include/bksge/fnd/cmath/detail/sph_neumann_impl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/cmath/include/bksge/fnd/cmath/detail/sph_neumann_impl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/cmath/include/bksge/fnd/cmath/detail/sph_neumann_impl.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file sph_neumann_impl.hpp
*
* @brief sph_neumann 関数の実装
*
* @author myoukaku
*/
#ifndef BKSGE_FND_CMATH_DETAIL_SPH_NEUMANN_IMPL_HPP
#define BKSGE_FND_CMATH_DETAIL_SPH_NEUMANN_IMPL_HPP
#include <bksge/fnd/cmath/isnan.hpp>
#include <bksge/fnd/cmath/detail/sph_bessel_jn.hpp>
#include <bksge/fnd/type_traits/float_promote.hpp>
#include <bksge/fnd/config.hpp>
#include <cmath>
#include <limits>
namespace bksge
{
namespace detail
{
#if defined(__cpp_lib_math_special_functions) && (__cpp_lib_math_special_functions >= 201603)
inline /*BKSGE_CONSTEXPR*/ double
sph_neumann_unchecked(unsigned int n, double x)
{
return std::sph_neumann(n, x);
}
inline /*BKSGE_CONSTEXPR*/ float
sph_neumann_unchecked(unsigned int n, float x)
{
return std::sph_neumannf(n, x);
}
inline /*BKSGE_CONSTEXPR*/ long double
sph_neumann_unchecked(unsigned int n, long double x)
{
return std::sph_neumannl(n, x);
}
#else
template <typename T>
inline BKSGE_CXX14_CONSTEXPR T
sph_neumann_unchecked_2(unsigned int n, T x)
{
T j_n, n_n, jp_n, np_n;
bksge::detail::sph_bessel_jn(n, x, j_n, n_n, jp_n, np_n);
return n_n;
}
template <typename T>
inline BKSGE_CXX14_CONSTEXPR T
sph_neumann_unchecked(unsigned int n, T x)
{
using value_type = bksge::float_promote_t<double, T>;
return static_cast<T>(sph_neumann_unchecked_2(n, static_cast<value_type>(x)));
}
#endif
template <typename T>
inline BKSGE_CXX14_CONSTEXPR T
sph_neumann_impl(unsigned int n, T x)
{
if (bksge::isnan(x))
{
return std::numeric_limits<T>::quiet_NaN();
}
if (x == T(0))
{
return -std::numeric_limits<T>::infinity();
}
return sph_neumann_unchecked(n, x);
}
} // namespace detail
} // namespace bksge
#endif // BKSGE_FND_CMATH_DETAIL_SPH_NEUMANN_IMPL_HPP
| 20.704545 | 94 | 0.716246 | myoukaku |
f3e21b4879890c56ff3ec94dd69083b78b703ad1 | 1,871 | cpp | C++ | library/cpp/blockcodecs/codecs/zstd/zstd.cpp | gwjknvwjn/catboost | a5644bf80e2e37985012fb3bdd285fc6d798c61c | [
"Apache-2.0"
] | 4 | 2020-06-24T06:07:52.000Z | 2021-04-16T22:58:09.000Z | library/cpp/blockcodecs/codecs/zstd/zstd.cpp | gwjknvwjn/catboost | a5644bf80e2e37985012fb3bdd285fc6d798c61c | [
"Apache-2.0"
] | null | null | null | library/cpp/blockcodecs/codecs/zstd/zstd.cpp | gwjknvwjn/catboost | a5644bf80e2e37985012fb3bdd285fc6d798c61c | [
"Apache-2.0"
] | 1 | 2020-10-17T09:28:08.000Z | 2020-10-17T09:28:08.000Z | #include <library/cpp/blockcodecs/core/codecs.h>
#include <library/cpp/blockcodecs/core/common.h>
#include <library/cpp/blockcodecs/core/register.h>
#define ZSTD_STATIC_LINKING_ONLY
#include <contrib/libs/zstd/zstd.h>
using namespace NBlockCodecs;
namespace {
struct TZStd08Codec: public TAddLengthCodec<TZStd08Codec> {
inline TZStd08Codec(unsigned level)
: Level(level)
, MyName(AsStringBuf("zstd08_") + ToString(Level))
{
}
static inline size_t CheckError(size_t ret, const char* what) {
if (ZSTD_isError(ret)) {
ythrow yexception() << what << AsStringBuf(" zstd error: ") << ZSTD_getErrorName(ret);
}
return ret;
}
static inline size_t DoMaxCompressedLength(size_t l) noexcept {
return ZSTD_compressBound(l);
}
inline size_t DoCompress(const TData& in, void* out) const {
return CheckError(ZSTD_compress(out, DoMaxCompressedLength(in.size()), in.data(), in.size(), Level), "compress");
}
inline void DoDecompress(const TData& in, void* out, size_t dsize) const {
const size_t res = CheckError(ZSTD_decompress(out, dsize, in.data(), in.size()), "decompress");
if (res != dsize) {
ythrow TDecompressError(dsize, res);
}
}
TStringBuf Name() const noexcept override {
return MyName;
}
const unsigned Level;
const TString MyName;
};
struct TZStd08Registrar {
TZStd08Registrar() {
for (int i = 1; i <= ZSTD_maxCLevel(); ++i) {
RegisterCodec(MakeHolder<TZStd08Codec>(i));
RegisterAlias("zstd_" + ToString(i), "zstd08_" + ToString(i));
}
}
};
static const TZStd08Registrar Registrar{};
}
| 31.183333 | 125 | 0.5938 | gwjknvwjn |
f3e5e1b8f97aef49070a35dc7a03dac8f4816e6d | 495 | cpp | C++ | examples/example3.cpp | waqqas/boost_sqlite | 5946f1d91a71e1bbc94da9270caef78d104873af | [
"BSD-3-Clause"
] | 2 | 2021-04-12T05:49:15.000Z | 2021-06-22T06:40:13.000Z | examples/example3.cpp | waqqas/boost_sqlite | 5946f1d91a71e1bbc94da9270caef78d104873af | [
"BSD-3-Clause"
] | null | null | null | examples/example3.cpp | waqqas/boost_sqlite | 5946f1d91a71e1bbc94da9270caef78d104873af | [
"BSD-3-Clause"
] | 1 | 2020-11-09T10:09:07.000Z | 2020-11-09T10:09:07.000Z |
#include "sqliter/sqliter.h"
#include <iostream>
#include <string>
using namespace sqliter::asio;
int main(int argc, char *argv[])
{
boost::asio::io_service io;
sqlite db(io);
if (argc != 2)
{
std::cout << argv[0] << " <sqlite db file>" << std::endl;
return -1;
}
db.open(argv[1]);
boost::system::error_code ec;
db.query("SELECT * from app", ec);
std::cout << "Result: " << ec.message() << std::endl;
io.run();
db.close(ec);
return 0;
} | 15.967742 | 61 | 0.563636 | waqqas |
f3e5f79765d6f4e37736c92540d50aa3125ff412 | 8,944 | cpp | C++ | mdc/src/v20200828/model/CreateInput.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | 1 | 2022-01-27T09:27:34.000Z | 2022-01-27T09:27:34.000Z | mdc/src/v20200828/model/CreateInput.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | mdc/src/v20200828/model/CreateInput.cpp | TencentCloud/tencentcloud-sdk-cpp-intl-en | 752c031f5ad2c96868183c5931eae3a42dd5ae6c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/mdc/v20200828/model/CreateInput.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Mdc::V20200828::Model;
using namespace std;
CreateInput::CreateInput() :
m_inputNameHasBeenSet(false),
m_protocolHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_allowIpListHasBeenSet(false),
m_sRTSettingsHasBeenSet(false),
m_rTPSettingsHasBeenSet(false),
m_failOverHasBeenSet(false)
{
}
CoreInternalOutcome CreateInput::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("InputName") && !value["InputName"].IsNull())
{
if (!value["InputName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CreateInput.InputName` IsString=false incorrectly").SetRequestId(requestId));
}
m_inputName = string(value["InputName"].GetString());
m_inputNameHasBeenSet = true;
}
if (value.HasMember("Protocol") && !value["Protocol"].IsNull())
{
if (!value["Protocol"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CreateInput.Protocol` IsString=false incorrectly").SetRequestId(requestId));
}
m_protocol = string(value["Protocol"].GetString());
m_protocolHasBeenSet = true;
}
if (value.HasMember("Description") && !value["Description"].IsNull())
{
if (!value["Description"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CreateInput.Description` IsString=false incorrectly").SetRequestId(requestId));
}
m_description = string(value["Description"].GetString());
m_descriptionHasBeenSet = true;
}
if (value.HasMember("AllowIpList") && !value["AllowIpList"].IsNull())
{
if (!value["AllowIpList"].IsArray())
return CoreInternalOutcome(Core::Error("response `CreateInput.AllowIpList` is not array type"));
const rapidjson::Value &tmpValue = value["AllowIpList"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_allowIpList.push_back((*itr).GetString());
}
m_allowIpListHasBeenSet = true;
}
if (value.HasMember("SRTSettings") && !value["SRTSettings"].IsNull())
{
if (!value["SRTSettings"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `CreateInput.SRTSettings` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_sRTSettings.Deserialize(value["SRTSettings"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_sRTSettingsHasBeenSet = true;
}
if (value.HasMember("RTPSettings") && !value["RTPSettings"].IsNull())
{
if (!value["RTPSettings"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `CreateInput.RTPSettings` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_rTPSettings.Deserialize(value["RTPSettings"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_rTPSettingsHasBeenSet = true;
}
if (value.HasMember("FailOver") && !value["FailOver"].IsNull())
{
if (!value["FailOver"].IsString())
{
return CoreInternalOutcome(Core::Error("response `CreateInput.FailOver` IsString=false incorrectly").SetRequestId(requestId));
}
m_failOver = string(value["FailOver"].GetString());
m_failOverHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void CreateInput::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_inputNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "InputName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_inputName.c_str(), allocator).Move(), allocator);
}
if (m_protocolHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Protocol";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_protocol.c_str(), allocator).Move(), allocator);
}
if (m_descriptionHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Description";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_description.c_str(), allocator).Move(), allocator);
}
if (m_allowIpListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AllowIpList";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_allowIpList.begin(); itr != m_allowIpList.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_sRTSettingsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SRTSettings";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_sRTSettings.ToJsonObject(value[key.c_str()], allocator);
}
if (m_rTPSettingsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RTPSettings";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_rTPSettings.ToJsonObject(value[key.c_str()], allocator);
}
if (m_failOverHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "FailOver";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_failOver.c_str(), allocator).Move(), allocator);
}
}
string CreateInput::GetInputName() const
{
return m_inputName;
}
void CreateInput::SetInputName(const string& _inputName)
{
m_inputName = _inputName;
m_inputNameHasBeenSet = true;
}
bool CreateInput::InputNameHasBeenSet() const
{
return m_inputNameHasBeenSet;
}
string CreateInput::GetProtocol() const
{
return m_protocol;
}
void CreateInput::SetProtocol(const string& _protocol)
{
m_protocol = _protocol;
m_protocolHasBeenSet = true;
}
bool CreateInput::ProtocolHasBeenSet() const
{
return m_protocolHasBeenSet;
}
string CreateInput::GetDescription() const
{
return m_description;
}
void CreateInput::SetDescription(const string& _description)
{
m_description = _description;
m_descriptionHasBeenSet = true;
}
bool CreateInput::DescriptionHasBeenSet() const
{
return m_descriptionHasBeenSet;
}
vector<string> CreateInput::GetAllowIpList() const
{
return m_allowIpList;
}
void CreateInput::SetAllowIpList(const vector<string>& _allowIpList)
{
m_allowIpList = _allowIpList;
m_allowIpListHasBeenSet = true;
}
bool CreateInput::AllowIpListHasBeenSet() const
{
return m_allowIpListHasBeenSet;
}
CreateInputSRTSettings CreateInput::GetSRTSettings() const
{
return m_sRTSettings;
}
void CreateInput::SetSRTSettings(const CreateInputSRTSettings& _sRTSettings)
{
m_sRTSettings = _sRTSettings;
m_sRTSettingsHasBeenSet = true;
}
bool CreateInput::SRTSettingsHasBeenSet() const
{
return m_sRTSettingsHasBeenSet;
}
CreateInputRTPSettings CreateInput::GetRTPSettings() const
{
return m_rTPSettings;
}
void CreateInput::SetRTPSettings(const CreateInputRTPSettings& _rTPSettings)
{
m_rTPSettings = _rTPSettings;
m_rTPSettingsHasBeenSet = true;
}
bool CreateInput::RTPSettingsHasBeenSet() const
{
return m_rTPSettingsHasBeenSet;
}
string CreateInput::GetFailOver() const
{
return m_failOver;
}
void CreateInput::SetFailOver(const string& _failOver)
{
m_failOver = _failOver;
m_failOverHasBeenSet = true;
}
bool CreateInput::FailOverHasBeenSet() const
{
return m_failOverHasBeenSet;
}
| 28.758842 | 141 | 0.677549 | TencentCloud |
f3e63b07283666bfe6aacb4e9e2fbb7fd86d626f | 1,025 | cpp | C++ | Pdf/pdfix_sdk_example_cpp-master/src/StandardLicenseDeactivate.cpp | laoola/ProjectCode | 498a66cb9274f6bb7cca0d6e6052304d61740ba2 | [
"Unlicense"
] | 1 | 2021-08-23T05:56:09.000Z | 2021-08-23T05:56:09.000Z | Pdf/pdfix_sdk_example_cpp-master/src/StandardLicenseDeactivate.cpp | laoola/ProjectCode | 498a66cb9274f6bb7cca0d6e6052304d61740ba2 | [
"Unlicense"
] | null | null | null | Pdf/pdfix_sdk_example_cpp-master/src/StandardLicenseDeactivate.cpp | laoola/ProjectCode | 498a66cb9274f6bb7cca0d6e6052304d61740ba2 | [
"Unlicense"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////
// StandardLicenseDeactivate.cpp
// Copyright (c) 2019 Pdfix. All Rights Reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////
#include "pdfixsdksamples/StandardLicenseDeactivate.h"
// system
#include <string>
#include <iostream>
// other libraries
#include "Pdfix.h"
using namespace PDFixSDK;
namespace StandardLicenseDeactivate {
// Adds a new text annotation.
void Run() {
// initialize Pdfix
if (!Pdfix_init(Pdfix_MODULE_NAME))
throw std::runtime_error("Pdfix initialization fail");
Pdfix* pdfix = GetPdfix();
if (!pdfix)
throw std::runtime_error("GetPdfix fail");
auto authorization = pdfix->GetStandardAuthorization();
if (!authorization)
throw PdfixException();
if (!authorization->Deactivate())
throw PdfixException();
pdfix->Destroy();
}
}
//! [StandardLicenseDeactivate_cpp]
| 26.973684 | 100 | 0.555122 | laoola |
f3ebb1b7c1aa09f9f05830500cf403ac6ccf4b92 | 3,874 | cpp | C++ | C++/test/check_biobase_matches.cpp | JohnReid/biopsy | 1eeb714ba5b53f2ecf776d865d32e2078cbc0338 | [
"MIT"
] | null | null | null | C++/test/check_biobase_matches.cpp | JohnReid/biopsy | 1eeb714ba5b53f2ecf776d865d32e2078cbc0338 | [
"MIT"
] | null | null | null | C++/test/check_biobase_matches.cpp | JohnReid/biopsy | 1eeb714ba5b53f2ecf776d865d32e2078cbc0338 | [
"MIT"
] | null | null | null |
#include "bio_test_data.h"
#include <bio/biobase_match.h>
#include <bio/matrix.h>
#include <bio/score_sequence.h>
USING_BIO_NS;
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/io/ios_state.hpp>
#include <boost/progress.hpp>
#include <boost/test/parameterized_test.hpp>
using namespace boost;
using boost::unit_test::test_suite;
#include <string>
using namespace std;
/**
Results from TRANSFAC for the test sequence:
matrix position core matrix sequence (always the factor name
identifier (strand) match match (+)-strand is shown)
V$DEAF1_01 86 (+) 1.000 0.857 gcgcctcagtgtacTTCCGaacgaa DEAF1
V$IPF1_Q4_01 111 (+) 1.000 0.975 tgagtCATTAataga IPF1
V$EFC_Q6 336 (-) 0.910 0.853 ttacccgaGTGACt RFX1
(EF-C)
V$AP1_Q4 343 (+) 1.000 0.990 agTGACTgact AP-1
V$CREBP1_01 384 (+) 1.000 1.000 TTACGtaa CRE-BP1
V$CREBP1_01 384 (-) 1.000 1.000 ttaCGTAA CRE-BP1
V$HNF3ALPHA_Q6 446 (+) 1.000 0.973 TGTTTgctctc HNF-3alpha
V$FOXP3_Q4 589 (+) 0.859 0.831 tatgaGCTGTttcagat FOXP3
V$HNF1_Q6 694 (-) 0.952 0.873 cttctgaaggAGTAActc HNF-1
V$COMP1_01 888 (+) 1.000 0.859 taggaaGATTGgccacatcagctt COMP1
V$CDPCR1_01 979 (-) 0.896 0.914 acgaTCTATg CDP CR1
*/
void check_biobase_matches(BiobaseParams const & params)
{
ensure_biobase_params_built();
cout << "******* check_biobase_matches(): Testing with " << params.name.c_str() << " parameters" << endl;
//progress_timer timer;
boost::io::ios_precision_saver saver(cout);
cout.precision(3);
//build the pssms
const Pssm matrix_pssm = *params.pssm;
const Pssm iupac_pssm = make_pssm_from_iupac(params.iupac->begin(), params.iupac->end());
#ifdef VERBOSE_CHECKING
cout
<< "Matrix pssm:" << endl
<< matrix_pssm
<< endl;
cout
<< "IUPAC pssm:" << endl
<< iupac_pssm
<< endl;
#endif
//match to compute the score
Hit pssm_match (-1.0, 0);
Hit iupac_match (-1.0, 0);
if (params.run_over_range)
{
pssm_match =
score_sequence(
matrix_pssm,
params.seq_begin,
params.seq_end,
params.match_complement);
iupac_match =
score_sequence(
iupac_pssm,
params.seq_begin,
params.seq_end,
params.match_complement);
}
else
{
assert(params.seq_end - params.seq_begin == int( matrix_pssm.size() ) );
pssm_match.score = matrix_pssm.score(params.seq_begin, params.match_complement);
iupac_match.score = iupac_pssm.score(params.seq_begin, params.match_complement);
}
//compare against expected
BOOST_CHECK_CLOSE(params.target_match.score, pssm_match.score, 1.0); //only compare to 1% (we have 3 figure accuracy)
BOOST_CHECK_CLOSE(iupac_match.score, pssm_match.score, params.iupac_tolerance); //IUPAC should be close to PSSM match
BOOST_CHECK_EQUAL(params.target_match.position, pssm_match.position); //position of the pssm match
BOOST_CHECK_EQUAL(params.target_match.complement, pssm_match.complement); //was it on the complementary strand
}
void register_biobase_matches_tests(boost::unit_test::test_suite * test)
{
ensure_biobase_params_built();
test->add(BOOST_PARAM_TEST_CASE(&check_biobase_matches, biobase_params.begin(), biobase_params.end()), 0);
//superceded
//test->add(BOOST_TEST_CASE(&check_ott_normaliser_cache), 0);
//test->add(BOOST_TEST_CASE(&check_ott_normalisation), 0);
//test->add(BOOST_TEST_CASE(&check_weak_pssms), 0);
}
| 34.900901 | 121 | 0.636035 | JohnReid |
f3ed2cfa2c8d264ea5ee1ea206ca9e13f3b1e6c1 | 1,405 | hpp | C++ | player/playerlib/android/render/MemcopyRender.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | player/playerlib/android/render/MemcopyRender.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | player/playerlib/android/render/MemcopyRender.hpp | zhenfei2016/FFL-v2 | 376c79a0611af580d4767a4bbb05822f1a4fd454 | [
"MIT"
] | null | null | null | /*
* This file is part of FFL project.
*
* The MIT License (MIT)
* Copyright (C) 2017-2018 zhufeifei All rights reserved.
*
* MemcopyRender.hpp
* Created by zhufeifei(34008081@qq.com) on 2018/06/28
* https://github.com/zhenfei2016/FFL-v2.git
* android ANativewindow数据拷贝显示方式
*
*/
#include "RenderInterface.hpp"
#include "VideoFormat.hpp"
namespace android{
class MemcopyRender : public RenderInterface{
public:
MemcopyRender();
~MemcopyRender();
public:
// 获取支持的格式
// wanted: 如果为nUll则返回所有支持的格式
// 非null 返回跟他匹配的
// fmtList: 返回支持的格式list
//
virtual void getSupportFormat(player::VideoSurface* surface,const player::VideoFormat* wanted,FFL::List<player::VideoFormat>& fmtList);
virtual bool getOptimalFormat(player::VideoSurface* surface,const player::VideoFormat* wanted,player::VideoFormat* optinal);
virtual bool isSupportFormat(player::VideoSurface* surface,const player::VideoFormat* wanted);
//
// 创建这个render ,arg自定义的参数
//
virtual status_t create(player::VideoSurface* surface,const player::VideoFormat* arg);
//
// 绘制图片tex到 surface上面
//
virtual status_t draw(player::VideoSurface* surface,player::VideoTexture* tex);
//
// 释放这个render,释放后这个render就不可用了
//
virtual void destroy();
};
} | 33.452381 | 143 | 0.649822 | zhenfei2016 |
f3f04d0fe9e13ec4f724e2c3d44bd42d5425d784 | 804 | cpp | C++ | sa2-battle-network/OnGameState.cpp | michael-fadely/sa2-battle-network | c8391dc5fdc9f1b6fc6c0c5020bbe4baabbb0aff | [
"MIT"
] | 13 | 2019-06-29T19:38:46.000Z | 2022-01-27T07:52:15.000Z | sa2-battle-network/OnGameState.cpp | SonicFreak94/sa2-battle-network | c8391dc5fdc9f1b6fc6c0c5020bbe4baabbb0aff | [
"MIT"
] | 37 | 2015-10-17T08:33:42.000Z | 2018-03-11T03:10:04.000Z | sa2-battle-network/OnGameState.cpp | SonicFreak94/sa2-battle-network | c8391dc5fdc9f1b6fc6c0c5020bbe4baabbb0aff | [
"MIT"
] | 1 | 2021-09-17T06:50:34.000Z | 2021-09-17T06:50:34.000Z | #include "stdafx.h"
#include <SA2ModLoader.h> // for everything
#include "Networking.h" // for MessageID
#include "globals.h"
#include "OnGameState.h"
DataPointer(uint, dword_174B058, 0x174B058);
// Note that the name is misleading. This only happens when the gamestate changes to Ingame.
// TODO: Real OnGameState
// TODO: Consider removing since PoseEffect2PStartMan is now synchronized
static void __stdcall OnGameState()
{
using namespace nethax;
using namespace globals;
// This is here because we overwrite its assignment with a call
// in the original code.
dword_174B058 = 0;
if (!is_connected())
{
return;
}
broker->send_ready_and_wait(MessageID::S_GameState);
}
// TODO: Make revertible
void nethax::events::InitOnGameState()
{
WriteCall((void*)0x0043AAEE, OnGameState);
}
| 22.333333 | 92 | 0.748756 | michael-fadely |
f3f0538d7b85c0c80e81d28f73da3e71517e6530 | 1,472 | cpp | C++ | bftengine/tests/simpleStorage/ObjectsMetadataHandler.cpp | definitelyNotFBI/utt | 1695e3a1f81848e19b042cdc4db9cf1d263c26a9 | [
"Apache-2.0"
] | 340 | 2018-08-27T16:30:45.000Z | 2022-03-28T14:31:44.000Z | bftengine/tests/simpleStorage/ObjectsMetadataHandler.cpp | yuliasherman/concord-bft | 81c5278828c4d05f4822087659decd4a926e85c9 | [
"Apache-2.0"
] | 706 | 2018-09-02T17:50:32.000Z | 2022-03-31T13:03:15.000Z | bftengine/tests/simpleStorage/ObjectsMetadataHandler.cpp | glevkovich/concord-bft | a1b7b57472f5375230428d16c613a760b33233fa | [
"Apache-2.0"
] | 153 | 2018-08-29T05:37:25.000Z | 2022-03-23T14:08:45.000Z | // Concord
//
// Copyright (c) 2018 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the subcomponent's license, as noted in the LICENSE
// file.
#include "ObjectsMetadataHandler.hpp"
#include <stdio.h>
#include <cstring>
using namespace std;
namespace bftEngine {
ostream &operator<<(ostream &stream, const ObjectsMetadataHandler &objectsMetadataHandler) {
stream << "ObjectsMetadataHandler: objectsNumber=" << objectsMetadataHandler.getObjectsNum() << '\n';
for (auto it : objectsMetadataHandler.getObjectsMap()) {
stream << it.second.toString() << '\n';
}
return stream;
}
size_t ObjectsMetadataHandler::getObjectsMetadataSize() {
return (sizeof(objectsNum_) + sizeof(MetadataObjectInfo) * objectsNum_);
}
void ObjectsMetadataHandler::setObjectInfo(const MetadataObjectInfo &objectInfo) {
objectsMap_.insert(pair<uint32_t, MetadataObjectInfo>(objectInfo.id, objectInfo));
}
MetadataObjectInfo *ObjectsMetadataHandler::getObjectInfo(uint32_t objectId) {
auto it = objectsMap_.find(objectId);
if (it != objectsMap_.end()) {
return &(it->second);
}
return nullptr;
}
} // namespace bftEngine
| 30.666667 | 103 | 0.746603 | definitelyNotFBI |
f3f15b4488dabbd980c8a269c993305fe37e475f | 34,525 | hpp | C++ | src/include/sweet/sphere/SphereData_Spectral.hpp | valentinaschueller/sweet | 27e99c7a110c99deeadee70688c186d82b39ac90 | [
"MIT"
] | 6 | 2017-11-20T08:12:46.000Z | 2021-03-11T15:32:36.000Z | src/include/sweet/sphere/SphereData_Spectral.hpp | valentinaschueller/sweet | 27e99c7a110c99deeadee70688c186d82b39ac90 | [
"MIT"
] | 4 | 2018-02-02T21:46:33.000Z | 2022-01-11T11:10:27.000Z | src/include/sweet/sphere/SphereData_Spectral.hpp | valentinaschueller/sweet | 27e99c7a110c99deeadee70688c186d82b39ac90 | [
"MIT"
] | 12 | 2016-03-01T18:33:34.000Z | 2022-02-08T22:20:31.000Z | /*
* SphereData.hpp
*
* Created on: 9 Aug 2016
* Author: Martin Schreiber <schreiberx@gmail.com>
*/
#ifndef SWEET_SPHERE_DATA_SPECTRAL_HPP_
#define SWEET_SPHERE_DATA_SPECTRAL_HPP_
#include <complex>
#include <functional>
#include <array>
#include <cstring>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cassert>
#include <limits>
#include <utility>
#include <functional>
#include <cmath>
#include <sweet/parmemcpy.hpp>
#include <sweet/MemBlockAlloc.hpp>
#include <sweet/openmp_helper.hpp>
#include <sweet/sphere/SphereData_Config.hpp>
#include <sweet/sphere/SphereData_Physical.hpp>
#include <sweet/sphere/SphereData_PhysicalComplex.hpp>
#include <sweet/SWEETError.hpp>
class SphereData_Spectral
{
friend class SphereData_SpectralComplex;
typedef std::complex<double> Tcomplex;
public:
const SphereData_Config *sphereDataConfig = nullptr;
public:
std::complex<double> *spectral_space_data = nullptr;
std::complex<double>& operator[](std::size_t i)
{
return spectral_space_data[i];
}
const std::complex<double>& operator[](std::size_t i) const
{
return spectral_space_data[i];
}
void swap(
SphereData_Spectral &i_sphereData
)
{
assert(sphereDataConfig == i_sphereData.sphereDataConfig);
std::swap(spectral_space_data, i_sphereData.spectral_space_data);
}
public:
SphereData_Spectral(
const SphereData_Config *i_sphereDataConfig
) :
sphereDataConfig(i_sphereDataConfig),
spectral_space_data(nullptr)
{
assert(i_sphereDataConfig != 0);
setup(i_sphereDataConfig);
}
public:
SphereData_Spectral(
const SphereData_Config *i_sphereDataConfig,
const std::complex<double> &i_value
) :
sphereDataConfig(i_sphereDataConfig),
spectral_space_data(nullptr)
{
assert(i_sphereDataConfig != 0);
setup(i_sphereDataConfig);
spectral_set_value(i_value);
}
public:
SphereData_Spectral(
const SphereData_Config *i_sphereDataConfig,
double &i_value
) :
sphereDataConfig(i_sphereDataConfig),
spectral_space_data(nullptr)
{
assert(i_sphereDataConfig != 0);
setup(i_sphereDataConfig);
spectral_set_value(i_value);
}
public:
SphereData_Spectral() :
sphereDataConfig(nullptr),
spectral_space_data(nullptr)
{
}
public:
SphereData_Spectral(
const SphereData_Spectral &i_sph_data
) :
sphereDataConfig(i_sph_data.sphereDataConfig),
spectral_space_data(nullptr)
{
if (i_sph_data.sphereDataConfig == nullptr)
return;
alloc_data();
operator=(i_sph_data);
}
public:
SphereData_Spectral(
SphereData_Spectral &&i_sph_data
) :
sphereDataConfig(i_sph_data.sphereDataConfig),
spectral_space_data(nullptr)
{
if (i_sph_data.sphereDataConfig == nullptr)
return;
alloc_data();
spectral_space_data = i_sph_data.spectral_space_data;
}
/**
* Run validation checks to make sure that the physical and spectral spaces match in size
*/
public:
inline void check(
const SphereData_Config *i_sphereDataConfig
) const
{
assert(sphereDataConfig->physical_num_lat == i_sphereDataConfig->physical_num_lat);
assert(sphereDataConfig->physical_num_lon == i_sphereDataConfig->physical_num_lon);
assert(sphereDataConfig->spectral_modes_m_max == i_sphereDataConfig->spectral_modes_m_max);
assert(sphereDataConfig->spectral_modes_n_max == i_sphereDataConfig->spectral_modes_n_max);
}
public:
SphereData_Spectral& operator=(
const SphereData_Spectral &i_sph_data
)
{
if (i_sph_data.sphereDataConfig == nullptr)
return *this;
if (sphereDataConfig == nullptr)
setup(i_sph_data.sphereDataConfig);
parmemcpy(spectral_space_data, i_sph_data.spectral_space_data, sizeof(Tcomplex)*sphereDataConfig->spectral_array_data_number_of_elements);
return *this;
}
/**
* This function implements copying the spectral data only.
*
* This becomes handy if coping with data which should be only transformed without dealiasing.
*/
public:
SphereData_Spectral& load_nodealiasing(
const SphereData_Spectral &i_sph_data ///< data to be converted to sphereDataConfig_nodealiasing
)
{
if (sphereDataConfig == nullptr)
SWEETError("sphereDataConfig not initialized");
parmemcpy(spectral_space_data, i_sph_data.spectral_space_data, sizeof(Tcomplex)*sphereDataConfig->spectral_array_data_number_of_elements);
return *this;
}
public:
SphereData_Spectral& operator=(
SphereData_Spectral &&i_sph_data
)
{
if (sphereDataConfig == nullptr)
setup(i_sph_data.sphereDataConfig);
std::swap(spectral_space_data, i_sph_data.spectral_space_data);
return *this;
}
public:
SphereData_Spectral spectral_returnWithDifferentModes(
const SphereData_Config *i_sphereDataConfig
) const
{
SphereData_Spectral out(i_sphereDataConfig);
/*
* 0 = invalid
* -1 = scale down
* 1 = scale up
*/
int scaling_mode = 0;
if (sphereDataConfig->spectral_modes_m_max < out.sphereDataConfig->spectral_modes_m_max)
{
scaling_mode = 1;
}
else if (sphereDataConfig->spectral_modes_m_max > out.sphereDataConfig->spectral_modes_m_max)
{
scaling_mode = -1;
}
if (sphereDataConfig->spectral_modes_n_max < out.sphereDataConfig->spectral_modes_n_max)
{
assert(scaling_mode != -1);
scaling_mode = 1;
}
else if (sphereDataConfig->spectral_modes_n_max > out.sphereDataConfig->spectral_modes_n_max)
{
assert(scaling_mode != 1);
scaling_mode = -1;
}
if (scaling_mode == 0)
{
// Just copy the data
out = *this;
return out;
}
if (scaling_mode == -1)
{
/*
* more modes -> less modes
*/
SWEET_THREADING_SPACE_PARALLEL_FOR
for (int m = 0; m <= out.sphereDataConfig->spectral_modes_m_max; m++)
{
Tcomplex *dst = &out.spectral_space_data[out.sphereDataConfig->getArrayIndexByModes(m, m)];
Tcomplex *src = &spectral_space_data[sphereDataConfig->getArrayIndexByModes(m, m)];
std::size_t size = sizeof(Tcomplex)*(out.sphereDataConfig->spectral_modes_n_max-m+1);
memcpy(dst, src, size);
}
}
else
{
/*
* less modes -> more modes
*/
// zero all values
out.spectral_set_zero();
SWEET_THREADING_SPACE_PARALLEL_FOR
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++)
{
Tcomplex *dst = &out.spectral_space_data[out.sphereDataConfig->getArrayIndexByModes(m, m)];
Tcomplex *src = &spectral_space_data[sphereDataConfig->getArrayIndexByModes(m, m)];
std::size_t size = sizeof(Tcomplex)*(sphereDataConfig->spectral_modes_n_max-m+1);
memcpy(dst, src, size);
}
}
return out;
}
/*
* Setup spectral sphere data based on data in physical space
*/
void loadSphereDataPhysical(
const SphereData_Physical &i_sphereDataPhysical
)
{
/**
* Warning: The sphat_to_SH function is an in-situ operation.
* Therefore, the data in the source array will be destroyed.
* Hence, we create a copy
*/
SphereData_Physical tmp(i_sphereDataPhysical);
spat_to_SH(sphereDataConfig->shtns, tmp.physical_space_data, spectral_space_data);
}
/*
* Return the data converted to physical space
*/
SphereData_Physical getSphereDataPhysical() const
{
/**
* Warning: This is an in-situ operation.
* Therefore, the data in the source array will be destroyed.
*/
SphereData_Spectral tmp(*this);
SphereData_Physical retval(sphereDataConfig);
SH_to_spat(sphereDataConfig->shtns, tmp.spectral_space_data, retval.physical_space_data);
return retval;
}
/*
* Return the data converted to physical space
*
* alias for "getSphereDataPhysical"
*/
SphereData_Physical toPhys() const
{
/**
* Warning: This is an in-situ operation.
* Therefore, the data in the source array will be destroyed.
*/
SphereData_Spectral tmp(*this);
SphereData_Physical retval(sphereDataConfig);
SH_to_spat(sphereDataConfig->shtns, tmp.spectral_space_data, retval.physical_space_data);
return retval;
}
SphereData_PhysicalComplex getSphereDataPhysicalComplex() const
{
SphereData_PhysicalComplex out(sphereDataConfig);
/*
* WARNING:
* We have to use a temporary array here because of destructive SH transformations
*/
SphereData_Spectral tmp_spectral(*this);
SphereData_Physical tmp_physical(sphereDataConfig);
SH_to_spat(sphereDataConfig->shtns, tmp_spectral.spectral_space_data, tmp_physical.physical_space_data);
parmemcpy(out.physical_space_data, tmp_physical.physical_space_data, sizeof(double)*sphereDataConfig->physical_array_data_number_of_elements);
return out;
}
SphereData_Spectral(
const SphereData_Physical &i_sphere_data_physical
)
{
setup(i_sphere_data_physical.sphereDataConfig);
loadSphereDataPhysical(i_sphere_data_physical);
}
SphereData_Spectral operator+(
const SphereData_Spectral &i_sph_data
) const
{
check(i_sph_data.sphereDataConfig);
SphereData_Spectral out(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
out.spectral_space_data[idx] = spectral_space_data[idx] + i_sph_data.spectral_space_data[idx];
return out;
}
SphereData_Spectral& operator+=(
const SphereData_Spectral &i_sph_data
)
{
check(i_sph_data.sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
spectral_space_data[idx] += i_sph_data.spectral_space_data[idx];
return *this;
}
SphereData_Spectral& operator-=(
const SphereData_Spectral &i_sph_data
)
{
check(i_sph_data.sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
spectral_space_data[idx] -= i_sph_data.spectral_space_data[idx];
return *this;
}
SphereData_Spectral operator-(
const SphereData_Spectral &i_sph_data
) const
{
check(i_sph_data.sphereDataConfig);
SphereData_Spectral out(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
out.spectral_space_data[idx] = spectral_space_data[idx] - i_sph_data.spectral_space_data[idx];
return out;
}
SphereData_Spectral operator-() const
{
SphereData_Spectral out(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
out.spectral_space_data[idx] = -spectral_space_data[idx];
return out;
}
SphereData_Spectral operator*(
const SphereData_Spectral &i_sph_data
) const
{
check(i_sph_data.sphereDataConfig);
SphereData_Physical a = getSphereDataPhysical();
SphereData_Physical b = i_sph_data.toPhys();
SphereData_Physical mul(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (std::size_t i = 0; i < sphereDataConfig->physical_array_data_number_of_elements; i++)
mul.physical_space_data[i] = a.physical_space_data[i]*b.physical_space_data[i];
SphereData_Spectral out(mul);
return out;
}
SphereData_Spectral operator/(
const SphereData_Spectral &i_sph_data
) const
{
check(i_sph_data.sphereDataConfig);
SphereData_Physical a = getSphereDataPhysical();
SphereData_Physical b = i_sph_data.toPhys();
SphereData_Physical div(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (std::size_t i = 0; i < sphereDataConfig->physical_array_data_number_of_elements; i++)
div.physical_space_data[i] = a.physical_space_data[i]/b.physical_space_data[i];
SphereData_Spectral out(div);
return out;
}
SphereData_Spectral operator*(
double i_value
) const
{
SphereData_Spectral out(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
out.spectral_space_data[idx] = spectral_space_data[idx]*i_value;
return out;
}
const SphereData_Spectral& operator*=(
double i_value
) const
{
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
spectral_space_data[idx] *= i_value;
return *this;
}
const SphereData_Spectral& operator/=(
double i_value
) const
{
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
spectral_space_data[idx] /= i_value;
return *this;
}
const SphereData_Spectral& operator*=(
const std::complex<double> &i_value
) const
{
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
spectral_space_data[idx] *= i_value;
return *this;
}
SphereData_Spectral operator/(
double i_value
) const
{
SphereData_Spectral out(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
out.spectral_space_data[idx] = spectral_space_data[idx]/i_value;
return out;
}
SphereData_Spectral operator+(
double i_value
) const
{
SphereData_Spectral out(*this);
out.spectral_space_data[0] += i_value*std::sqrt(4.0*M_PI);
return out;
}
SphereData_Spectral operator_scalar_sub_this(
double i_value
) const
{
SphereData_Spectral out(sphereDataConfig);
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int idx = 0; idx < sphereDataConfig->spectral_array_data_number_of_elements; idx++)
out.spectral_space_data[idx] = -spectral_space_data[idx];
out.spectral_space_data[0] = i_value*std::sqrt(4.0*M_PI) + out.spectral_space_data[0];
return out;
}
const SphereData_Spectral& operator+=(
double i_value
) const
{
spectral_space_data[0] += i_value*std::sqrt(4.0*M_PI);
return *this;
}
SphereData_Spectral operator-(
double i_value
) const
{
SphereData_Spectral out(*this);
out.spectral_space_data[0] -= i_value*std::sqrt(4.0*M_PI);
return out;
}
SphereData_Spectral& operator-=(
double i_value
)
{
spectral_space_data[0] -= i_value*std::sqrt(4.0*M_PI);
return *this;
}
public:
void setup(
const SphereData_Config *i_sphereDataConfig
)
{
sphereDataConfig = i_sphereDataConfig;
alloc_data();
}
public:
void setup(
const SphereData_Config *i_sphereDataConfig,
double i_value
)
{
sphereDataConfig = i_sphereDataConfig;
alloc_data();
spectral_set_value(i_value);
}
private:
void alloc_data()
{
assert(spectral_space_data == nullptr);
spectral_space_data = MemBlockAlloc::alloc<Tcomplex>(sphereDataConfig->spectral_array_data_number_of_elements * sizeof(Tcomplex));
}
public:
void setup_if_required(
const SphereData_Config *i_sphereDataConfig
)
{
if (sphereDataConfig != nullptr)
return;
setup(i_sphereDataConfig);
}
public:
void free()
{
if (spectral_space_data != nullptr)
{
MemBlockAlloc::free(spectral_space_data, sphereDataConfig->spectral_array_data_number_of_elements * sizeof(Tcomplex));
spectral_space_data = nullptr;
sphereDataConfig = nullptr;
}
}
public:
~SphereData_Spectral()
{
free();
}
/**
* Solve a Helmholtz problem given by
*
* (a + b D^2) x = rhs
*/
inline
SphereData_Spectral spectral_solve_helmholtz(
const double &i_a,
const double &i_b,
double r
)
{
SphereData_Spectral out(*this);
const double a = i_a;
const double b = i_b/(r*r);
out.spectral_update_lambda(
[&](
int n, int m,
std::complex<double> &io_data
)
{
io_data /= (a + (-b*(double)n*((double)n+1.0)));
}
);
return out;
}
/**
* Solve a Laplace problem given by
*
* (D^2) x = rhs
*/
inline
SphereData_Spectral spectral_solve_laplace(
double r
)
{
SphereData_Spectral out(*this);
const double b = 1.0/(r*r);
out.spectral_update_lambda(
[&](
int n, int m,
std::complex<double> &io_data
)
{
if (n == 0)
io_data = 0;
else
io_data /= (-b*(double)n*((double)n+1.0));
}
);
return out;
}
/**
* Truncate modes which are not representable in spectral space
*/
const SphereData_Spectral& spectral_truncate() const
{
SphereData_Physical tmp(sphereDataConfig);
SH_to_spat(sphereDataConfig->shtns, spectral_space_data, tmp.physical_space_data);
spat_to_SH(sphereDataConfig->shtns, tmp.physical_space_data, spectral_space_data);
return *this;
}
void spectral_update_lambda(
std::function<void(int,int,Tcomplex&)> i_lambda
)
{
SWEET_THREADING_SPACE_PARALLEL_FOR
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++)
{
std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++)
{
i_lambda(n, m, spectral_space_data[idx]);
idx++;
}
}
}
const std::complex<double>& spectral_get_DEPRECATED(
int i_n,
int i_m
) const
{
static const std::complex<double> zero = {0,0};
if (i_n < 0 || i_m < 0)
return zero;
if (i_n > sphereDataConfig->spectral_modes_n_max)
return zero;
if (i_m > sphereDataConfig->spectral_modes_m_max)
return zero;
if (i_m > i_n)
return zero;
assert (i_m <= sphereDataConfig->spectral_modes_m_max);
return spectral_space_data[sphereDataConfig->getArrayIndexByModes(i_n, i_m)];
}
const std::complex<double>& spectral_get_(
int i_n,
int i_m
) const
{
assert(i_n >= 0 && i_m >= 0);
assert(i_n <= sphereDataConfig->spectral_modes_n_max);
assert(i_m <= sphereDataConfig->spectral_modes_m_max);
assert(i_m <= i_n);
return spectral_space_data[sphereDataConfig->getArrayIndexByModes(i_n, i_m)];
}
void spectral_set(
int i_n,
int i_m,
const std::complex<double> &i_data
) const
{
#if SWEET_DEBUG
if (i_n < 0 || i_m < 0)
SWEETError("Out of boundary a");
if (i_n > sphereDataConfig->spectral_modes_n_max)
SWEETError("Out of boundary b");
if (i_m > sphereDataConfig->spectral_modes_m_max)
SWEETError("Out of boundary c");
if (i_m > i_n)
SWEETError("Out of boundary d");
assert (i_m <= sphereDataConfig->spectral_modes_m_max);
#endif
spectral_space_data[sphereDataConfig->getArrayIndexByModes(i_n, i_m)] = i_data;
}
/*
* Set all values to zero
*/
void spectral_set_zero()
{
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++)
spectral_space_data[i] = {0,0};
}
/*
* Set all values to value
*/
void spectral_set_value(
const std::complex<double> &i_value
)
{
SWEET_THREADING_SPACE_PARALLEL_FOR_SIMD
for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++)
spectral_space_data[i] = i_value;
}
/*
* Add a constant in physical space by adding the corresponding value in spectral space
*/
void spectral_add_physical_constant(
double i_value
) const
{
this->spectral_space_data[0] += i_value*std::sqrt(4.0*M_PI);
}
/**
* return the maximum of all absolute values, use quad precision for reduction
*/
std::complex<double> spectral_reduce_sum_quad_increasing() const
{
std::complex<double> sum = 0;
std::complex<double> c = 0;
#if SWEET_THREADING_SPACE
//#pragma omp parallel for PROC_BIND_CLOSE reduction(+:sum,c)
#endif
for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++)
{
std::complex<double> value = spectral_space_data[i]*(double)i;
// Use Kahan summation
std::complex<double> y = value - c;
std::complex<double> t = sum + y;
c = (t - sum) - y;
sum = t;
}
sum -= c;
return sum;
}
/**
* return the sum of all values, use quad precision for reduction
*/
std::complex<double> spectral_reduce_sum_quad() const
{
std::complex<double> sum = 0;
std::complex<double> c = 0;
#if SWEET_THREADING_SPACE
//#pragma omp parallel for PROC_BIND_CLOSE reduction(+:sum,c)
#endif
for (int i = 0; i < sphereDataConfig->spectral_array_data_number_of_elements; i++)
{
std::complex<double> value = spectral_space_data[i];
// Use Kahan summation
std::complex<double> y = value - c;
std::complex<double> t = sum + y;
c = (t - sum) - y;
sum = t;
}
sum -= c;
return sum;
}
/**
* return the sum of squares of all values, use quad precision for reduction
* Important: Since m=0 modes appear only once and m>0 appear twice in the full spectrum
*/
double spectral_reduce_sum_sqr_quad() const
{
std::complex<double> sum = 0;
//std::complex<double> c = 0;
//m=0 case - weight 1
std::size_t idx = sphereDataConfig->getArrayIndexByModes(0, 0);
for (int n = 0; n <= sphereDataConfig->spectral_modes_n_max; n++)
{
sum += spectral_space_data[idx]*std::conj(spectral_space_data[idx]);
idx++;
}
//m>0 case - weight 2, as they appear twice
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++)
{
std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++)
{
sum += 2.0*spectral_space_data[idx]*std::conj(spectral_space_data[idx]);
idx++;
}
}
return sum.real();
}
/**
* Return the minimum value
*/
std::complex<double> spectral_reduce_min() const
{
std::complex<double> error = std::numeric_limits<double>::infinity();
for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++)
{
error.real(std::min(spectral_space_data[j].real(), error.real()));
error.imag(std::min(spectral_space_data[j].imag(), error.imag()));
}
return error;
}
/**
* Return the max value
*/
std::complex<double> spectral_reduce_max() const
{
std::complex<double> error = -std::numeric_limits<double>::infinity();
for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++)
{
error.real(std::max(spectral_space_data[j].real(), error.real()));
error.imag(std::max(spectral_space_data[j].imag(), error.imag()));
}
return error;
}
/**
* Return the max abs value
*/
double spectral_reduce_max_abs() const
{
double error = -std::numeric_limits<double>::infinity();
std::complex<double> w = {0,0};
for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++)
{
w = spectral_space_data[j]*std::conj(spectral_space_data[j]);
error = std::max(std::abs(w), error);
}
return error;
}
/**
* Return the minimum abs value
*/
double spectral_reduce_min_abs() const
{
double error = std::numeric_limits<double>::infinity();
std::complex<double> w = {0,0};
for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++)
{
w = spectral_space_data[j]*std::conj(spectral_space_data[j]);
error = std::min(std::abs(w), error);
}
return error;
}
bool spectral_reduce_is_any_nan_or_inf() const
{
bool retval = false;
#if SWEET_THREADING_SPACE
#pragma omp parallel for simd reduction(|:retval)
#endif
for (int j = 0; j < sphereDataConfig->spectral_array_data_number_of_elements; j++)
{
retval |= std::isnan(spectral_space_data[j].real());
retval |= std::isinf(spectral_space_data[j].real());
retval |= std::isnan(spectral_space_data[j].imag());
retval |= std::isinf(spectral_space_data[j].imag());
}
return retval;
}
bool spectral_is_first_nan_or_inf() const
{
bool retval = false;
retval |= std::isnan(spectral_space_data[0].real());
retval |= std::isinf(spectral_space_data[0].real());
retval |= std::isnan(spectral_space_data[0].imag());
retval |= std::isinf(spectral_space_data[0].imag());
return retval;
}
void spectral_print(
int i_precision = 16,
double i_abs_threshold = -1
) const
{
std::cout << std::setprecision(i_precision);
std::cout << "m \\ n ----->" << std::endl;
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++)
{
std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++)
{
if (std::abs(spectral_space_data[idx]) < i_abs_threshold)
std::cout << 0 << "\t";
else
std::cout << spectral_space_data[idx] << "\t";
idx++;
}
std::cout << std::endl;
}
}
void spectral_structure_print(
int i_precision = 16,
double i_abs_threshold = -1
) const
{
std::cout << std::setprecision(i_precision);
std::cout << "m \\ n ----->" << std::endl;
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++)
{
//std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++)
{
std::cout << "(" << m <<"," << n <<")" << "\t";
}
std::cout << std::endl;
}
}
void spectrum_file_write(
const std::string &i_filename,
const char *i_title = "",
int i_precision = 20
) const
{
std::ofstream file(i_filename, std::ios_base::trunc);
file << std::setprecision(i_precision);
file << "#SWEET_SPHERE_SPECTRAL_DATA_ASCII" << std::endl;
file << "#TI " << i_title << std::endl;
// Use 0 to make it processable by python
file << "0\t";
std::complex<double> w = {0,0};
std::vector<double> sum(sphereDataConfig->spectral_modes_n_max+1,0);
std::vector<double> sum_squared(sphereDataConfig->spectral_modes_n_max+1,0);
std::vector<double> max(sphereDataConfig->spectral_modes_n_max+1,0);
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max; m++)
{
std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max; n++)
{
w = spectral_space_data[idx];
idx++;
sum[n] += std::abs(w);
sum_squared[n] += std::abs(w * w);
if (std::abs(w) >= max[n]) max[n] = std::abs(w);
}
}
file << sphereDataConfig->spectral_modes_m_max << " "
<< sphereDataConfig->spectral_modes_n_max << std::endl;
for (int n = 0; n <= sphereDataConfig->spectral_modes_n_max; n++)
file << n << " " << sum[n] << " " << max[n] << " " << std::sqrt(sum_squared[n]) << std::endl;
file.close();
}
void spectrum_abs_file_write_line(
const std::string &i_filename,
const char *i_title = "",
const double i_time = 0.0,
int i_precision = 20,
double i_abs_threshold = -1,
int i_reduce_mode_factor = 1
) const
{
std::ofstream file;
if(i_time == 0.0){
file.open(i_filename, std::ios_base::trunc);
file << std::setprecision(i_precision);
file << "#SWEET_SPHERE_SPECTRAL_ABS_EVOL_ASCII" << std::endl;
file << "#TI " << i_title << std::endl;
file << "0\t"<< std::endl; // Use 0 to make it processable by python
file << "(n_max="<<sphereDataConfig->spectral_modes_n_max << " m_max="
<< sphereDataConfig->spectral_modes_n_max << ")" << std::endl;
file << "timestamp\t" ;
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++)
{
//std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++)
{
file << "(" << n << ";" << m << ")\t" ;
}
}
file<< "SpectralSum" <<std::endl;
}
else{
file.open(i_filename, std::ios_base::app);
file << std::setprecision(i_precision);
}
std::complex<double> w = {0,0};
double wabs = 0.0;
double sum = 0.0;
//std::cout << "n" << " " << "m" << " " << "norm" <<std::endl;
file << i_time << "\t";
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++)
{
std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++)
{
w = spectral_space_data[idx];
wabs = std::abs(w * std::conj(w));
if ( m > 0 ) sum += 2*wabs; //term appears twice in the spectrum
else sum += wabs; // term appears only once
if ( wabs < i_abs_threshold){
//file << "(" << n << "," << m << ")\t"<<std::endl;
file << 0 << "\t"; //<<std::endl;
}
else{
//file << "(" << n << "," << m << ")\t"<<std::endl;
file << wabs << "\t"; //<<std::endl;;
//std::cout << n << " " << m << " " << wabs <<std::endl;
}
idx++;
}
}
file<< sum << std::endl;
file.close();
}
void spectrum_phase_file_write_line(
const std::string &i_filename,
const char *i_title = "",
const double i_time = 0.0,
int i_precision = 20,
double i_abs_threshold = -1,
int i_reduce_mode_factor = 1
) const
{
std::ofstream file;
if(i_time == 0.0){
file.open(i_filename, std::ios_base::trunc);
file << std::setprecision(i_precision);
file << "#SWEET_SPHERE_SPECTRAL_PHASE_EVOL_ASCII" << std::endl;
file << "#TI " << i_title << std::endl;
file << "0\t"<< std::endl; // Use 0 to make it processable by python
file << "(n_max="<<sphereDataConfig->spectral_modes_n_max << " m_max="
<< sphereDataConfig->spectral_modes_n_max << ")" << std::endl;
file << "timestamp\t" ;
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++)
{
//std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++)
{
file << "(" << n << ";" << m << ")\t" ;
}
}
file << std::endl;
}
else{
file.open(i_filename, std::ios_base::app);
file << std::setprecision(i_precision);
}
std::complex<double> w = {0,0};
double wphase = 0.0;
//std::cout << "n" << " " << "m" << " " << "norm" <<std::endl;
file << i_time << "\t";
for (int m = 0; m <= sphereDataConfig->spectral_modes_m_max/i_reduce_mode_factor; m++)
{
std::size_t idx = sphereDataConfig->getArrayIndexByModes(m, m);
for (int n = m; n <= sphereDataConfig->spectral_modes_n_max/i_reduce_mode_factor; n++)
{
w = spectral_space_data[idx];
wphase = std::arg(w); // std::abs(w * std::conj(w));
//file << "(" << n << "," << m << ")\t"<<std::endl;
file << wphase << "\t"; //<<std::endl;;
//std::cout << n << " " << m << " " << wabs <<std::endl;
idx++;
}
}
file<< std::endl;
file.close();
}
/**
* Write the spectral data to a file in binary format
*/
void file_write_binary_spectral(
const std::string &i_filename
) const
{
std::ofstream file(i_filename, std::ios_base::trunc | std::ios_base::binary);
if (!file.is_open())
SWEETError("Error while opening file");
file << "SWEET" << std::endl;
file << "DATA_TYPE SH_DATA" << std::endl;
file << "MODES_M_MAX " << sphereDataConfig->spectral_modes_m_max << std::endl;
file << "MODES_N_MAX " << sphereDataConfig->spectral_modes_n_max << std::endl;
file << "GRID_TYPE GAUSSIAN" << std::endl;
file << "NUM_ELEMENTS " << sphereDataConfig->spectral_array_data_number_of_elements << std::endl;
file << "FIN" << std::endl;
file.write((const char*)spectral_space_data, sizeof(std::complex<double>)*sphereDataConfig->spectral_array_data_number_of_elements);
file.close();
}
void file_read_binary_spectral(
const std::string &i_filename
)
{
std::ifstream file(i_filename, std::ios_base::binary);
if (!file.is_open())
SWEETError("Error while opening file");
std::string magic;
std::getline(file, magic);
if (magic != "SWEET")
SWEETError("Magic code 'SWEET' not found");
std::string data_type;
int num_lon = -1;
int num_lat = -1;
int size = -1;
while (true)
{
std::string buf;
file >> buf;
if (buf == "FIN")
break;
if (buf == "DATA_TYPE")
{
// load data type
file >> data_type;
std::cout << data_type << std::endl;
continue;
}
if (buf == "NUM_LON")
{
file >> buf;
num_lon = std::stoi(buf);
std::cout << num_lon << std::endl;
continue;
}
if (buf == "NUM_LAT")
{
file >> buf;
num_lat = std::stoi(buf);
std::cout << num_lat << std::endl;
continue;
}
if (buf == "SIZE")
{
file >> buf;
size = std::stoi(buf);
std::cout << size << std::endl;
continue;
}
SWEETError("Unknown Tag '"+buf+"'");
}
// read last newline
char nl;
file.read(&nl, 1);
std::cout << file.tellg() << std::endl;
if (data_type != "SH_DATA")
SWEETError("Unknown data type '"+data_type+"'");
if (num_lon != sphereDataConfig->spectral_modes_m_max)
SWEETError("NUM_LON "+std::to_string(num_lon)+" doesn't match SphereDataConfig");
if (num_lat != sphereDataConfig->spectral_modes_n_max)
SWEETError("NUM_LAT "+std::to_string(num_lat)+" doesn't match SphereDataConfig");
file.read((char*)spectral_space_data, sizeof(std::complex<double>)*sphereDataConfig->spectral_array_data_number_of_elements);
file.close();
}
void normalize(
const std::string &normalization = ""
)
{
if (normalization == "avg_zero")
{
// move average value to 0
double phi_min = getSphereDataPhysical().physical_reduce_min();
double phi_max = getSphereDataPhysical().physical_reduce_max();
double avg = 0.5*(phi_max+phi_min);
operator-=(avg);
}
else if (normalization == "min_zero")
{
// move minimum value to zero
double phi_min = getSphereDataPhysical().physical_reduce_min();
operator-=(phi_min);
}
else if (normalization == "max_zero")
{
// move maximum value to zero
double phi_max = getSphereDataPhysical().physical_reduce_max();
operator-=(phi_max);
}
else if (normalization == "")
{
}
else
{
SWEETError("Normalization not supported!");
}
}
};
/**
* operator to support operations such as:
*
* 1.5 * arrayData;
*
* Otherwise, we'd have to write it as arrayData*1.5
*
*/
inline
static
SphereData_Spectral operator*(
double i_value,
const SphereData_Spectral &i_array_data
)
{
return ((SphereData_Spectral&)i_array_data)*i_value;
}
/**
* operator to support operations such as:
*
* 1.5 + arrayData
*
*/
inline
static
SphereData_Spectral operator+(
double i_value,
const SphereData_Spectral &i_array_data
)
{
return ((SphereData_Spectral&)i_array_data)+i_value;
}
/**
* operator to support operations such as:
*
* 1.5 - arrayData
*
*/
inline
static
SphereData_Spectral operator-(
double i_value,
const SphereData_Spectral &i_array_data
)
{
return i_array_data.operator_scalar_sub_this(i_value);
}
#endif /* SWEET_SPHERE_DATA_HPP_ */
| 22.894562 | 144 | 0.683852 | valentinaschueller |
f3f1aca35572a63cf1ee1c3582a44a241b834d5a | 478 | cpp | C++ | Algorithm_BaekJoon/1110.cpp | dongdong97/TIL | 22fab3bc5509ac46510071cb6a7ce390fd4df75a | [
"MIT"
] | null | null | null | Algorithm_BaekJoon/1110.cpp | dongdong97/TIL | 22fab3bc5509ac46510071cb6a7ce390fd4df75a | [
"MIT"
] | null | null | null | Algorithm_BaekJoon/1110.cpp | dongdong97/TIL | 22fab3bc5509ac46510071cb6a7ce390fd4df75a | [
"MIT"
] | null | null | null | ////
//// 1110.cpp
//// Algorithm
////
//// Created by 동균 on 2018. 6. 1..
//// Copyright © 2018년 동균. All rights reserved.
////
//
//#include <iostream>
//using namespace std;
//
//int main() {
//
// int number, number2 , tmp1, tmp2, tmp3;
// int cnt =0;
//
// cin >> number;
// number2 = number;
//
// tmp1 = number2/10;
// tmp2 = number2%10;
// tmp3 = (tmp1+tmp2) % 10;
//
// number2 = tmp2 *10 + tmp3;
//
// return 0;
//
//}
| 16.482759 | 48 | 0.476987 | dongdong97 |
f3f37f3df5f380d30a4d8d0df2ef82493e3da8e8 | 1,285 | cpp | C++ | packages/nextclade/src/qc/ruleMixedSites.cpp | kibet-gilbert/nextclade | 21ac3c910ccdcbf1804f53273e6609ac20e760dc | [
"MIT"
] | 108 | 2020-09-29T14:06:08.000Z | 2022-03-19T03:07:35.000Z | packages/nextclade/src/qc/ruleMixedSites.cpp | amkram/nextclade | 3703f4013f69407c9b91172997abc2e19b902b91 | [
"MIT"
] | 500 | 2020-09-15T09:45:10.000Z | 2022-03-30T04:28:38.000Z | packages/nextclade/src/qc/ruleMixedSites.cpp | amkram/nextclade | 3703f4013f69407c9b91172997abc2e19b902b91 | [
"MIT"
] | 55 | 2020-10-13T11:40:47.000Z | 2022-02-27T04:35:12.000Z | #include "ruleMixedSites.h"
#include <frozen/set.h>
#include <nextclade/nextclade.h>
#include <algorithm>
#include <optional>
#include <vector>
#include "../utils/mapFind.h"
#include "getQcRuleStatus.h"
namespace Nextclade {
namespace {
constexpr frozen::set<Nucleotide, 6> GOOD_NUCLEOTIDES = {
Nucleotide::A,
Nucleotide::C,
Nucleotide::G,
Nucleotide::T,
Nucleotide::N,
Nucleotide::GAP,
};
}//namespace
std::optional<QCResultMixedSites> ruleMixedSites(//
const AnalysisResult& result, //
const std::vector<NucleotideSubstitution>&, //
const QCRulesConfigMixedSites& config //
) {
if (!config.enabled) {
return {};
}
int totalMixedSites = 0;
for (const auto& [nuc, total] : result.nucleotideComposition) {
if (has(GOOD_NUCLEOTIDES, nuc)) {
continue;
}
totalMixedSites += total;
}
const auto score = std::max(0.0, 100.0 * (totalMixedSites / config.mixedSitesThreshold));
const auto& status = getQcRuleStatus(score);
return QCResultMixedSites{
.score = score,
.status = status,
.totalMixedSites = totalMixedSites,
.mixedSitesThreshold = config.mixedSitesThreshold,
};
}
}// namespace Nextclade
| 24.245283 | 93 | 0.635798 | kibet-gilbert |
f3f6941492d8fd5bd7965764ff995ac2282c7fad | 12,739 | cpp | C++ | avs/vis_avs/r_videodelay.cpp | czeskij/vis_avs | 10cbc47adbc128f17505c695535d8cbec243410e | [
"Unlicense"
] | null | null | null | avs/vis_avs/r_videodelay.cpp | czeskij/vis_avs | 10cbc47adbc128f17505c695535d8cbec243410e | [
"Unlicense"
] | null | null | null | avs/vis_avs/r_videodelay.cpp | czeskij/vis_avs | 10cbc47adbc128f17505c695535d8cbec243410e | [
"Unlicense"
] | null | null | null | /*
LICENSE
-------
Copyright 2005 Nullsoft, 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 Nullsoft 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.
*/
// video delay
// copyright tom holden, 2002
// mail: cfp@myrealbox.com
#include "r_defs.h"
#include "resource.h"
#include <windows.h>
#ifndef LASER
#define MOD_NAME "Trans / Video Delay"
#define C_DELAY C_VideoDelayClass
class C_DELAY : public C_RBASE {
protected:
public:
// standard ape members
C_DELAY();
virtual ~C_DELAY();
virtual int render(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h);
virtual HWND conf(HINSTANCE hInstance, HWND hwndParent);
virtual char* get_desc();
virtual void load_config(unsigned char* data, int len);
virtual int save_config(unsigned char* data);
// saved members
bool enabled;
bool usebeats;
unsigned int delay;
// unsaved members
LPVOID buffer;
LPVOID inoutpos;
unsigned long buffersize;
unsigned long virtualbuffersize;
unsigned long oldvirtualbuffersize;
unsigned long framessincebeat;
unsigned long framedelay;
unsigned long framemem;
unsigned long oldframemem;
};
// global configuration dialog pointer
static C_DELAY* g_Delay;
// global DLL instance pointer
static HINSTANCE g_hDllInstance;
// configuration screen
static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
char value[16];
int val;
unsigned int objectcode, objectmessage;
HWND hwndEdit;
switch (uMsg) {
case WM_INITDIALOG: //init
CheckDlgButton(hwndDlg, IDC_CHECK1, g_Delay->enabled);
CheckDlgButton(hwndDlg, IDC_RADIO1, g_Delay->usebeats);
CheckDlgButton(hwndDlg, IDC_RADIO2, !g_Delay->usebeats);
hwndEdit = GetDlgItem(hwndDlg, IDC_EDIT1);
_itoa(g_Delay->delay, value, 10);
SetWindowText(hwndEdit, value);
return 1;
case WM_COMMAND:
objectcode = LOWORD(wParam);
objectmessage = HIWORD(wParam);
// see if enable checkbox is checked
if (objectcode == IDC_CHECK1) {
g_Delay->enabled = IsDlgButtonChecked(hwndDlg, IDC_CHECK1) == 1;
return 0;
}
// see if beats radiobox is checked
if (objectcode == IDC_RADIO1) {
if (IsDlgButtonChecked(hwndDlg, IDC_RADIO1) == 1) {
g_Delay->usebeats = true;
CheckDlgButton(hwndDlg, IDC_RADIO2, BST_UNCHECKED);
g_Delay->framedelay = 0;
g_Delay->framessincebeat = 0;
hwndEdit = GetDlgItem(hwndDlg, IDC_EDIT1); //new
if (g_Delay->delay > 16) { //new
g_Delay->delay = 16; //new
SetWindowText(hwndEdit, "16"); //new
} //new
} else
g_Delay->usebeats = false;
return 0;
}
// see if frames radiobox is checked
if (objectcode == IDC_RADIO2) {
if (IsDlgButtonChecked(hwndDlg, IDC_RADIO2) == 1) {
g_Delay->usebeats = false;
CheckDlgButton(hwndDlg, IDC_RADIO1, BST_UNCHECKED);
g_Delay->framedelay = g_Delay->delay;
} else
g_Delay->usebeats = true;
return 0;
}
//get and put data from the delay box
if (objectcode == IDC_EDIT1) {
hwndEdit = GetDlgItem(hwndDlg, IDC_EDIT1);
if (objectmessage == EN_CHANGE) {
GetWindowText(hwndEdit, value, 16);
val = atoi(value);
if (g_Delay->usebeats) {
if (val > 16)
val = 16;
} //new
else {
if (val > 200)
val = 200;
} //new
g_Delay->delay = val;
g_Delay->framedelay = g_Delay->usebeats ? 0 : g_Delay->delay;
} else if (objectmessage == EN_KILLFOCUS) {
_itoa(g_Delay->delay, value, 10);
SetWindowText(hwndEdit, value);
}
return 0;
}
}
return 0;
}
// set up default configuration
C_DELAY::C_DELAY()
{
// enable
enabled = true;
usebeats = false;
delay = 10;
framedelay = 10;
framessincebeat = 0;
buffersize = 1;
virtualbuffersize = 1;
oldvirtualbuffersize = 1;
buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE);
inoutpos = buffer;
}
// virtual destructor
C_DELAY::~C_DELAY()
{
VirtualFree(buffer, buffersize, MEM_DECOMMIT);
}
// RENDER FUNCTION:
// render should return 0 if it only used framebuffer, or 1 if the new output data is in fbout
// w and h are the-width and height of the screen, in pixels.
// isBeat is 1 if a beat has been detected.
// visdata is in the format of [spectrum:0,wave:1][channel][band].
int C_DELAY::render(char visdata[2][2][576], int isBeat, int* framebuffer, int* fbout, int w, int h)
{
if (isBeat & 0x80000000)
return 0;
framemem = w * h * 4;
if (usebeats) {
if (isBeat) {
framedelay = framessincebeat * delay; //changed
if (framedelay > 400)
framedelay = 400; //new
framessincebeat = 0;
}
framessincebeat++;
}
if (enabled && framedelay != 0) {
virtualbuffersize = framedelay * framemem;
if (framemem == oldframemem) {
if (virtualbuffersize != oldvirtualbuffersize) {
if (virtualbuffersize > oldvirtualbuffersize) {
if (virtualbuffersize > buffersize) {
// allocate new memory
if (!VirtualFree(buffer, buffersize, MEM_DECOMMIT))
return 0;
if (usebeats) {
buffersize = 2 * virtualbuffersize;
if (buffersize > framemem * 400)
buffersize = framemem * 400; //new
buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE);
if (buffer == NULL) {
buffersize = virtualbuffersize;
buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE);
}
} else {
buffersize = virtualbuffersize;
buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE);
}
inoutpos = buffer;
if (buffer == NULL) {
framedelay = 0;
framessincebeat = 0;
return 0;
}
} else {
unsigned long size = (((unsigned long)buffer) + oldvirtualbuffersize) - ((unsigned long)inoutpos);
unsigned long l = ((unsigned long)buffer) + virtualbuffersize;
unsigned long d = l - size;
MoveMemory((LPVOID)d, inoutpos, size);
for (l = (unsigned long)inoutpos; l < d; l += framemem)
CopyMemory((LPVOID)l, (LPVOID)d, framemem);
}
} else { // virtualbuffersize < oldvirtualbuffersize
unsigned long presegsize = ((unsigned long)inoutpos) - ((unsigned long)buffer) + framemem;
if (presegsize > virtualbuffersize) {
MoveMemory(buffer, (LPVOID)(((unsigned long)buffer) + presegsize - virtualbuffersize), virtualbuffersize);
inoutpos = (LPVOID)(((unsigned long)buffer) + virtualbuffersize - framemem);
} else if (presegsize < virtualbuffersize)
MoveMemory((LPVOID)(((unsigned long)inoutpos) + framemem), (LPVOID)(((unsigned long)buffer) + oldvirtualbuffersize + presegsize - virtualbuffersize), virtualbuffersize - presegsize);
}
oldvirtualbuffersize = virtualbuffersize;
}
} else {
// allocate new memory
if (!VirtualFree(buffer, buffersize, MEM_DECOMMIT))
return 0;
if (usebeats) {
buffersize = 2 * virtualbuffersize;
buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE);
if (buffer == NULL) {
buffersize = virtualbuffersize;
buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE);
}
} else {
buffersize = virtualbuffersize;
buffer = VirtualAlloc(NULL, buffersize, MEM_COMMIT, PAGE_READWRITE);
}
inoutpos = buffer;
if (buffer == NULL) {
framedelay = 0;
framessincebeat = 0;
return 0;
}
oldvirtualbuffersize = virtualbuffersize;
}
oldframemem = framemem;
CopyMemory(fbout, inoutpos, framemem);
CopyMemory(inoutpos, framebuffer, framemem);
inoutpos = (LPVOID)(((unsigned long)inoutpos) + framemem);
if ((unsigned long)inoutpos >= ((unsigned long)buffer) + virtualbuffersize)
inoutpos = buffer;
return 1;
} else
return 0;
}
HWND C_DELAY::conf(HINSTANCE hInstance, HWND hwndParent) // return NULL if no config dialog possible
{
g_Delay = this;
return CreateDialog(hInstance, MAKEINTRESOURCE(IDD_CFG_VIDEODELAY), hwndParent, g_DlgProc);
}
char* C_DELAY::get_desc(void)
{
return MOD_NAME;
}
// load_/save_config are called when saving and loading presets (.avs files)
#define GET_INT() (data[pos] | (data[pos + 1] << 8) | (data[pos + 2] << 16) | (data[pos + 3] << 24))
void C_DELAY::load_config(unsigned char* data, int len) // read configuration of max length "len" from data.
{
int pos = 0;
// always ensure there is data to be loaded
if (len - pos >= 4) {
// load activation toggle
enabled = (GET_INT() == 1);
pos += 4;
}
if (len - pos >= 4) {
// load beats toggle
usebeats = (GET_INT() == 1);
pos += 4;
}
if (len - pos >= 4) {
// load delay
delay = GET_INT();
if (usebeats) {
if (delay > 16)
delay = 16;
} //new
else {
if (delay > 200)
delay = 200;
} //new
pos += 4;
}
}
// write configuration to data, return length. config data should not exceed 64k.
#define PUT_INT(y) \
data[pos] = (y)&255; \
data[pos + 1] = (y >> 8) & 255; \
data[pos + 2] = (y >> 16) & 255; \
data[pos + 3] = (y >> 24) & 255
int C_DELAY::save_config(unsigned char* data)
{
int pos = 0;
PUT_INT((int)enabled);
pos += 4;
PUT_INT((int)usebeats);
pos += 4;
PUT_INT((unsigned int)delay);
pos += 4;
return pos;
}
// export stuff
C_RBASE* R_VideoDelay(char* desc) // creates a new effect object if desc is NULL, otherwise fills in desc with description
{
if (desc) {
strcpy(desc, MOD_NAME);
return NULL;
}
return (C_RBASE*)new C_DELAY();
}
#endif | 36.606322 | 206 | 0.572886 | czeskij |
f3f87b5cbc7421a4ef6d9b694a77ab668ec6aa8e | 1,858 | hpp | C++ | metrics.hpp | Steve132/librange | 5818a238dc0dc4d657dde8533cf6a7a9befe339e | [
"MIT"
] | null | null | null | metrics.hpp | Steve132/librange | 5818a238dc0dc4d657dde8533cf6a7a9befe339e | [
"MIT"
] | null | null | null | metrics.hpp | Steve132/librange | 5818a238dc0dc4d657dde8533cf6a7a9befe339e | [
"MIT"
] | null | null | null | #ifndef METRICS_HPP
#define METRICS_HPP
static const size_t MAX_NORM=~size_t(0);
template<class FloatType,size_t P>
struct Lnorm_impl
{
static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask)
{
FloatType sm=0.0;
for(size_t di=0;di<n;di++)
{
if(mask.size() == n && mask[di])
{
FloatType diff=f2[di]-f1[di];
sm+=std::pow(std::fabs(diff),P);
}
}
return std::pow(sm,1.0/static_cast<double>(P));
}
};
template<class FloatType>
struct Lnorm_impl<FloatType,MAX_NORM>
{
static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask)
{
FloatType sm=0.0;
for(size_t di=0;di<n;di++)
{
if(mask.size() == n && mask[di])
{
FloatType diff=f2[di]-f1[di];
sm=std::max(sm,std::fabs(diff));
}
}
return sm;
}
};
template<class FloatType>
struct Lnorm_impl<FloatType,1>
{
static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask)
{
FloatType sm=0.0;
for(size_t di=0;di<n;di++)
{
if(mask.size() == n && mask[di])
{
FloatType diff=f2[di]-f1[di];
sm+=std::abs(diff);
}
}
return sm;
}
};
template<class FloatType>
struct Lnorm_impl<FloatType,2>
{
static FloatType call(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask)
{
FloatType sm=0.0;
for(size_t di=0;di<n;di++)
{
if(mask.size() == n && mask[di])
{
FloatType diff=f2[di]-f1[di];
sm+=diff*diff;
}
}
return std::sqrt(sm);
}
};
//premature optimization is the root of all evil but it's possible to implement this recursively and compile-time.
template<class FloatType,size_t P>
inline FloatType Lnorm(const FloatType* f1,const FloatType* f2,size_t n,const std::vector<bool>& mask)
{
return Lnorm_impl<FloatType,P>::call(f1,f2,n,mask);
}
#endif
| 22.119048 | 114 | 0.661464 | Steve132 |
f3f97d9dda48b76df6f48b20bf558d7a52b13fd9 | 933 | cpp | C++ | client/public_key.cpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | client/public_key.cpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | 6 | 2020-02-16T21:25:21.000Z | 2020-03-11T07:42:00.000Z | client/public_key.cpp | irl-game/irl | ba507a93371ab172b705c1ede8cd062123fc96f5 | [
"MIT"
] | null | null | null | #include "public_key.hpp"
extern const RsaPublicKey PublicKey = {
0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xe0, 0x15, 0x69, 0x00, 0x55,
0x3c, 0x6a, 0x56, 0x35, 0x6d, 0x3c, 0x2a, 0x3d, 0xd6, 0xdc, 0x7a, 0xe2,
0x72, 0x3f, 0x87, 0xa3, 0x13, 0x26, 0x86, 0x75, 0x75, 0x79, 0x45, 0xbe,
0xc8, 0xb5, 0x57, 0xaa, 0x4a, 0x9a, 0xff, 0x3a, 0x30, 0xd7, 0xa2, 0x33,
0xa0, 0x64, 0x1e, 0xbf, 0x3b, 0x13, 0x2c, 0x01, 0x57, 0x90, 0xc1, 0x78,
0xf7, 0x6d, 0x6c, 0x41, 0x87, 0xe2, 0x53, 0x77, 0x77, 0x28, 0x27, 0xf4,
0x56, 0xf2, 0x85, 0x5f, 0x79, 0xa8, 0xc6, 0x84, 0x5e, 0x75, 0x45, 0x77,
0x47, 0x0c, 0x51, 0x3d, 0xab, 0xf4, 0xbe, 0xe4, 0xb1, 0x54, 0x8b, 0x88,
0x39, 0xe6, 0x3a, 0x03, 0x69, 0x71, 0x25, 0x5e, 0xcc, 0x6b, 0x38, 0xfa,
0xfc, 0x80, 0x15, 0xf9, 0x90, 0x4e, 0xe4, 0x52, 0x31, 0xe5, 0x26, 0xa2,
0xc7, 0x88, 0xc8, 0x30, 0x64, 0xdd, 0x86, 0x22, 0xbb, 0xe0, 0x79, 0xe1,
0x50, 0x66, 0x6d, 0x02, 0x03, 0x01, 0x00, 0x01
};
| 54.882353 | 73 | 0.655949 | irl-game |
f3fcec92c6daa5e81dcc7d85623348a157c8bbe2 | 5,269 | cc | C++ | ui/app_list/views/search_box_view.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-02-03T05:19:48.000Z | 2021-11-15T15:07:21.000Z | ui/app_list/views/search_box_view.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/app_list/views/search_box_view.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 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 "ui/app_list/views/search_box_view.h"
#include <algorithm>
#include "grit/ui_resources.h"
#include "ui/app_list/search_box_model.h"
#include "ui/app_list/search_box_view_delegate.h"
#include "ui/base/events/event.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/textfield/textfield.h"
namespace app_list {
namespace {
const int kPadding = 14;
const int kIconDimension = 32;
const int kPreferredWidth = 360;
const int kPreferredHeight = 48;
const int kMenuButtonDimension = 29;
const SkColor kHintTextColor = SkColorSetRGB(0xA0, 0xA0, 0xA0);
} // namespace
SearchBoxView::SearchBoxView(SearchBoxViewDelegate* delegate,
AppListViewDelegate* view_delegate)
: delegate_(delegate),
model_(NULL),
menu_(view_delegate),
icon_view_(new views::ImageView),
search_box_(new views::Textfield),
contents_view_(NULL) {
AddChildView(icon_view_);
ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
#if !defined(OS_CHROMEOS)
menu_button_ = new views::MenuButton(NULL, string16(), this, false);
menu_button_->set_border(NULL);
menu_button_->SetIcon(*rb.GetImageSkiaNamed(IDR_APP_LIST_TOOLS_NORMAL));
menu_button_->SetHoverIcon(*rb.GetImageSkiaNamed(IDR_APP_LIST_TOOLS_HOVER));
menu_button_->SetPushedIcon(*rb.GetImageSkiaNamed(
IDR_APP_LIST_TOOLS_PRESSED));
AddChildView(menu_button_);
#endif
search_box_->RemoveBorder();
search_box_->SetFont(rb.GetFont(ui::ResourceBundle::MediumFont));
search_box_->set_placeholder_text_color(kHintTextColor);
search_box_->SetController(this);
AddChildView(search_box_);
}
SearchBoxView::~SearchBoxView() {
if (model_)
model_->RemoveObserver(this);
}
void SearchBoxView::SetModel(SearchBoxModel* model) {
if (model_ == model)
return;
if (model_)
model_->RemoveObserver(this);
model_ = model;
if (model_) {
model_->AddObserver(this);
IconChanged();
HintTextChanged();
}
}
bool SearchBoxView::HasSearch() const {
return !search_box_->text().empty();
}
void SearchBoxView::ClearSearch() {
search_box_->SetText(string16());
// Updates model and fires query changed manually because SetText() above
// does not generate ContentsChanged() notification.
UpdateModel();
NotifyQueryChanged();
}
gfx::Size SearchBoxView::GetPreferredSize() {
return gfx::Size(kPreferredWidth, kPreferredHeight);
}
void SearchBoxView::Layout() {
gfx::Rect rect(GetContentsBounds());
if (rect.IsEmpty())
return;
gfx::Rect icon_frame(rect);
icon_frame.set_width(kIconDimension + 2 * kPadding);
icon_view_->SetBoundsRect(icon_frame);
gfx::Rect menu_button_frame(rect);
#if !defined(OS_CHROMEOS)
menu_button_frame.set_width(kMenuButtonDimension);
menu_button_frame.set_x(rect.right() - menu_button_frame.width() - kPadding);
menu_button_frame.ClampToCenteredSize(gfx::Size(menu_button_frame.width(),
kMenuButtonDimension));
menu_button_->SetBoundsRect(menu_button_frame);
#else
menu_button_frame.set_width(0);
#endif
gfx::Rect edit_frame(rect);
edit_frame.set_x(icon_frame.right());
edit_frame.set_width(
rect.width() - icon_frame.width() - kPadding - menu_button_frame.width());
edit_frame.ClampToCenteredSize(
gfx::Size(edit_frame.width(), search_box_->GetPreferredSize().height()));
search_box_->SetBoundsRect(edit_frame);
}
bool SearchBoxView::OnMouseWheel(const ui::MouseWheelEvent& event) {
if (contents_view_)
return contents_view_->OnMouseWheel(event);
return false;
}
void SearchBoxView::UpdateModel() {
// Temporarily remove from observer to ignore notifications caused by us.
model_->RemoveObserver(this);
model_->SetText(search_box_->text());
model_->SetSelectionModel(search_box_->GetSelectionModel());
model_->AddObserver(this);
}
void SearchBoxView::NotifyQueryChanged() {
DCHECK(delegate_);
delegate_->QueryChanged(this);
}
void SearchBoxView::ContentsChanged(views::Textfield* sender,
const string16& new_contents) {
UpdateModel();
NotifyQueryChanged();
}
bool SearchBoxView::HandleKeyEvent(views::Textfield* sender,
const ui::KeyEvent& key_event) {
bool handled = false;
if (contents_view_ && contents_view_->visible())
handled = contents_view_->OnKeyPressed(key_event);
return handled;
}
void SearchBoxView::OnMenuButtonClicked(View* source, const gfx::Point& point) {
menu_.RunMenuAt(menu_button_,
menu_button_->GetBoundsInScreen().bottom_right());
}
void SearchBoxView::IconChanged() {
icon_view_->SetImage(model_->icon());
}
void SearchBoxView::HintTextChanged() {
search_box_->set_placeholder_text(model_->hint_text());
}
void SearchBoxView::SelectionModelChanged() {
search_box_->SelectSelectionModel(model_->selection_model());
}
void SearchBoxView::TextChanged() {
search_box_->SetText(model_->text());
}
} // namespace app_list
| 28.79235 | 80 | 0.728411 | devasia1000 |
f3fd26e46f21b6ecfb8fa6ef072ce98546c474fa | 48,543 | hpp | C++ | runtime.Kokkos.NET/Analyzes/RadialBasisFunctionInterp2D.hpp | trmcnealy/Kokkos.NET | d81aa03d720c7d8a089fdb42da18b240f127758c | [
"MIT"
] | null | null | null | runtime.Kokkos.NET/Analyzes/RadialBasisFunctionInterp2D.hpp | trmcnealy/Kokkos.NET | d81aa03d720c7d8a089fdb42da18b240f127758c | [
"MIT"
] | null | null | null | runtime.Kokkos.NET/Analyzes/RadialBasisFunctionInterp2D.hpp | trmcnealy/Kokkos.NET | d81aa03d720c7d8a089fdb42da18b240f127758c | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <iostream>
using namespace std;
#include "r8lib/r8lib.hpp"
#pragma once
//void daxpy ( int n, double da, double dx[], int incx, double dy[], int incy );
//double ddot ( int n, double dx[], int incx, double dy[], int incy );
//double dnrm2 ( int n, double x[], int incx );
//void drot ( int n, double x[], int incx, double y[], int incy, double c, double s );
//void drotg ( double *sa, double *sb, double *c, double *s );
//void dscal ( int n, double sa, double x[], int incx );
int dsvdc ( double a[], int lda, int m, int n, double s[], double e[], double u[], int ldu, double v[], int ldv, double work[], int job );
//void dswap ( int n, double x[], int incx, double y[], int incy );
void phi1 ( int n, double r[], double r0, double v[] );
void phi2 ( int n, double r[], double r0, double v[] );
void phi3 ( int n, double r[], double r0, double v[] );
void phi4 ( int n, double r[], double r0, double v[] );
double *r8mat_solve_svd ( int m, int n, double a[], double b[] );
double *rbf_interp ( int m, int nd, double xd[], double r0, void (*phi) ( int n, double r[], double r0, double v[] ), double w[], int ni, double xi[] );
double *rbf_weight ( int m, int nd, double xd[], double r0, void (*phi) ( int n, double r[], double r0, double v[] ), double fd[] );
#include <mkl.h>
#define CBLAS
#ifdef CBLAS
#define BLASFunc(name) cblas_ ## name
#else
#define BLASFunc(name) name
#endif
////
//// Purpose:
////
//// DAXPY computes constant times a vector plus a vector.
////
//// Discussion:
////
//// This routine uses unrolled loops for increments equal to one.
////
//// Licensing:
////
//// This code is distributed under the GNU LGPL license.
////
//// Modified:
////
//// 02 May 2005
////
//// Author:
////
//// Original FORTRAN77 version by Charles Lawson, Richard Hanson,
//// David Kincaid, Fred Krogh.
//// C++ version by John Burkardt.
////
//// Reference:
////
//// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
//// LINPACK User's Guide,
//// SIAM, 1979,
//// ISBN13: 978-0-898711-72-1,
//// LC: QA214.L56.
////
//// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
//// Basic Linear Algebra Subprograms for Fortran Usage,
//// Algorithm 539,
//// ACM Transactions on Mathematical Software,
//// Volume 5, Number 3, September 1979, pages 308-323.
////
//// Parameters:
////
//// Input, int N, the number of elements in DX and DY.
////
//// Input, double DA, the multiplier of DX.
////
//// Input, double DX[*], the first vector.
////
//// Input, int INCX, the increment between successive entries of DX.
////
//// Input/output, double DY[*], the second vector.
//// On output, DY[*] has been replaced by DY[*] + DA * DX[*].
////
//// Input, int INCY, the increment between successive entries of DY.
////
//void daxpy(int n, double da, double dx[], int incx, double dy[], int incy)
//{
// int i;
// int ix;
// int iy;
// int m;
//
// if (n <= 0)
// {
// return;
// }
//
// if (da == 0.0)
// {
// return;
// }
// //
// // Code for unequal increments or equal increments
// // not equal to 1.
// //
// if (incx != 1 || incy != 1)
// {
// if (0 <= incx)
// {
// ix = 0;
// }
// else
// {
// ix = (-n + 1) * incx;
// }
//
// if (0 <= incy)
// {
// iy = 0;
// }
// else
// {
// iy = (-n + 1) * incy;
// }
//
// for (i = 0; i < n; ++i)
// {
// dy[iy] = dy[iy] + da * dx[ix];
// ix = ix + incx;
// iy = iy + incy;
// }
// }
// //
// // Code for both increments equal to 1.
// //
// else
// {
// m = n % 4;
//
// for (i = 0; i < m; ++i)
// {
// dy[i] = dy[i] + da * dx[i];
// }
//
// for (i = m; i < n; i = i + 4)
// {
// dy[i] = dy[i] + da * dx[i];
// dy[i + 1] = dy[i + 1] + da * dx[i + 1];
// dy[i + 2] = dy[i + 2] + da * dx[i + 2];
// dy[i + 3] = dy[i + 3] + da * dx[i + 3];
// }
// }
//
// return;
//}
//
////
//// Purpose:
////
//// DDOT forms the dot product of two vectors.
////
//// Discussion:
////
//// This routine uses unrolled loops for increments equal to one.
////
//// Licensing:
////
//// This code is distributed under the GNU LGPL license.
////
//// Modified:
////
//// 02 May 2005
////
//// Author:
////
//// Original FORTRAN77 version by Charles Lawson, Richard Hanson,
//// David Kincaid, Fred Krogh.
//// C++ version by John Burkardt.
////
//// Reference:
////
//// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
//// LINPACK User's Guide,
//// SIAM, 1979,
//// ISBN13: 978-0-898711-72-1,
//// LC: QA214.L56.
////
//// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
//// Basic Linear Algebra Subprograms for Fortran Usage,
//// Algorithm 539,
//// ACM Transactions on Mathematical Software,
//// Volume 5, Number 3, September 1979, pages 308-323.
////
//// Parameters:
////
//// Input, int N, the number of entries in the vectors.
////
//// Input, double DX[*], the first vector.
////
//// Input, int INCX, the increment between successive entries in DX.
////
//// Input, double DY[*], the second vector.
////
//// Input, int INCY, the increment between successive entries in DY.
////
//// Output, double DDOT, the sum of the product of the corresponding
//// entries of DX and DY.
////
//double ddot(int n, double dx[], int incx, double dy[], int incy)
//{
// double dtemp;
// int i;
// int ix;
// int iy;
// int m;
//
// dtemp = 0.0;
//
// if (n <= 0)
// {
// return dtemp;
// }
// //
// // Code for unequal increments or equal increments
// // not equal to 1.
// //
// if (incx != 1 || incy != 1)
// {
// if (0 <= incx)
// {
// ix = 0;
// }
// else
// {
// ix = (-n + 1) * incx;
// }
//
// if (0 <= incy)
// {
// iy = 0;
// }
// else
// {
// iy = (-n + 1) * incy;
// }
//
// for (i = 0; i < n; ++i)
// {
// dtemp = dtemp + dx[ix] * dy[iy];
// ix = ix + incx;
// iy = iy + incy;
// }
// }
// //
// // Code for both increments equal to 1.
// //
// else
// {
// m = n % 5;
//
// for (i = 0; i < m; ++i)
// {
// dtemp = dtemp + dx[i] * dy[i];
// }
//
// for (i = m; i < n; i = i + 5)
// {
// dtemp = dtemp + dx[i] * dy[i] + dx[i + 1] * dy[i + 1] +
// dx[i + 2] * dy[i + 2] + dx[i + 3] * dy[i + 3] +
// dx[i + 4] * dy[i + 4];
// }
// }
//
// return dtemp;
//}
//
////
//// Purpose:
////
//// DNRM2 returns the euclidean norm of a vector.
////
//// Discussion:
////
//// DNRM2 ( X ) = sqrt ( X' * X )
////
//// Licensing:
////
//// This code is distributed under the GNU LGPL license.
////
//// Modified:
////
//// 02 May 2005
////
//// Author:
////
//// Original FORTRAN77 version by Charles Lawson, Richard Hanson,
//// David Kincaid, Fred Krogh.
//// C++ version by John Burkardt.
////
//// Reference:
////
//// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
//// LINPACK User's Guide,
//// SIAM, 1979,
//// ISBN13: 978-0-898711-72-1,
//// LC: QA214.L56.
////
//// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
//// Basic Linear Algebra Subprograms for Fortran Usage,
//// Algorithm 539,
//// ACM Transactions on Mathematical Software,
//// Volume 5, Number 3, September 1979, pages 308-323.
////
//// Parameters:
////
//// Input, int N, the number of entries in the vector.
////
//// Input, double X[*], the vector whose norm is to be computed.
////
//// Input, int INCX, the increment between successive entries of X.
////
//// Output, double DNRM2, the Euclidean norm of X.
////
//double dnrm2(int n, double x[], int incx)
//{
// double absxi;
// int i;
// int ix;
// double norm;
// double scale;
// double ssq;
// double value;
//
// if (n < 1 || incx < 1)
// {
// norm = 0.0;
// }
// else if (n == 1)
// {
// norm = r8_abs(x[0]);
// }
// else
// {
// scale = 0.0;
// ssq = 1.0;
// ix = 0;
//
// for (i = 0; i < n; ++i)
// {
// if (x[ix] != 0.0)
// {
// absxi = r8_abs(x[ix]);
// if (scale < absxi)
// {
// ssq = 1.0 + ssq * (scale / absxi) * (scale / absxi);
// scale = absxi;
// }
// else
// {
// ssq = ssq + (absxi / scale) * (absxi / scale);
// }
// }
// ix = ix + incx;
// }
//
// norm = scale * sqrt(ssq);
// }
//
// return norm;
//}
//
////
//// Purpose:
////
//// DROT applies a plane rotation.
////
//// Licensing:
////
//// This code is distributed under the GNU LGPL license.
////
//// Modified:
////
//// 02 May 2005
////
//// Author:
////
//// Original FORTRAN77 version by Charles Lawson, Richard Hanson,
//// David Kincaid, Fred Krogh.
//// C++ version by John Burkardt.
////
//// Reference:
////
//// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
//// LINPACK User's Guide,
//// SIAM, 1979,
//// ISBN13: 978-0-898711-72-1,
//// LC: QA214.L56.
////
//// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
//// Basic Linear Algebra Subprograms for Fortran Usage,
//// Algorithm 539,
//// ACM Transactions on Mathematical Software,
//// Volume 5, Number 3, September 1979, pages 308-323.
////
//// Parameters:
////
//// Input, int N, the number of entries in the vectors.
////
//// Input/output, double X[*], one of the vectors to be rotated.
////
//// Input, int INCX, the increment between successive entries of X.
////
//// Input/output, double Y[*], one of the vectors to be rotated.
////
//// Input, int INCY, the increment between successive elements of Y.
////
//// Input, double C, S, parameters (presumably the cosine and
//// sine of some angle) that define a plane rotation.
////
//void drot(int n, double x[], int incx, double y[], int incy, double c, double s)
//{
// int i;
// int ix;
// int iy;
// double stemp;
//
// if (n <= 0)
// {
// }
// else if (incx == 1 && incy == 1)
// {
// for (i = 0; i < n; ++i)
// {
// stemp = c * x[i] + s * y[i];
// y[i] = c * y[i] - s * x[i];
// x[i] = stemp;
// }
// }
// else
// {
// if (0 <= incx)
// {
// ix = 0;
// }
// else
// {
// ix = (-n + 1) * incx;
// }
//
// if (0 <= incy)
// {
// iy = 0;
// }
// else
// {
// iy = (-n + 1) * incy;
// }
//
// for (i = 0; i < n; ++i)
// {
// stemp = c * x[ix] + s * y[iy];
// y[iy] = c * y[iy] - s * x[ix];
// x[ix] = stemp;
// ix = ix + incx;
// iy = iy + incy;
// }
// }
//
// return;
//}
//
////
//// Purpose:
////
//// DROTG constructs a Givens plane rotation.
////
//// Discussion:
////
//// Given values A and B, this routine computes
////
//// SIGMA = sign ( A ) if abs ( A ) > abs ( B )
//// = sign ( B ) if abs ( A ) <= abs ( B );
////
//// R = SIGMA * ( A * A + B * B );
////
//// C = A / R if R is not 0
//// = 1 if R is 0;
////
//// S = B / R if R is not 0,
//// 0 if R is 0.
////
//// The computed numbers then satisfy the equation
////
//// ( C S ) ( A ) = ( R )
//// ( -S C ) ( B ) = ( 0 )
////
//// The routine also computes
////
//// Z = S if abs ( A ) > abs ( B ),
//// = 1 / C if abs ( A ) <= abs ( B ) and C is not 0,
//// = 1 if C is 0.
////
//// The single value Z encodes C and S, and hence the rotation:
////
//// If Z = 1, set C = 0 and S = 1;
//// If abs ( Z ) < 1, set C = sqrt ( 1 - Z * Z ) and S = Z;
//// if abs ( Z ) > 1, set C = 1/ Z and S = sqrt ( 1 - C * C );
////
//// Licensing:
////
//// This code is distributed under the GNU LGPL license.
////
//// Modified:
////
//// 15 May 2006
////
//// Author:
////
//// Original FORTRAN77 version by Charles Lawson, Richard Hanson,
//// David Kincaid, Fred Krogh.
//// C++ version by John Burkardt.
////
//// Reference:
////
//// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
//// LINPACK User's Guide,
//// SIAM, 1979,
//// ISBN13: 978-0-898711-72-1,
//// LC: QA214.L56.
////
//// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
//// Basic Linear Algebra Subprograms for Fortran Usage,
//// Algorithm 539,
//// ACM Transactions on Mathematical Software,
//// Volume 5, Number 3, September 1979, pages 308-323.
////
//// Parameters:
////
//// Input/output, double *SA, *SB, On input, SA and SB are the values
//// A and B. On output, SA is overwritten with R, and SB is
//// overwritten with Z.
////
//// Output, double *C, *S, the cosine and sine of the Givens rotation.
////
//void drotg(double *sa, double *sb, double *c, double *s)
//{
// double r;
// double roe;
// double scale;
// double z;
//
// if (r8_abs(*sb) < r8_abs(*sa))
// {
// roe = *sa;
// }
// else
// {
// roe = *sb;
// }
//
// scale = r8_abs(*sa) + r8_abs(*sb);
//
// if (scale == 0.0)
// {
// *c = 1.0;
// *s = 0.0;
// r = 0.0;
// }
// else
// {
// r = scale *
// sqrt((*sa / scale) * (*sa / scale) + (*sb / scale) * (*sb / scale));
// r = r8_sign(roe) * r;
// *c = *sa / r;
// *s = *sb / r;
// }
//
// if (0.0 < r8_abs(*c) && r8_abs(*c) <= *s)
// {
// z = 1.0 / *c;
// }
// else
// {
// z = *s;
// }
//
// *sa = r;
// *sb = z;
//
// return;
//}
//
////
//// Purpose:
////
//// DSCAL scales a vector by a constant.
////
//// Licensing:
////
//// This code is distributed under the GNU LGPL license.
////
//// Modified:
////
//// 02 May 2005
////
//// Author:
////
//// Original FORTRAN77 version by Charles Lawson, Richard Hanson,
//// David Kincaid, Fred Krogh.
//// C++ version by John Burkardt.
////
//// Reference:
////
//// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
//// LINPACK User's Guide,
//// SIAM, 1979,
//// ISBN13: 978-0-898711-72-1,
//// LC: QA214.L56.
////
//// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
//// Basic Linear Algebra Subprograms for Fortran Usage,
//// Algorithm 539,
//// ACM Transactions on Mathematical Software,
//// Volume 5, Number 3, September 1979, pages 308-323.
////
//// Parameters:
////
//// Input, int N, the number of entries in the vector.
////
//// Input, double SA, the multiplier.
////
//// Input/output, double X[*], the vector to be scaled.
////
//// Input, int INCX, the increment between successive entries of X.
////
//void dscal(int n, double sa, double x[], int incx)
//{
// int i;
// int ix;
// int m;
//
// if (n <= 0)
// {
// }
// else if (incx == 1)
// {
// m = n % 5;
//
// for (i = 0; i < m; ++i)
// {
// x[i] = sa * x[i];
// }
//
// for (i = m; i < n; i = i + 5)
// {
// x[i] = sa * x[i];
// x[i + 1] = sa * x[i + 1];
// x[i + 2] = sa * x[i + 2];
// x[i + 3] = sa * x[i + 3];
// x[i + 4] = sa * x[i + 4];
// }
// }
// else
// {
// if (0 <= incx)
// {
// ix = 0;
// }
// else
// {
// ix = (-n + 1) * incx;
// }
//
// for (i = 0; i < n; ++i)
// {
// x[ix] = sa * x[ix];
// ix = ix + incx;
// }
// }
//
// return;
//}
//
// Purpose:
//
// DSVDC computes the singular value decomposition of a real rectangular
// matrix.
//
// Discussion:
//
// This routine reduces an M by N matrix A to diagonal form by orthogonal
// transformations U and V. The diagonal elements S(I) are the singular
// values of A. The columns of U are the corresponding left singular
// vectors, and the columns of V the right singular vectors.
//
// The form of the singular value decomposition is then
//
// A(MxN) = U(MxM) * S(MxN) * V(NxN)'
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 03 May 2007
//
// Author:
//
// Original FORTRAN77 version by Jack Dongarra, Cleve Moler, Jim Bunch,
// Pete Stewart.
// C++ version by John Burkardt.
//
// Reference:
//
// Jack Dongarra, Cleve Moler, Jim Bunch, Pete Stewart,
// LINPACK User's Guide,
// SIAM, (Society for Industrial and Applied Mathematics),
// 3600 University City Science Center,
// Philadelphia, PA, 19104-2688.
// ISBN 0-89871-172-X
//
// Parameters:
//
// Input/output, double A[LDA*N]. On input, the M by N matrix whose
// singular value decomposition is to be computed. On output, the matrix
// has been destroyed. Depending on the user's requests, the matrix may
// contain other useful information.
//
// Input, int LDA, the leading dimension of the array A.
// LDA must be at least M.
//
// Input, int M, the number of rows of the matrix.
//
// Input, int N, the number of columns of the matrix A.
//
// Output, double S[MM], where MM = min(M+1,N). The first
// min(M,N) entries of S contain the singular values of A arranged in
// descending order of magnitude.
//
// Output, double E[MM], where MM = min(M+1,N), ordinarily contains zeros.
// However see the discussion of INFO for exceptions.
//
// Output, double U[LDU*K]. If JOBA = 1 then K = M;
// if 2 <= JOBA, then K = min(M,N). U contains the M by M matrix of left
// singular vectors. U is not referenced if JOBA = 0. If M <= N or if JOBA
// = 2, then U may be identified with A in the subroutine call.
//
// Input, int LDU, the leading dimension of the array U.
// LDU must be at least M.
//
// Output, double V[LDV*N], the N by N matrix of right singular vectors.
// V is not referenced if JOB is 0. If N <= M, then V may be identified
// with A in the subroutine call.
//
// Input, int LDV, the leading dimension of the array V.
// LDV must be at least N.
//
// Workspace, double WORK[M].
//
// Input, int JOB, controls the computation of the singular
// vectors. It has the decimal expansion AB with the following meaning:
// A = 0, do not compute the left singular vectors.
// A = 1, return the M left singular vectors in U.
// A >= 2, return the first min(M,N) singular vectors in U.
// B = 0, do not compute the right singular vectors.
// B = 1, return the right singular vectors in V.
//
// Output, int *DSVDC, status indicator INFO.
// The singular values (and their corresponding singular vectors)
// S(*INFO+1), S(*INFO+2),...,S(MN) are correct. Here MN = min ( M, N ).
// Thus if *INFO is 0, all the singular values and their vectors are
// correct. In any event, the matrix B = U' * A * V is the bidiagonal
// matrix with the elements of S on its diagonal and the elements of E on
// its superdiagonal. Thus the singular values of A and B are the same.
//
int dsvdc(double a[], int lda, int m, int n, double s[], double e[], double u[],
int ldu, double v[], int ldv, double work[], int job)
{
double b;
double c;
double cs;
double el;
double emm1;
double f;
double g;
int i;
int info;
int iter;
int j;
int jobu;
int k;
int kase;
int kk;
int l;
int ll;
int lls;
int ls;
int lu;
int maxit = 30;
int mm;
int mm1;
int mn;
int mp1;
int nct;
int nctp1;
int ncu;
int nrt;
int nrtp1;
double scale;
double shift;
double sl;
double sm;
double smm1;
double sn;
double t;
double t1;
double test;
bool wantu;
bool wantv;
double ztest;
//
// Determine what is to be computed.
//
info = 0;
wantu = false;
wantv = false;
jobu = (job % 100) / 10;
if (1 < jobu)
{
ncu = i4_min(m, n);
}
else
{
ncu = m;
}
if (jobu != 0)
{
wantu = true;
}
if ((job % 10) != 0)
{
wantv = true;
}
//
// Reduce A to bidiagonal form, storing the diagonal elements
// in S and the super-diagonal elements in E.
//
nct = i4_min(m - 1, n);
nrt = i4_max(0, i4_min(m, n - 2));
lu = i4_max(nct, nrt);
for (l = 1; l <= lu; l++)
{
//
// Compute the transformation for the L-th column and
// place the L-th diagonal in S(L).
//
if (l <= nct)
{
s[l - 1] = BLASFunc(dnrm2)(m - l + 1, a + l - 1 + (l - 1) * lda, 1);
if (s[l - 1] != 0.0)
{
if (a[l - 1 + (l - 1) * lda] != 0.0)
{
s[l - 1] = r8_sign(a[l - 1 + (l - 1) * lda]) * r8_abs(s[l - 1]);
}
BLASFunc(dscal)(m - l + 1, 1.0 / s[l - 1], a + l - 1 + (l - 1) * lda, 1);
a[l - 1 + (l - 1) * lda] = 1.0 + a[l - 1 + (l - 1) * lda];
}
s[l - 1] = -s[l - 1];
}
for (j = l + 1; j <= n; ++j)
{
//
// Apply the transformation.
//
if (l <= nct && s[l - 1] != 0.0)
{
t = -BLASFunc(ddot)(m - l + 1, a + l - 1 + (l - 1) * lda, 1, a + l - 1 + (j - 1) * lda, 1) / a[l - 1 + (l - 1) * lda];
BLASFunc(daxpy)(m - l + 1, t, a + l - 1 + (l - 1) * lda, 1, a + l - 1 + (j - 1) * lda, 1);
}
//
// Place the L-th row of A into E for the
// subsequent calculation of the row transformation.
//
e[j - 1] = a[l - 1 + (j - 1) * lda];
}
//
// Place the transformation in U for subsequent back multiplication.
//
if (wantu && l <= nct)
{
for (i = l; i <= m; ++i)
{
u[i - 1 + (l - 1) * ldu] = a[i - 1 + (l - 1) * lda];
}
}
if (l <= nrt)
{
//
// Compute the L-th row transformation and place the
// L-th superdiagonal in E(L).
//
e[l - 1] = BLASFunc(dnrm2)(n - l, e + l, 1);
if (e[l - 1] != 0.0)
{
if (e[l] != 0.0)
{
e[l - 1] = r8_sign(e[l]) * r8_abs(e[l - 1]);
}
BLASFunc(dscal)(n - l, 1.0 / e[l - 1], e + l, 1);
e[l] = 1.0 + e[l];
}
e[l - 1] = -e[l - 1];
//
// Apply the transformation.
//
if (l + 1 <= m && e[l - 1] != 0.0)
{
for (j = l + 1; j <= m; ++j)
{
work[j - 1] = 0.0;
}
for (j = l + 1; j <= n; ++j)
{
BLASFunc(daxpy)(m - l, e[j - 1], a + l + (j - 1) * lda, 1, work + l, 1);
}
for (j = l + 1; j <= n; ++j)
{
BLASFunc(daxpy)(m - l, -e[j - 1] / e[l], work + l, 1, a + l + (j - 1) * lda, 1);
}
}
//
// Place the transformation in V for subsequent back multiplication.
//
if (wantv)
{
for (j = l + 1; j <= n; ++j)
{
v[j - 1 + (l - 1) * ldv] = e[j - 1];
}
}
}
}
//
// Set up the final bidiagonal matrix of order MN.
//
mn = i4_min(m + 1, n);
nctp1 = nct + 1;
nrtp1 = nrt + 1;
if (nct < n)
{
s[nctp1 - 1] = a[nctp1 - 1 + (nctp1 - 1) * lda];
}
if (m < mn)
{
s[mn - 1] = 0.0;
}
if (nrtp1 < mn)
{
e[nrtp1 - 1] = a[nrtp1 - 1 + (mn - 1) * lda];
}
e[mn - 1] = 0.0;
//
// If required, generate U.
//
if (wantu)
{
for (i = 1; i <= m; ++i)
{
for (j = nctp1; j <= ncu; ++j)
{
u[(i - 1) + (j - 1) * ldu] = 0.0;
}
}
for (j = nctp1; j <= ncu; ++j)
{
u[j - 1 + (j - 1) * ldu] = 1.0;
}
for (ll = 1; ll <= nct; ll++)
{
l = nct - ll + 1;
if (s[l - 1] != 0.0)
{
for (j = l + 1; j <= ncu; ++j)
{
t = -BLASFunc(ddot)(m - l + 1, u + (l - 1) + (l - 1) * ldu, 1, u + (l - 1) + (j - 1) * ldu, 1) / u[l - 1 + (l - 1) * ldu];
BLASFunc(daxpy)(m - l + 1, t, u + (l - 1) + (l - 1) * ldu, 1, u + (l - 1) + (j - 1) * ldu, 1);
}
BLASFunc(dscal)(m - l + 1, -1.0, u + (l - 1) + (l - 1) * ldu, 1);
u[l - 1 + (l - 1) * ldu] = 1.0 + u[l - 1 + (l - 1) * ldu];
for (i = 1; i <= l - 1; ++i)
{
u[i - 1 + (l - 1) * ldu] = 0.0;
}
}
else
{
for (i = 1; i <= m; ++i)
{
u[i - 1 + (l - 1) * ldu] = 0.0;
}
u[l - 1 + (l - 1) * ldu] = 1.0;
}
}
}
//
// If it is required, generate V.
//
if (wantv)
{
for (ll = 1; ll <= n; ll++)
{
l = n - ll + 1;
if (l <= nrt && e[l - 1] != 0.0)
{
for (j = l + 1; j <= n; ++j)
{
t = -BLASFunc(ddot)(n - l, v + l + (l - 1) * ldv, 1, v + l + (j - 1) * ldv, 1) / v[l + (l - 1) * ldv];
BLASFunc(daxpy)(n - l, t, v + l + (l - 1) * ldv, 1, v + l + (j - 1) * ldv, 1);
}
}
for (i = 1; i <= n; ++i)
{
v[i - 1 + (l - 1) * ldv] = 0.0;
}
v[l - 1 + (l - 1) * ldv] = 1.0;
}
}
//
// Main iteration loop for the singular values.
//
mm = mn;
iter = 0;
while (0 < mn)
{
//
// If too many iterations have been performed, set flag and return.
//
if (maxit <= iter)
{
info = mn;
return info;
}
//
// This section of the program inspects for
// negligible elements in the S and E arrays.
//
// On completion the variables KASE and L are set as follows:
//
// KASE = 1 if S(MN) and E(L-1) are negligible and L < MN
// KASE = 2 if S(L) is negligible and L < MN
// KASE = 3 if E(L-1) is negligible, L < MN, and
// S(L), ..., S(MN) are not negligible (QR step).
// KASE = 4 if E(MN-1) is negligible (convergence).
//
for (ll = 1; ll <= mn; ll++)
{
l = mn - ll;
if (l == 0)
{
break;
}
test = r8_abs(s[l - 1]) + r8_abs(s[l]);
ztest = test + r8_abs(e[l - 1]);
if (ztest == test)
{
e[l - 1] = 0.0;
break;
}
}
if (l == mn - 1)
{
kase = 4;
}
else
{
mp1 = mn + 1;
for (lls = l + 1; lls <= mn + 1; lls++)
{
ls = mn - lls + l + 1;
if (ls == l)
{
break;
}
test = 0.0;
if (ls != mn)
{
test = test + r8_abs(e[ls - 1]);
}
if (ls != l + 1)
{
test = test + r8_abs(e[ls - 2]);
}
ztest = test + r8_abs(s[ls - 1]);
if (ztest == test)
{
s[ls - 1] = 0.0;
break;
}
}
if (ls == l)
{
kase = 3;
}
else if (ls == mn)
{
kase = 1;
}
else
{
kase = 2;
l = ls;
}
}
l = l + 1;
//
// Deflate negligible S(MN).
//
if (kase == 1)
{
mm1 = mn - 1;
f = e[mn - 2];
e[mn - 2] = 0.0;
for (kk = 1; kk <= mm1; kk++)
{
k = mm1 - kk + l;
t1 = s[k - 1];
BLASFunc(drotg)(&t1, &f, &cs, &sn);
s[k - 1] = t1;
if (k != l)
{
f = -sn * e[k - 2];
e[k - 2] = cs * e[k - 2];
}
if (wantv)
{
BLASFunc(drot)(n, v + 0 + (k - 1) * ldv, 1, v + 0 + (mn - 1) * ldv, 1, cs, sn);
}
}
}
//
// Split at negligible S(L).
//
else if (kase == 2)
{
f = e[l - 2];
e[l - 2] = 0.0;
for (k = l; k <= mn; k++)
{
t1 = s[k - 1];
BLASFunc(drotg)(&t1, &f, &cs, &sn);
s[k - 1] = t1;
f = -sn * e[k - 1];
e[k - 1] = cs * e[k - 1];
if (wantu)
{
BLASFunc(drot)(m, u + 0 + (k - 1) * ldu, 1, u + 0 + (l - 2) * ldu, 1, cs, sn);
}
}
}
//
// Perform one QR step.
//
else if (kase == 3)
{
//
// Calculate the shift.
//
scale =
r8_max(r8_abs(s[mn - 1]),
r8_max(r8_abs(s[mn - 2]),
r8_max(r8_abs(e[mn - 2]),
r8_max(r8_abs(s[l - 1]), r8_abs(e[l - 1])))));
sm = s[mn - 1] / scale;
smm1 = s[mn - 2] / scale;
emm1 = e[mn - 2] / scale;
sl = s[l - 1] / scale;
el = e[l - 1] / scale;
b = ((smm1 + sm) * (smm1 - sm) + emm1 * emm1) / 2.0;
c = (sm * emm1) * (sm * emm1);
shift = 0.0;
if (b != 0.0 || c != 0.0)
{
shift = sqrt(b * b + c);
if (b < 0.0)
{
shift = -shift;
}
shift = c / (b + shift);
}
f = (sl + sm) * (sl - sm) - shift;
g = sl * el;
//
// Chase zeros.
//
mm1 = mn - 1;
for (k = l; k <= mm1; k++)
{
BLASFunc(drotg)(&f, &g, &cs, &sn);
if (k != l)
{
e[k - 2] = f;
}
f = cs * s[k - 1] + sn * e[k - 1];
e[k - 1] = cs * e[k - 1] - sn * s[k - 1];
g = sn * s[k];
s[k] = cs * s[k];
if (wantv)
{
BLASFunc(drot)(n, v + 0 + (k - 1) * ldv, 1, v + 0 + k * ldv, 1, cs, sn);
}
BLASFunc(drotg)(&f, &g, &cs, &sn);
s[k - 1] = f;
f = cs * e[k - 1] + sn * s[k];
s[k] = -sn * e[k - 1] + cs * s[k];
g = sn * e[k];
e[k] = cs * e[k];
if (wantu && k < m)
{
BLASFunc(drot)(m, u + 0 + (k - 1) * ldu, 1, u + 0 + k * ldu, 1, cs, sn);
}
}
e[mn - 2] = f;
iter = iter + 1;
}
//
// Convergence.
//
else if (kase == 4)
{
//
// Make the singular value nonnegative.
//
if (s[l - 1] < 0.0)
{
s[l - 1] = -s[l - 1];
if (wantv)
{
BLASFunc(dscal)(n, -1.0, v + 0 + (l - 1) * ldv, 1);
}
}
//
// Order the singular value.
//
for (;;)
{
if (l == mm)
{
break;
}
if (s[l] <= s[l - 1])
{
break;
}
t = s[l - 1];
s[l - 1] = s[l];
s[l] = t;
if (wantv && l < n)
{
BLASFunc(dswap)(n, v + 0 + (l - 1) * ldv, 1, v + 0 + l * ldv, 1);
}
if (wantu && l < m)
{
BLASFunc(dswap)(m, u + 0 + (l - 1) * ldu, 1, u + 0 + l * ldu, 1);
}
l = l + 1;
}
iter = 0;
mn = mn - 1;
}
}
return info;
}
////
//// Purpose:
////
//// DSWAP interchanges two vectors.
////
//// Licensing:
////
//// This code is distributed under the GNU LGPL license.
////
//// Modified:
////
//// 02 May 2005
////
//// Author:
////
//// Original FORTRAN77 version by Charles Lawson, Richard Hanson,
//// David Kincaid, Fred Krogh.
//// C++ version by John Burkardt.
////
//// Reference:
////
//// Jack Dongarra, Jim Bunch, Cleve Moler, Pete Stewart,
//// LINPACK User's Guide,
//// SIAM, 1979,
//// ISBN13: 978-0-898711-72-1,
//// LC: QA214.L56.
////
//// Charles Lawson, Richard Hanson, David Kincaid, Fred Krogh,
//// Basic Linear Algebra Subprograms for Fortran Usage,
//// Algorithm 539,
//// ACM Transactions on Mathematical Software,
//// Volume 5, Number 3, September 1979, pages 308-323.
////
//// Parameters:
////
//// Input, int N, the number of entries in the vectors.
////
//// Input/output, double X[*], one of the vectors to swap.
////
//// Input, int INCX, the increment between successive entries of X.
////
//// Input/output, double Y[*], one of the vectors to swap.
////
//// Input, int INCY, the increment between successive elements of Y.
////
//void dswap(int n, double x[], int incx, double y[], int incy)
//{
// int i;
// int ix;
// int iy;
// int m;
// double temp;
//
// if (n <= 0)
// {
// }
// else if (incx == 1 && incy == 1)
// {
// m = n % 3;
//
// for (i = 0; i < m; ++i)
// {
// temp = x[i];
// x[i] = y[i];
// y[i] = temp;
// }
//
// for (i = m; i < n; i = i + 3)
// {
// temp = x[i];
// x[i] = y[i];
// y[i] = temp;
//
// temp = x[i + 1];
// x[i + 1] = y[i + 1];
// y[i + 1] = temp;
//
// temp = x[i + 2];
// x[i + 2] = y[i + 2];
// y[i + 2] = temp;
// }
// }
// else
// {
// if (0 <= incx)
// {
// ix = 0;
// }
// else
// {
// ix = (-n + 1) * incx;
// }
//
// if (0 <= incy)
// {
// iy = 0;
// }
// else
// {
// iy = (-n + 1) * incy;
// }
//
// for (i = 0; i < n; ++i)
// {
// temp = x[ix];
// x[ix] = y[iy];
// y[iy] = temp;
// ix = ix + incx;
// iy = iy + incy;
// }
// }
//
// return;
//}
//
// Purpose:
//
// PHI1 evaluates the multiquadric radial basis function.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// William Press, Brian Flannery, Saul Teukolsky, William Vetterling,
// Numerical Recipes in FORTRAN: The Art of Scientific Computing,
// Third Edition,
// Cambridge University Press, 2007,
// ISBN13: 978-0-521-88068-8,
// LC: QA297.N866.
//
// Parameters:
//
// Input, int N, the number of points.
//
// Input, double R[N], the radial separation.
// 0 < R.
//
// Input, double R0, a scale factor.
//
// Output, double V[N], the value of the radial basis function.
//
void phi1(int n, double r[], double r0, double v[])
{
int i;
for (i = 0; i < n; ++i)
{
v[i] = sqrt(r[i] * r[i] + r0 * r0);
}
return;
}
//
// Purpose:
//
// PHI2 evaluates the inverse multiquadric radial basis function.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// William Press, Brian Flannery, Saul Teukolsky, William Vetterling,
// Numerical Recipes in FORTRAN: The Art of Scientific Computing,
// Third Edition,
// Cambridge University Press, 2007,
// ISBN13: 978-0-521-88068-8,
// LC: QA297.N866.
//
// Parameters:
//
// Input, int N, the number of points.
//
// Input, double R[N], the radial separation.
// 0 < R.
//
// Input, double R0, a scale factor.
//
// Output, double V[N], the value of the radial basis function.
//
void phi2(int n, double r[], double r0, double v[])
{
int i;
for (i = 0; i < n; ++i)
{
v[i] = 1.0 / sqrt(r[i] * r[i] + r0 * r0);
}
return;
}
//
// Purpose:
//
// PHI3 evaluates the thin-plate spline radial basis function.
//
// Discussion:
//
// Note that PHI3(R,R0) is negative if R < R0. Thus, for this basis
// function, it may be desirable to choose a value of R0 smaller than any
// possible R.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// William Press, Brian Flannery, Saul Teukolsky, William Vetterling,
// Numerical Recipes in FORTRAN: The Art of Scientific Computing,
// Third Edition,
// Cambridge University Press, 2007,
// ISBN13: 978-0-521-88068-8,
// LC: QA297.N866.
//
// Parameters:
//
// Input, int N, the number of points.
//
// Input, double R[N], the radial separation.
// 0 < R.
//
// Input, double R0, a scale factor.
//
// Output, double V[N], the value of the radial basis function.
//
void phi3(int n, double r[], double r0, double v[])
{
int i;
for (i = 0; i < n; ++i)
{
if (r[i] <= 0.0)
{
v[i] = 0.0;
}
else
{
v[i] = r[i] * r[i] * log(r[i] / r0);
}
}
return;
}
//
// Purpose:
//
// PHI4 evaluates the gaussian radial basis function.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// William Press, Brian Flannery, Saul Teukolsky, William Vetterling,
// Numerical Recipes in FORTRAN: The Art of Scientific Computing,
// Third Edition,
// Cambridge University Press, 2007,
// ISBN13: 978-0-521-88068-8,
// LC: QA297.N866.
//
// Parameters:
//
// Input, int N, the number of points.
//
// Input, double R[N], the radial separation.
// 0 < R.
//
// Input, double R0, a scale factor.
//
// Output, double V[N], the value of the radial basis function.
//
void phi4(int n, double r[], double r0, double v[])
{
int i;
for (i = 0; i < n; ++i)
{
v[i] = exp(-0.5 * r[i] * r[i] / r0 / r0);
}
return;
}
//
// Purpose:
//
// R8MAT_SOLVE_SVD solves a linear system A*x=b using the SVD.
//
// Discussion:
//
// When the system is determined, the solution is the solution in the
// ordinary sense, and A*x = b.
//
// When the system is overdetermined, the solution minimizes the
// L2 norm of the residual ||A*x-b||.
//
// When the system is underdetermined, ||A*x-b|| should be zero, and
// the solution is the solution of minimum L2 norm, ||x||.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2012
//
// Author:
//
// John Burkardt
//
// Parameters:
//
// Input, int M, N, the number of rows and columns
// in the matrix A.
//
// Input, double A[M,*N], the matrix.
//
// Input, double B[M], the right hand side.
//
// Output, double R8MAT_SOLVE_SVD[N], the solution.
//
double *r8mat_solve_svd(int m, int n, double a[], double b[])
{
double *a_copy;
double *a_pseudo;
double *e;
int i;
int info;
int j;
int k;
int l;
int lda;
int ldu;
int ldv;
int job;
int lwork;
double *s;
double *sp;
double *sdiag;
double *u;
double *v;
double *work;
double *x;
//
// Compute the SVD decomposition.
//
a_copy = r8mat_copy_new(m, n, a);
lda = m;
sdiag = new double[i4_max(m + 1, n)];
e = new double[i4_max(m + 1, n)];
u = new double[m * m];
ldu = m;
v = new double[n * n];
ldv = n;
work = new double[m];
job = 11;
//void dgesvd(const char* jobu, const char* jobvt, const MKL_INT* m,
// const MKL_INT* n, double* a, const MKL_INT* lda, double* s,
// double* u, const MKL_INT* ldu, double* vt, const MKL_INT* ldvt,
// double* work, const MKL_INT* lwork, MKL_INT* info);
info = dsvdc(a_copy, lda, m, n, sdiag, e, u, ldu, v, ldv, work, job);
if (info != 0)
{
cerr << std::endl;
cerr << "R8MAT_SOLVE_SVD - Fatal error!\n";
cerr << " The SVD could not be calculated.\n";
cerr << " LINPACK routine DSVDC returned a nonzero\n";
cerr << " value of the error flag, INFO = " << info << std::endl;
exit(1);
}
s = new double[m * n];
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
s[i + j * m] = 0.0;
}
}
for (i = 0; i < i4_min(m, n); ++i)
{
s[i + i * m] = sdiag[i];
}
//
// Compute the pseudo inverse.
//
sp = new double[n * m];
for (j = 0; j < m; ++j)
{
for (i = 0; i < n; ++i)
{
sp[i + j * m] = 0.0;
}
}
for (i = 0; i < i4_min(m, n); ++i)
{
if (s[i + i * m] != 0.0)
{
sp[i + i * n] = 1.0 / s[i + i * m];
}
}
a_pseudo = new double[n * m];
for (j = 0; j < m; ++j)
{
for (i = 0; i < n; ++i)
{
a_pseudo[i + j * n] = 0.0;
for (k = 0; k < n; k++)
{
for (l = 0; l < m; l++)
{
a_pseudo[i + j * n] = a_pseudo[i + j * n] + v[i + k * n] * sp[k + l * n] * u[j + l * m];
}
}
}
}
//
// Compute x = A_pseudo * b.
//
x = r8mat_mv_new(n, m, a_pseudo, b);
delete[] a_copy;
delete[] a_pseudo;
delete[] e;
delete[] s;
delete[] sdiag;
delete[] sp;
delete[] u;
delete[] v;
delete[] work;
return x;
}
//
// Purpose:
//
// RBF_INTERP_ND evaluates a radial basis function interpolant.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// William Press, Brian Flannery, Saul Teukolsky, William Vetterling,
// Numerical Recipes in FORTRAN: The Art of Scientific Computing,
// Third Edition,
// Cambridge University Press, 2007,
// ISBN13: 978-0-521-88068-8,
// LC: QA297.N866.
//
// Parameters:
//
// Input, int M, the spatial dimension.
//
// Input, int ND, the number of data points.
//
// Input, double XD[M*ND], the data points.
//
// Input, double R0, a scale factor. R0 should be larger than the typical
// separation between points, but smaller than the maximum separation.
// The value of R0 has a significant effect on the resulting interpolant.
//
// Input, void PHI ( int N, double R[], double R0, double V[] ), a
// function to evaluate the radial basis functions.
//
// Input, double W[ND], the weights, as computed by RBF_WEIGHTS.
//
// Input, int NI, the number of interpolation points.
//
// Input, double XI[M*NI], the interpolation points.
//
// Output, double RBF_INTERP_ND[NI], the interpolated values.
//
double *rbf_interp(int m, int nd, double xd[], double r0,
void(*phi)(int n, double r[], double r0, double v[]),
double w[], int ni, double xi[])
{
double *fi;
int i;
int j;
int k;
double *r;
double *v;
fi = new double[ni];
r = new double[nd];
v = new double[nd];
for (i = 0; i < ni; ++i)
{
for (j = 0; j < nd; ++j)
{
r[j] = 0.0;
for (k = 0; k < m; k++)
{
r[j] = r[j] + pow(xi[k + i * m] - xd[k + j * m], 2);
}
r[j] = sqrt(r[j]);
}
phi(nd, r, r0, v);
fi[i] = r8vec_dot_product(nd, v, w);
}
delete[] r;
delete[] v;
return fi;
}
//
// Purpose:
//
// RBF_WEIGHT computes weights for radial basis function interpolation.
//
// Discussion:
//
// We assume that there are N (nonsingular) equations in N unknowns.
//
// However, it should be clear that, if we are willing to do some kind
// of least squares calculation, we could allow for singularity,
// inconsistency, or underdetermine systems. This could be associated
// with data points that are very close or repeated, a smaller number
// of data points than function values, or some other ill-conditioning
// of the system arising from a peculiarity in the point spacing.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 30 June 2012
//
// Author:
//
// John Burkardt
//
// Reference:
//
// William Press, Brian Flannery, Saul Teukolsky, William Vetterling,
// Numerical Recipes in FORTRAN: The Art of Scientific Computing,
// Third Edition,
// Cambridge University Press, 2007,
// ISBN13: 978-0-521-88068-8,
// LC: QA297.N866.
//
// Parameters:
//
// Input, int M, the spatial dimension.
//
// Input, int ND, the number of data points.
//
// Input, double XD[M*ND], the data points.
//
// Input, double R0, a scale factor. R0 should be larger than the typical
// separation between points, but smaller than the maximum separation.
// The value of R0 has a significant effect on the resulting interpolant.
//
// Input, void PHI ( int N, double R[], double R0, double V[] ), a
// function to evaluate the radial basis functions.
//
// Input, double FD[ND], the function values at the data points.
//
// Output, double RBF_WEIGHT[ND], the weights.
//
double *rbf_weight(int m, int nd, double xd[], double r0,
void(*phi)(int n, double r[], double r0, double v[]),
double fd[])
{
double *a;
int i;
int j;
int k;
double *r;
double *v;
double *w;
a = new double[nd * nd];
r = new double[nd];
v = new double[nd];
for (i = 0; i < nd; ++i)
{
for (j = 0; j < nd; ++j)
{
r[j] = 0.0;
for (k = 0; k < m; k++)
{
r[j] = r[j] + pow(xd[k + i * m] - xd[k + j * m], 2);
}
r[j] = sqrt(r[j]);
}
phi(nd, r, r0, v);
for (j = 0; j < nd; ++j)
{
a[i + j * nd] = v[j];
}
}
//
// Solve for the weights.
//
w = r8mat_solve_svd(nd, nd, a, fd);
delete[] a;
delete[] r;
delete[] v;
return w;
}
| 24.198903 | 152 | 0.434378 | trmcnealy |
f3fdf26449b98a8d45a36da2f43552cd5a82462c | 16,748 | cpp | C++ | src/tasks/http/server/initialize_client_requests_task.cpp | proconsular/Email-Server | 4cc6974a5e086bc09a4c9e80c6e61b0302579d38 | [
"MIT"
] | null | null | null | src/tasks/http/server/initialize_client_requests_task.cpp | proconsular/Email-Server | 4cc6974a5e086bc09a4c9e80c6e61b0302579d38 | [
"MIT"
] | null | null | null | src/tasks/http/server/initialize_client_requests_task.cpp | proconsular/Email-Server | 4cc6974a5e086bc09a4c9e80c6e61b0302579d38 | [
"MIT"
] | null | null | null | //
// Created by Chris Luttio on 3/27/21.
//
#include "initialize_client_requests_task.h"
#include "load_requested_file_task.h"
#include "general/utils.h"
#include "general/route_resolver.h"
#include "authorize_user_task.h"
#include "jwt-cpp/jwt.h"
#include "general/json.hpp"
#include "objects/mail/email_parser.h"
#include "models/email_model.h"
using json = nlohmann::json;
void InitializeClientRequestsTask::perform() {
for (const auto& pair: state->requests) {
auto request = std::make_shared<ClientRequest>(*pair.second);
if (request->status == RequestStatus::New) {
switch (request->type) {
case RetrieveFile: {
state->scheduler->add(std::make_shared<LoadRequestedFileTask>(_controller, request, state->config));
request->status = RequestStatus::Working;
_controller->apply(Action(ModifyClientRequest, request));
break;
}
case ResolveRoute: {
auto headers = request->http_request->headers;
RouteResolver resolver;
resolver.resolve(state->routes, request->uri.to_string());
bool authorized = false;
if (resolver.attributes.find("Access") != resolver.attributes.end()) {
std::string role = resolver.attributes["Access"];
if (role != "public") {
if (headers.find("Authorization") != headers.end()) {
auto authorization = headers["Authorization"];
auto components = split_string(" ", *authorization);
if (components.size() == 2 && components[0] == "Bearer") {
std::string access_token = components[1];
for (const auto& account : state->accounts) {
if (account->role == role) {
for (const auto& auth : account->authorizations) {
if (auth.access_token == access_token) {
auto decoded = jwt::decode(access_token);
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::hs256{"helloworld"})
.with_issuer("auth0");
authorized = true;
try {
verifier.verify(decoded);
} catch (std::exception& e) {
authorized = false;
}
break;
}
}
if (authorized)
break;
}
}
}
}
} else {
authorized = true;
}
} else {
authorized = true;
}
if (authorized) {
request->response_headers = resolver.attributes;
request->uri = URL::parse(resolver.url);
request->type = RetrieveFile;
} else {
request->type = Forbidden;
request->status = Failed;
}
_controller->apply(Action(ModifyClientRequest, request));
break;
}
case Authorize: {
state->scheduler->add(std::make_shared<AuthorizeUserTask>(state, _controller, request));
request->status = Working;
_controller->apply(Action(ModifyClientRequest, request));
break;
}
case Refresh: {
bool authorized = false;
std::string new_token;
if (!request->data->empty()) {
json body = json::parse(*request->data);
std::string refresh_token;
if (body.find("refresh_token") != body.end())
refresh_token = body["refresh_token"];
for (const auto& account: state->accounts) {
for (auto& auth: account->authorizations) {
if (auth.refresh_token == refresh_token) {
auto decoded = jwt::decode(refresh_token);
auto verifier = jwt::verify()
.allow_algorithm(jwt::algorithm::hs256{"helloworld"})
.with_issuer("auth0");
authorized = true;
try {
verifier.verify(decoded);
} catch (std::exception& e) {
authorized = false;
}
if (authorized) {
auto now = std::chrono::system_clock::now();
auth.access_token = jwt::create()
.set_issuer("auth0")
.set_type("JWT")
.set_issued_at(now)
.set_expires_at(now + std::chrono::minutes{60})
.set_payload_claim("username", jwt::claim(std::string(account->username)))
.set_payload_claim("password", jwt::claim(std::string(account->password)))
.set_payload_claim("client_id", jwt::claim(auth.client_id))
.sign(jwt::algorithm::hs256{"helloworld"});
new_token = auth.access_token;
}
break;
}
}
if (authorized)
break;
}
}
if (authorized) {
json body({{"access_token", new_token}});
request->data = std::make_shared<std::string>(body.dump());
request->status = Complete;
} else {
request->type = Authorize;
request->status = Failed;
}
_controller->apply(Action(ModifyClientRequest, request));
break;
}
case SendMail: {
std::shared_ptr<UserAccount> user;
if (authorize(request, user)) {
json body = json::parse(*request->data);
auto message = Email::create(body["from"], body["to"], body["subject"], std::make_shared<std::string>(body["body"]));
state->mail->append_send_queue(message);
request->status = Complete;
} else {
request->type = Forbidden;
request->status = Failed;
}
_controller->apply(Action(ModifyClientRequest, request));
break;
}
case ListMail: {
std::shared_ptr<UserAccount> user;
if (authorize(request, user)) {
auto sql =
"SELECT * "
"FROM emails_with_labels "
"WHERE account_id = %0 "
"ORDER BY id DESC";
auto list_query = state->database->query(sql);
list_query.parse();
auto rows = list_query.store(user->id);
int last_id = 0;
std::vector<json> labels;
json output;
for (int i = 0; i < rows.size(); i++) {
auto row = rows[i];
int id = atoi(row["id"]);
if (!row["label_id"].is_null()) {
json label;
label["id"] = atoi(row["label_id"]);
label["name"] = row["label_name"].c_str();
labels.push_back(label);
}
if ((i + 1 < rows.size() && atoi(rows[i + 1]["id"]) != id) || i + 1 == rows.size()) {
json summary;
summary["id"] = id;
summary["message-id"] = row["name"].c_str();
summary["sender"] = row["sender"].c_str();
summary["to"] = row["to"].c_str();
summary["subject"] = row["subject"].c_str();
summary["created_at"] = row["created_at"].c_str();
summary["account_id"] = atoi(row["account_id"]);
summary["labels"] = labels;
output.push_back(summary);
labels.clear();
}
last_id = id;
}
request->data = std::make_shared<std::string>(output.dump());
request->response_headers["Content-Type"] = "application/json";
request->type = OK;
request->status = Complete;
} else {
request->type = Forbidden;
request->status = Failed;
}
_controller->apply(Action(ModifyClientRequest, request));
break;
}
case GetMail: {
std::shared_ptr<UserAccount> user;
if (authorize(request, user)) {
request->type = NotFound;
request->status = Complete;
if (request->uri.components.size() == 2) {
auto endpoint = request->uri.components[1];
std::string name;
std::map<std::string, std::string> query;
int i = 0;
while (i < endpoint.size() && endpoint[i] != '?') i++;
name = endpoint.substr(0, i);
if (i < endpoint.size() && endpoint[i] == '?') {
i++;
while (i < endpoint.size()) {
int s = i;
while (i < endpoint.size() && endpoint[i] != '=') i++;
std::string key = endpoint.substr(s, i - s);
i++;
s = i;
std::string value;
while (i < endpoint.size() && endpoint[i] != '&') {
if (endpoint[i] == '_') {
value += '/';
} else {
value += endpoint[i];
}
i++;
}
query[key] = value;
i++;
}
}
auto path = "emails/" + name + ".eml";
FILE* file = fopen(path.c_str(), "r");
if (file) {
auto data = std::make_shared<std::string>();
const size_t len = 10 * 1024;
char *buffer = new char[len];
size_t amount = 0;
do {
amount = fread(buffer, 1, len, file);
data->append(std::string(buffer, buffer + amount));
} while (amount == len);
delete[] buffer;
fclose(file);
auto output = std::make_shared<std::string>();
std::string type = "text/plain";
try {
auto email = EmailParser::parse(data);
auto content_type = email->header->get_content_type_header();
if (content_type == nullptr) {
output->append(email->generate_body());
} else {
if (content_type->type != "multipart") {
output->append(email->generate_body());
} else {
if (content_type->subtype == "alternative" && !query.empty()) {
if (query.find("accept") != query.end())
type = query["accept"];
const BodyPart* part = email->body->find_alternative(type);
if (part == nullptr)
part = email->body->find_alternative("text/plain");
if (part != nullptr && part->content) {
output->append(*part->content);
} else {
output->append(email->generate_body());
}
} else {
output->append(email->generate_body());
}
}
}
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
request->type = OK;
request->data = output;
request->response_headers["Content-Type"] = type;
}
}
} else {
request->type = Forbidden;
request->status = Failed;
}
_controller->apply(Action(ModifyClientRequest, request));
break;
}
default:
break;
}
}
}
}
bool InitializeClientRequestsTask::authorize(const std::shared_ptr<ClientRequest> &request, std::shared_ptr<UserAccount> &user) {
std::string token;
auto headers = request->http_request->headers;
if (headers.find("Authorization") != headers.end()) {
auto auth = headers["Authorization"];
if (auth->size() > 7)
token = auth->substr(7);
}
return state->authenticator->authenicate(token, user);
} | 50.294294 | 141 | 0.34428 | proconsular |
f3ff7731859ca5aea0b95a5b4604fb8ce80ecb9b | 3,591 | cpp | C++ | src/pooling.cpp | kyper999/clDNN_neuset | 85148cef898dbf1b314ef742092824c447474f2d | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | 1 | 2018-06-07T09:21:08.000Z | 2018-06-07T09:21:08.000Z | src/pooling.cpp | kyper999/clDNN_neuset | 85148cef898dbf1b314ef742092824c447474f2d | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null | src/pooling.cpp | kyper999/clDNN_neuset | 85148cef898dbf1b314ef742092824c447474f2d | [
"BSL-1.0",
"Intel",
"Apache-2.0"
] | null | null | null | /*
// Copyright (c) 2016 Intel Corporation
//
// 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 "pooling_inst.h"
#include "primitive_type_base.h"
namespace cldnn
{
primitive_type_id pooling_type_id()
{
static primitive_type_base<pooling, pooling_inst> instance;
return &instance;
}
layout pooling_inst::calc_output_layout(parent::typed_node const& node)
{
auto desc = node.get_primitive();
auto input_layout = node.input().get_output_layout();
auto input_spatial_size = node.input().get_output_layout().size.spatial.size();
if (input_spatial_size != 2)
throw std::runtime_error("Only two dimensional spatials are supported by pooling");
auto input_offsets = desc->input_offset.sizes();
auto strides = desc->stride.sizes();
auto window_sizes = desc->size.sizes();
//TODO !!!implement correct output size calculation!!!
auto output_sizes = input_layout.size.sizes();
auto spatial_offset = CLDNN_TENSOR_BATCH_DIM_MAX + CLDNN_TENSOR_FEATURE_DIM_MAX;
for (decltype(input_spatial_size) i = spatial_offset; i < input_spatial_size + spatial_offset; i++)
{
// TODO: Consider moving general parameter verification to arguments constructor.
if (strides[i] <= 0)
throw std::runtime_error("Stride must be positive (>= 1)");
if (2 * input_offsets[i] >= output_sizes[i])
throw std::runtime_error("Input offset is greater than input data range. There is no input data to process");
output_sizes[i] = static_cast<cldnn::tensor::value_type>(
2 * input_offsets[i] < output_sizes[i]
// ? std::max(output_sizes[i] - 2 * input_offsets[i] - window_sizes[i], 0) / strides[i] + 1
? ceil_div(std::max(output_sizes[i] - 2 * input_offsets[i] - window_sizes[i], 0), strides[i]) + 1
: 0);
}
return{ input_layout.data_type, input_layout.format, output_sizes };
}
std::string pooling_inst::to_string(pooling_node const& node)
{
std::stringstream primitive_description;
auto desc = node.get_primitive();
auto input = node.input();
auto strd = desc->stride;
auto kernel_size = desc->size;
auto mode = desc->mode == pooling_mode::average ? "avarage" : "max";
primitive_description << "id: " << desc->id << ", type: pooling" << ", mode: " << mode <<
"\n\tinput: " << input.id() << ", count: " << input.get_output_layout().count() << ", size: " << input.get_output_layout().size <<
"\n\tstride: " << strd.spatial[0] << "x" << strd.spatial[1] <<
"\n\tkernel size: " << kernel_size.spatial[0] << "x" << kernel_size.spatial[1] <<
"\n\toutput padding lower size: " << desc->output_padding.lower_size() <<
"\n\toutput padding upper size: " << desc->output_padding.upper_size() <<
"\n\toutput: count: " << node.get_output_layout().count() << ", size: " << node.get_output_layout().size << '\n';
return primitive_description.str();
}
}
| 42.247059 | 146 | 0.646895 | kyper999 |
6d00895d14c5f6f9a4a3f7953782bd1c93a46107 | 1,806 | cpp | C++ | 10. DP/Q_stair-case.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | 10. DP/Q_stair-case.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | 10. DP/Q_stair-case.cpp | bhavinvirani/Competitive-Programming-coding-ninjas | 5e50ae7ad3fc969a4970f91f8d895c986353bb71 | [
"MIT"
] | null | null | null | /* StairCase Problem
Send Feedback
A child is running up a staircase with n steps and can hop either 1 step, 2 steps or 3 steps at a time. Implement a method to count how many possible ways the child can run up to the stairs. You need to return all possible number of ways.
Time complexity of your code should be O(n).
Since the answer can be pretty large print the answer % mod(10^9 +7)
Input Format:
First line will contain T (number of test case).
Each test case is consists of a single line containing an integer N.
Output Format:
For each test case print the answer in new line
Constraints :
1 <= T < = 10
1 <= N <= 10^5 */
#include <bits/stdc++.h>
using namespace std;
int steps(int n)
{
if (n == 0)
return 1;
if (n == 1)
return 1;
if (n == 2)
return 2;
return steps(n - 1) + steps(n - 2) + steps(n - 3);
}
int steps_memo(int n, long memo[])
{
if (n == 0)
return 1;
if (n == 1)
return 1;
if (n == 2)
return 2;
if(memo[n] > 0){
return memo[n];
}
int output = steps_memo(n-1, memo) + steps_memo(n-2, memo) + steps_memo(n-3, memo);
memo[n] = output;
return output;
}
int steps_iter(int n){
int arr[n+1];
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
for(int i = 4; i <= n; i++){
arr[i] = arr[i-1] + arr[i-2] + arr[i-3];
}
return arr[n];
}
int main()
{
freopen("/home/spy/Desktop/input.txt", "r", stdin);
freopen("/home/spy/Desktop/output.txt", "w", stdout);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
// int ans = steps(n);
// long memo[10000000] = {0};
// int ans = steps_memo(n, memo);
int ans = steps_iter(n);
cout << ans << endl;
}
return 0;
} | 22.02439 | 238 | 0.555925 | bhavinvirani |
6d00f970a8e31c0262c67ea67b7b2442ae81fd8f | 1,269 | hpp | C++ | Systems/Physics/EllipsoidCollider.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | Systems/Physics/EllipsoidCollider.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | Systems/Physics/EllipsoidCollider.hpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Claeys, Joshua Davis
/// Copyright 2010-2017, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#pragma once
namespace Zero
{
/// Defines the collision volume for an ellipsoid (3 dimensional ellipse) defined by three radius values.
class EllipsoidCollider : public Collider
{
public:
ZilchDeclareType(TypeCopyMode::ReferenceType);
EllipsoidCollider();
// Component interface
void Serialize(Serializer& stream) override;
void DebugDraw() override;
// Collider Interface
void ComputeWorldAabbInternal() override;
void ComputeWorldBoundingSphereInternal() override;
real ComputeWorldVolumeInternal() override;
void ComputeLocalInverseInertiaTensor(real mass, Mat3Ref localInvInertia) override;
void Support(Vec3Param direction, Vec3Ptr support) const override;
/// The x, y, and z radius of the ellipsoid.
Vec3 GetRadii() const;
void SetRadii(Vec3Param radii);
/// The radii of the ellipsoid after transform is applied (scale and rotation).
Vec3 GetWorldRadii() const;
private:
Vec3 mRadii;
};
}//namespace Zero
| 28.840909 | 106 | 0.638298 | RachelWilSingh |
6d0282d543b2fffb53690d952166994781812219 | 347 | cpp | C++ | arc/arc038/b/main.cpp | wotsushi/competitive-programming | 17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86 | [
"MIT"
] | 3 | 2019-06-25T06:17:38.000Z | 2019-07-13T15:18:51.000Z | arc/arc038/b/main.cpp | wotsushi/competitive-programming | 17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86 | [
"MIT"
] | null | null | null | arc/arc038/b/main.cpp | wotsushi/competitive-programming | 17ec8fd5e1c23aee626aee70b1c0da8d7f8b8c86 | [
"MIT"
] | null | null | null | #include "template.hpp"
int main() {
ll(H, W);
vin(string, S, H);
auto dp = vecv(bool, H + 1, W + 1, true);
rrep(i, H) {
rrep(j, W) {
if (S[i][j] == '#') {
dp[i][j] = true;
} else {
dp[i][j] = not(dp[i + 1][j] and dp[i][j + 1] and dp[i + 1][j + 1]);
}
}
}
yes(dp[0][0], "First", "Second");
}
| 19.277778 | 75 | 0.397695 | wotsushi |
6d05166714660b022668d3a4249c41cc957e5644 | 6,055 | cpp | C++ | test/ProcessRegionAggregatorTest.cpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | test/ProcessRegionAggregatorTest.cpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | test/ProcessRegionAggregatorTest.cpp | avilcheslopez/geopm | 35ad0af3f17f42baa009c97ed45eca24333daf33 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2015 - 2022, Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <memory>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "ProcessRegionAggregator.hpp"
#include "record.hpp"
#include "geopm_test.hpp"
#include "MockApplicationSampler.hpp"
using geopm::ProcessRegionAggregator;
using geopm::ProcessRegionAggregatorImp;
using geopm::record_s;
using geopm::short_region_s;
using geopm::EVENT_REGION_ENTRY;
using geopm::EVENT_REGION_EXIT;
using geopm::EVENT_SHORT_REGION;
using testing::Return;
class ProcessRegionAggregatorTest : public ::testing::Test
{
protected:
void SetUp();
MockApplicationSampler m_app_sampler;
std::shared_ptr<ProcessRegionAggregator> m_account;
int m_num_process = 4;
};
void ProcessRegionAggregatorTest::SetUp()
{
EXPECT_CALL(m_app_sampler, per_cpu_process())
.WillOnce(Return(std::vector<int>({11, 12, 13, 14})));
m_account = std::make_shared<ProcessRegionAggregatorImp>(m_app_sampler);
}
TEST_F(ProcessRegionAggregatorTest, entry_exit)
{
std::vector<record_s> records;
{
// enter region
records = {
{1.0, 12, EVENT_REGION_ENTRY, 0xDADA}
};
m_app_sampler.inject_records(records);
m_account->update();
EXPECT_DOUBLE_EQ(0.0, m_account->get_runtime_average(0xDADA));
EXPECT_DOUBLE_EQ(0.0, m_account->get_count_average(0xDADA));
}
{
// exit region
records = {
{2.6, 12, EVENT_REGION_EXIT, 0xDADA}
};
m_app_sampler.inject_records(records);
m_account->update();
EXPECT_DOUBLE_EQ(0.4, m_account->get_runtime_average(0xDADA));
EXPECT_DOUBLE_EQ(0.25, m_account->get_count_average(0xDADA));
}
}
TEST_F(ProcessRegionAggregatorTest, short_region)
{
std::vector<record_s> records;
short_region_s short_region;
{
records = {
{1.0, 12, EVENT_SHORT_REGION, 0}
};
short_region = {0xDADA, 2, 1.0};
m_app_sampler.inject_records(records);
EXPECT_CALL(m_app_sampler, get_short_region(0))
.WillOnce(Return(short_region));
m_account->update();
// average across 4 processes
EXPECT_DOUBLE_EQ(0.25, m_account->get_runtime_average(0xDADA));
EXPECT_DOUBLE_EQ(0.5, m_account->get_count_average(0xDADA));
}
{
records = {
{2.0, 12, EVENT_SHORT_REGION, 0}
};
short_region = {0xDADA, 1, 0.5};
m_app_sampler.inject_records(records);
EXPECT_CALL(m_app_sampler, get_short_region(0))
.WillOnce(Return(short_region));
m_account->update();
EXPECT_DOUBLE_EQ(1.5 / m_num_process, m_account->get_runtime_average(0xDADA));
EXPECT_DOUBLE_EQ(0.75, m_account->get_count_average(0xDADA));
}
}
TEST_F(ProcessRegionAggregatorTest, multiple_processes)
{
std::vector<record_s> records;
short_region_s short_region;
{
// enter region
records = {
{1.1, 11, EVENT_REGION_ENTRY, 0xDADA},
{1.2, 12, EVENT_REGION_ENTRY, 0xDADA},
{1.3, 13, EVENT_REGION_ENTRY, 0xDADA},
{1.4, 14, EVENT_REGION_ENTRY, 0xDADA},
};
m_app_sampler.inject_records(records);
m_account->update();
EXPECT_DOUBLE_EQ(0.0, m_account->get_runtime_average(0xDADA));
EXPECT_DOUBLE_EQ(0.0, m_account->get_count_average(0xDADA));
EXPECT_DOUBLE_EQ(0.0, m_account->get_runtime_average(0xBEAD));
EXPECT_DOUBLE_EQ(0.0, m_account->get_count_average(0xBEAD));
}
{
records = {
{2.2, 11, EVENT_REGION_EXIT, 0xDADA},
{2.4, 11, EVENT_SHORT_REGION, 0},
{2.0, 12, EVENT_SHORT_REGION, 1},
{2.0, 13, EVENT_SHORT_REGION, 2},
{2.0, 14, EVENT_SHORT_REGION, 3},
{2.8, 14, EVENT_REGION_EXIT, 0xDADA},
};
m_app_sampler.inject_records(records);
short_region = {0xBEAD, 2, 0.15};
EXPECT_CALL(m_app_sampler, get_short_region(0))
.WillOnce(Return(short_region));
short_region = {0xBEAD, 2, 0.25};
EXPECT_CALL(m_app_sampler, get_short_region(1))
.WillOnce(Return(short_region));
short_region = {0xBEAD, 1, 0.35};
EXPECT_CALL(m_app_sampler, get_short_region(2))
.WillOnce(Return(short_region));
short_region = {0xBEAD, 1, 0.45};
EXPECT_CALL(m_app_sampler, get_short_region(3))
.WillOnce(Return(short_region));
m_account->update();
EXPECT_DOUBLE_EQ((1.1 + 1.4) / m_num_process, m_account->get_runtime_average(0xDADA));
EXPECT_DOUBLE_EQ(2.0 / m_num_process, m_account->get_count_average(0xDADA));
EXPECT_DOUBLE_EQ((0.15 + 0.25 + 0.35 + 0.45) / m_num_process,
m_account->get_runtime_average(0xBEAD));
EXPECT_DOUBLE_EQ( 6.0 / m_num_process, m_account->get_count_average(0xBEAD));
}
{
records = {
{3.2, 12, EVENT_REGION_EXIT, 0xDADA},
{3.3, 13, EVENT_REGION_EXIT, 0xDADA},
{2.0, 12, EVENT_SHORT_REGION, 0},
{2.0, 13, EVENT_SHORT_REGION, 1},
};
m_app_sampler.inject_records(records);
short_region = {0xBEAD, 1, 0.15};
EXPECT_CALL(m_app_sampler, get_short_region(0))
.WillOnce(Return(short_region));
short_region = {0xBEAD, 2, 0.25};
EXPECT_CALL(m_app_sampler, get_short_region(1))
.WillOnce(Return(short_region));
m_account->update();
// average of all procs
EXPECT_DOUBLE_EQ((1.1 + 2.0 + 2.0 + 1.4) / m_num_process,
m_account->get_runtime_average(0xDADA));
EXPECT_DOUBLE_EQ(1.0, m_account->get_count_average(0xDADA));
EXPECT_DOUBLE_EQ((0.15 + 0.25 + 0.35 + 0.45 + 0.15 + 0.25) / m_num_process,
m_account->get_runtime_average(0xBEAD));
EXPECT_DOUBLE_EQ((6.0 + 3.0) / m_num_process, m_account->get_count_average(0xBEAD));
}
}
| 33.638889 | 94 | 0.631049 | avilcheslopez |
6d07102768ee771dfda1082bb8778c914213efac | 1,701 | cpp | C++ | devel/game/PoweredByWindow.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | null | null | null | devel/game/PoweredByWindow.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | null | null | null | devel/game/PoweredByWindow.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | 2 | 2019-04-26T03:00:59.000Z | 2022-01-04T17:36:28.000Z |
#include "PoweredByWindow.h"
#include "screen.h"
CPoweredByWindow::CPoweredByWindow() {
mGUI = DynaGUI::getInstance();
// mText = mGUI->createWindow( BetaGUI::MAX, BetaGUI::CENTERED );
mWindow = mGUI->createWindow( DWindow::MAX, DWindow::CENTERED );
mWindow->addText( "Powered by :", 175 );
mWindow->newLine();
mLogo = mWindow->addImage( 175,50, "Logo/Ogre" );
/*
float screenwidth = CScreen::getInstance()->getRenderWindow()->getWidth();
float screenheight = CScreen::getInstance()->getRenderWindow()->getHeight();
float width = 175;
float height = 50;
float x = screenwidth - width - 20;
float y = (screenheight - height) / 2 + 32;
*/
mLogoNames.push_back("Logo/Ogre");
mLogoNames.push_back("Logo/OgreOde");
mLogoNames.push_back("Logo/ODE");
mLogoNames.push_back("Logo/OpenAL");
mLogoNames.push_back("Logo/SQlite");
mCurrentLogo = mLogoNames.begin();
//mLogo=mGUI->createImage(Ogre::Vector4(x,y,width, height), (*mCurrentLogo) );
mLogo->setMaterial( (*mCurrentLogo) );
mFadeOutDone = false;
mDelay = new CDelay( 2000 );
}
void CPoweredByWindow::run() {
if( mDelay->isOver() ) {
if( mFadeOutDone ) {
mCurrentLogo++;
if( mCurrentLogo == mLogoNames.end() )
mCurrentLogo = mLogoNames.begin() ;
mLogo->setMaterial( (*mCurrentLogo) );
mFadeOutDone = false;
mDelay->restart();
}
else {
// mLogo->setTransparency( ... );
mFadeOutDone = true;
}
}
}
CPoweredByWindow::~CPoweredByWindow() {
mGUI->destroyWindow( mWindow );
delete( mDelay );
}
| 21.2625 | 82 | 0.600823 | madeso |
6d0718a12956ee63c198b06128b2d6bb453f6a3e | 5,968 | cpp | C++ | src/bgwin.cpp | zeralight/hikvision-liveview | ce9ac88821c27689112c5c03a1096c1d42f0b793 | [
"Apache-2.0"
] | 1 | 2021-05-24T03:55:10.000Z | 2021-05-24T03:55:10.000Z | src/bgwin.cpp | zeralight/hikvision-liveview | ce9ac88821c27689112c5c03a1096c1d42f0b793 | [
"Apache-2.0"
] | null | null | null | src/bgwin.cpp | zeralight/hikvision-liveview | ce9ac88821c27689112c5c03a1096c1d42f0b793 | [
"Apache-2.0"
] | 1 | 2021-10-05T11:30:33.000Z | 2021-10-05T11:30:33.000Z | #include "winheaders.h"
#include <cmath>
#include <functional>
#include <future>
#include <iostream>
#include <queue>
#include <thread>
#include <utility>
#include "HCNetSDK.h"
#include "bgwin.h"
#include "cursors.h"
#include "main.h"
#include "synchronized_ostream.h"
#include "util.h"
#include "soap.h"
namespace app {
auto zoom_func = [](BGWindow* w, float zdelta) -> bool { return w->updateZPos(zdelta); };
auto pt_func = [](BGWindow* w, float p, float t) -> bool {
soap::soap_thread.queue(
new soap::SoapStartContinuousMoveAction(soap::soap_thread, soap::do_nothing_runner, p, t));
return true;
};
auto zoom_accumulate = [](const std::queue<std::tuple<float>>& q) -> std::tuple<float> {
float z_total = 0;
auto queue_copy = q;
while (!queue_copy.empty()) {
int elem = std::get<0>(queue_copy.front());
queue_copy.pop();
z_total += elem;
}
return std::make_tuple(z_total);
};
auto pt_accumulate = [](const std::queue<std::tuple<float, float>>& q) -> std::tuple<float, float> {
return q.back();
};
BGWindow::BGWindow()
: m_dwnd(nullptr),
m_onDraw(false),
update_z_thread_(std::bind(zoom_func, this, std::placeholders::_1), zoom_accumulate),
update_pt_thread_(std::bind(pt_func, this, std::placeholders::_1, std::placeholders::_2),
pt_accumulate) {}
BGWindow::~BGWindow() {}
const MainWindow* BGWindow::DrawingWindow() const { return this->m_dwnd; }
MainWindow*& BGWindow::DrawingWindow() { return this->m_dwnd; }
void BGWindow::setOnDraw(bool onDraw) {
std::unique_lock<std::mutex> lock(this->m_lock);
this->m_onDraw = onDraw;
}
bool BGWindow::onDraw() {
std::unique_lock<std::mutex> lock(this->m_lock);
return this->m_onDraw;
}
LRESULT BGWindow::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_CREATE: {
update_z_thread_.run();
update_pt_thread_.run();
return 0;
}
case WM_DESTROY: {
PostQuitMessage(0);
return 0;
}
case WM_PAINT: {
PAINTSTRUCT ps;
if (BeginPaint(this->Window(), &ps)) EndPaint(this->Window(), &ps);
return 0;
}
case WM_WINDOWPOSCHANGING: {
auto& pos = *reinterpret_cast<WINDOWPOS*>(lParam);
if (DrawingWindow()) pos.hwndInsertAfter = m_dwnd->Window();
return DefWindowProc(this->Window(), uMsg, wParam, lParam);
}
case WM_WINDOWPOSCHANGED: {
RECT r;
::GetClientRect(this->Window(), &r);
config.streamResolution = {r.right - r.left, r.bottom - r.top};
if (this->DrawingWindow()) {
POINT p = {0, 0};
::ClientToScreen(m_hwnd, &p);
::SetWindowPos(m_dwnd->Window(), 0, p.x, p.y, r.right - r.left, r.bottom - r.top,
SWP_NOZORDER | SWP_SHOWWINDOW | SWP_DRAWFRAME);
}
return 0;
}
case WM_LBUTTONDOWN: {
setOnDraw(true);
::SetCapture(this->Window());
if (onDraw() && this->DrawingWindow()) {
start_pt_move_thread_wrapper();
}
return 0;
}
case WM_MOUSEMOVE: {
if (onDraw()) start_pt_move_thread_wrapper();
return 0;
}
case WM_LBUTTONUP: {
if (onDraw() && this->DrawingWindow())
::InvalidateRgn(this->DrawingWindow()->Window(), nullptr, true);
soap::soap_thread.queue(
new soap::SoapStopContinuousMoveAction(soap::soap_thread, *this));
setOnDraw(false);
::ReleaseCapture();
return 0;
}
case WM_MOUSEWHEEL: {
auto zDelta = GET_WHEEL_DELTA_WPARAM(wParam);
update_z_thread_.queue(zDelta);
return 0;
}
}
return DefWindowProc(this->Window(), uMsg, wParam, lParam);
}
bool BGWindow::updateZPos(int zDelta) {
if (zDelta == 0) return true;
clog.log("BGWindow::updatezpos: zDelta = ", zDelta);
float d = (zDelta * config.z_sensitivity) / (20.f * WHEEL_DELTA);
clog.log("BGWindow::updateZPos: initial dz = ", d);
d = std::max(-1.f, std::min(1.f, d));
clog.log("BGWindow::updateZPos: final dz = ", d);
update_z_thread_.block_process();
const auto action = new soap::SoapRelativeMoveAction(soap::soap_thread, *this, 0.f, 0.f, d);
soap::soap_thread.queue(action);
return true;
}
bool BGWindow::start_pt_move_thread_wrapper() {
clog.log("start_pt_move_thread_wrapper: Invoked");
RECT rect;
::GetClientRect(this->Window(), &rect);
POINT p;
::GetCursorPos(&p);
::ScreenToClient(m_hwnd, &p);
if (p.x < rect.left || p.x >= rect.right || p.y < rect.top || p.y >= rect.bottom) return false;
clog.log("start_pt_move_thread_wrapper: position changed.");
const auto lx = rect.right - rect.left;
const auto ly = rect.bottom - rect.top;
const auto dx = 2 * ((p.x - lx / 2) * 1. / lx);
const auto dy = 2 * -((p.y - ly / 2) * 1. / ly);
clog.log("Queueing [dp=", dx, ", dt=", dy, "]");
soap::soap_thread.queue(
new soap::SoapStartContinuousMoveAction(soap::soap_thread, *this, dx, dy));
return true;
}
void BGWindow::soap_absolute_move_is_done(soap::SoapAbsoluteMove* action) {
globalwin_->refresh_bars();
clog.log("BGWindow::soap_absolute_move_is_done");
}
void BGWindow::soap_relative_move_is_done(soap::SoapRelativeMoveAction* action) {
clog.log("BGWindow::soap_relative_move_is_done");
update_z_thread_.unblock_process();
}
void BGWindow::start_continuous_move_is_done(soap::SoapStartContinuousMoveAction* action) {
clog.log("BGWindow::start_continuous_move_is_done: start");
clog.log("BGWindow::start_continuous_move_is_done: done");
}
void BGWindow::stop_continuous_move_is_done(soap::SoapStopContinuousMoveAction* action) {
clog.log("BGWindow::stop_continuous_move_is_done: start");
globalwin_->refresh_bars();
clog.log("BGWindow::stop_continuous_move_is_done: done");
}
} // namespace app | 28.830918 | 101 | 0.632875 | zeralight |
6d07c9ca38de896b5121e64fe609f68894bcb4d4 | 2,352 | cpp | C++ | Source/Render.cpp | cschladetsch/VulkanDemo | ea3ebd86f47c2d8f37b9eb790253e0a55284e943 | [
"MIT"
] | null | null | null | Source/Render.cpp | cschladetsch/VulkanDemo | ea3ebd86f47c2d8f37b9eb790253e0a55284e943 | [
"MIT"
] | null | null | null | Source/Render.cpp | cschladetsch/VulkanDemo | ea3ebd86f47c2d8f37b9eb790253e0a55284e943 | [
"MIT"
] | null | null | null | #include "vtb/Render.hpp"
#include "vtb/Device.hpp"
#include "vtb/SwapChain.hpp"
#include "vtb/Semaphore.hpp"
VTB_BEGIN
void Render::Create(
const Device& device,
const SwapChain& swapChain,
const std::vector<VkCommandBuffer>& buffers)
{
device_ = &device;
swapChain_ = &swapChain;
commandBuffers_ = &buffers;
imageReadySemaphor_.Create(device.Get());
renderFinishedSemaphore_.Create(device.Get());
}
void Render::Destroy()
{
imageReadySemaphor_.Destroy();
renderFinishedSemaphore_.Destroy();
}
void Render::Draw() const
{
// wait for last frame
VTB_CALL(vkQueueWaitIdle(device_->PresentQueue()));
// get next frame
uint32_t imageIndex = swapChain_->Next(imageReadySemaphor_.Get());
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = { imageReadySemaphor_.Get()};
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers_->at(imageIndex);
VkSemaphore signalSemaphores[] = { renderFinishedSemaphore_.Get() };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
// The last parameter references an optional fence that will be signaled when the command buffers finish execution.
// We're using semaphores for synchronization, so we'll just pass a VK_NULL_HANDLE.
VTB_CALL(vkQueueSubmit(device_->GraphicsQueue(), 1, &submitInfo, VK_NULL_HANDLE));
// Submit the result back to the swap chain to have it eventually show up on the screen.
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
// specify the swap chains to present images to and the index of the image for each swap chain.
VkSwapchainKHR swapChains[] = { swapChain_->Get() };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
VTB_CALL(vkQueuePresentKHR(device_->PresentQueue(), &presentInfo));
}
VTB_END
| 34.588235 | 119 | 0.738946 | cschladetsch |
6d09abf8e4aa4b5966027c71f956344eb12a758d | 4,778 | cpp | C++ | allegro-5.0/examples/ex_audio_props.cpp | fsande/PFC-2012-2013-EMIR-PedroHernandez | 2387a8e97ee399ae453f3f9e43e2dd1cb4c0cd4c | [
"MIT"
] | null | null | null | allegro-5.0/examples/ex_audio_props.cpp | fsande/PFC-2012-2013-EMIR-PedroHernandez | 2387a8e97ee399ae453f3f9e43e2dd1cb4c0cd4c | [
"MIT"
] | null | null | null | allegro-5.0/examples/ex_audio_props.cpp | fsande/PFC-2012-2013-EMIR-PedroHernandez | 2387a8e97ee399ae453f3f9e43e2dd1cb4c0cd4c | [
"MIT"
] | null | null | null | /*
* Example program for the Allegro library, by Peter Wang.
*
* Test audio properties (gain and panning, for now).
*/
#include "allegro5/allegro.h"
#include "allegro5/allegro_image.h"
#include "allegro5/allegro_font.h"
#include "allegro5/allegro_primitives.h"
#include "allegro5/allegro_audio.h"
#include "allegro5/allegro_acodec.h"
#include "nihgui.hpp"
#include <cstdio>
#include "common.c"
ALLEGRO_FONT *font_gui;
ALLEGRO_SAMPLE *sample;
ALLEGRO_SAMPLE_INSTANCE *sample_inst;
class Prog {
private:
Dialog d;
ToggleButton pan_button;
HSlider pan_slider;
Label speed_label;
HSlider speed_slider;
ToggleButton bidir_button;
Label gain_label;
VSlider gain_slider;
Label mixer_gain_label;
VSlider mixer_gain_slider;
Label two_label;
Label one_label;
Label zero_label;
public:
Prog(const Theme & theme, ALLEGRO_DISPLAY *display);
void run();
void update_properties();
};
Prog::Prog(const Theme & theme, ALLEGRO_DISPLAY *display) :
d(Dialog(theme, display, 40, 20)),
pan_button(ToggleButton("Pan")),
pan_slider(HSlider(1000, 2000)),
speed_label(Label("Speed")),
speed_slider(HSlider(1000, 5000)),
bidir_button(ToggleButton("Bidir")),
gain_label(Label("Gain")),
gain_slider(VSlider(1000, 2000)),
mixer_gain_label(Label("Mixer gain")),
mixer_gain_slider(VSlider(1000, 2000)),
two_label(Label("2.0")),
one_label(Label("1.0")),
zero_label(Label("0.0"))
{
pan_button.set_pushed(true);
d.add(pan_button, 2, 10, 4, 1);
d.add(pan_slider, 6, 10, 22, 1);
d.add(speed_label, 2, 12, 4, 1);
d.add(speed_slider, 6, 12, 22, 1);
d.add(bidir_button, 2, 14, 4, 1);
d.add(gain_label, 29, 1, 2, 1);
d.add(gain_slider, 29, 2, 2, 17);
d.add(mixer_gain_label, 33, 1, 6, 1);
d.add(mixer_gain_slider, 35, 2, 2, 17);
d.add(two_label, 32, 2, 2, 1);
d.add(one_label, 32, 10, 2, 1);
d.add(zero_label, 32, 18, 2, 1);
}
void Prog::run()
{
d.prepare();
while (!d.is_quit_requested()) {
if (d.is_draw_requested()) {
update_properties();
al_clear_to_color(al_map_rgb(128, 128, 128));
d.draw();
al_flip_display();
}
d.run_step(true);
}
}
void Prog::update_properties()
{
float pan;
float speed;
float gain;
float mixer_gain;
if (pan_button.get_pushed())
pan = pan_slider.get_cur_value() / 1000.0f - 1.0f;
else
pan = ALLEGRO_AUDIO_PAN_NONE;
al_set_sample_instance_pan(sample_inst, pan);
speed = speed_slider.get_cur_value() / 1000.0f;
al_set_sample_instance_speed(sample_inst, speed);
if (bidir_button.get_pushed())
al_set_sample_instance_playmode(sample_inst, ALLEGRO_PLAYMODE_BIDIR);
else
al_set_sample_instance_playmode(sample_inst, ALLEGRO_PLAYMODE_LOOP);
gain = gain_slider.get_cur_value() / 1000.0f;
al_set_sample_instance_gain(sample_inst, gain);
mixer_gain = mixer_gain_slider.get_cur_value() / 1000.0f;
al_set_mixer_gain(al_get_default_mixer(), mixer_gain);
}
int main(int argc, char **argv)
{
ALLEGRO_DISPLAY *display;
const char *filename;
if (argc >= 2) {
filename = argv[1];
}
else {
filename = "data/testing.ogg";
}
if (!al_init()) {
abort_example("Could not init Allegro\n");
return 1;
}
al_install_keyboard();
al_install_mouse();
al_init_image_addon();
al_init_font_addon();
al_init_primitives_addon();
al_init_acodec_addon();
if (!al_install_audio()) {
abort_example("Could not init sound!\n");
return 1;
}
if (!al_reserve_samples(1)) {
abort_example("Could not set up voice and mixer.\n");
return 1;
}
sample = al_load_sample(filename);
if (!sample) {
abort_example("Could not load sample from '%s'!\n", filename);
}
al_set_new_display_flags(ALLEGRO_GENERATE_EXPOSE_EVENTS);
display = al_create_display(640, 480);
if (!display) {
abort_example("Unable to create display\n");
return 1;
}
font_gui = al_load_font("data/fixed_font.tga", 0, 0);
if (!font_gui) {
abort_example("Failed to load data/fixed_font.tga\n");
return 1;
}
/* Loop the sample. */
sample_inst = al_create_sample_instance(sample);
al_set_sample_instance_playmode(sample_inst, ALLEGRO_PLAYMODE_LOOP);
al_attach_sample_instance_to_mixer(sample_inst, al_get_default_mixer());
al_play_sample_instance(sample_inst);
/* Don't remove these braces. */
{
Theme theme(font_gui);
Prog prog(theme, display);
prog.run();
}
al_destroy_sample_instance(sample_inst);
al_destroy_sample(sample);
al_uninstall_audio();
al_destroy_font(font_gui);
return 0;
(void)argc;
(void)argv;
}
/* vim: set sts=3 sw=3 et: */
| 23.653465 | 75 | 0.66869 | fsande |
6d09f3888fd57c69b14fae18c602bf3b1c68a260 | 2,698 | hh | C++ | src/windows/kernel/nt/types/registry/HIVE_IMPL.hh | srpape/IntroVirt | fe553221c40b8ef71f06e79c9d54d9e123a06c89 | [
"Apache-2.0"
] | null | null | null | src/windows/kernel/nt/types/registry/HIVE_IMPL.hh | srpape/IntroVirt | fe553221c40b8ef71f06e79c9d54d9e123a06c89 | [
"Apache-2.0"
] | null | null | null | src/windows/kernel/nt/types/registry/HIVE_IMPL.hh | srpape/IntroVirt | fe553221c40b8ef71f06e79c9d54d9e123a06c89 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 Assured Information Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "HBASE_BLOCK_IMPL.hh"
#include "windows/kernel/nt/structs/structs.hh"
#include <introvirt/core/memory/guest_ptr.hh>
#include <introvirt/fwd.hh>
#include <introvirt/windows/kernel/nt/types/registry/CM_KEY_NODE.hh>
#include <introvirt/windows/kernel/nt/types/registry/HIVE.hh>
#include <memory>
#include <optional>
namespace introvirt {
namespace windows {
namespace nt {
template <typename PtrType>
class NtKernelImpl;
template <typename PtrType>
class CM_KEY_NODE_IMPL;
template <typename PtrType>
class HIVE_IMPL final : public HIVE {
public:
const std::string& FileFullPath() const override;
const std::string& FileUserName() const override;
const std::string& HiveRootPath() const override;
const HBASE_BLOCK& BaseBlock() const override;
const CM_KEY_NODE* RootKeyNode() const override;
const CM_KEY_NODE* KeyNode(uint32_t KeyIndex) const override;
GuestVirtualAddress CellAddress(uint32_t KeyIndex) const override;
const HIVE* PreviousHive() const override;
const HIVE* NextHive() const override;
uint32_t HiveFlags() const override;
GuestVirtualAddress address() const override;
HIVE_IMPL(const NtKernelImpl<PtrType>& kernel, const GuestVirtualAddress& gva);
~HIVE_IMPL() override;
private:
GuestVirtualAddress getBlockAddress(GuestVirtualAddress pEntry) const;
const NtKernelImpl<PtrType>& kernel_;
const GuestVirtualAddress gva_;
const structs::CMHIVE* cmhive_;
const structs::DUAL* dual_;
const structs::HMAP_ENTRY* hmap_entry_;
guest_ptr<char[]> cmhive_buffer_;
mutable std::unordered_map<uint32_t, std::unique_ptr<CM_KEY_NODE_IMPL<PtrType>>>
KeyIndexNodeMap_;
mutable std::optional<HBASE_BLOCK_IMPL<PtrType>> BaseBlock_;
mutable std::string FileFullPath_;
mutable std::string FileUserName_;
mutable std::string HiveRootPath_;
mutable std::unique_ptr<HIVE_IMPL<PtrType>> PreviousHive_;
mutable std::unique_ptr<HIVE_IMPL<PtrType>> NextHive_;
};
} // namespace nt
} // namespace windows
} // namespace introvirt | 32.506024 | 84 | 0.752039 | srpape |
6d0e9d9ba5800bc7279128bb9514268c45937e64 | 70 | cpp | C++ | Source/RenderSettings.cpp | historyme/MineCraft-One-Week-Challenge | 7053beef10f841f52879e025026d08e4c26c4b62 | [
"Apache-2.0"
] | 1 | 2020-04-21T18:47:09.000Z | 2020-04-21T18:47:09.000Z | Source/RenderSettings.cpp | UglySwedishFish/MineCraft-One-Week-Challenge | 2d8859a977224c1f3d184ab8f2d50f17e43ce6ba | [
"Apache-2.0"
] | null | null | null | Source/RenderSettings.cpp | UglySwedishFish/MineCraft-One-Week-Challenge | 2d8859a977224c1f3d184ab8f2d50f17e43ce6ba | [
"Apache-2.0"
] | 1 | 2018-09-14T09:01:50.000Z | 2018-09-14T09:01:50.000Z | #include "RenderSettings.h"
RenderSettings g_renderSettings = {0, 0}; | 23.333333 | 41 | 0.771429 | historyme |
6d0f175c01af31d5bfb0c5bea4d8f9ce695de2c7 | 7,129 | cpp | C++ | chocChipChess/search.cpp | GenericCinnamon/chocchipchess | 793ea775b6b96df1157c9e712a420add7d21f89b | [
"MIT"
] | null | null | null | chocChipChess/search.cpp | GenericCinnamon/chocchipchess | 793ea775b6b96df1157c9e712a420add7d21f89b | [
"MIT"
] | null | null | null | chocChipChess/search.cpp | GenericCinnamon/chocchipchess | 793ea775b6b96df1157c9e712a420add7d21f89b | [
"MIT"
] | null | null | null | #include "search.h"
#include <math.h>
Search::Search()
{
}
//function negamax(node, depth, α, β, color)
int Search::negamax(Position& position, int depth, int alpha, int beta)
{
if (stopThinking)
throw exit_search();
// From https://en.wikipedia.org/wiki/Negamax
//alphaOrig : = α
int alpha_original = alpha;
// Transposition Table Lookup; node is the lookup key for ttEntry
//ttEntry : = TranspositionTableLookup(node)
auto tt_entry = tt->retrieve(zobristHash);
//if ttEntry is valid and ttEntry.depth ≥ depth
if (tt_entry != NULL && tt_entry->depth >= depth)
{
// Add depth punishment if there's a checkmate coming up
int retrieved_eval = tt_entry->eval;
//if ttEntry.Flag = EXACT
if (tt_entry->flag == TranspositionTable::EntryType::EXACT)
//return ttEntry.Value
return retrieved_eval;
//else if ttEntry.Flag = LOWERBOUND
else if (tt_entry->flag == TranspositionTable::EntryType::LOWER)
//α : = max(α, ttEntry.Value)
alpha = max(alpha, retrieved_eval);
//else if ttEntry.Flag = UPPERBOUND
else if (tt_entry->flag == TranspositionTable::EntryType::UPPER)
//β : = min(β, ttEntry.Value)
beta = min(beta, retrieved_eval);
//if α ≥ β
if (alpha >= beta)
//return ttEntry.Value
return tt_entry->eval;
}
//if depth = 0 or node is a terminal node
if (depth == 0)
//return color * the heuristic value of node
return sideSign(sideToMove) * calculateStaticEval();
//bestValue : = -∞
int best_value = -CHECKMATE_VALUE;
//childNodes : = GenerateMoves(node)
auto move_list = genMoves();
// If this is a terminal node return the checkmate or stalemate score
if (move_list.size() == 0) {
int ending_value = checkCheck(sideToMove) ? -CHECKMATE_VALUE : 0;
tt->insert(zobristHash, ending_value, depth, TranspositionTable::EntryType::EXACT);
return ending_value;
}
//childNodes : = OrderMoves(childNodes)
sort(move_list.begin(), move_list.end(), Move::greater);
//foreach child in childNodes
for (auto move : move_list)
{
performMove(&move);
//v : = -negamax(child, depth - 1, -β, -α, -color)
int value = -negamax(depth - 1, -beta, -alpha);
undoMove(&move);
//bestValue : = max(bestValue, v)
best_value = max(best_value, value);
//α : = max(α, v)
alpha = max(alpha, value);
//if α ≥ β
if (alpha >= beta)
//break
break;
}
// Transposition Table Store; node is the lookup key for ttEntry
TranspositionTable::EntryType entry_type;
//ttEntry.Value : = bestValue
//if bestValue ≤ alphaOrig
if (best_value <= alpha_original)
//ttEntry.Flag : = UPPERBOUND
entry_type = TranspositionTable::EntryType::UPPER;
//else if bestValue ≥ β
else if (best_value >= beta)
//ttEntry.Flag : = LOWERBOUND
entry_type = TranspositionTable::EntryType::LOWER;
//else
else
//ttEntry.Flag : = EXACT
entry_type = TranspositionTable::EntryType::EXACT;
//endif
//ttEntry.depth : = depth
//TranspositionTableStore(node, ttEntry)
tt->insert(zobristHash, best_value, depth, entry_type);
//return bestValue
return best_value;
}
int Search::terminateSearch(int alpha, int beta)
{
if (stopThinking)
throw exit_search();
vector<Move> move_list = genMoves();
move_list.erase(remove_if(move_list.begin(), move_list.end(), Move::isNotCapture), move_list.end());
if (move_list.size() == 0)
return calculateStaticEval();
int best_value = sideToMove == WHITE ? INT_MIN : INT_MAX;
sort(move_list.begin(), move_list.end(), sideToMove == WHITE ? Move::greater : Move::lesser);
for (auto& move : move_list) {
int eval;
performMove(&move);
auto tt_entry = tt->retrieve(zobristHash);
if (tt_entry == NULL) {
eval = terminateSearch(alpha, beta);
tt->insert(zobristHash, eval, 1, TranspositionTable::EntryType::EXACT);
}
else
eval = tt_entry->eval;
undoMove(&move);
best_value = sideToMove == WHITE ? max(best_value, eval) : min(best_value, eval);
sideToMove == WHITE ? alpha = max(alpha, eval) : beta = min(beta, eval);
if (beta <= alpha)
break;
}
return best_value;
}
/*
ponder - analyse the position without care for depth of the search
*/
void Search::ponderPosition(Position& position)
{
ponderPosition(position, 0);
}
/*
ponder - analyse the position without care for depth of the search
*/
void Search::ponderPosition(Position& position, int depth)
{
if (stopThinking)
return;
try {
string send = "info score cp ";
int score = sideSign(sideToMove) * negamax(depth, INT_MIN, INT_MAX);
send += to_string(score) + " depth " + to_string(depth) + " pv";
auto pvs = new vector<Move>();
getPV(pvs, depth);
for (auto it : *pvs)
send += " " + it.getName();
output->output(send);
}
catch (exit_search e) {}
vector<Move> move_list = genMoves();
if (move_list.size() == 0)
return;
sort(move_list.begin(), move_list.end(), Move::greater);
auto best_move = move_list.at(0);
if (abs(best_move.eval) > CHECKMATE_THRESHOLD)
output->debug("Found a checkmate in " + to_string(best_move.depth) + " starting with " + best_move.getName());
int padding = 10;
string debugStringMoveName = "Move |";
string debugStringEval = "Eval |";
string debugStringDepth = "Depth |";
for (auto move : move_list) {
string move_name = move.getName();
string move_eval = to_string(move.eval);
string move_depth = to_string(move.depth);
debugStringMoveName += " " + string(10 - move_name.length(), ' ') + move.getName() + " |";
debugStringEval += " " + string(10 - move_eval.length(), ' ') + to_string(move.eval) + " |";
debugStringDepth += " " + string(10 - move_depth.length(), ' ') + to_string(move.depth) + " |";
}
output->debug("Debug: move list\n" + debugStringMoveName + "\n" + debugStringEval + "\n" + debugStringDepth + "\n");
output->debug("Debug: bestmove " + best_move.getName());
ponder(depth + 1);
}
/*
getPV - return what the engine considers the best line for the given depth
*/
void Search::getPV(vector<Move>* move_list, int depth)
{
Move* pv = topMove();
if (pv == NULL)
return;
move_list->push_back(Move(*pv));
performMove(pv);
if (depth > 0)
getPV(move_list, depth - 1);
undoMove(pv);
}
/*
topMove - Return the current top move
*/
Move* Search::topMove()
{
// Evaluate each move
vector<Move> move_list = genMoves();
sort(move_list.begin(), move_list.end(), Move::greater);
if (move_list.size() == 0)
return NULL;
return new Move(move_list[0]);
} | 29.217213 | 120 | 0.605695 | GenericCinnamon |
6d108cff1f392ac70a03f7d89aa3b8edb99e29eb | 1,188 | cpp | C++ | framework/statusobject.cpp | kephale/Physics-Abstraction-Layer | 3d5ef62213143bb9ddc410edef348c94bda70cab | [
"BSD-3-Clause"
] | 6 | 2018-02-27T12:32:05.000Z | 2020-12-21T09:43:38.000Z | framework/statusobject.cpp | 5l1v3r1/Physics-Abstraction-Layer | 3d5ef62213143bb9ddc410edef348c94bda70cab | [
"BSD-3-Clause"
] | null | null | null | framework/statusobject.cpp | 5l1v3r1/Physics-Abstraction-Layer | 3d5ef62213143bb9ddc410edef348c94bda70cab | [
"BSD-3-Clause"
] | 4 | 2015-07-25T16:55:16.000Z | 2020-07-15T05:46:30.000Z | #include "statusobject.h"
//(c) Adrian Boeing 2004, see liscence.txt (BSD liscence)
/*
Abstract:
Status object for message/error passing, without exceptions
Author:
Adrian Boeing
Revision History:
Version 1.1 : 04/08/03
TODO:
-Allow integration of status tracker, or similar, to enable multiple path error recovery.
*/
#ifndef NULL
#define NULL 0
#endif
StatusObject::StatusObject() : m_pParent(0), m_StatusCode(SOK) {
}
StatusObject::StatusObject(const StatusObject& so) : m_pParent(so.m_pParent), m_StatusCode(so.m_StatusCode) {
}
StatusObject::~StatusObject() {}
void StatusObject::SetStatus(StatusCode Statuscode) {
if (m_StatusCode & TEST_ERROR)
return; //dont overwrite existing errors
m_StatusCode = Statuscode;
if (m_pParent!=NULL) {
if (!(m_pParent->m_StatusCode & TEST_ERROR) ) {
m_pParent->SetStatus(Statuscode);
//dont overwrite existing errors
}
}
}
void StatusObject::ClearStatus(StatusCode Statuscode) {
m_StatusCode = Statuscode;
if (m_pParent!=NULL)
m_pParent->ClearStatus(Statuscode);
}
void StatusObject::SetParent(StatusObject *pParent) {
m_pParent=pParent;
}
StatusObject *StatusObject::GetParent() {
return m_pParent;
}
| 23.294118 | 109 | 0.743266 | kephale |
6d11c34c4c0f95e44b6fd6706510363a865d813d | 4,839 | cpp | C++ | src/aimp_dotnet/SDK/MusicLibrary/DataFilter/AimpDataFilterGroup.cpp | Smartoteka/aimp_dotnet | 544502b8d080c9280ba11917ef0cc3e8dec44234 | [
"Apache-2.0"
] | 52 | 2015-04-14T14:39:30.000Z | 2022-02-07T07:16:05.000Z | src/aimp_dotnet/SDK/MusicLibrary/DataFilter/AimpDataFilterGroup.cpp | Smartoteka/aimp_dotnet | 544502b8d080c9280ba11917ef0cc3e8dec44234 | [
"Apache-2.0"
] | 11 | 2015-04-02T10:45:55.000Z | 2022-02-03T07:21:53.000Z | src/aimp_dotnet/SDK/MusicLibrary/DataFilter/AimpDataFilterGroup.cpp | Smartoteka/aimp_dotnet | 544502b8d080c9280ba11917ef0cc3e8dec44234 | [
"Apache-2.0"
] | 9 | 2015-04-05T18:25:57.000Z | 2022-02-07T07:20:23.000Z | // ----------------------------------------------------
// AIMP DotNet SDK
// Copyright (c) 2014 - 2020 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
// Mail: mail4evgeniy@gmail.com
// ----------------------------------------------------
#include "Stdafx.h"
#include "AimpDataFilterGroup.h"
#include "AimpDataFieldFilter.h"
#include "AimpDataFieldFilterByArray.h"
using namespace AIMP::SDK;
// TODO: #18
AimpDataFilterGroup::AimpDataFilterGroup(IAIMPMLDataFilterGroup* filterGroup) : AimpObject(filterGroup, false) {
}
FilterGroupOperationType AimpDataFilterGroup::Operation::get() {
return FilterGroupOperationType(PropertyListExtension::GetInt32(InternalAimpObject, AIMPML_FILTERGROUP_OPERATION));
}
void AimpDataFilterGroup::Operation::set(FilterGroupOperationType val) {
PropertyListExtension::SetInt32(InternalAimpObject, AIMPML_FILTERGROUP_OPERATION, static_cast<int>(val));
}
AimpActionResult<IAimpDataFieldFilter^>^ AimpDataFilterGroup::Add(
String^ field,
Object^ value1,
Object^ value2,
FieldFilterOperationType operation) {
IAimpDataFieldFilter^ filter = nullptr;
IAIMPMLDataFieldFilter* nativeFilter = nullptr;
ActionResultType result = ActionResultType::Fail;
VARIANT val1 = AimpConverter::ToNativeVariant(value1);
VARIANT val2 = AimpConverter::ToNativeVariant(value2);
VARIANT v1;
VariantInit(&v1);
auto sField = AimpConverter::ToAimpString(field);
try {
result = CheckResult(InternalAimpObject->Add(
sField,
&val1,
&val2,
static_cast<int>(operation),
&nativeFilter));
if (result == ActionResultType::OK && nativeFilter != nullptr) {
filter = gcnew AimpDataFieldFilter(nativeFilter);
}
}
finally {
if (sField != nullptr) {
sField->Release();
sField = nullptr;
}
}
return gcnew AimpActionResult<IAimpDataFieldFilter^>(result, filter);
}
AimpActionResult<IAimpDataFieldFilterByArray^>^ AimpDataFilterGroup::Add(
String^ field,
array<Object^>^ values,
int count) {
IAIMPMLDataFieldFilterByArray* nativeObj = nullptr;
auto cnt = values->Length;
VARIANT* variants = new VARIANT[cnt];
IAimpDataFieldFilterByArray^ filter = nullptr;
for (int i = 0; i < values->Length; i++) {
variants[i] = AimpConverter::ToNativeVariant(values[i]);
}
const auto result = CheckResult(InternalAimpObject->Add2(
AimpConverter::ToAimpString(field),
&variants[0],
count,
&nativeObj));
if (result == ActionResultType::OK && nativeObj != nullptr) {
filter = gcnew AimpDataFieldFilterByArray(nativeObj);
}
return gcnew AimpActionResult<IAimpDataFieldFilterByArray^>(result, filter);
}
AimpActionResult<IAimpDataFilterGroup^>^ AimpDataFilterGroup::AddGroup() {
IAIMPMLDataFilterGroup* nativeGroup = nullptr;
const ActionResultType result = CheckResult(InternalAimpObject->AddGroup(&nativeGroup));
IAimpDataFilterGroup^ group = nullptr;
if (result == ActionResultType::OK && nativeGroup != nullptr) {
group = gcnew AimpDataFilterGroup(nativeGroup);
}
return gcnew AimpActionResult<IAimpDataFilterGroup^>(result, group);
}
ActionResult AimpDataFilterGroup::Clear() {
return ACTION_RESULT(CheckResult(InternalAimpObject->Clear()));
}
ActionResult AimpDataFilterGroup::Delete(int index) {
return ACTION_RESULT(CheckResult(InternalAimpObject->Delete(index)));
}
int AimpDataFilterGroup::GetChildCount() {
return InternalAimpObject->GetChildCount();
}
AimpActionResult<IAimpDataFilterGroup^>^ AimpDataFilterGroup::GetFilterGroup(int index) {
IAimpDataFilterGroup^ group = nullptr;
IAIMPMLDataFilterGroup* child = nullptr;
const auto result = CheckResult(
InternalAimpObject->GetChild(index, IID_IAIMPMLDataFilterGroup, reinterpret_cast<void**>(&child)));
if (result == ActionResultType::OK && child != nullptr) {
group = gcnew AimpDataFilterGroup(child);
}
return gcnew AimpActionResult<IAimpDataFilterGroup^>(result, group);
}
AimpActionResult<IAimpDataFieldFilter^>^ AimpDataFilterGroup::GetFieldFilter(int index) {
IAimpDataFieldFilter^ fieldFilter = nullptr;
IAIMPMLDataFieldFilter* child = nullptr;
const auto result = CheckResult(
InternalAimpObject->GetChild(index, IID_IAIMPMLDataFieldFilter, reinterpret_cast<void**>(&child)));
if (result == ActionResultType::OK && child != nullptr) {
fieldFilter = gcnew AimpDataFieldFilter(child);
}
return gcnew AimpActionResult<IAimpDataFieldFilter^>(result, fieldFilter);
}
void AimpDataFilterGroup::BeginUpdate() {
InternalAimpObject->BeginUpdate();
}
void AimpDataFilterGroup::EndUpdate() {
InternalAimpObject->EndUpdate();
}
| 32.695946 | 119 | 0.701178 | Smartoteka |
6d1337af03e61ddd1c955499c7c72044c3eb2584 | 13,491 | cpp | C++ | src/pal/tests/palsuite/file_io/MoveFileA/test1/MoveFileA.cpp | mans0954/debian-dotnet-coreclr | 5e42f510f19534800c8271bf83a9bf5e0c730b84 | [
"MIT"
] | 6 | 2017-09-22T06:55:45.000Z | 2021-07-02T07:07:08.000Z | src/pal/tests/palsuite/file_io/MoveFileA/test1/MoveFileA.cpp | mthalman/coreclr | 102bea2e12753af9b723cf5370108b7eea3d74cb | [
"MIT"
] | 2 | 2017-09-23T08:21:05.000Z | 2017-09-27T03:31:06.000Z | src/pal/tests/palsuite/file_io/MoveFileA/test1/MoveFileA.cpp | mthalman/coreclr | 102bea2e12753af9b723cf5370108b7eea3d74cb | [
"MIT"
] | 2 | 2017-06-04T15:47:12.000Z | 2020-03-16T07:01:47.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=====================================================================
**
** Source: MoveFileA.c
**
** Purpose: Tests the PAL implementation of the MoveFileA function.
**
**
**===================================================================*/
#include <palsuite.h>
LPSTR lpSource[4] = {"src_existing.txt",
"src_non-existant.txt",
"src_dir_existing",
"src_dir_non-existant"};
LPSTR lpDestination[4] = {"dst_existing.txt",
"dst_non-existant.txt",
"dst_dir_existing",
"dst_dir_non-existant"};
/* Create all the required test files */
int createExisting(void)
{
FILE* tempFile = NULL;
DWORD dwError;
BOOL bRc = FALSE;
char szBuffer[100];
/* create the src_existing file */
tempFile = fopen(lpSource[0], "w");
if (tempFile != NULL)
{
fprintf(tempFile, "MoveFileA test file: src_existing.txt\n");
fclose(tempFile);
}
else
{
Trace("ERROR: couldn't create %s\n", lpSource[0]);
return FAIL;
}
/* create the src_dir_existing directory and files */
bRc = CreateDirectoryA(lpSource[2], NULL);
if (bRc != TRUE)
{
Trace("MoveFileA: ERROR: couldn't create \"%s\" because of "
"error code %ld\n",
lpSource[2],
GetLastError());
return FAIL;
}
memset(szBuffer, 0, 100);
sprintf_s(szBuffer, _countof(szBuffer), "%s/test01.txt", lpSource[2]);
tempFile = fopen(szBuffer, "w");
if (tempFile != NULL)
{
fprintf(tempFile, "MoveFileA test file: %s\n", szBuffer);
fclose(tempFile);
}
else
{
Trace("ERROR[%ld]:MoveFileA couldn't create %s\n", GetLastError(), szBuffer);
return FAIL;
}
memset(szBuffer, 0, 100);
sprintf_s(szBuffer, _countof(szBuffer), "%s/test02.txt", lpSource[2]);
tempFile = fopen(szBuffer, "w");
if (tempFile != NULL)
{
fprintf(tempFile, "MoveFileA test file: %s\n", szBuffer);
fclose(tempFile);
}
else
{
Trace("ERROR[%ld]: couldn't create %s\n", GetLastError(), szBuffer);
return FAIL;
}
/* create the dst_existing file */
tempFile = fopen(lpDestination[0], "w");
if (tempFile != NULL)
{
fprintf(tempFile, "MoveFileA test file: dst_existing.txt\n");
fclose(tempFile);
}
else
{
Trace("ERROR[%ld]:MoveFileA couldn't create \"%s\"\n", GetLastError(), lpDestination[0]);
return FAIL;
}
/* create the dst_dir_existing directory and files */
bRc = CreateDirectoryA(lpDestination[2], NULL);
if (bRc != TRUE)
{
dwError = GetLastError();
Trace("Error[%ld]:MoveFileA: couldn't create \"%s\"\n", GetLastError(), lpDestination[2]);
return FAIL;
}
tempFile = fopen("dst_dir_existing/test01.txt", "w");
if (tempFile != NULL)
{
fprintf(tempFile, "MoveFileA test file: dst_dir_existing/test01.txt\n");
fclose(tempFile);
}
else
{
Trace("ERROR: couldn't create dst_dir_existing/test01.txt\n");
return FAIL;
}
tempFile = fopen("dst_dir_existing/test02.txt", "w");
if (tempFile != NULL)
{
fprintf(tempFile, "MoveFileA test file: dst_dir_existing/test02.txt\n");
fclose(tempFile);
}
else
{
Trace("ERROR[%ul]: couldn't create dst_dir_existing/test02.txt\n", GetLastError());
return FAIL;
}
return PASS;
}
void removeDirectoryHelper(LPSTR dir, int location)
{
DWORD dwAtt = GetFileAttributesA(dir);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
if(!RemoveDirectoryA(dir))
{
Fail("ERROR: Failed to remove Directory [%s], Error Code [%d], location [%d]\n", dir, GetLastError(), location);
}
}
}
void removeFileHelper(LPSTR pfile, int location)
{
FILE *fp;
fp = fopen( pfile, "r");
if (fp != NULL)
{
if(fclose(fp))
{
Fail("ERROR: Failed to close the file [%s], Error Code [%d], location [%d]\n", pfile, GetLastError(), location);
}
if(!DeleteFileA(pfile))
{
Fail("ERROR: Failed to delete file [%s], Error Code [%d], location [%d]\n", pfile, GetLastError(), location);
}
else
{
// Trace("Success: deleted file [%S], Error Code [%d], location [%d]\n", wfile, GetLastError(), location);
}
}
}
/* remove all created files in preparation for the next test */
void removeAll(void)
{
char szTemp[40];
DWORD dwAtt;
/* get rid of source dirs and files */
removeFileHelper(lpSource[0], 1);
removeFileHelper(lpSource[1], 2);
dwAtt = GetFileAttributesA(lpSource[2]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[2]);
removeFileHelper(szTemp, 18);
sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[2]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpSource[2], 103);
}
else
{
removeFileHelper(lpSource[2], 17);
}
dwAtt = GetFileAttributesA(lpSource[3]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpSource[3]);
removeFileHelper(szTemp, 18);
sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpSource[3]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpSource[3], 103);
}
else
{
removeFileHelper(lpSource[3], 17);
}
/* get rid of destination dirs and files */
dwAtt = GetFileAttributesA(lpDestination[0]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[0]);
removeFileHelper(szTemp, 18);
sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[0]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[0], 103);
}
else
{
removeFileHelper(lpDestination[0], 17);
}
dwAtt = GetFileAttributesA(lpDestination[1]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[1]);
removeFileHelper(szTemp, 18);
sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[1]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[1], 103);
}
else
{
removeFileHelper(lpDestination[1], 17);
}
dwAtt = GetFileAttributesA(lpDestination[2]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[2]);
removeFileHelper(szTemp, 18);
sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[2]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[2], 103);
}
else
{
removeFileHelper(lpDestination[2], 17);
}
dwAtt = GetFileAttributesA(lpDestination[3]);
if (( dwAtt != INVALID_FILE_ATTRIBUTES ) && ( dwAtt & FILE_ATTRIBUTE_DIRECTORY) )
{
sprintf_s(szTemp, _countof(szTemp), "%s/test01.txt", lpDestination[3]);
removeFileHelper(szTemp, 18);
sprintf_s(szTemp, _countof(szTemp), "%s/test02.txt", lpDestination[3]);
removeFileHelper(szTemp, 19);
removeDirectoryHelper(lpDestination[3], 103);
}
else
{
removeFileHelper(lpDestination[3], 17);
}
}
int __cdecl main(int argc, char *argv[])
{
BOOL bRc = TRUE;
BOOL bSuccess = TRUE;
char results[40];
FILE* resultsFile = NULL;
int nCounter = 0;
int i, j;
char tempSource[] = {'t','e','m','p','k','.','t','m','p','\0'};
char tempDest[] = {'t','e','m','p','2','.','t','m','p','\0'};
HANDLE hFile;
DWORD result;
if (0 != PAL_Initialize(argc,argv))
{
return FAIL;
}
/* read in the expected results to compare with actual results */
memset (results, 0, 20);
resultsFile = fopen("expectedresults.txt", "r");
if (resultsFile == NULL)
{
Fail("MoveFileA ERROR[%ul]: Unable to open \"expectedresults.txt\"\n", GetLastError());
}
fgets(results, 20, resultsFile);
fclose(resultsFile);
/* clean the slate */
removeAll();
if (createExisting() != 0)
{
removeAll();
}
/* lpSource loop */
for (i = 0; i < 4; i++)
{
/* lpDestination loop */
for (j = 0; j < 4; j++)
{
bRc = MoveFileA(lpSource[i], lpDestination[j]);
if (!(
((bRc == TRUE) && (results[nCounter] == '1'))
||
((bRc == FALSE ) && (results[nCounter] == '0')) )
)
{
Trace("MoveFileA: FAILED: test[%d][%d]: \"%s\" -> \"%s\"\n",
i, j, lpSource[i], lpDestination[j]);
bSuccess = FALSE;
}
/* undo the last move */
removeAll();
createExisting();
nCounter++;
}
}
removeAll();
if (bSuccess == FALSE)
{
Fail("MoveFileA: Test Failed");
}
/* create the temp source file */
hFile = CreateFileA(tempSource, GENERIC_WRITE, 0, 0, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, 0);
if( hFile == INVALID_HANDLE_VALUE )
{
Fail("Error[%ul]:MoveFileA: CreateFile failed to "
"create the file correctly.\n", GetLastError());
}
bRc = CloseHandle(hFile);
if(!bRc)
{
Trace("MoveFileA: CloseHandle failed to close the "
"handle correctly. ERROR:%u\n",GetLastError());
/* delete the created file */
bRc = DeleteFileA(tempSource);
if(!bRc)
{
Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the"
"file correctly.\n", GetLastError());
}
Fail("");
}
/* set the file attributes to be readonly */
bRc = SetFileAttributesA(tempSource, FILE_ATTRIBUTE_READONLY);
if(!bRc)
{
Trace("MoveFileA: SetFileAttributes failed to set file "
"attributes correctly. GetLastError returned %u\n",GetLastError());
/* delete the created file */
bRc = DeleteFileA(tempSource);
if(!bRc)
{
Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the"
"file correctly.\n", GetLastError());
}
Fail("");
}
/* move the file to the new location */
bRc = MoveFileA(tempSource, tempDest);
if(!bRc)
{
/* delete the created file */
bRc = DeleteFileA(tempSource);
if(!bRc)
{
Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the"
"file correctly.\n", GetLastError());
}
Fail("Error[%ul]:MoveFileA(%S, %S): GetFileAttributes "
"failed to get the file's attributes.\n",
GetLastError(), tempSource, tempDest);
}
/* check that the newly moved file has the same file attributes
as the original */
result = GetFileAttributesA(tempDest);
if(result == 0)
{
/* delete the created file */
bRc = DeleteFileA(tempDest);
if(!bRc)
{
Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the"
"file correctly.\n", GetLastError());
}
Fail("Error[%ul]:MoveFileA: GetFileAttributes failed to get "
"the file's attributes.\n", GetLastError());
}
if((result & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY)
{
/* delete the newly moved file */
bRc = DeleteFileA(tempDest);
if(!bRc)
{
Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the"
"file correctly.\n", GetLastError());
}
Fail("Error[%ul]MoveFileA: GetFileAttributes failed to get "
"the correct file attributes.\n", GetLastError());
}
/* set the file attributes back to normal, to be deleted */
bRc = SetFileAttributesA(tempDest, FILE_ATTRIBUTE_NORMAL);
if(!bRc)
{
/* delete the newly moved file */
bRc = DeleteFileA(tempDest);
if(!bRc)
{
Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the"
"file correctly.\n", GetLastError());
}
Fail("Error[%ul]:MoveFileA: SetFileAttributes failed to set "
"file attributes correctly.\n", GetLastError());
}
/* delete the newly moved file */
bRc = DeleteFileA(tempDest);
if(!bRc)
{
Fail("Error[%ul]:MoveFileA: DeleteFileA failed to delete the"
"file correctly.\n", GetLastError());
}
PAL_Terminate();
return PASS;
}
| 28.704255 | 135 | 0.559262 | mans0954 |
6d17b72637d5643b6b1ef7724ba53c07b8f67c4e | 9,369 | hpp | C++ | externals/stlsoft-1.9.118/include/inetstl/error/exceptions.hpp | betasheet/diffingo | 285d21b16c118155e5c149b20fcb20a20276f3d7 | [
"MIT"
] | 17 | 2015-03-26T14:10:25.000Z | 2022-02-09T20:55:04.000Z | externals/stlsoft-1.9.118/include/inetstl/error/exceptions.hpp | betasheet/diffingo | 285d21b16c118155e5c149b20fcb20a20276f3d7 | [
"MIT"
] | null | null | null | externals/stlsoft-1.9.118/include/inetstl/error/exceptions.hpp | betasheet/diffingo | 285d21b16c118155e5c149b20fcb20a20276f3d7 | [
"MIT"
] | 3 | 2019-05-05T22:10:56.000Z | 2019-08-22T22:24:23.000Z | /* /////////////////////////////////////////////////////////////////////////
* File: inetstl/error/exceptions.hpp
*
* Purpose: Contains the internet_exception class.
*
* Created: 25th April 2004
* Updated: 10th August 2009
*
* Home: http://stlsoft.org/
*
* Copyright (c) 2004-2009, Matthew Wilson and Synesis Software
* 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(s) of Matthew Wilson and Synesis Software nor the names of
* any 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 inetstl/error/exceptions.hpp
*
* \brief [C++ only] Definition of the inetstl::internet_exception and
* exception class and the inetstl::throw_internet_exception_policy
* exception policy class
* (\ref group__library__error "Error" Library).
*/
#ifndef INETSTL_INCL_INETSTL_ERROR_HPP_EXCEPTIONS
#define INETSTL_INCL_INETSTL_ERROR_HPP_EXCEPTIONS
#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_MAJOR 4
# define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_MINOR 2
# define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_REVISION 1
# define INETSTL_VER_INETSTL_ERROR_HPP_EXCEPTIONS_EDIT 42
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////
* Compatibility
*/
/*
[DocumentationStatus:Ready]
*/
/* /////////////////////////////////////////////////////////////////////////
* Includes
*/
#ifndef INETSTL_INCL_INETSTL_H_INETSTL
# include <inetstl/inetstl.h>
#endif /* !INETSTL_INCL_INETSTL_H_INETSTL */
#ifndef STLSOFT_INCL_STLSOFT_ERROR_HPP_EXCEPTIONS
# include <stlsoft/error/exceptions.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_ERROR_HPP_EXCEPTIONS */
#ifndef STLSOFT_INCL_STLSOFT_UTIL_HPP_EXCEPTION_STRING
# include <stlsoft/util/exception_string.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_UTIL_HPP_EXCEPTION_STRING */
#ifndef INETSTL_OS_IS_WINDOWS
# include <errno.h>
#endif /* !INETSTL_OS_IS_WINDOWS */
#ifndef STLSOFT_CF_EXCEPTION_SUPPORT
# error This file cannot be included when exception-handling is not supported
#endif /* !STLSOFT_CF_EXCEPTION_SUPPORT */
/* /////////////////////////////////////////////////////////////////////////
* Namespace
*/
#ifndef _INETSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::inetstl */
namespace inetstl
{
# else
/* Define stlsoft::inetstl_project */
namespace stlsoft
{
namespace inetstl_project
{
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_INETSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////
* Classes
*/
/** \brief General exception class for internet-related failures.
*
* \ingroup group__library__error
*
*/
class internet_exception
: public os_exception
{
/// \name Types
/// @{
protected:
typedef stlsoft_ns_qual(exception_string) string_type;
public:
typedef os_exception parent_class_type;
#ifdef INETSTL_OS_IS_WINDOWS
typedef is_dword_t error_code_type;
#else /* ? INETSTL_OS_IS_WINDOWS */
typedef int error_code_type;
#endif /* INETSTL_OS_IS_WINDOWS */
typedef internet_exception class_type;
/// @}
/// \name Construction
/// @{
public:
ss_explicit_k internet_exception(error_code_type err)
: m_reason()
, m_errorCode(err)
{}
internet_exception(class_type const& rhs)
: m_reason(rhs.m_reason)
, m_errorCode(rhs.m_errorCode)
{}
internet_exception(char const* reason, error_code_type err)
: m_reason(class_type::create_reason_(reason, err))
, m_errorCode(err)
{}
protected:
internet_exception(string_type const& reason, error_code_type err)
: m_reason(reason)
, m_errorCode(err)
{}
public:
/// Destructor
///
/// \note This does not do have any implementation, but is required to placate
/// the Comeau and GCC compilers, which otherwise complain about mismatched
/// exception specifications between this class and its parent
virtual ~internet_exception() stlsoft_throw_0()
{}
/// @}
/// \name Accessors
/// @{
public:
virtual char const* what() const stlsoft_throw_0()
{
if(!m_reason.empty())
{
return m_reason.c_str();
}
else
{
return "internet failure";
}
}
/// The error code associated with the exception
error_code_type get_error_code() const stlsoft_throw_0()
{
return m_errorCode;
}
/// [DEPRECATED] The error code associated with the exception
///
/// \deprecated Use get_error_code() instead.
error_code_type last_error() const stlsoft_throw_0()
{
return get_error_code();
}
/// [DEPRECATED] The error code associated with the exception
///
/// \deprecated Use get_error_code() instead.
error_code_type error() const stlsoft_throw_0()
{
return get_error_code();
}
/// @}
/// \name Implementation
/// @{
private:
static string_type create_reason_(char const* reason, error_code_type err)
{
#ifdef INETSTL_OS_IS_WINDOWS
if( err == static_cast<error_code_type>(E_OUTOFMEMORY) ||
err == static_cast<error_code_type>(ERROR_OUTOFMEMORY) ||
NULL == reason ||
'\0' == reason[0])
{
return string_type();
}
else
#endif /* INETSTL_OS_IS_WINDOWS */
{
return string_type(reason);
}
}
/// @}
/// \name Members
/// @{
private:
const string_type m_reason;
error_code_type m_errorCode;
/// @}
/// \name Not to be implemented
/// @{
private:
class_type& operator =(class_type const&);
/// @}
};
/* /////////////////////////////////////////////////////////////////////////
* Policies
*/
/** \brief The policy class, which throws a internet_exception class.
*
* \ingroup group__library__error
*
*/
// [[synesis:class:exception-policy: throw_internet_exception_policy]]
struct throw_internet_exception_policy
{
/// \name Member Types
/// @{
public:
/// The thrown type
typedef internet_exception thrown_type;
typedef internet_exception::error_code_type error_code_type;
/// @}
/// \name Operators
/// @{
public:
/// Function call operator, taking no parameters
void operator ()() const
{
#ifdef INETSTL_OS_IS_WINDOWS
STLSOFT_THROW_X(thrown_type(::GetLastError()));
#else /* ? INETSTL_OS_IS_WINDOWS */
STLSOFT_THROW_X(thrown_type(errno));
#endif /* INETSTL_OS_IS_WINDOWS */
}
/// Function call operator, taking one parameter
void operator ()(error_code_type err) const
{
STLSOFT_THROW_X(thrown_type(err));
}
/// Function call operator, taking two parameters
void operator ()(char const* reason, error_code_type err) const
{
STLSOFT_THROW_X(thrown_type(reason, err));
}
/// @}
};
/* ////////////////////////////////////////////////////////////////////// */
#ifndef _INETSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} // namespace inetstl
# else
} // namespace inetstl_project
} // namespace stlsoft
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_INETSTL_NO_NAMESPACE */
/* ////////////////////////////////////////////////////////////////////// */
#endif /* INETSTL_INCL_INETSTL_ERROR_HPP_EXCEPTIONS */
/* ///////////////////////////// end of file //////////////////////////// */
| 31.23 | 83 | 0.62045 | betasheet |
6d1843e5d96480fee0262275e9f376e0f8684137 | 792 | cpp | C++ | snippets/cpp/VS_Snippets_CLR_System/system.Decimal.ConvFrom.SInts/CPP/cfromint16.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2020-03-12T19:26:36.000Z | 2022-01-10T21:45:33.000Z | snippets/cpp/VS_Snippets_CLR_System/system.Decimal.ConvFrom.SInts/CPP/cfromint16.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 555 | 2019-09-23T22:22:58.000Z | 2021-07-15T18:51:12.000Z | snippets/cpp/VS_Snippets_CLR_System/system.Decimal.ConvFrom.SInts/CPP/cfromint16.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 3 | 2020-01-29T16:31:15.000Z | 2021-08-24T07:00:15.000Z | //<Snippet3>
using namespace System;
void main()
{
// Define an array of 16-bit integer values.
array<Int16>^ values = { Int16::MinValue, Int16::MaxValue,
0xFFF, 12345, -10000 };
// Convert each value to a Decimal.
for each (Int16 value in values) {
Decimal decValue = value;
Console::WriteLine("{0} ({1}) --> {2} ({3})", value,
value.GetType()->Name, decValue,
decValue.GetType()->Name);
}
}
// The example displays the following output:
// -32768 (Int16) --> -32768 (Decimal)
// 32767 (Int16) --> 32767 (Decimal)
// 4095 (Int16) --> 4095 (Decimal)
// 12345 (Int16) --> 12345 (Decimal)
// -10000 (Int16) --> -10000 (Decimal)
//</Snippet3>
| 33 | 64 | 0.526515 | BohdanMosiyuk |
6d18e091c4fb941c97454f0a7a5347699a590586 | 3,434 | cpp | C++ | Source/PanelConfiguration.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 10 | 2019-02-25T11:36:23.000Z | 2021-11-03T22:51:30.000Z | Source/PanelConfiguration.cpp | solidajenjo/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 146 | 2019-02-05T13:57:33.000Z | 2019-11-07T16:21:31.000Z | Source/PanelConfiguration.cpp | FractalPuppy/Engine | 409516f15e0f083e79b749b9c9184f2f04184325 | [
"MIT"
] | 3 | 2019-11-17T20:49:12.000Z | 2020-04-19T17:28:28.000Z | #include "PanelConfiguration.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "ModuleRender.h"
#include "ModuleCamera.h"
#include "ModuleInput.h"
#include "ModuleTextures.h"
#include "ModuleScene.h"
#include "ModuleScript.h"
#include "ModuleUI.h"
#include "ModuleAudioManager.h"
#include "imgui.h"
#include "Math/MathConstants.h"
#define NUMFPS 100
PanelConfiguration::PanelConfiguration()
{
fps.reserve(NUMFPS);
ms.reserve(NUMFPS);
}
PanelConfiguration::~PanelConfiguration()
{
}
void PanelConfiguration::Draw()
{
if (!ImGui::Begin("Configuration", &enabled))
{
ImGui::End();
return;
}
if (ImGui::CollapsingHeader("Application"))
{
UpdateExtrems();
DrawFPSgraph();
DrawMSgraph();
DrawMemoryStats();
}
if (ImGui::CollapsingHeader("Window"))
{
App->window->DrawGUI();
}
if (ImGui::CollapsingHeader("Camera"))
{
App->camera->DrawGUI();
}
if (ImGui::CollapsingHeader("Render"))
{
App->renderer->DrawGUI();
}
if (ImGui::CollapsingHeader("Input"))
{
App->input->DrawGUI();
}
if (ImGui::CollapsingHeader("Textures"))
{
App->textures->DrawGUI();
}
if (ImGui::CollapsingHeader("Scene"))
{
App->scene->DrawGUI();
}
if (ImGui::CollapsingHeader("UI"))
{
App->ui->DrawGUI();
}
if (ImGui::CollapsingHeader("Audio"))
{
App->audioManager->DrawGUI();
}
if (ImGui::CollapsingHeader("Scripts"))
{
App->scripting->DrawGUI();
}
if (ImGui::CollapsingHeader("Skybox"))
{
App->renderer->DrawSkyboxGUI();
}
ImGui::End();
}
void PanelConfiguration::DrawFPSgraph() const
{
if (fps.size() == 0) return;
char avg[32];
char showmin[32];
sprintf_s(avg, "%s%.2f", "avg:", totalfps / fps.size());
sprintf_s(showmin, "%s%.2f", "min:", minfps);
ImGui::PlotHistogram("FPS", &fps[0], fps.size(), 0, avg, 0.0f, 300.0f, ImVec2(0, 80));
ImGui::Text(showmin);
}
void PanelConfiguration::DrawMSgraph() const
{
if (ms.size() == 0) return;
char avg[32];
char showmax[32];
sprintf_s(avg, "%s%.2f", "avg:", totalms / ms.size());
sprintf_s(showmax, "%s%.2f", "max:", maxms);
ImGui::PlotHistogram("MS", &ms[0], ms.size(), 0, avg, 0.0f, 20.0f, ImVec2(0, 80));
ImGui::Text(showmax);
}
void PanelConfiguration::AddFps(float dt)
{
if (dt == 0.0f) return;
if (fps.size() == NUMFPS)
{
totalfps -= fps.back();
fps.pop_back();
totalms -= ms.back();
ms.pop_back();
}
float newfps = 1 / dt;
float newms = dt * 1000;
fps.insert(fps.begin(), newfps);
ms.insert(ms.begin(), newms);
totalfps += newfps;
totalms += newms;
}
void PanelConfiguration::UpdateExtrems()
{
minfps = 1000.f;
maxms = 0.f;
for (unsigned i = 0; i < fps.size(); i++)
{
minfps = MIN(minfps, fps[i]);
maxms = MAX(maxms, ms[i]);
}
}
void PanelConfiguration::DrawMemoryStats() const
{
//sMStats stats = m_getMemoryStatistics();
//ImGui::Text("Total Reported Mem: %u", stats.totalReportedMemory);
//ImGui::Text("Total Actual Mem: %u", stats.totalActualMemory);
//ImGui::Text("Peak Reported Mem: %u", stats.peakReportedMemory);
//ImGui::Text("Peak Actual Mem: %u", stats.peakActualMemory);
//ImGui::Text("Accumulated Reported Mem: %u", stats.accumulatedReportedMemory);
//ImGui::Text("Accumulated Actual Mem: %u", stats.accumulatedActualMemory);
//ImGui::Text("Accumulated Alloc Unit Count: %u", stats.accumulatedAllocUnitCount);
//ImGui::Text("Total Alloc Unit Count: %u", stats.totalAllocUnitCount);
//ImGui::Text("Peak Alloc Unit Count: %u", stats.peakAllocUnitCount);
}
| 21.872611 | 88 | 0.665987 | solidajenjo |
6d1999805e0042b613ef2c70600491b641c28346 | 248 | cpp | C++ | tournaments/phoneCall/phoneCall.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 5 | 2020-02-06T09:51:22.000Z | 2021-03-19T00:18:44.000Z | tournaments/phoneCall/phoneCall.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | null | null | null | tournaments/phoneCall/phoneCall.cpp | gurfinkel/codeSignal | 114817947ac6311bd53a48f0f0e17c0614bf7911 | [
"MIT"
] | 3 | 2019-09-27T13:06:21.000Z | 2021-04-20T23:13:17.000Z | int phoneCall(int min1, int min2_10, int min11, int s) {
if (s < min1) {
return 0;
}
for (int i = 2; i <= 10; i++) {
if (s < min1 + min2_10 * (i - 1)) {
return i - 1;
}
}
return 10 + (s - min1 - min2_10 * 9) / min11;
}
| 19.076923 | 56 | 0.471774 | gurfinkel |